SlideShare a Scribd company logo
www.cyberlabzone.com
C Programming
www.cyberlabzone.com
Topics for C Language
1.Introduction to C language
2.Programming Languages
3.Data Types
4.Basic Input/Output (I/O)
5.Control Constructs
6.Array
7.Fuctions
8.Program Design Example
9.Pointers
10.Structures & Unions
11.File Operation in C
12.The C Preprocessor
13.Computational Complexity
www.cyberlabzone.com
Introduction to C languages
C is a traditional, Procedural language,i.e. one that requires the programmer to
provide step-by-step instructions for the processor (i.e., the main logic unit of a
computer).
The great success of C is due to its simplicity, efficiency,
flexibility and small memory requirements. It is also due to the portability of
programs that are written in it, i.e., the ability to be easily adapted to new
platforms (i.e., operating systems and processors).
C's great portability is in very large part a result of the fact that
compilers and libraries are available for numerous platforms. A compiler is a
specialized computer program that converts source code (i.e., the original,
human-readable form of a program typed into a computer by a programmer in a
programming language) into another language, usually machine language (also
called object code or machine code) so that it can be directly understood by
processors. A library is a collection of routines (also called subprograms,
procedures or functions) that perform operations which are commonly required
by programs.
www.cyberlabzone.com
Programming Languages
Programming Languages classified as ”Low Level/High Level”
1.Low Level
•Machine Language
(binary-based code; machine dependent)
• Assembly Language
(mnemonic form of machine language)
2.High Level
Closer to natural languages.
Generally, machine independent
Usually, several machine instructions are combined into one high-
level instruction.
Examples:
FORTRAN, COBOL,BASIC, Java, Pascal, Ada, PL/I, Lisp, C
GPSS,C++, Matlab
www.cyberlabzone.com
Processing a High-level Language
Program
Programs written in high-level languages must be converted to
machine language.
Two approaches:
(1) Compilation used with C, C++, Fortran,...
(2) Interpretation
Used with Matlab, Visual Basic,...
www.cyberlabzone.com
STEP 1) Use Dos Prompt to create a “Directory”. In this Directory
We write and save all Programme name source files with a suffix “.c”.
STEP 2)In Dos Prompt to compile the desired Programme we use “Ctrl
+F9” to get a desired result While programme is on the monitor .
STEP 3) Check the error if any caught by compiler, remove
that error and go back to step 2,repeat whole process again.
STEP 4) Run the program by using “Ctrl+F9” and for
OUTPUT we use “Alt+F5”
in the Dos prompt.
Compilation (In Window Environment)
www.cyberlabzone.com
C Program Examples
1. Requirements Specification (Problem Definition)
Write a simple C program to request the users’ SSN and print the message “Hello
(SSN)!” (where SSN is the value the user supplied) to the screen of the computer
monitor.
2. Analysis---Refine, Generalize, Decompose the problem definition
(i.e., identify sub problems, I/O, etc.)
Input = SSN
Output= A prompt for the SSN then
“Hello (SSN)!”
3. Design---Develop Algorithm
Pseudo-code Algorithm
print “Enter SSN (no dashes)”
read SSN
print “Hello (SSN) !”
4. Implementation --- Write the "Program" (Code)
www.cyberlabzone.com
C Examples
/* C Program to greet the user */
#include <stdio.h> /* makes the function printf “known” */
/* to the C compiler */
void main(void)
{
int ssn; /* variable ssn declared */
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn); /* read the SSN */
printf(”Hello %d !n”,ssn); /* print the message */
}
www.cyberlabzone.com
Main Function
#include ... /* preprocessor directive */
.
.
.
void main(void) /*function header*/
{ .
. /* function body */
.
}
In the following set of slides we will define the
component parts of the main function.
www.cyberlabzone.com
Preprocessor Directives
#include ... /* preprocessor directive */
.
.
.
void main(void)
{ .
.
.
}
Statements beginning with the symbol # are called preprocessor
directives. The #include directives allow the C program to access
libraries of functions that are not available directly in C. These
libraries are referred to as header files:
stdio.h standard input-output functions
math.h math functions
stdlib.h a “standard” library of functions
www.cyberlabzone.com
Main Function Header
#include ...
.
.
.
void main(void) /*function header*/
{ .
.
.
}
The “initial” input is any value(s) passed at initial execution, e.g.
>a.out 1.0 3.5
Typing the above at the Unix prompt attempts to pass the values 1.0
and 3.5 to main. At this point we will not do this. The header for the
programs in some C programs is of the form:
int main(void)
and there is a corresponding statement in the function body:
return (0);
main has no
“initial” input
values. (see
below)
main function
returns no value
www.cyberlabzone.com
Main Function (body)
#include ...
.
.
.
void main(void)
{ .
. /* function body */
.
}
• The body of a function is all the declarations and executable
statements between the braces (in the block). The declarations
must precede the executable statements in this block.
• When you run a program, the first statement executed is the first
(from the top of the file) executable statement in main. The
execution of statements proceeds until the terminating “}” right
brace is encountered or a return statement is executed.
a “block” in C is
defined by a set
of curly braces.
www.cyberlabzone.com
Declaration
#include <stdio.h>
void main(void)
{
int ssn; /* variable ssn declared */
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn);
printf(”Hello %d !n”,ssn);
}
One form of a declaration in C :
data-type variable_name ;
www.cyberlabzone.com
Data Types
Fixed Point(Integers) Floating Point Character
short float char
int
double
long
long double
www.cyberlabzone.com
Variable Names
Variable Names - reference to memory locations storing data values.
A variable name is one example of an identifier in C.
An identifier can use a combination of letters, numerical digits, and
the underscore ( _ ) that starts with a letter. Only the first 31
characters of an identifier are recognized by most compilers.
Identifiers cannot be the same as a reserved word or keyword, such as
void, float, or return. Examples: x sum force2
rate_Of_Change
Examples of invalid variable names (why?):
2force rate-of-change x.5 return
C case-sensitive, so that the following three names all represent
different variables (i.e., different storage locations):
time Time TIME
www.cyberlabzone.com
#include <stdio.h>
void main(void)
{
int ssn;
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn);
printf(”Hello %d !n”,ssn);
}
The printf and scanf functions appear in
‘expression’ statements.
1st executable
statement
3rd executable
statement
2nd executable
statement
Executable Statements
www.cyberlabzone.com
Executable Statements
Statements are grouped by their type:
expression statement
do-while and while statements
for statement
if and if-else statements
return statement
switch statement
assignment statement
Every executable statement in C must be followed
by a “ ; “ semicolon.
www.cyberlabzone.com
Assignment Statement
•Interpretation: compute the value on the
right-hand-side of the = and put this value in memory at
location named (or tagged) by the name variable .
• an expression can be a constant, a variable or
operators with operands.
variable = expression;
www.cyberlabzone.com
Constants
Literal Constants(examples)
Numeric: 3 6.248 -7.25 1.5e4 (=15000)
Single Character: 'A' 'a' '9' '+' ' '
Character String: “Enter a positive number: ”
Symbolic Constants(example)
#define PI 3.14159265 /* preprocessor directive */
By default, constants declared in #define are of type
double.
Standard practice is to use all upper-case letters for the
constant name, to avoid confusion with a variable name.
A “constant” means you cannot change the value, e.g.
PI = 3.0;
will generate a compiler error from gcc.
www.cyberlabzone.com
Arithmetic Operators
- for integer arithmetic, the / operator yields an integer result, and
% gives the remainder after dividing two integers. E.g.,
5 / 3 1 5 / 6 0
5 % 3 2 5 % 6 5
(Note: division by 0 creates an "overflow" run-time error.)
- use arithmetic operators, with parentheses for grouping; e.g., (a
- b) / (2 * c)
e.g, without parentheses, the example above would evaluate b/2
first, then do the multiplication, then the subtraction.
+, - , * , / , % (modulus) (no ^ operator as in Matlab)
www.cyberlabzone.com
Rules of Precedence
( ) Higher
*, /, % (left to right for tie)
+, - (left to right for tie) Lower
Examples,
: x = 3 + 2 * 3; /* x now has the value 9 */
y = 3 * 2 % 3; /* y now has the value 0 */
- Precedence Order for Arithmetic Operators:
www.cyberlabzone.com
Understanding the Assignment
statement
• Example
int time;
.
.
.
time = 0;
.
0time
1200
Main Memory
Memory map after the
assignment statement
time = 0 is executed
.
unknowntime
1200
Main Memory
Memory map before the
assignment statement
time = 0 is executed
www.cyberlabzone.com
Understanding the Assignment
statement
• Example
double force;
force = 5.0;
.
.
.
force = force * 3.0;
.
15.0force
1400
Main Memory
Memory map after the
assignment statement
force = force * 3.0;
is executed
.
5.0force
1400
Main Memory
Memory map before the
assignment statement
force = force * 3.0;
but after
force = 5.0;
is executed
www.cyberlabzone.com
Character Values
Individual characters may be assign to variables of data-type
char.
Example: Write a program to prompt the user for a Y/ N
response. Print the users response to the screen.
#include <stdio.h>
void main(void)
{
char letter;
printf(“Please enter a response (Y/N):”);
scanf(“%c”,&letter);
printf(“Your response was: %c n”,letter);
}
www.cyberlabzone.com
Expression Statements
One form of a expression statement in C :
function(argument list) ;
Scanf function
accepts input from standard input device,
usually a keyboard
scanf("format string", &var1, &var2, ...);
The number of conversion specifiers should match the
number of variables that follow the “format string”.
%i,%d - decimal integer (d=decimal)
%f - float
%lf - double(where lf="long float")
%Lf - long double
%c - character
where “format string” is the string of conversion
specifiers for the various data types in the variable list.
e.g.,
www.cyberlabzone.com
Basic Input/Output (I/O)
sends output to standard output device,
usually a video monitor
printf("format string", output-list);
where ”format string” can contain characters to be output
and the conversion specifiers indicating type and position
of the output values. For output, we specify formats
conversion specifiers) a little differently than we do for
input. For example:
%i, %d -decimal integer
%o -octal integer
%x, %X -hex integer (use X for caps A - F)
%f -float, double
%c -character
%s -character string
Printf function
www.cyberlabzone.com
Output Control: Special characters
Each is represented by an escape sequence,
which is a backslash () and an escape character.
Examples are:
" - output double quotes
b – backspace
? - output question-mark character (?)
 - output backslash character ()
n - new line
www.cyberlabzone.com
Output Control: Field Width
The number of print positions to be used in the output
of display values. For floating-point numbers, we can
also specify the number of digits to be displayed after
the decimal point.
Examples:
%3d - display an integer using 3 print positions.
%7.3f - display a floating-point number (float, or
double) using a total field width of 7 and with 3 places
after the decimal point.
www.cyberlabzone.com
Printf and scanf Examples
Example:
scanf("%i %f %lf %c", &n, &a, &x, &code);
Example:
printf("The sum of %i values is %f.n“,numValues,
sum);
printf("%sn", "Temperature Variations");
printf("The output is: n");
www.cyberlabzone.com
Comments
Comments in C are of the general form:
/* . . . */
Comments can be inserted anywhere you can put a space (blank).
Comments are ignored by the C compiler and not included in the
executable file.
The */ can be on the next line but then every character between
the /* and the */ is ignored by the C compiler.
www.cyberlabzone.com
Programming Errors
Syntax Errors
Run-time Errors
Logical Errors
The gcc compiler will catch these errors and give you
Error messages.
Example: x + 1 = x; (should be x = x+1; for a valid
assignment statement)
The gcc compiler will not catch these errors.
Example: User enters the value 0 and your code reads
this value into variable x, and then computes 1/x .
The gcc compiler will not catch these errors. Program
will run and not generate any error messages but
results outputted by the program are incorrect.
Example: User programs solution using the wrong
formula.
www.cyberlabzone.com
1. Problem Definition
Write a program that reads a number and computes the square root if
the number is non-negative.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = real number
Output=real number
3. Develop Algorithm
(processing steps to solve problem)
C problem examples
www.cyberlabzone.com
C problem Example
Flowchart
Print “enter value”
Read value
value >= 0.0
Print sqrt(value)
TrueFalse
www.cyberlabzone.com
C program Example
/* C Program to compute the square root of a positive
number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”); /* request
user input */
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
}
www.cyberlabzone.com
Selection Structures Decision statements
if(expression)
statement;
• if expression evaluates to true, the statement
is executed; otherwise execution passes to the
next statement in the program.
• if Selection Structure
if(value >= 0.0);
printf(”square_root(%f) = %f n", value,sqrt(value));
/* Error! Don’t put semicolon here */
/* This is an example of a logical error */
1. Problem Definition
Modify the previous program to notify the user when
the input is invalid.
www.cyberlabzone.com
C Program Examples (Modified)
Flowchart
Print “enter value”
Read value
value >= 0.0
Print sqrt(value);
TrueFalse
Print “invalid input”
www.cyberlabzone.com
C Program Examples (Modified)
/* C Program to compute the square root of a positive number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”);/*request user input*/
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
else
printf(“invalid user input, please enter non-negative valuen”);
}
www.cyberlabzone.com
Math Library in C
- in header file math.h
Arguments (parameters) for each of the following
functions are assumed to be of type double. If not, a
type double copy is made for use in the function. To
compile a program that contains math functions you
need to use the -lm (Lm not 1m )option for gcc.
> gcc file.c -lm
See next slide
www.cyberlabzone.com
fabs (x) - |x|
sqrt (x) - square root of x
pow (x, a) - x to the power ‘a’
exp (x) - e to the power ‘x’ (e = 2.718281828 …)
log (x) - ln x = loge x
log10 (x) - log10 x
sin (x) - sine function (x in radians)
cos (x) - cosine function (x in radians)
tan (x) - tangent function (x in radians)
fmod (a, b) - remainder of a/b in floating-point
ceil (x) - smallest integer >= x
floor (x) - largest integer <= x
www.cyberlabzone.com
If- else Selection Structure
if (expression)
statement1;
else
statement2;
-if expression evaluates to true, statement1 is
executed and execution skips statement2
-If expression evaluates to false, execution skips
statement1 , statement2 is executed
Control Constructs
www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
Example -
if(b < a){
temp = a;
a = b;
b = temp;
}
or
...
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
else {
else-statement1;
else-statement2;
else-statementm;
}
(what does this
code accomplish?)
...
...
If-else Selection Structure
www.cyberlabzone.com
C Problem Example
1. Problem Definition
Modify the previous program to compute the following:
You must check that the value is legal, i.e.
value >= 1.0 or value <= -1.0
0.1
2
value
www.cyberlabzone.com
C Problem Example
Flowchart
Print “enter
value”
Read
value
value >= 1.0 or value <= -
1.0
Print sqrt(value*value -
1.0);
TrueFalse
Print “invalid
input”
www.cyberlabzone.com
/* C Program to compute the square root of */
/* value*value -1.0 */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
/* request user input*/
printf(”Please enter value >= 1.0 or <= -1.0 :”);
scanf("%lf", &value); /* read value */
/* Output the square root. */
if ((value >= 1.0) || (value <= -1.0))
printf(”square_root(%f) = %f n", value,sqrt(value*value - 1.0));
else {
printf(“invalid user inputn”);
printf(“input should be a value >= 1.0 or <= -1.0 n”);
}
}
C Problem Example (Modified)
www.cyberlabzone.com
Logical Expression (Relational Operator)
In logical expressions (which evaluate to true or
false), we can use the following Relational
operators:
Relational
Operator
Type of Test
== equal to (don’t use =)
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
www.cyberlabzone.com
Logical Expression (Relational Operations)
Logical(Boolean)
Operators
&& and (true if both true)
|| or (true if at least one is true)
! not (a unary operator)
Operation
In logical expressions (which evaluate to true or
false), we can use the following Logical operators:
www.cyberlabzone.com
Logical Expressions
int ans, x = 3, y = 4;
ans = (x < 5)||(y >= 5); /* ans now has the value 1 */
ans = (x < 5)&&(y >= 5); /* ans now has the value 0 */
In C the value for False is represented by the value zero
and True is represented by any nonzero value. The value
False can be any zero value such as the number 0 or 0.0
or null character ‘ 0 ’ or the NULL pointer.
Example 2:
int x = 0; /* x declared as an integer variable */
/* and initialized to the value 0 */
if (x = 0) /* note the error, == should be used */
printf(“ x is zeron”); /*message not printed, why?*/
Example 1:
Caution: Avoid testing floating-
point numbers for equality! Why?
www.cyberlabzone.com
Nested if- else Selection Structure
1. Problem Definition
Write a program that returns a letter grade based on a quiz score. The input
will be the integer score from a 10 point quiz. The letter grades are assigned
by:
9 - 10 “A”
7 - 8 “B”
5 - 6 “C”
3 - 4 “D”
< 3 “F”
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = integer score
Output=character “grade”
3. Develop Algorithm
(processing steps to solve problem)
www.cyberlabzone.com
C Problem Example
Flowchart
Print “enter score”
Read score
score == 10 || score == 9
Print “A”
TrueFalse
(continued on next slide)
(skip else part of statement)
www.cyberlabzone.com
C Problem Example
False
score == 8 || score == 7
Print “B”;
True
(skip else part of statement)
(continued on next slide)
False
www.cyberlabzone.com
C Problem Example
False
score == 6 || score == 5
Print “C”;
True
(skip else part of statement)
(continued on next slide)
False
www.cyberlabzone.com
C Problem Example
False
score == 4 || score == 3
Print “D”
True
False
Print “F”
www.cyberlabzone.com
C Problem Example
/* C Program to compute the letter grade for a quiz.
*/
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
printf(”Please enter a score :”); /* request user input
*/
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
www.cyberlabzone.com
C Problem Example
if ((score == 10) || (score == 9))
printf(“An”);
else
if ((score == 8) || (score == 7))
printf(“Bn”);
else
if ((score == 6) || (score == 5))
printf(“Cn”);
else
if ((score == 4) || (score == 3))
printf(“Dn”);
else
printf(“Fn”);
} /* end of program */
Unless { } are used the else matches the first if in the code above.
www.cyberlabzone.com
Switch Selection structure
1. Problem Definition
Redo the previous problem by using a switch statement rather
than the nested if-else statement.
Pseudo-code Algorithm
print “enter score”
read score
switch score
score = 9,10 print “A”
score = 7,8 print “B”
score = 5,6 print “C”
score = 3,4 print “D”
otherwise print “F”
www.cyberlabzone.com
C Program Example
/* C Program to compute the letter grade for a quiz. */
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
/* request user input */
printf(”Please enter a score :”);
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
www.cyberlabzone.com
C Program Example
switch (score) {
case 10:
case 9: printf(“An”);
break;
case 8:
case 7: printf(“Bn”);
break;
case 6:
case 5: printf(“Cn”);
break;
case 4:
case 3: printf(“Dn”);
break;
default: printf(“Fn”);
} /* end of switch */
} /* end of program */
www.cyberlabzone.com
Switch Selection Structure
The switch structure can be used when we have
multiple alternatives based on a value of type int or
type char (but not floating point). This structure has
the general form:
switch (controlling expression) {
case label1:
statements1;
case label2:
statements2;
default:
default statements;
}
(controlling expr.
must evaluate to an
integer or a
character value;
each case should
end with a break
stmt.)
...
www.cyberlabzone.com
1. Problem Definition
Use a while statement to read a list of integers from a file and
compute the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average =(sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C problem Example
www.cyberlabzone.com
Flowchart
while EOF != scanf value
total = total + value;
count = count + 1;
TrueFalse
total = 0;
count = 0;
printf total/(double) count
(double) is a cast
see slide #14
C problem Example
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count = 0; /*Why are total and count set to
zero?*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count + 1;
} /* end of while loop */
/* Output the average. */
printf(”Average of the %i numbers = %f
n“,count,total/(float)count);
}
C problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
C problem Example-Execution
www.cyberlabzone.com
4. Run the program using Unix redirection <
a.out < input.dat
5. What happens if you type
a.out < input.dat > output.dat
Note: if you do this a second time it will fail because
Unix will not let you over-write an existing file.
6. To append the results to the existing file output.dat
a.out < input.dat >> output.dat
C problem Example-I/O Redirection
www.cyberlabzone.com
A second form of a declaration in C :
data-type variable_name = initializer;
/*Why are total and count initialized to zero?*/
Answer: Un-initialized variables have unknown (garbage) values.
int value,total = 0,count = 0;
Assignment statement
www.cyberlabzone.com
while(expression)
statement;
• if expression evaluates to true, the statement
is executed and then execution loops up and
re-evaluates expression; otherwise execution
passes to the next statement in the program.
• while statement format
while(value >= 0.0);
/* Error! Don’t put semicolon here */
/* This is an example of a logical error*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count +1;
} /* end of while loop */
While-loop Statement
www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
while (expression) {
while-statement1;
while-statement2;
while-statementn;
}
• if expression evaluates to true, all the
statements are executed and then execution
loops up and re-evaluates expression;
otherwise execution passes to the next
statement in the program.
While-General Format
www.cyberlabzone.com
{
statement1;
statement2;
.
.
.
statementn;
}
A sequence of statements surrounded by a pair
of curly braces is called a block or
compound statement
1) From outside, the compound statement looks
like a single statement. A compound statement
can go where any single C statement can go.
(e.g. a branch of if-else, body of a for loop, ...)
What is a Compound statement?
www.cyberlabzone.com
What is all this fuss about blocks?
A block is any compound statement that may include variable
declaration(s).
1.As a compound statement, from outside, the
block looks like a single C statement. A
block can go where any single C statement
can go.
2.The importance of a block is that, the curly
braces of the block delimit the Scope (i.e.
the region of validity) of the variables
declared in the block.
3. The concept of Scoping lies at the heart of
Structured Programming, as will be
discussed in a future lecture on Modularity.
www.cyberlabzone.com
The program makes use of the fact that the scanf function returns
and integer value representing the number of successful
conversions. For example in the code fragment:
Example:
int number,value1,value2,value3;
number = scanf(“%d%d%d”,&value1,&value2,&value3);
the variable number could take the value 0,1,2 or 3.
EOF is a built-in constant in C(usually assigned -1).
If you are checking for End-of-File then use this constant.
EOF != scanf("%i", &value)
Scanf-Revisited
www.cyberlabzone.com
To fix the above use the cast operator
where data_type is a valid C data type.
float result;
int total = 10 , count = 4 ;
result = total / (float) count; /* result now has the value 2.5 */
Example,
float result;
int total = 10 , count = 4 ;
result = total / count; /* result has the value 2.0 */
( data_type )
printf(”Average of the %i numbers = %fn“,count, total/(float)count );
Arithmetic Conversions-Cast
www.cyberlabzone.com
data_type1 x;
data_type2 result;
result = x;
If x and result have different data types then an automatic
conversion takes place. Data could be lost.
Example,
float x = 3.1416;
int result;
result = x; /* result now has the value 3 */
1) Conversion of assigned values
Arithmetic Conversions
www.cyberlabzone.com
+, - , * , /x op y ; where op is
If x and y have different (mixed) data types then C automatically
converts data from the lower rank to the higher rank and then
performs the computation.
Note: % (modulus) is only defined on integers.
The ranking is given by the following table.
long double Higher
double
float
long integer
integer
short integer Lower
2) Conversion of values with mixed data types
in an expression using arithmetic operators
Arithmetic Conversions
www.cyberlabzone.com
Example,
float result , x = 3.1416;
int y = 3;
result = x + y; /* result now has the value 6.1416 */
Example,
int x = 2.5;
float result, y;
y = x;
result = 1 / y; /* result now has the value .5 */
Arithmetic Conversions
www.cyberlabzone.com
1. Problem Definition
Write a program that reads a file of characters one
character at a time and writes out each non-blank character to
another file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = characters in a file “input2.dat” Assume this file
is non-empty.
Output=Non-blank characters from input2.dat are
output to the file output2.dat
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example
www.cyberlabzone.com
Flowchart
while EOF != scanf c
TrueFalse
scanf c
if c != ‘ ‘ /* a blank */
printf c
C Problem Example
www.cyberlabzone.com
/* C Program to remove the blanks from a text file. */
#include <stdio.h>
void main(void){
char c;
scanf("%c",&c);
do {
if (c != ' ')
printf("%c",c);
} while(EOF != scanf("%c",&c));
}
C Problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem2.c ,
and make sure to save the file.
2. Use xemacs to create an input file input2.dat and enter in any
number of lines of text including blanks. Save and exit this file.
3. Compile the problem2.c code by typing
gcc problem2.c
4. Run the program using Unix redirection < and >
a.out < input2.dat > output2.dat
5. View the contents of output2.dat
more output2.dat
C Problem Example-Execution
www.cyberlabzone.com
do
statement;
while(expression);
• The statement is executed first. Then if expression
evaluates to true, execution loops up and the statement is
executed again; otherwise execution passes to the next
statement in the program. The general form of the do-while
statement is:
• do/while statement format
do {
while-statement1;
while-statement2;
while-statementn;
} while (expression);
C Problem Example
www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. The first number in the list gives the count
of the numbers to be read. This first value is not used in the
computation of the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input3.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
Use a counter controlled loop.
(processing steps to solve problem)
C Problem Example
www.cyberlabzone.com
Flowchart
for i = 1 ; i <= count; i=i+1
scanf value
total = total + value;
TrueFalse
total = 0;
scanf count
printf total/(double) count
C Problem Example
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
scanf(“%i”,&count);
for(i=1;i<=count;i=i+1) {
scanf(“%i”,&value); /* read value */
total = total + value;
} /* end of for loop */
/* Output the average. */
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem3.c ,
and make sure to save the file.
2. Use xemacs to create an input file input3.dat and enter in integers
into this file .The first integer is the count of integers to be
averaged. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem3.c
4. Run the program using Unix redirection <
a.out < input3.dat
C Problem Example-Execution
www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. )
statement1;
C allows more than one initialization expression or update statement but
these statements or expressions must be separated by a comma not a
semicolon. Also, if there is more than one init. expression or update
statement then the order of execution is from left to right.
The initialization expressions are executed once (and only once) .
If expression evaluates to true, statement1 is executed and execution loops
up and evaluates all the update stmnts. and then expression is
re-evaluated; otherwise execution passes to the next statement in the
program.
The following order of must be observed …
init. expressions; expression ; update stmnts
for-loop Statement
www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. ){
statement1;
statement2;
.
.
.
statementn;
}
The initialization expressions are executed once (and only once) ,
next:
if expression evaluates to true, the statements
statement1,... ,statementn are executed and execution
loops up and evaluates all the update stmnts. and then
expression is re-evaluated;
otherwise execution passes to the next statement in the program.
for-General Format
www.cyberlabzone.com
Write a code fragment to add the integers from 1 to 100.
int i,total;
total = 0;
for(i=1;i<=100;i=i+1)
total = total + i;
The above code could be re-written as:
int i,total;
for(i=1, total = 0; i<=100; total=total+i, i=i+1);
but not as:
int i,total;
for(i=1, total = 0; i<=100; i=i+1, total=total+i);
Why not? The order of the statements is critical!
for-Examples
www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. Read the integers until the sentinel value of
-999 occurs. Do not use the sentinel value in the computation of
the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input4.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example-Revisited
www.cyberlabzone.com
Flowchart
for i = 1 ; ; i=i+1
scanf value
if value == -999
break;
total = total+value;
TrueFalse
total = 0;
printf total/(float) (i-1)
C Problem Example-Revisited
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
for(i=1; ;i=i+1) {
scanf(“%i”,&value); /* read value */
if (value == -999) /* -999 is the sentinel value */
break;
total = total + value;
} /* end of for loop */
/* Output the average. */
count = i-1;
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example-Revisited
www.cyberlabzone.com
Omitting the logical expression in a for statement means
that the for statement executes as an infinite loop.
for(i=1; ;i=i+1) {
As with the switch statement the break statement causes
the termination of the loop but not the program.
Break Statement
www.cyberlabzone.com
A one dimensional array is a list of data values, with
all values having the same data type(the base type),
such as:
• integer
• float
• double
• char
Technically, an array is a uniform data structure.
Individual array elements are referenced using
the array name and a subscript that identifies the
element position in the array.
What is an Array?
Array
www.cyberlabzone.com
For a one dimensional array, we specify the array name, its
base data type, and the number of storage locations
required using declarations such as
int a[25];
float x[100], y[100];
which specifies 25 integer locations for a and 100 floating-
point locations for arrays x and y.
Storage for array elements are in contiguous locations in
memory, referenced by subscript(or index) values starting at 0.
Thus for array a above, the storage is
. . .
a[0] a[1] a[24]
RAM
Declaring an Array
www.cyberlabzone.com
We can initialize array elements in declaration
statements; e.g.,
int counts[5] = {1, 2, 3, 4, 5};
int evens[] = {2, 4, 6, 8};
The array size could also be specified using a symbolic
constant:
#define ARRAY_SIZE 25
int a[ARRAY_SIZE];
.
.
.
/* evens has 4 elements */
We cannot specify more initial values than there are array
elements, but we can specify fewer initial values, and the
remaining elements will be initialized to 0. e.g.,
int b[10] = {2};
double x[250] = {0};
Declaring and initializing an Array
www.cyberlabzone.com
Note: when referencing a particular element of an array use
square brackets, not parenthesis or curly braces.
Given that the array x is declared as:
int x[250];
To initialize a large array to a nonzero value - say 10, we
can use a loop. e.g.,
for (k = 0; k <= 249; k = k+1)
x[k] = 10;
k is a subscript
Arrays-Subscripting
www.cyberlabzone.com
A subscript value for an array element can be specified as any
integer expression.
For example, given the following declarations:
double y[4] = {-1.0, 12.0, 3.5, 3.2e-2};
int c = 2;
the following statement would assign the value of 5.5 to y[1]
y[2 * c - 3] = 5.5;
Arrays-Subscripting
www.cyberlabzone.com
Given an integer value n, we can use the
following code to compute and store the first n
Fibonacci numbers in an array:
1. Problem Definition
Write a program “fib” that prompts the user for an integer n. The
program prints the first n Fibonacci numbers.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = n - the count of Fibonacci Numbers to be printed
Output= Fib Numbers printed to screen.
3. Develop Algorithm
Use the formula: fib0= 1, fib1 =1 and for k > 1
fibk = fibk-1 + fibk-2
Example-Fibonacci Numbers
www.cyberlabzone.com
#include <stdio.h>
/* C program to print the first n Fibonacci Numbers. */
void main(void){
int k,n;
int fib[100] = {1,1}; /* note: n must be <= 100 , why ? */
printf(“How many Fibonacci number do you want listed?”);
scanf(“%i”,&n);
for (k = 2; k < n; k++) /* the ++ is the increment operator */
fib[k] = fib[k-1] + fib[k-2];
/* print the results, four per line */
for (k = 0; k < n;++k){
if (k % 4 == 0)
printf(“n”);
printf("%8i", fib[k]); /* that’s 8 ints */
} /* end of for loop */
printf(“n”);
} /* end of main */
(For large values of parameter n, we would need more space for each
print column. Also, even with data type long , the calculated values may
become too large for the allocated storage space.)
www.cyberlabzone.com
:
.
Since incrementing and decrementing (negative increments)
are common programming operations, the C language
provides shortcut Increment / Decrement operators.
++k Increment k by 1 and use incremented value
in expression containing ++k.
k++ Use the current value of k then increment by 1.
--k Decrement k by 1 and use decremented value
in expression containing --k.
k-- Use current value of k then decrement by 1.
++k;
Increment and Decrement Operators
www.cyberlabzone.com
++k; /*C statement k = k + 1; */
int x,z;
int y = 1;
int a = 2;
x = y + a++;
/* now x = 3 , y = 1 , a = 3 */
z = x + --a;
/* now a = 2, z = 5, x = 3, y = 1 */
z = --x * ++y;
/* now x = 2, y = 2, z = 4, a = 2 */
x = a++ / --y;
/* now y = 1, x = 2, a = 3, z = 4 */
Note: The increment/decrement operators can be
applied only to single variables. They cannot be
applied to expressions.
Increment and Decrement Operators-Examples
www.cyberlabzone.com
Given an integer value n, we can use the following code to
compute and store the first n Fibonacci numbers in an array:
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
www.cyberlabzone.com
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
double sum = 0.0;
/* read the file and compute the average */
counter = 0;
while (EOF != scanf("%lf", &datVal[counter])){
sum += datVal[counter]; /* += is an assignment operator */
counter++;
}
/* compute and print the average */
datAve = sum /counter;
printf(“The average is:%lf n", datAve);
/* compute and print the diff list */
for(k=0;k<counter;++k)
printf(“%lfn", datVal[k]-datAve);
Example-Average and difference List
www.cyberlabzone.com
- a shortcut method for writing assignment statements of the
form
var1 = var1 op expression;
Using an "assignment operator", we can rewrite the above as
var1 op= expression;
where op can be any one of the arithmetic
binary operators:
+ - * / %
sum += datVal[counter];
Assignment-operators
www.cyberlabzone.com
sum += datVal[counter]; or
sum = sum + datVal[counter];
k += 5; or k = k +5;
n -= 4; or n = n -4;
a *= 2.0; or a = a*2.0;
x /= b; or x = x/b;
remainder %= 6; or
remainder = remainder % 6;
newValue += (a-b)/(2*c); or
newValue = newValue + (a-b)/(2*c);
Assignment-operators-Examples
www.cyberlabzone.com
Unlike many other languages, there is no data type for
character strings in C. But we can reference a string as
a one dimensional array of characters. That is, each
element of the array is a single character.
Character Arrays
www.cyberlabzone.com
char aString[5] = "Zip!";
char atomic[ ] = "hydrogen";
char aString[] = {'Z', 'i', 'p', '!',
'0'};
Declaring a string array with character constants
Declaring character arrays with a string constant
IMPORTANT!!!
In C, you must always terminate a character array with the
NULL character, ‘0’ . Therefore, the array size of your
character array should be one plus the maximum length of
the string you want to store. Example: In the declaration
char atomic[ ] = "hydrogen";
“atomic” is an array of nine elements, the last being ‘0’
Declaring a Character Array
www.cyberlabzone.com
char atomic[ ] = "hydrogen";
You may declare and initialize a character arrays
with a string constant as in,
but you cannot assign an array in the same
manner, e.g.
atomic = "hydrogen"; not legal in C!
One of the mysteries of C!
Declaring a Character Array
www.cyberlabzone.com
Use the %s conversion specifier to read in a string of
characters. Any blanks will be skipped.
There should not be any blank character input such as in the
string “Hello World”, since a blank signals an end of input for
the string.
Again, don’t forget to declare the array size as one more than
the length of the longest string that you want to read in
order to accommodate the NULL character.
char strArray [10];
printf("Input a string with at most nine characters ”);
printf("with no blanks in the string: n");
scanf("%s", strArray);
/* Notice: No & is used for an array argument! */
printf(“n%s", strArray);
Input and output of Strings
www.cyberlabzone.com
You can use the %c conversion specifier to output
the string character by character.
k = 0;
while (strArray[k] != NULL)
printf("%c", strArray[k++]);
NULL is a built-in constant (‘0’). You must have
#include <stdio.h> in your file to be able to use NULL.
Outputing a String
www.cyberlabzone.com
• strlen(str) - string length, not counting NULL char.
• strcpy(str1, str2) - copy string2 to string1.
• strcmp(str1, str2) - returns a negative , zero or positive int
depending on whether str1 is lexicographically
less than, equal or greater than str2 respectively.
• strncmp(str1,str2,n) - like strcmp but just the first n characters
of str1 are compared to str2.
#include <string.h>
Arguments str1 and str2 in the following functions can be
character array names, string pointers(discussed in a future
lecture), or string constants.
See Chapter 13.3 for examples. There are many other string
functions (see Appendix G p. 1036 for a complete list).
String.h Library Functions
www.cyberlabzone.com
1. Problem Definition
Write a C program that converts a Morse code string into alphabet.
(Morse code is a sequence of dots and dashes). If the input is not a
valid string (see table on next slide) then a message is output to the
user. You will do a variation of this program in a future lab
assignment.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = a single string of characters.
Output= A single letter A-Z.
Example-Morse Code
www.cyberlabzone.com
A .- , N -.
B -... O ---
C -.-. P .--.
D -.. Q --.-
E . R .-.
F ..-. S ...
G --. T -
H .... U ..-
I .. V ...-
J .--- W .--
K -.- X -..-
L .-.. Y -.--
M -- Z --..
www.cyberlabzone.com
#include <stdio.h>
#include <string.h>
typedef char string[5];
void main(void){
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
www.cyberlabzone.com
char alphabet[26] = {'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char input[5];
int i;
int flag = 0; /* flag = 0 means match not found ,
flag = 1 means match found */
printf("Please enter a Morse code string:");
scanf("%s",input); /* no & for array */
www.cyberlabzone.com
/* loop through the Morse array to find a match */
for(i=0;i<26;++i)
if (strcmp(input,morse[i]) == 0)
{
printf("%cn",alphabet[i]);
flag = 1;
break; /*terminate for loop */
}
if (flag == 0)
printf("Input not a valid Morse character.n");
} /* end of main */
www.cyberlabzone.com
The typedef mechanism in C enables a programmer to create
a “custom” data-type.
Examples of the use of typedef are
typedef int blah; /* don’t do this !!!!! */
typedef char string[5];
In the first example we give another name or alias to the
data-type int .
In the second example we create a new data-type named
string.
typedef
www.cyberlabzone.com
To declare a variable of data-type blah ,
blah x;
this declaration is equivalent to
int x;
To declare a variable of data-type string ,
string var =“init”; /* declare and initialize */
scanf(“%s”,var); /* we can read in a string of chars */
var = “next”; But we can’t do this!!!
The declaration
string morse[26];
declares morse as an array of 26 elements. Each element
has data-type string.
typedef
www.cyberlabzone.com
The declaration and initialization:
string morse[26] =
{".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
declares morse as an array of 26 elements with
morse[0] = “.-”
morse[1] = “-...” and so on...
typedef
www.cyberlabzone.com
- Two dimensional arrays are declared
similarly to one dimensional arrays:
char t[20][10]; (and referred to as a
matrix, or as a "table")
The first subscript gives the row number, and
the second subscript specifies column number.
Two-Dimensional Arrays
www.cyberlabzone.com
We can also initialize a two-dimensional array
in a declaration statement; E.g.,
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
which specifies the elements in each row of the
array (the interior braces around each row of
values could be omitted). The matrix for this
example is







654
321
m
Declaration and Initialization
www.cyberlabzone.com
Specification of the number of rows could be
omitted. But other subscript specifications can
not be omitted. So, we could also write the
initialization as
int m[ ][3] = {{1, 2, 3}, {4, 5, 6}};
Declaration and Initialization
www.cyberlabzone.com
int a[2][3]= {1,2,3,4,5,6};
specifies 6 integer locations.
Storage for array elements are in contiguous locations in
memory in row major order (unlike column major order in
Fortran), referenced by subscripts(or index) values starting at
0 for both rows and columns.
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
RAM
1 2 3 4 5 6
Memory Storage for a Two dimensional Array
www.cyberlabzone.com
1. Problem Definition
Assume we have a file “in.dat” (located in the pwd) consisting of 10 rows of
10 integers per row (100 integers total). Write a C program which reads
from the file and stores the numbers in a two dimensional array named
‘mat’, computes the largest of all of these numbers and prints the largest
value to the screen.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = from file “in.dat”
Output= Largest of the 100 integers printed to screen.
3. Develop Algorithm
Use Unix redirection to read file “in.dat”.
Use nested for loop to go through two dimensional array to
find the largest value.
Example-Maximum Value
www.cyberlabzone.com
#include <stdio.h>
void main(void){
int row, col, maximum;
/* Declare a 2-D array called ‘mat’ which can hold a 10-by-10 */
/* matrix of integers */
int mat[10][10];
/* Write code here to read from the file ‘in.dat’ */
for(row=0;row<10;++row)
for(col=0;col<10;++col)
scanf(“%d”,&mat[row][col]);
/* Write code to find the largest value in the array ‘mat’ */
maximum = mat[0][0]; /* why ??? */
for(row=0;row<10;++row) /* How does this work??? */
for(col=0;col<10;++col)
if (mat[row][col] > maximum)
maximum = mat[row][col];
/* Print the largest value to the screen */
printf(“ max value in the array = %dn”,maximum);
}
www.cyberlabzone.com
Another example of the use of typedef is:
typedef double matrix[size][size];
In this example we create a new data-type named matrix.
We can declare a variable of data-type matrix by
matrix a;
this declaration is equivalent to
double a[size][size];
Typedef Revisited
www.cyberlabzone.com
Standard (ANSI) C allows up to 12 dimension.
But more computation is required by the system
to locate elements in multi-subscripted arrays.
Therefore, in problems involving intensive
numerical calculations, we should use arrays
with fewer dimension.
We can also use 3, 4, … dimensional arrays,
e.g.,
threeDArray [i][j][k];
Higher Dimensional Arrays
www.cyberlabzone.com
In slides 2-15 and 11-15 we discussed a method for creating
programs. In step three “Develop the Algorithm”, the nature of the
programming problem may suggest that we use top down
programming (as opposed to bottom-up programming , ...)
An analogy for top-down design is the following: Suppose a
general contractor was hired to construct a commercial building. The
contractor would need to know where to build and what are the blue-
prints. Then the contractor would hire various sub-contractors to dig
foundation, install electric, plumbing, frame, roof. That is, the large
job would be broken into smaller jobs, however these jobs must be
performed in some sequence and not at random.
Function-”Top Down Design”
www.cyberlabzone.com
In top-down design for programming, we specify the first function to
be invoked (the top function or “general contractor”). In C the top
function is called “main”.
The programmer then refines “main” into its component functions
(sub-contractors), which may in turn be refined into further functions,
and so on.
Function-”Top Down Design”
www.cyberlabzone.com
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
www.cyberlabzone.com
#include <stdio.h>
int read(double datVal[]); /* prototype for read function */
double ave(int counter,double datVal[]);
/* prototype for ave function */
void diff(double datAve, int counter, double datVal[]);
/* prototype for diff function */
void main(void){
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
counter = read(datVal); /* read file into datVal */
datAve = ave(counter,datVal); /* compute & print average */
printf(“The average is:%f n", datAve);
diff(datAve,counter,datVal); /* compute diff list */
for(k=0;k<counter;++k) /* print the diff list */
printf(“%lfn", datVal[k]);
} /* end of main */
www.cyberlabzone.com
/* read function */
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf", &array[count])){
++count;
}
return count;
} /* end of read function */
/* ave function */
double ave(int count,double array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
} /* end of ave function */
/* diff function */
void diff(double average, int count, double array[]){
int i;
for (i = 0;i<count;++i)
array[i] -= average;
} /* end of diff */
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
4. Run the program using Unix redirection <
a.out < input.dat
C Problem Example-Execution
www.cyberlabzone.com
Example:
If the file input.dat has the values:
1.0 2.0 3.0 4.0 5.0
Then the program would execute as follows:
dclsn70> a.out < input.dat
The average is:3.000000
-2.000000
-1.000000
0.000000
1.000000
2.000000
dclsn70>
C Problem Example-Execution
www.cyberlabzone.com
#include <stdio.h> /* include statements */
int read(double datVal[]); /* prototype for read function */
void main(void) /* definiton of the main function */
{
/* C code here */
} /* end of main */
int read(double array[]) /* function definition */
{
/* more C code here */
} /* end of read */
One method to code the function “read”in C :
Functions-Prototypes
Functions
www.cyberlabzone.com
In the latest versions of standard C ("ANSI C"),
the function prototype is used to define the data
type to be returned by the function, the number
and data type of function parameters, and the
order of the function parameters. This info is
used by the C compiler to validate calls to the
function.
A general principle in C is that you must declare
or define the variable or function before you use
them.
Functions-Prototypes
www.cyberlabzone.com
The actual variable or array name is not needed in the
function prototype.
Examples:
Instead of the following prototypes
int read(double datVal[]);
double ave(int counter,double datVal[]);
void diff(double datAve, int counter, double datVal[]);
we could have used
int read(double []);
double ave(int ,double []);
void diff(double , int , double []);
Functions-Prototypes
www.cyberlabzone.com
#include <stdio.h> /* include statements */
/* Since the definition of read occurs before it is */
/* used (called) by main, we don’t need a prototype.*/
int read(double array[]) /* function definition */
{
/* C code for read here */
} /* end of read */
void main(void) /* definiton of the main function */
{
/* C code for main function here */
} /* end of main */
Another method to code the function “read ” in C
without using a prototype :
Functions-Prototypes
www.cyberlabzone.com
• The function definition in C is of the form:
return-type function-name(parameter-list)
{
/* function code */
return (value); /* parenthesis optional */
}
• The “value” can be a single variable, constant, or any C expression.
• The data type of “value” should be of type “return-type”, if not
then a conversion of the “value” to the “return-type” is specified
by the C compiler.
• If the “return-type is void then the programmer can omit the return
statement or code: return ; /* return nothing */
Function- definition
www.cyberlabzone.com
/* function called */
int x = 1;
float y = 2.0;
float value;
double z = 5.0;
value = sum(x,y,z+4.0);
/* more code here */
/* sum adds an integer a float and a double and returns */
/* a double */
double sum(int a, float b, double c)
{
double result;
result = a + b + c;
return result;
}
Data-types agree!
Since value has type
float and sum returns
a double, a conversion
takes place.
Function Type Checking
www.cyberlabzone.com
• A function that does not return a value is declared to
be of type void. e.g.,
void printFunction (int, int);
• If a function takes no parameters, we specify the
parameter list as void. e.g.,
void printPageHeading (void);
It is also possible to specify an "empty" parameter list:
void myFunction ( );
- argument checking is "turned off", so that anything
can be passed to myFunction. Best to avoid this in C.
Function Type Checking
www.cyberlabzone.com
• By default , if you omit the data type of the return
value, C assumes that the function returns an int value
(not void). Therefore the following function header:
main(void)
int main(void)
is equivalent to:
Function Type Checking
www.cyberlabzone.com
• A function may be called from any function (including itself) in C.
• A call is of the form:
function-name(argument-list)
• To “call” or invoke a function, you must pass the same
number of arguments for which the function has been defined.
The order of the arguments is important!!!
• If the data types in the argument list do not match the data
types in the parameter list, a conversion(or coercion) takes
place.
Function Call
www.cyberlabzone.com
.
.
.
int x = 1;
double y = 2.0;
float result;
/* function called */
result = F1(x,x+1,sin(y)); /* argument list */
.
.
.
} /* end main */
/* data types match */
float F1(int var1, int var2, double var3){ /*parameter list
*/
/* function code */
return (value);}
Example-Function Type Checking
www.cyberlabzone.com
• Arrays are passed as call-by-reference.
counter = read(datVal);
.
.
.
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf",
&array[count])){
++count;
}
return count;
} 2.0
1.0
1200
Main Memory after call
unknowndatVal[0]
datVal[1]
datVal[2]
1200
Main Memory before call
datVal[0]
datVal[1]
datVal[2]
.
.
.
.
.
.
.
.
.
.
.
.
The parameter “array” can be
considered as a pseudonym or
alias for “datVal”. There is only
one array in memory.
Passing arguments in a function Call
www.cyberlabzone.com
For two dimensional arrays, we could omit
specification of the number of rows in
function prototype and header. But we must
include size declaration for the number of
columns.
(see example on next slide)
Two-Dimensional Arrays Function Parameters
www.cyberlabzone.com
#define ROWS 10
#define COLS 5
void doSumpin(int [][COLS]);
int main (void)
{
int a[ROWS][COLS] = {{0}};
doSumpin (a);
}
void doSumpin(int b[][COLS]){ /* array passed by reference */
...
}
/* function prototype */
/* function call */
Examples of passing 2-D arrays
www.cyberlabzone.com
We can replace any 2-D array with an equivalent 1-D
array. For instance the following 2-D array
int A[2][3]= {1,2,3,4,5,6};
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
can be replaced with the equivalent 1-D array,
int a[6]= {1,2,3,4,5,6};
however a[0][0] , a[0][1] , … is not defined.
Alternative to 2-D arrays
www.cyberlabzone.com
In order to reference A[0][0] , A[0][1] , … with a[ ]
we use the following formula,
int a[]= {1,2,3,4,5,6};
A[row][col] = a[row*3 + col]
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
a[0] a[1] a[2] a[3] a[4] a[5]
Alternative to 2-D arrays
www.cyberlabzone.com
1. Problem Definition
Write a function that performs matrix – vector multiplication.
Assume that the matrix is passed as a
1-D array using the formula on the previous slide.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = A matrix and vector of reals .
Output= The vector that results from the matrix - vector
multiplication.
Alternative to 2-D arrays
www.cyberlabzone.com
/* The function mvmult works with any size matrix a. */
/* This function assumes that the number of Cols of a is */
/* equal to the number of Rows of invec */
/* a is 1-D version of matrix A[Rows][Cols] */
void mvmult(double a[], int Rows, int Cols, double invec[],
double outvec[]){
int row, col;
/* A[row][col] = a[row*cols + col] */
for(row=0;row<Rows;++row){
outvec[row] = 0.0;
for(col=0;col<Cols;++col)
outvec[row] += a[row*Cols +col] * invec[col];
}
} /* end of mvmult */
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file mvmult.c ,
and make sure to save the file.
2. Use xemacs to create a file test.c and write the main function that
calls the mvmult function. Don’t forget the prototype!
3. Compile the code in the two files mvmult.c and test.c by typing,
gcc test.c mvmult.c -o mult
4. Run the program
mult
C Problem Example-Execution
www.cyberlabzone.com
#include <stdio.h>
#define ROWS 2
#define COLS 3
mvmult(double [], int , int double [] , double []); /* prototype */
void main(void){
double a[ROWS*COLS] = {1,2,3,4,5,6};
double invec[COLS] = {1,1,1};
double outvec[ROWS];
int row,col;
mvmult(a,ROWS,COLS,invec,outvec); /* call mvmult */
for(row=0;row<ROWS;++row) /* print the values of a */
for(col=0;col<COLS;++col)
printf("a[%i][%i] = %lfn",row,col,a[row*COLS+col]);
for(row=0;row<COLS;++row) /* print invec */
printf("invec[%i] = %lfn",row,invec[row]);
for(row=0;row<ROWS;++row) /* print outvec */
printf("outvec[%i] = %lfn",row,outvec[row]);
}
www.cyberlabzone.com
eesn23> mult
a[0][0] = 1.000000
a[0][1] = 2.000000
a[0][2] = 3.000000
a[1][0] = 4.000000
a[1][1] = 5.000000
a[1][2] = 6.000000
invec[0] = 1.000000
invec[1] = 1.000000
invec[2] = 1.000000
outvec[0] = 6.000000
outvec[1] = 15.000000
eesn23>
C Problem Example-Execution
www.cyberlabzone.com
• Non-arrays are passed as call-by-value.
datAve = ave(counter,datVal);
.
.
.
double ave(int count,double
array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
}
1196
Main Memory while executing ave
5
counter
1196
Main Memory before call
counter
.
.
.
The value of the parameter “counter” is copied into the
memory location for the variable “count”. Therefore any
change to “count” would have no affect on “counter”.
1192count 5
55
Passing arguments in a function Call
www.cyberlabzone.com
1. Problem Definition
Write a function “sinc” that computes the value of
sin(x)/x . If x is zero return 1.0.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = One real number of type double.
Output= sin(x)/x as a double if x is not zero else 1.0.
3. Develop Algorithm
Use an if statement to check for a non-zero value.
But since the user could input 1.0e-600 , this may cause an
overflow when the value 1/x is computed so we will actually not
check for equality with zero but will check if the input value is
close to zero.
Example-Call-by-value
www.cyberlabzone.com
#include <stdio.h>
#include <math.h>
double sinc (double); /* function prototype */
void main(void){
double x, y;
printf("Enter a number: ");
scanf("%lf", &x);
y = sinc(x); /* function call */
printf(“n sinc(%f) = %f n”, x, y);
}
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15)
return 1.0;
else
return sin(x) / x; } /* notice that sinc calls sin */
Example: function sinc(x)=sin(x)/x
www.cyberlabzone.com
Using Xemacs, user-defined functions can be typed into the same
file as “main”.
Functions may be typed into a separate file. For example, suppose
“main” is in the file test.c and the user defined function “sinc” is
entered into the file func.c then to compile both “main” and “sinc”
you would type (at the Unix prompt)
gcc test.c func.c -lm Note the use of the “-lm” option
The -lm option is needed only if you use a math library function in
“main” or “sinc”.
Don’t forget that if you put the function “sinc” into a separate file,
then you must still put the prototype for “sinc” in the same file as
main. The prototype for “sinc” must precede the function main.
Example: Location of user-defined functions
www.cyberlabzone.com
We present some methods to debug C programs.
We can categorize errors as
A) compile errors
B) run-time errors
C) Logical errors
Logical errors are the most difficult since they may involve using
the incorrect formula. This has nothing to do with C so we will not
discuss these types of errors any further.
Debugging
www.cyberlabzone.com
We present some methods to debug C programs.
A) compile errors
If your program doesn’t compile.
1) Check the line number that gcc returns for the error.
Note: a warning message is not an error. If you only have
warning messages gcc will go ahead and compile your code.
2) Sometimes the line number of the error is not where the
actual error occurred. An error on one line can produce
errors messages for subsequent lines. Therefore it is best in
general to fix the errors occurring on the earliest line numbers
first. Also, if you can’t find an error on the line specified by
gcc then look at the preceding lines.
Compiler Errors
www.cyberlabzone.com
A) compile errors(continued)
3) If you can’t find the error specified by gcc then try removing
some code by using the #ifdef feature of C. This is a
preprocessor command that will optionally compile (or not
compile) a group of statements. Or gcc allows you to use the
characters // at the beginning of a line to comment out that line
of code.
Compiler Errors
www.cyberlabzone.com
Example: On slide 25 add a semicolon to the which contains the
code:
if (fabs(x) < 1.0e-15);
When you compile you get an error message.
The error message states the problem is before line 15 but the
actual problem occurred on line 13.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
test.c: In function `sinc':
test.c:15: parse error before `else'
dclsn70>
Compiler Errors
www.cyberlabzone.com
Example: Use #ifdef to have the compiler skip
compiling line(s) of code.
From the previous problem add the #ifdef as follows:
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15);
#ifdef foo
return 1.0;
#endif
else
return sin(x) / x; } /* notice that sinc calls sin */
Compiler Errors
www.cyberlabzone.com
From the above we can see that the code now compiles without
errors.
The reason for this is that the if-else statement is now a valid
statement. If the condition is true do nothing else return sin(x)/x .
Even if you don’t see the extra semicolon, at this point you know
that your if-else statement was the source of your previous compile
error.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70>
Compiler Errors
www.cyberlabzone.com
B) run-time errors
If your program compiles without errors but you get incorrect
values or a message like “Segmentation fault”.
1) Use the statement:
fprintf(stderr, “format string”,variable-list);
Run-time Errors
www.cyberlabzone.com
On slide 25 remove the “&” symbol to obtain the following line:
scanf("%lf", x);
When you compile and run a.out you get the run-time error
“Segmentation Fault”,
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Enter a number: 3.14159
Segmentation fault
dclsn70>
Run-time Errors
www.cyberlabzone.com
Example: Use the fprintf statement to debug your code.
void main(void){
double x, y;
printf("Enter a number: ");
fprintf(stderr,“Before scanfn”);
scanf("%lf", &x);
fprintf(stderr,”After scanf x = %lfn”,x);
y = sinc(x); /* function call */
fprintf(stderr,“After sincn”);
printf(“n sinc(%f) = %f n”, x, y);
}
Run-time Errors
www.cyberlabzone.com
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Before scanf
Enter a number: 3.14159
Segmentation fault
dclsn70>
Since only “Before scanf” prints to the screen (specified by stderr).
This indicates that the problem occurs in the scanf statement.
Run-time Errors
www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two integer input arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
temp = a;
a = b;
b = temp;
Example-call-by-value
www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int, int); /* prototype for swap */
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int a , int b){
int temp = a;
a = b;
b = temp;
return;
}
Example-bad Swap!!!
www.cyberlabzone.com
x
1000
Main Memory before call
1
The swap function will successfully swap the values of the variables a and
b.
But, since non-arrays are passed by value the swap of the values for a and
b will not have any affect on the variables x and y.
It is important to note that even if we had used the variable names x and y
rather than a and b the swap function would still not work. See the next
slide...
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
a 2
b 1
3000
Why swap doesn’t work.
www.cyberlabzone.com
/* Modified function to swap values. */
#include <stdio.h>
void swap(int, int);
void main(void){
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){ /* we now use x and y */
int temp = x;
x = y;
y = temp;
return;
}
Example-bad Swap!!!
www.cyberlabzone.com
x
1000
Main Memory before call
1
The C compiler will keep track of the variables x and y declared in main and
the variables x and y declared in swap. The x in main is a different variable
than the x in swap. Similarly for the y variable.
The reason that the x variable in main is different than the x variable in
swap is that two declarations of x occur in different blocks. That is the
scope of the x in main is different than the scope of x in swap.
One solution to the problem is to use pointer variables. We will discuss
pointer variables in a future lecture.
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
x 2
y 1
3000
Why the modified swap doesn’t work.
www.cyberlabzone.com
An identifier is a name that is composed of a sequence of letters,
digits, and the ‘_’ underscore character.
Variable names are identifiers and so are function names and
symbolic constant names.
The scope of an identifier is the portion of the program in which
the identifier is visible or accessible.
Both variables and functions have two attributes: type and
storage class. The scope of a variable or function is related to its
storage class.
Scope of Identifiers
www.cyberlabzone.com
•Local Variables - are declared within a block and cannot be referenced
by outside the block; i.e., each function is assigned its own "local"
storage areas.
•Global Variables - declared outside any block and are known to all
blocks in the same file . By default, global variables are "static”
storage class.
In the examples on the following slides, drawing a picture of memory is
helpful in understanding how scoping works.
Scope of Variable Names
www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
printf(“%d”,globalVar); /* prints “2” */
printf(“%d”,x); /* compile error! x not known in main */
}
int myFunction(int x){ /* Local variable x */
++x;
printf(“%d”,x); /* prints value “2” */
printf(“%d”,globalVar); /*prints value“1” */
++globalVar;
return x;
}
Example1:Scope of Variables
Program Design Example
www.cyberlabzone.com
globalVar
1000
Main Memory before call to Myfunction
1
result
???
Main Memory while executing MyFunction, but before ++globalVar;
1000
1
x 2
3000
???
globalVar
result
Example1:Scope of Variables
www.cyberlabzone.com
globalVar
1000
Main Memory after call to Myfunction
2
result
2
Main Memory while executing MyFunction, but before return(x);
1000
2
???
x 2
3000
globalVar
result
Example1:Scope of Variables
www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
}
int myFunction(int x){/* Local variables: x, globalVar */
int globalVar; /* new “local” variable */
printf(“%dn”,globalVar);/* prints ??? */
return x + 1;
}
Example2:Scope of Variables
www.cyberlabzone.com
int myFunction(int); /* function prototypes */
void main(void){ /* local variables: x,result in main */
int result, x = 2;
result = myFunction(x); /* call myFunction */
printf(“%d”,result); /* prints “3” */
printf(“%d”,x); /* prints “2” WHY??? */
}
int myFunction(int x){/* Local variable: x */
x = x + 1;
printf(“%dn”,x);/* prints “3” */
return x;
}
Example3:Scope of Variables
www.cyberlabzone.com
/* C Function to swap values.This doesn’t work!!!! */
#include <stdio.h>
int x; /* x is a global variable */
int y; /* y is a global variable */
void swap(int, int); /* prototype for swap */
void main(void){
x = 1; /* note that x and y are not declared here!!! */
y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){
int temp = x;
x = y;
y = temp;
return;
}
Example4:Scope of Variables
www.cyberlabzone.com
A function can be called by any other function, provided that
either the function definition or its prototype is in the same
file as the calling function and precedes the function call.
If no prototype is specified for a function, its header serves as
the function prototype.
Note: Functions cannot be defined within each other
Scope of Function Names
www.cyberlabzone.com
- Determines the storage duration and scope of identifiers,
and also linkage between files.
auto - creates storage for variables when the block that
declares them is entered, and deletes the storage when the
block is exited. Local variables have "auto" storage by
default.
e.g.,typing auto float a, b, c; is equivalent to typing float a, b, c;
Storage Classes-auto
www.cyberlabzone.com
static - creates and initializes storage for variables when the program
begins execution. Storage continues to exist until execution terminates. If
an initial value is not explicitly stated, a static variable is initialized to 0. We
can retain values of local variables by declaring them to be static.
In the following example, the static variable sum is initialized to 1.
static int sum = 1;
The initialization takes place only once. If the above declaration appears in
a user defined function , the first time the function is called, the variable
sum is initialized to 1. The next time the function (containing the above
declaration) is executed sum is not reset to 1.
Storage Classes-static
www.cyberlabzone.com
extern - used to reference identifiers in another file. Function names
are extern by default.
e.g., extern int foreignVar;
Storage Classes-extern
www.cyberlabzone.com
1. Problem Definition
Write a function “sum”that keeps a running total of the sum of
every value passed to “sum”. To test this function, modify the
previous program of slide 15 -3 that compute the average of
values in a file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
Example-static variable
www.cyberlabzone.com
Flowchart for main
while EOF != scanf value
total = sum(value);
++count;
TrueFalse
count = 0;
printf total/(double) count
Example-static variable
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
int sum(int); /* function protoype */
void main(void)
{
int value,total,count = 0;
while (EOF != scanf("%i", &value)) { /* read value */
total = sum(value);
++count;
} /* end of while loop */
printf(”Average of the %i numbers = %f n“,count,total/(double)count);
}
int sum(int val){ /* function header */
static int total_val = 0; /* static variable, */
total_val += val;
return total_val;
}
Example-static variable
www.cyberlabzone.com
Pointer variables are variables that store memory addresses.
Pointers variables are useful in passing storage addresses in
function calls (call-by-reference) and for applications involving
dynamic data structures (e.g., linked lists)
Example: int *intPtr;
float *floatPtr;
declares intPtr to be a pointer variable to an object of type
integer. and floatPtr to be a pointer variable to an object of
type float.
Pointers
www.cyberlabzone.com
We can write the pointer variable declaration
as int* intPtr;
or as int * intPtr;
Note that when we declare more than two pointer
variables in one line each pointer name requires an
asterisk:
int *ptr1, *ptr2;
otherwise we are just declaring a regular variable ,
not a pointer variable.
Pointer Declaration-syntax
www.cyberlabzone.com
There are two C operators that are necessary when using
pointer variables.
& - the address operator returns the address of a variable
x
1000
3
ptrX 1000
ptrX holds the address of x.
We say ptrX “points” to x.
We will apply the & operator only to variables, e.g. &77 or &(x+1)
are not valid.
The declaration of ptrX initializes the variable ptrX = &x;
Example:
int x = 3;
int * ptrX = &x;
1004
& Operator
www.cyberlabzone.com
Example:
int x;
int * pt;
pt = &x; /* another way to assign an address to a pointer variable */
Suppose the address of the variable x is 9640
Then, the effect of pt = &x; will be:
x pt
Address
9640 9640
& Operator
www.cyberlabzone.com
int x;
int * pt;
pt = &x;
To assign the value “3” to the variable x in C:
x = 3;
We can use the “ * ” operator to indirectly reference x.
We can assign “3” to x by:
*pt = 3;
Here we use the fact that “pt” points to integer values.
x pt
Address
9640 96403
* - means "a pointer to" and is called an indirection operator or
dereferencing operator, since a pointer "indirectly" references a
value in a storage location. Example:
*Operator
www.cyberlabzone.com
double *ptr;
ptr = NULL;
Assigning a NULL value (zero) to a pointer
A null pointer points to nothing. We often depict it as
ptr
/*called a null pointer*/
Null Pointer
www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two input integer arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
Pass the addresses of the variables and not their values. In the
swap function the parameters that hold the addresses are
pointers. Use the indirection operator to swap the values.
Example-call-by-Reference
www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int * , int *);
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(&x,&y); /* pass the addresses of x and y */
printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */
}
void swap(int *ptrX , int *ptrY){ /* pointer variables */
int temp = *ptrX;
*ptrX = *ptrY ;
*ptrY = temp;
return;
}
Example-good Swap
www.cyberlabzone.com
x
1000
Main Memory before call to swap
1
y
2
Main Memory while executing swap, after temp = *ptrX;
but before *ptrX = *ptrY ;
10001
ptrX 1000 3000
2
x
y 1004
1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrX = *ptrY ;
but before *ptrY = temp;
10002
ptrX 1000 3000
2 1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrY = temp;
but before return;
10002
ptrX 1000 3000
1 1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
The array name in C is assigned the address of the
first element of the array.
The following code will assign the address of
xArray[0] to xArrayPtr :
float xArray[50];
float * xArrayPtr;
xArrayPtr = xArray;
The assignment statement above is equivalent to:
xArrayPtr = &xArray[0];
Array Names are Constant Pointers
www.cyberlabzone.com
A string literal (e.g. “A – your course graden”) is actually
represented in C by a pointer to an address in memory that holds the
first byte of the array of characters.
Therefore the following declaration of the pointer variable “string” is
valid:
char * string = “A – your course graden”;
and to print the value of “string” , use the “%s” conversion specifier,
printf(“%s”,string);
Although a pointer can be used as an array name, we cannot modify
the values of “string” by using the square brackets of array notation.
string[0] = ‘B’; /* error !!! */
The error is due to the fact that the literal “A – your course graden”
is stored in a location in memory that cannot be accessed by
pointers.
String Literal is pointer to an array
www.cyberlabzone.com
One use of char * pointers is ragged arrays.
In slide 15-24 we used the following code fragment in the “Morse
Code” example to declare and initialize the array “morse” as :
typedef char string[5];
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
An alternative would be the use of a ragged “morse” array declared
as:
typedef char * string;
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
String Literal is Pointer to an Array
www.cyberlabzone.com
The later declaration of the array “morse” is called ragged since
each element of the array , morse[0], morse[1], … takes up
exactly the number of bytes necessary in memory to hold the
initialized strings whereas in the previous declaration of “morse”
each element of the array takes exactly five character values in
memory no matter what length of the initializing string.
As discussed on slide 15, we cannot change the values of the
ragged “morse” array. But in the “Morse Code” problem we know
that the morse strings should never be changed.
Ragged Arrays
www.cyberlabzone.com
To sort means to put in place or rank according to kind, class or nature.
For example, consider a herd of cows. We can sort the cows by weight,
age, amount of milk produced, etc. . The sort can be in ascending or
descending order.
Note that we could not include a lizard in among the sort if we were
sorting with respect to amount of milk produced. That is, the items we
want to sort must have the same nature.
In C we will use arrays to do our sorting. Since the data-type(kind, class
or nature) for each element of the array must be the same we are able to
compare any two elements in the array (no lizards in the array of milk
producing cows).
Why sort?
Sorting
www.cyberlabzone.com
One method of sorting is called “selection sort”.
The algorithm: find the smallest element in the list and swap the first item in
the list with the smallest value.
For example, suppose you are given the values(below):
5 3 7 2 4 ( 2 is the smallest value )
step 1
2 3 7 5 4 ( swap 2 with 5, now 3 is the smallest element)
step 2
2 3 7 5 4 ( 3 is in place don’t swap, now 4 is the smallest element)
step 3
2 3 4 5 7 ( swap 4 with 7, now 5 is the smallest element)
step 4
2 3 4 5 7 ( 5 is in place don’t swap, 7 is in place )
www.cyberlabzone.com
Another method of sorting is called “insertion sort”.
You use insertion sort when you sort a hand of cards.
For example, suppose you are given the five cards (below):
5 3 7 2 4 (cards in Right hand)
empty (cards in Left hand)
step 1
3 7 2 4 (Right hand)
5 (Left hand)
step 2
7 2 4 ( R )
3 5 ( L )
step 3
2 4 ( R )
3 5 7 ( L )
step 4
4 ( R) )
2 3 5 7 ( L )
step 5
empty ( R )
2 3 4 5 7 ( L ) ( the cards are now sorted )
www.cyberlabzone.com
1. Problem Definition
Write a program that sorts the values in an array in ascending
order. Use the built-in function ‘qsort’ to do the work of sorting.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Array of integers.
Output= Sorted array of integers (ascending order) is printed.
Qsort-Sorting an array
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(int *ptr1, int *ptr2) {
if ( *ptr1 > *ptr2)
return 1;
else if ( *ptr1 < *ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
www.cyberlabzone.com
Execution:
dclsn67>./a.out
Enter an array of no more than 100 integers.
3 4 2 1 5 (hit Enter and then Control-d to signal EOF)
1 2 3 4 5 (this is the output the program produces)
dclsn67>
Qsort-Sorting an array
www.cyberlabzone.com
arrayname - is the name of an existing array. This array
can have any data-type. It can even be an array of
pointers. We will refer to the array’s type as datatype .
elts is the number of elements of array.
qsort(arrayname,elts,size_of_elts,compare_function)
The qsort function is a built-in C function that sorts values
in an array. The algorithm behind qsort is called “Quick
Sort” . In CS101 we are interested only in how to call this
function.
The general format of the qsort function is:
Sorting Example-qsort
www.cyberlabzone.com
size_of_elts is the size in bytes of each element in the
array. Use the built-in operator sizeof that returns an
integer value representing the number of bytes a variable
or data-type takes up in RAM.
Example:
sizeof(integer) returns the value 4 on the Lab machines.
sizeof(numbers[0]) returns the number of bytes the variable
numbers[0] takes up in RAM, which is 4 since numbers is
an integer array.
compare_function is the name of the user defined function
that actually does the comparison.
qsort(arrayname,elts,size_of_elts,compare_function)
Sorting Example-qsort
www.cyberlabzone.com
The general format of the header for the user defined compare
function is:
int compare_function( datatype * ptr1,datatype * ptr2)
qsort will call the compare_function and pass two pointers ptr1
and ptr2 . Both ptr1 and ptr2 “point” to values in the array
arrayname (see previous slide).
The user must code the function compare_function so that it
returns an integer value back to qsort (the function that called
compare_function) . qsort will use this integer to determine
whether or not to swap the values in the array.
To sort in ascending order the return value is:
0 if the elements *ptr1 and *ptr2 of the array are equal
positive if *ptr1 > *ptr2 (i.e. swap the array values)
negative if *ptr1 < *ptr2 (i.e. don’t swap the array values)
Sorting Example- compare_function
www.cyberlabzone.com
Writing the code for compare_function depends on the data-type
datatype and whether the data is sorted in ascending order,
descending order, ... or by some other rule.
Therefore it’s not possible to write one version of
compare_function that does all.
Sorting Example- compare_function
www.cyberlabzone.com
The datatype in the sorting example is int . Therefore the
header for the compare_function has the form:
int compare( int * ptr1,int * ptr2)
where ptr1 and ptr2 are pointers to values in the array
numbers . As an example of how qsort works with compare see
the pictures of memory in the following slides.
Sorting Example
www.cyberlabzone.com
ptr1 ptr2 numbers[0] numbers[1] numbers[4]
3 4
Address 2000 2004 …
20042000 2 1 5
. . .
Suppose qsort called the compare function and *ptr1 is “3” and
*ptr2 is “4”. The picture above shows this situation. In this
example, we want to tell qsort to sort 3 before 4(don’t swap the
values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 < *ptr2
( 3 < 4) we return a -1 value to qsort. That’s why we have the
code(slide 20):
else if ( *ptr1 < *ptr2)
{
return -1;
Sorting Example
www.cyberlabzone.com
ptr1 ptr2 numbers[1] numbers[2] numbers[4]
3 4
Address 2000 2004 2008…
20082004 2 1 5
. . .
Now suppose qsort called the compare function and *ptr1 is “4” and
*ptr2 is “2”. The picture above shows this situation. In this
example, we want to tell qsort to sort 2 before 4( swap the values).
To do this, we use *ptr1 and *ptr2 . Since *ptr1 > *ptr2 ( 4 > 2)
we return +1 value to qsort. That’s why we have the code(slide
20):
if ( *ptr1 > *ptr2)
{
return 1;
}
Sorting Example
www.cyberlabzone.com
The previous code works correctly but will generate a warning
message. We can avoid the error messages if we obey the
rules that qsort expects the compare_function to observe.
The code on the next slide will sort the numbers as before but
gcc will not display any warning messages.
In the compare function (on the next slide), note the use of the
void pointer data-type and the use of the cast operators on the
pointer variables.
const int x = 1;
x = 2; /* illegal */
Compiler Warning Messages
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(const void *ptr1, const void *ptr2) {
if ( *(int *)ptr1 > *(int *)ptr2)
return 1;
else if ( *(int *)ptr1 < *(int *)ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
www.cyberlabzone.com
#include <stdio.h>
void main(void){
int z = 3;
float w = 4.0;
void * ptr;
ptr = &z;
/* add one to z */
*(int *)ptr = *(int *)ptr + 1; /* cast ptr */
ptr = &w;
/* add 1.0 to w */
*(float *)ptr = *(float *)ptr + 1.0; /* cast ptr */
printf("z = %i n",z); /* prints 4 */
printf("w = %f n",w); /* prints 5.000 */
}
www.cyberlabzone.com
1. Problem Definition
Write a program that creates a new data type named “vector”. A “vector”
represents a 2 dimensional vector v =<x,y> in the plane. The values of v are of
type double. Along with this new data-type, create functions add, sub, and dot
which will add , subtract and take the vector dot product of two vectors.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
We first define a new data type “vector”. Then in main we will declare v1,v2,v3 of
data type “vector”. We will assign values to these vectors and then perform
addition, subtraction and the dot product.
Input = None
Output= The values of v1,v2 will be printed along with the results from add, sub
and dot.
Example-Defining a 2D “vector data type”
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* user defined data-type called vector */
double x; /* this is a definition*/
/* no variables are declared */
double y; /* location is outside any block */
} vector;
vector add(vector vec1, vector vec2) ; /* prototype */
vector sub(vector vec1, vector vec2) ; /* prototype */
double dot(vector vec1, vector vec2) ; /* prototype */
/* see explanation of the above in subsequent slides */
void main(void){
vector v1,v2,v3 ={1.0,2.0}; /* three variables of type vector*/
/* v3 initialized to {1.0,2.0} */
v1.x = 2.5; /* use the . to access individual fields */
v1.y = -1.5;
v2 = v3; /* can assign all the values with one statement */
/* continued on next slide */
www.cyberlabzone.com
printf(“v1 = [%f,%f]n”,v1.x,v1.y);
printf(“v2 = [%f,%f]n”,v2.x,v2.y);
v3 = add(v1,v2);
printf(“add(v1,v2) = [%f,%f]n”,v3.x,v3.y);
v3 = sub(v1,v2);
printf(“sub(v1,v2) = [%f,%f]n”,v3.x,v3.y);
printf(“dot(v1,v2) = %fn”,dot(v1,v2));
} /* end of main */
vector add(vector vec1, vector vec2){
vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y};
return v4;
} /* end of add */
vector sub(vector vec1, vector vec2){
vector v4 = {vec1.x - vec2.x, vec1.y - vec2.y};
return v4;
} /* end of sub */
double dot(vector vec1, vector vec2){
return (vec1.x * vec2.x) + (vec1.y * vec2.y);
} /* end of dot */
www.cyberlabzone.com
> a.out
v1 = [2.500000,-1.500000]
v2 = [1.000000,2.000000]
add(v1,v2) = [3.500000,0.500000]
sub(v1,v2) = [1.500000,-3.500000]
dot(v1,v2) = -0.500000
Example-Execution
www.cyberlabzone.com
To set up a structure in C, we need to
(1) Define a structure type. There are
several ways to do this in C. In general,
we will use the typedef mechanism to
do this.
(2) Declare variables to be of that type.
Note: The built-in data types (e.g. int, float, char,…)
can be used to declare variables in the C language.
These data types don’t have to be defined by the
user.
Structures provide the user with the means to define
custom designed data types.
Structures & Union -How it Works
Structures & Union
www.cyberlabzone.com
Structures & Union -How it Works
Union is same as the structure. As the structure contains
members of different data types. In the structure each member
has its own memory location. Whereas members of Unions has
same memory location. we can assign values to only one
member at a time, so assigning value to another member that
time has no meaning. When a union is declared, Compiler
automatically allocates a memory locations to hold the largest
largest data type of members in the Union. Thus the Union is
used for saving memory. The concept of union is useful when it
is not necessary to assign the values to all the members of the
union at a time. Union can be declared as
Union union_name {
member1
member2
………….
…………
} variable_name
www.cyberlabzone.com
You can use the typedef mechanism in C to
create an alias for a structure.
The code above names “vector” as a synonym for,
typedef struct {
double x;
double y;
} vector;
struct {
double x;
double y;
};
Structures & Union -How it Works
www.cyberlabzone.com
Structure definitions do not reserve storage,
they are used to define a new data type.
For example, the code above doesn’t allocate any
storage. It doesn’t reserve memory for the variables
x or y --- the fields or members of the structure.
Also, no variable of type vector is declared yet.
typedef struct {
double x;
double y;
} vector;
Structures & Union -How it Works
www.cyberlabzone.com
Once you have defined a new data type, or a synonym
for this type, you can declare variables of this data
type as in,
The variables v1, v2, and v3 are declared to be of
data type “vector” where “vector” is a synonym for
the structure, struct {
double x;
double y;
};
vector v1,v2,v3 ={1.0,2.0};
Structure variables, like v3 above, are initialized in the
same way you initialize an array.
Structures & Union -How it Works
www.cyberlabzone.com
struct Vector_2D v1,v2,v3 ={1.0,2.0};
A second, alternative method in using structures in C
is to code the following immediately after the
preprocessor directives as in slide 4,
struct Vector_2D{
double x;
double y;
};
The name Vector_2D is called a “tag name”.
And in your functions, declare variables by
Structures & Union -How it Works
www.cyberlabzone.com
A third, alternative method in using structures in C is
to combine the struct and declaration of the variable
in one statement.
struct Vector_2D{
double x;
double y;
} v1,v2,v3 ={1.0,2.0};
Structures & Union -How it Works
www.cyberlabzone.com
We have seen primitive built-in single variable data
types such as int, float, char.
These data types can also be applied uniformly to an
array. All elements of the array have the identical
data type.
Structures provide the mechanism in C for grouping
values of different data types.
Example:
typedef struct {
int employeeID;
float salary;
int departmentID;
char name[30]; /* same as char * name;??? */
} Employee;
Structure can have members of different data-type
www.cyberlabzone.com
Accessing(storing and fetching) values from/to
fields in the structure is accomplished with the
"dot operator" (.), also called the "structure
member operator ".
Example: (From slide 4)
v1.x = 2.5; /* use the . to access individual fields */
v1.y = -1.5;
Example: (From the previous slide)
Employee emp1; /* declare a variable of type Employee */
emp1.employeeID = 1004; /* initialize the variable */
emp1.salary = 45123.50;
Structure-Accessing Fields
www.cyberlabzone.com
scanf(“%f”,&emp1.salary); /* you can also use scanf */
emp1.departmentID = 37;
strcpy(emp1.name,“John”);/* strcpy function */
scanf(“%s”,emp1.name); /* this is ok, no & needed */
emp1.name[0] = ‘J’; /* this also works */
emp1.name[1] = ‘o’;
emp1.name[2] = ‘h’;
emp1.name[3] = ‘n’;
emp1.name[4] = ‘0’;
Structure-Accessing Fields
www.cyberlabzone.com
v3 = add(v1,v2);
vector add(vector vec1, vector vec2){
Function calls with an argument having a structure
data-type are implement as call-by-value. In this
regard structures differ from arrays in that arrays are
passed as call-by-reference.
For example, in slide 5, function add is called
with arguments v1 and v2 of data-type vector.
The header for the function add has two parameters,
vec1 and vec2.
The variables vec1 and vec2 are “local” in scope to
the function add. In call-by-value the values of v1 and
v2 are copied into vec1 and vec2 respectively.
Structure-passed as cal-by-value
www.cyberlabzone.com
v3 = add(v1,v2);
Functions can return values of structure data-type.
For example, in slide 5, function add is called
The header for the function add indicates it returns a
value of data-type vector (a structure).
vector add(vector vec1, vector vec2){
vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y};
return v4;
}
Functions can return values of structure data-type
www.cyberlabzone.com
1. Problem Definition
Write a program that reads in data for the elements in the periodic system, (e.g.
Hydrogen, Helium,...) the name as a string , symbol as a string, atomic number as
an int and atomic weight as a double. After the elements have been entered they
are sorted using qsort in ascending alphabetical order and then printed back to
the terminal.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
We have four values per atomic element:
name,symbol,atomicNum and atomicWt
Rather than using five separate arrays of 102 elements we will
use one array AtomicElement of 102 elements. The data-type of
AtomicElement is a user-defined structure named Element.
Input = Input data from keyboard as above.
Output= Sort the elements by atomic name, using qsort.
Structure-Accessing Fields
Example-Sort an array of structures
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* user defined data-type called Element */
char name[15]; /* this is a definition, no variables are declared */
char symbol[3];/* location of this definition is outside any block */
int atomicNum;
double atomicWt;
} Element;
int cmpnames(Element * ptr1, Element * ptr2) ; /* prototype */
/* see explanation of the above in subsequent slides */
void main(void){
int num, i;
Element AtomicElement[102]; /* AtomicElement is an array */
printf(“How many elements are you going to enter?”);
scanf(“%d”,&num);
for(i=0;i<num;++i){
scanf(“%s”,AtomicElement[i].name);
scanf(“%s”,AtomicElement[i].symbol);
scanf(“%d”,&AtomicElement[i].atomicNum);
scanf(“%lf”,&AtomicElement[i].atomicWt);
}
www.cyberlabzone.com
/* sort the arrays by name */
qsort(AtomicElement, num, sizeof(AtomicElement[0]), cmpnames);
/* print the sorted array */
printf(“n”);
for (i=0;i<num;++i){
printf(“%s ”,AtomicElement[i].name);
printf(“%s ”,AtomicElement[i].symbol);
printf(“%d ”,AtomicElement[i].atomicNum);
printf(“%.5lf ”,AtomicElement[i].atomicWt);
printf(“n”); /* print one element per line */
} /* end of for */
} /* end of main */
int cmpnames(Element * ptr1, Element * ptr2) {
return strcmp(ptr1->name, ptr2->name); /* why arrow and not dot??? */
} /* end of cmpnames */
www.cyberlabzone.com
> a.out
How many elements are you going to enter?4
Hydrogen H 1 1.00794
Beryllium Be 4 9.01218
Gold Au 79 196.96655
Carbon C 6 12.0107
Beryllium Be 4 9.01218
Carbon C 6 12.01070
Gold Au 79 196.96655
Hydrogen H 1 1.00794
input
output
Example-Execution
www.cyberlabzone.com
strcmp(ptr1->name, ptr2->name)
If the string ptr1->name < ptr2->name (alphabetically)
then strcmp(ptr1->name, ptr2->name) has a negative value
else if ptr1->name > ptr2->name
then strcmp(ptr1->name, ptr2->name) has a positive value
else if ptr1->name == ptr2->name
then strcmp(ptr1->name, ptr2->name) has the value 0.
These are the correct values we want to return to qsort and
we do this by
From Lecture 15 slide 21:
strcmp(str1, str2) - returns a negative , zero or positive int
depending on whether str1 is alphabetically
less than, equal or greater than str2 respectively.
qsort calls our function cmpnames and passes two addresses
which are assigned to the pointer variables, ptr1 and ptr2.
return strcmp(ptr1->name, ptr2->name);
Strcmp
www.cyberlabzone.com
Address 2030
prt1 ptr2 AtomicElement[0]
“Beryllium”
Address 2000
20302000
“Be” 4 9.01218
“Hydrogen” “H” 1 1.00794
AtomicElement[1]
When qsort calls ‘cmpnames’
Sorting Example
www.cyberlabzone.com
Address 2030
prt1 ptr2 AtomicElement[0]
“Hydrogen”
Address 2000
20302000
“H” 1
9.01218“Beryllium” “Be” 4
1.00794
AtomicElement[1]
After qsort calls ‘cmpnames’
Since ‘cmpnames’ function returns a positive value to the
function ‘qsort’. The function ‘qsort’ does the work of
swapping the 30 bytes of AtomicElement[0] with
the 30 bytes of AtomicElement[1].
Sorting Example
www.cyberlabzone.com
We can declare an array of the struct data
type Autopart.
AutoPart structArray[50];
declares structArray as an array which contains
50 cells (in memory) of type AutoPart.
typedef struct {
int id;
char name[30];
} AutoPart;
Given the data-type definition:
Arrays of Structure data-type
www.cyberlabzone.com
We can access the field in the structure with pointers
and arrow operator “ -> ” (also called the indirect
component selection operator ). The general format of
the use of the arrow operator is:
(see example on next slide)
pointer_to_structure -> member_name
Pointer to variables of structure data-type
www.cyberlabzone.com
typedef struct {
int employeeID;
float salary;
int departmentID;
char name[30];
} Employee;
Employee emp1;
Employee *empPtr; /* pointer to data-type Employee */
emp1.employeeID = 1004;
emp1.salary = 45123.50;
emp1.departmentID = 37;
empPtr = &emp1; /* empPtr now points to emp1 */
printf(“emplayeeID is %d in department %d n”,
empPtr->employeeID, empPtr->departmentID);
Pointer to variables of structure data-type
www.cyberlabzone.com
Rather than use the arrow operator we could use “ * ” the
dereferencing operator.
From the last example:
printf(“emplayeeID is %d in department %d n”,
(*empPtr).employeeID, (*empPtr).departmentID);
However, do not write:
printf(“emplayeeID is %d in department %d n”,
*empPtr.employeeID, *empPtr.departmentID);
because in C this means (see operator precedence rules)
printf(“emplayeeID is %d in department %d n”,
*(empPtr.employeeID), *(empPtr.departmentID));
and these expressions are not equivalent. Why?
Therefore, it may be “safer” to use the arrow operator, so
that we don’t make the mistake shown above.
Why use the arrow “”?
www.cyberlabzone.com
So far, we have seen that one way to manipulate
files in a program is to redirect the standard input
and output.
E.g. in UNIX command line
a.out < input.dat > output.dat
We redirect standard input as the file, input.dat (not a
keyboard) And standard output as the file, output.dat(not
screen) This method works for one input file and one
output file.
In this lecture we will consider an alternative,
using FILE pointers.
File Input/Output (I/O)
File Operation in C
www.cyberlabzone.com
1. Problem Definition
Write a program that computes the average of a list of integers.
The program should prompt the user for the name of both the
input and output files and then read the values from the input file
and print the average value in the output file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = String naming the file of integers to be read and a string
naming the output file. Also, the integers in the file.
Output = The average value is written to the output file.
Example-Compute the Average value of a File of Integers
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void) {
int value,total = 0,count = 0;
/* fileptrIn and fileptrOut are variables of type “FILE *” */
FILE * fileptrIn, * fileptrOut;
char filenameIn[100],filenameOut[100];
printf(“Please enter an input filename (use path if needed):”);
scanf(“%s”,filenameIn);
printf(“Please enter an output filename (use path if
needed):”);
scanf(“%s”,filenameOut);
/* open files to read “r” and write “w” */
fileptrIn = fopen(filenameIn,”r”);
fileptrOut = fopen(filenameOut,”w”);
/* check to see if program found file */
if ((fileptrIn == NULL) || (fileptrOut == NULL))
{ printf(“file not opened, program terminated.n”);
return;
}
Example-Computing the Average value
www.cyberlabzone.com
/* fscanf */
while( EOF != fscanf(fileptrIn,"%i", &value)){
total += value;
++count;
} /* end of while loop */
/* Write the average value to the file. fprintf */
fprintf(fileptrOut,”Ave of %i numbers = %f n“
,count,total/(double)count);
fclose(fileptrIn);
fclose(fileptrOut);
}
www.cyberlabzone.com
/* fscanf */
while( EOF != fscanf(fileptrIn,"%i", &value)){
total += value;
++count;
} /* end of while loop */
/* Write the average value to the file. fprintf */
fprintf(fileptrOut,”Ave of %i numbers = %f n“
,count,total/(double)count);
fclose(fileptrIn);
fclose(fileptrOut);
}
Example-Compute the Average value of a File of Integers
www.cyberlabzone.com
After the above program is compiled execution from the
Unix prompt:
> more input.dat
1
2
3
4
5
> ./a.out
Please enter an input filename (use path if needed):input.dat
Please enter an output filename (use path if needed):output.dat
> more output.dat
Ave of 5 numbers = 3.000000
>
Execution-How it Works
www.cyberlabzone.com
FILE (all caps) is a structure defined in <stdio.h>.
In CS101 we will only use this data type in the
declaration of pointer variables.
Examples:
FILE *ptrFileIn;
FILE *ptrFileOut;
declares ptrFileIn and ptrFileOut as pointer
variables. They both “point” to values of data-type
FILE. We must have #include <stdio.h> in our
source file to use FILE pointers.
File-data-type
www.cyberlabzone.com
fprintf function is in <stdio.h>. It is the
same as the printf function except that the
first argument for fprintf is a file pointer:
fprintf(ptrFileOut, ctrlString, expression(s));
where ctrlString contains the format
specifiers, and expression(s) can contain
one or more variable names and constants.
Examples:
fprintf(ptrFileOut, "%d ", intVlaue);
fprintf(ptrFileOut, "%f ", a + 5.0 * b);
fprintf
www.cyberlabzone.com
fscanf function is also in <stdio.h>. It is the
same as the scanf function except that the
first argument for fscanf is a file pointer; i.e.,
fscanf(ptrFileIn, ctrlString,address(es));
Examples -
fscanf(ptrFileIn, "%lf", &dataValue);
fscanf(ptrFileIn, "%c%s%d", &ch, str, &num);
- returns an int value equal to number of items
successfully read from file (e.g., 0, 1, 2, 3 in last
example), or returns the value of EOF if end of file is
encountered before any values are read in. Thus,
fscanf can be used as an input check just like scanf.
fscanf
www.cyberlabzone.com
To use fscanf and fprintf you must first open a file, we
use the library function fopen (defined in <stdio.h>.)
For example, to open the file input.dat for reading, we
write
FILE *fileIn;
fileIn = fopen(“infile.dat”, “r”);
The first argument “infile.dat” is a string that names the
file to be read. The second argument the mode, “ r ”,
stands for “reading” mode only. If the file cannot be
opened, fopen returns NULL. (e.g. file doesn’t exit)
fopen returns a pointer to the file(in this case infile.dat).
The file pointer is the handle to the file, once the file is
opened with fopen a programmer can manipulate the file
with this pointer.
fopen
www.cyberlabzone.com
FILE *fileOut;
fileOut = fopen(“output.dat”, “w”);
The first argument “output.dat” is a string that names the
file to be read. The second argument the mode, “ w ”,
stands for “write” mode only.
fopen returns a pointer to the file(in this case (output.dat).
Example:
If an already existing file is opened with mode “w” the
old contents are discarded.
fopen
www.cyberlabzone.com
FILE *fileOut;
fileOut = fopen(“out.dat”, “a”);
The first argument “out.dat” is a string that names the
file the you to which you want to write .
The writing takes place at the end of the original file.
If the file out.dat already exists it will not be destroyed as
in the case for “w” mode.
fopen returns a pointer to the file(in this case (out.dat).
Example:
fopen
www.cyberlabzone.com
When we open a file such as infile.dat we
need to specify in advance whether we want to
read from the file, write to the file, append to
the file. A file can be opened in one mode,
closed and then reopened in another mode.
Mode If the file exists If the file
doesn’t exist
“r” Opens the file for reading Error
“w” Opens a new file for writing Create a new
file
“a” Opens a file for appending
(writing at the end of the file)
Create a new
file
Fopen-mode
www.cyberlabzone.com
To close a file that is opened, you must use
fclose. The function expects one argument,
a pointer to FILE. The function fclose
returns zero if it successfully closes the file
and EOF otherwise.(e.g file doesn’t exist)
FILE *fileIn;
fileIn = fopen(“infile.dat”, “r”)
…
fclose(fileIn);
When a program terminates, all open files are
automatically closed.
fclose
www.cyberlabzone.com
1. Problem Definition Write a program that reads a list of real
numbers into an array from the keyboard (or a file using Unix
redirection). The array can be of arbitrary length but the user
must first specify the length of the array. The program then
calculates the average value, and then prints a list of
differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition (i.e.,
identify sub-problems, I/O, etc.)
Input = Since the length of the array is specified at run-time we must
use Dynamic Memory Allocation. This is accomplished in C by
the use of the built-in function calloc (or malloc). Use data-type
double to hold the values.
Output= The average and the list of differences.
Example-DMA example
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
void main(void){
int k,num;
double * datValptr; /* pointer used in DMA */
double datAve;
double sum = 0.0;
/* prompt the user for the number of array elements */
printf(“Please enter the number of array elements:”);
scanf(“%d”,&num);
/* use calloc to allocate a block of memory */
datValptr = calloc(num,sizeof(double));
/* verify that calloc was successful */
if (datValptr = = NULL){
printf(“Memory not allocated!n”);
return;
}
(continued on next slide)
www.cyberlabzone.com
/* read the values and compute the average */
k = 0;
for(k=0;k<num;++k){
scanf("%lf", &datValptr[k]);/* use pointer as array name */
sum += datValptr[k];
}
/* compute the average */
datAve = sum /num;
printf(“The average is:%f n", datAve);
/* compute and print the diff list */
for(k=0;k<num;++k){
printf(“%fn", datValptr[k]-datAve);
} /* end of for*/
/* free up any memory that was dynamically allocated */
free(datValptr);
} /* end of main */
www.cyberlabzone.com
dclsn75> ./a.out
Please enter the number of array elements:5
1 2 3 4 5
The average is:3.000000
-2.000000
-1.000000
0.000000
1.000000
2.000000
dclsn75>
Execution
www.cyberlabzone.com
In C, we can dynamically allocate storage with either of
the following two functions (both are in <stdlib.h>).
• malloc(numberOfBytes)
• calloc(numberOfItems, itemSize)
Both functions return a pointer to the address of the block
of storage that has been allocated. If no memory is
available, a NULL value will be returned.
Function calloc returns a contiguous block of
locations that are initialized to 0 and that can be
referenced as array locations, using pointer operations.
Calloc and malloc
www.cyberlabzone.com
In both cases above (calloc or malloc) return memory
locations to the system ("memory manager") with:
free (ptr);
Example: Declare ptr as a pointer variable to data-
type double and use dynamic memory allocation
(calloc or malloc) to allocate 100 elements of data-
type double.
double * ptr;
ptr = calloc(100,sizeof(double));
or
ptr = malloc(100*sizeof(double));
free
www.cyberlabzone.com
Lecture 19 slide 8 mentioned that array names
are constant pointers. Conversely, pointer variables
can be used as array names.
Example:
int x[5] ={2,4,6,8,10};
int * ptr;
ptr = x; /* or ptr = &x[0] , that is ptr points to x-array*/
ptr[0] = 3; /* is the same as x[0] = 3 */
printf(“%d”,ptr[1]); /* prints 4 */
Pointer Variables can be Used as Array Names
www.cyberlabzone.com
1. Problem Definition
Read a file “input.dat” that has employee data(“records”). Read
the records into an array (using dynamic memory allocation) of
data-type Employee (defined below) and then sort the employee
data alphabetically by name. Write the sorted data to the file
“output.dat”.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Use the structure
typedef struct {
int employeeID;
float salary;
int departmentID;
char fname[30];
char lname[30];
} Employee;
Output= The employee records in alphabetic order.
Example-Sorting Employee Records
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int employeeID;
float salary;
int departmentID;
char fname[30];
char lname[30];
} Employee;
int cmpnames(Employee *ptr1,Employee *ptr2) /* prototype */
void main(void){
FILE * fileptrIn;
FILE * fileptrOut;
int i, num;
char filenameIn[100];
char filenameOut[100];
Employee * ptr; /* ptr is a pointer variable */
Employee temp;
(continued on next slide)
www.cyberlabzone.com
/* prompt user and get the name of employee input */
/* and output file */
printf("Enter the file name that contains the records. n");
scanf("%s",filenameIn);
printf("Enter the output file name. n");
scanf("%s",filenameOut);
/* open file for reading */
fileptrIn = fopen(filenameIn,”r”);
/*open file for writing */
fileptrOut = fopen(filenameOut,”w”);
/* verify that files were successfully opened */
if (fileptrIn == NULL){
printf(“Input file not found.n”);
return; /* terminate program */
}
if (fileptrOut == NULL){
printf(“Output file not opened.n”);
return; /* terminate program */
}
(continued on next slide)
www.cyberlabzone.com
/* find the number of Employee records by reading the */
/* input file. Then reset the file to read from the */
/* beginning of the file again. */
num = 0;
while (
(EOF !=fscanf(fileptrIn,"%d",&temp.employeeID))&&
(EOF !=fscanf(fileptrIn,"%f",&temp.salary))&&
(EOF !=fscanf(fileptrIn,"%d",&temp.departmentID))&&
(EOF !=fscanf(fileptrIn,"%s",temp.fname))&&
(EOF !=fscanf(fileptrIn,”%s”,temp.lname)))
++num;
rewind(fileptrIn);
/* calloc is a built-in C function that performs DMA*/
ptr = calloc(num,sizeof(Employee));
(continued on next slide)
www.cyberlabzone.com
/* read the records into the area in memory pointed to */
/* by ptr. See the previous statement ptr = calloc(… */
/* Use ptr as the “name” of an array */
for(i = 0;i<num;++i){
fscanf(fileptrIn,"%d",&ptr[i].employeeID);
fscanf(fileptrIn,"%f",&ptr[i].salary);
fscanf(fileptrIn,"%d",&ptr[i].departmentID);
fscanf(fileptrIn,"%s",ptr[i].fname);
fscanf(fileptrIn,"%s",ptr[i].lname);
}
/* use qsort to sort the records by employee name */
qsort(ptr,num,sizeof(Employee),cmpnames);
/* write the records to the output file */
/* note the space after the conversion specifiers */
for(i = 0;i<num;++i){
fprintf(fileptrOut,"%d ",ptr[i].employeeID);
fprintf(fileptrOut,"%.2f ",ptr[i].salary);
fprintf(fileptrOut,"%d ",ptr[i].departmentID);
fprintf(fileptrOut,"%s ",ptr[i].fname);
fprintf(fileptrOut,"%sn",ptr[i].lname);
}
(continued on next slide)
www.cyberlabzone.com
/* free up dynamic memory */
free(ptr);
/* close all files before you terminate the program */
fclose(fileptrIn);
fclose(fileptrOut);
} /* end of main */
/* cmpnames is called by qsort */
int cmpnames(Employee *ptr1,Employee *ptr2){
return strcmp(ptr1->lname, ptr2->lname);
}
How would you modify the cmpnames function above to sort
the array by if the last names were the same?
How would you modify the compare function to sort by
employeeID, or by departmentID, or by salary ?
www.cyberlabzone.com
Given that the input file “input.dat” has the following
data:
12345 34500.00 24 Brad Pitt
12346 28888.00 23 Jennifer Aniston
12347 47595.00 24 Britney Spears
12348 55675.00 23 Jim Carey
The program described in the previous slides
produces the output shown on the next slide.
Example-Execution
www.cyberlabzone.com
dclsn75> ./a.out
Enter the file name that contains the records.
input.dat
Enter the file name that contains the records.
output.dat
dclsn75> more output.dat
12346 28888.00 23 Jennifer Aniston
12348 55675.00 23 Jim Carey
12345 34500.00 24 Brad Pitt
12347 47595.00 24 Britney Spears
dclsn75>
Example-Execution
www.cyberlabzone.com
fclose(fileptrIn);
fileptrIn = fopen(filenameIn,”r”);
In slide 13 we used the built-in C function rewind. To
illustrate the meaning of rewind, consider the
following example: If the data was written on a
magnetic tape, then the rewind command causes
the tape to be rewound back to the beginning of the
tape. So the next read command would begin
reading from the beginning of the file.
In the program in slides 10-15 we could replace
the code:
rewind(fileptrIn);
by the following code:
Rewind
www.cyberlabzone.com
C has the special feature of preprocessor directive which makes it
different from other languages (which hasn’t this type of facility). C
preprocessor provides the facility to programmers to make program
more efficient (for Understanding and modification of program). The
preprocessor processes the C source code before it passes to the
compiler preprocessor directives are executed before the C source code
passes through the compiler. The preprocessor directives usually
written at the beginning of the C program. These directives are
preceded with the # symbol and there is no semicolon at the end. This is
not necessary to write the preprocessor directives at the beginning of
the program, These can be written anywhere in the program but they
are generally written before main function or other functions. The
preprocessor directives are as given below:-
# define, #ifdef, #ifndef, #else, #elif,#if
#error, #endif, #undef, #line, #pragma
Stringizing operator #
Token pasting operator ##
The C Preprocessor
www.cyberlabzone.com
Recursive functions are defined in terms of
themselves; i.e., a function is recursive if it
contains calls back to itself or to another function
that calls the original function. Recursive
programming usually requires more memory and
runs more slowly than non-recursive programs.
This is due to the cost of implementing the “stack”.
However, recursion is often a natural way to
define a problem.
Recursive Functions
www.cyberlabzone.com
1. Problem Definition
Write a factorial function. 0! = 1 and n! = n*(n-1)!.
Use “recursion” to implement the factorial function.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Non-negative integers as input.
Output= return the factorial of the input value.
Note: that 69! = 1.711224524... x 1098
so our function will only work for small integer
values. It would be better to return a
value of data-type double (Why?)
Example-Factorial function
www.cyberlabzone.com
double fact(int n)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
In main we can call the factorial function by the following
command:
printf(“%lf”, fact(6));
or by (if x is of data-type int and y is of data-type double) :
x = 5;
y = fact(x);
Example-(Recursive) Factorial function
www.cyberlabzone.com
double fact(int n)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
When we call the factorial function with fact(2) we “stop” executing the
factorial function at the line:
return ( 2 * fact(1)); (n = 2) (values are substituted for the variables).
We cannot return a value because we must first compute fact(1), so this
statement is put on hold or “pushed on the stack” until fact(1) is computed. A
second call to factorial function is made, i.e. fact(1) and we execute,
(continued on the next slide)
Example-How it Works
www.cyberlabzone.com
and since n = = 1 is true then the following executes:
return 1.0; (n = 1)
But to where does the value 1.0 return ? From where fact was last called ,
the fact function(see previous slide). So when this call to fact terminates
(at return 1.0;) the statement
return ( 2 * fact(1)); (n = 2)
is “popped” from the stack and fact(1) gets the value 1.0, that is, we can
now execute this statement which (effectively) says
return ( 2 * 1.0);
double fact(int n) (n = 1)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
Example-How it Works
www.cyberlabzone.com
Note the contents of the “stack” when we execute a call fact(3) from main.:
(push) return ( 3 * fact(2)); (n = 3)
(push) return ( 2 * fact(1)); (n = 2)
return 1.0; (n = 1)
(pop) return ( 2 * 1.0); (n = 2)
(pop) return ( 3 * 2.0); (n = 3)
return ( 3 * fact(2)); (n = 3)
return ( 2 * fact(1)); (n = 2)
return ( 3 * fact(2)); (n = 3)
(STACK)
The “stack” contains “stack frames” see FER 21.2.1.
Example-fact(3)
www.cyberlabzone.com
1. Problem Definition
Write a solve_maze function. Read the maze from a file, “maze.txt”
and display one path that traverses the maze. Use “recursion” to
implement the maze function.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = The file “maze.txt” contains the following
**********
* *
**** * *O*
* * ***
* * *X*
* ** *** *
* * *
* *** ** *
* * *
**********
Your program will have to find its way through a
10x10 maze where the symbols “ * ” , “O” and “X”
denote:
“ * ” are solid walls through which you cannot travel
"O" denotes the starting position,
"X" is the exit for which you are looking for
Example-Traversing a Maze
www.cyberlabzone.com
* * * * * * * * * *
* *
* * * * * * O *
* * * * *
* * * X *
* * * * * * *
* * *
* * * * * * *
* * *
* * * * * * * * * *
www.cyberlabzone.com
2. Refine, Generalize, Decompose the problem definition
Input (continued): Read the maze into the 2D array,
**********
* *
**** * *O*
* * ***
* * *X*
* ** *** *
* * *
* *** ** *
* * *
**********
char maze[NUMROWS][NUMCOLS];
where NUMROWS and NUMCOLS are
constants with value 10. The upper left-hand
corner of the maze has the value maze[0][0] .
If we want to test whether the cell in the
fourth row and fourth column contains
a wall then it's enough to use an
if statement like this:
if (maze[3][3] == ‘ * ')
Example-Traversing a Maze
www.cyberlabzone.com
2. Refine, Generalize, Decompose the problem definition
Output : Display a solution as follows:
**********
* OOOOO*
****O* *O*
* *O* ***
* *O* *X*
* **O***O*
* OO *O*
* ***O**O*
* * OOOO*
**********
Example-Traversing a Maze
www.cyberlabzone.com
3. Develop Algorithm
(processing steps to solve problem)
Step 1 Read in the “maze” and find the starting Row and Column (the
position of the “O”).
Use variables “curRow” and “curCol” to keep track of the current position
as we traverse through the maze (the 2D matrix “maze”).
Step 2 Display the maze.
Step 3 Check to see if current position is an “X” then we are done.
Otherwise first try to go up and if not then down and if not then left and
if not then right and if you can go up/down/left/right then go back to
Step 2. Otherwise, go back to the previous position [curRow,curCol] and
try another direction.
Example-Traversing a Maze
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
#define NUMROWS 10
#define NUMCOLS 10
/* prototypes */
int read_maze (char[][], int *, int *);
void display_maze (char[][]);
void solve_maze (char[][], int, int);
www.cyberlabzone.com
void main (void)
{
int startRow, startCol; /* Starting point in maze. */
char maze[NUMROWS][NUMCOLS]; /* Stores maze read from input file.
*/
if (read_maze(maze, &startRow, &startCol) == 0)
{
printf ("Error reading maze from file maze.txt!n");
return;
}
solve_maze(maze, startRow, startCol);
} /*end of main */
www.cyberlabzone.com
void solve_maze(char maze[][NUMCOLS], int curRow, int curCol){
int i;
display_maze(maze);
/* Check if solution found. */
if ((maze[curRow - 1][curCol] == 'X') ||
(maze[curRow + 1][curCol] == 'X') ||
(maze[curRow][curCol + 1] == 'X') ||
(maze[curRow][curCol - 1] == 'X'))
exit (0);
/* Recurse in each possible direction that is empty. */
/* Move up */
if (maze[curRow - 1][curCol] == ' ') {
maze[curRow - 1][curCol] = 'O';
solve_maze(maze, curRow - 1, curCol);
maze[curRow - 1][curCol] = ' ';
}
/* continued on next slide */
www.cyberlabzone.com
/* Move down */
if (maze[curRow + 1][curCol] == ' ') {
maze[curRow + 1][curCol] = 'O';
solve_maze (maze, curRow + 1, curCol);
maze[curRow + 1][curCol] = ' ';
}
/* Move left */
if (maze[curRow][curCol - 1] == ' ') {
maze[curRow][curCol - 1] = 'O';
solve_maze (maze, curRow, curCol - 1);
maze[curRow][curCol - 1] = ' ';
}
/* Move right */
if (maze[curRow][curCol + 1] == ' ') {
maze[curRow][curCol + 1] = 'O';
solve_maze (maze, curRow, curCol + 1);
maze[curRow][curCol + 1] = ' ';
}
return;
}
www.cyberlabzone.com
/* Display the maze passed as a parameter to standard output. */
void display_maze (char maze[ ][NUMCOLS])
{
int i, row, col;
for (row = 0; row < NUMROWS; row++)
{
for (col = 0; col < NUMCOLS; col++)
{
printf ("%c", maze[row][col]);
}
printf ("n");
}
usleep (600000);
printf ("n");
}
www.cyberlabzone.com
int read_maze (char maze[ ][NUMCOLS], int *sRow, int *sCol){
FILE *fpMaze;
int row, col;
char endofline; /* end of line character */
/* Open maze text file, make sure it opens OK. */
if ((fpMaze = fopen ("maze.txt", "r")) == NULL)
return 0;
for (row = 0; row < NUMROWS; row++){ /* Loop through the rows. */
for(col=0;col<NUMCOLS;++col){/* Loop through columns */
fscanf(fpMaze,"%c",&maze[row][col]);
if (maze[row][col] == 'O') { /*Check if this is the starting
position.*/
*sRow = row;
*sCol = col;
}
} /* end of for(col=... loop */
fscanf(fpMaze,"%c",&endofline);
} /* end of for(row=... loop */
fclose(fpMaze);
return 1;
}
www.cyberlabzone.com
According to legend, in the great temple of Benares, beneath
the dome which marks the center of the world, rests a brass
plate on which are fixed three diamond needles. On one of
these needles at creation, there were placed 64 discs of pure
gold, the largest disc resting on the brass plate and the others
getting smaller up to the top one. This is the TOWERS OF
HANOI. Day and night, the people on duty move the discs from
one needle to another, according to the two following laws:
Law 1: Only one disc at a time may be moved.
Law 2: A larger disc may never rest on a smaller disc.
The workers labor in the belief that once the tower has been
transferred to another needle there will be heaven on earth, so
they want to complete the task in the least number of moves.
Towers of Hanoi
www.cyberlabzone.com
Actually, the Tower of Hanoi puzzle was invented in 1883 by
the French mathematician Edouard Lucas (1842-1891), who
made up the legend to accompany it.
Towers of Hanoi
www.cyberlabzone.com
An elegant and efficient way to solve this problem is
to think recursively.
Suppose that you, somehow or other, have found the
most efficient way possible to transfer a tower of n-1
disks one by one from one pole to another obeying
the restriction that you never place a larger disk on
top of a smaller one. Then, what is the most efficient
way to move a tower of n disks from one pole to
another?
Towers of Hanoi
www.cyberlabzone.com
Assume we know how to move n-1 disks from one peg to
another.Then can we move n disks from peg 1 to peg 3 ?
1. Move n-1 disks from peg 1 to peg 2, peg 3 is just a
temporary holding area
2. Move the last disk(the largest) from peg 1 to peg 3
3. Move the n-1 disks from peg 2 to peg 3, peg 1 is just a
temporary holding area.
1 2 3
n disks
Pseudo-code
www.cyberlabzone.com
Click on Picture to start game
1 2 3
Example-Animation
www.cyberlabzone.com
/* function prototype*/
void hanoi( int origin, int dest, int spare, int how_many);
void main(void){
int how_many;
printf(“ntHow many disks initially on peg1?”);
scanf(“%d”, &how_many);
hanoi(1, 3, 2, how_many);
}
Example-Towers of Hanoi
www.cyberlabzone.com
void hanoi( int origin, int dest, int spare, int how_many){
int new_origin, new_dest, new_spare;
if(how_many == 1){
printf(“nntMove top disk from peg %d to peg %d.”, origin, dest);
return;
}
new_origin = origin;
new_dest = spare;
new_spare = dest;
hanoi(new_origin, new_dest, new_spare, how_many - 1);
printf(“nnt Move top disk from peg %d, to peg %d.”, origin, dest);
new_origin = spare;
new_dest = dest;
new_spare = origin;
hanoi(new_origin, new_dest, new_spare, how_many - 1) ;
}
Example-Towers of Hanoi
www.cyberlabzone.com
Going back to the legend, suppose the priests work
rapidly and move one disk every second. As shown earlier,
the minimum sequence of moves must be :
The minimum
number of moves
needed to transfer
a tower of n disks
from peg1 to peg3
The minimum
number of moves
needed to transfer
n-1 disks from
peg1 to peg2
The minimum
number of moves
needed to transfer
the n th disk from
peg1 to peg3
The minimum
number of moves
needed to transfer
n-1 disks from peg2
to peg3 on top of
the n th disk
Therefore, the recurrence relation is moves(n) = 2*moves(n-1) + 1 and
initial case is moves(1) = 1 second.
For example, moves(2) = 2*moves(1) + 1 = 3,
moves(3) = 2*moves(2) + 1 = 7,
moves(4) = 2*moves(3) + 1 = 15.
Then, the time to move all 64 disks from one peg to the other, and end
the universe would be moves(64) seconds or 584.5 billion years!!
= + +
Computational Complexity

More Related Content

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
C tokens
C tokensC tokens
C tokens
Manu1325
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
C++ programming
C++ programmingC++ programming
C++ programming
Emertxe Information Technologies Pvt Ltd
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
University of Madras
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Himanshu Kaushik
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
Strings
StringsStrings
Strings
Mitali Chugh
 

Viewers also liked (20)

Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
Wingston
 
C ppt
C pptC ppt
C ppt
jasmeen kr
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
Farooq Mian
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
nTier Custom Solutions
 
CHAPTER 3
CHAPTER 3CHAPTER 3
CHAPTER 3
mohd_mizan
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
SULTHAN BASHA
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
AAKASH KUMAR
 
C Language Program
C Language ProgramC Language Program
C Language Program
Warawut
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
Chitrank Dixit
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
Jitin Pillai
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
Mahantesh Devoor
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving
Khan Yousafzai
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
C++ Language
C++ LanguageC++ Language
C++ Language
Vidyacenter
 
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT IIC PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
Wingston
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
Farooq Mian
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
SULTHAN BASHA
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
AAKASH KUMAR
 
C Language Program
C Language ProgramC Language Program
C Language Program
Warawut
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
Chitrank Dixit
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
Jitin Pillai
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
Mahantesh Devoor
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving
Khan Yousafzai
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
Ad

Similar to Complete C programming Language Course (20)

C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
Durga Padma
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
tarifarmarie
 
C prog ppt
C prog pptC prog ppt
C prog ppt
xinoe
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
Indira Gnadhi National Open University (IGNOU)
 
C language tutorial
C language tutorialC language tutorial
C language tutorial
Jitendra Ahir
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
Mohamed Fawzy
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
intro to programming languge c++ for computer department
intro to programming languge c++ for computer departmentintro to programming languge c++ for computer department
intro to programming languge c++ for computer department
MemMem25
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
farishah
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
rajkumar490591
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programming
vipulkondekar
 
C Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptxC Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptx
kumaranand07297
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
PushkarNiroula1
 
C introduction
C introductionC introduction
C introduction
MadhuriPareek
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
Leandro Schenone
 
C introduction
C introductionC introduction
C introduction
Kamran
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
rohassanie
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Rohit Singh
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
tarifarmarie
 
C prog ppt
C prog pptC prog ppt
C prog ppt
xinoe
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
intro to programming languge c++ for computer department
intro to programming languge c++ for computer departmentintro to programming languge c++ for computer department
intro to programming languge c++ for computer department
MemMem25
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
farishah
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
rajkumar490591
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programming
vipulkondekar
 
C Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptxC Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptx
kumaranand07297
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
PushkarNiroula1
 
C introduction
C introductionC introduction
C introduction
Kamran
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Rohit Singh
 
Ad

More from Vivek Singh Chandel (20)

Deceptive Marketing.pdf
Deceptive Marketing.pdfDeceptive Marketing.pdf
Deceptive Marketing.pdf
Vivek Singh Chandel
 
brain controled wheel chair.pdf
brain controled wheel chair.pdfbrain controled wheel chair.pdf
brain controled wheel chair.pdf
Vivek Singh Chandel
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Vivek Singh Chandel
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Vivek Singh Chandel
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking drivers
Vivek Singh Chandel
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using Thoughts
Vivek Singh Chandel
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Vivek Singh Chandel
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
Vivek Singh Chandel
 
Net framework session03
Net framework session03Net framework session03
Net framework session03
Vivek Singh Chandel
 
Net framework session02
Net framework session02Net framework session02
Net framework session02
Vivek Singh Chandel
 
04 intel v_tune_session_05
04 intel v_tune_session_0504 intel v_tune_session_05
04 intel v_tune_session_05
Vivek Singh Chandel
 
03 intel v_tune_session_04
03 intel v_tune_session_0403 intel v_tune_session_04
03 intel v_tune_session_04
Vivek Singh Chandel
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
Vivek Singh Chandel
 
01 intel v_tune_session_01
01 intel v_tune_session_0101 intel v_tune_session_01
01 intel v_tune_session_01
Vivek Singh Chandel
 
09 intel v_tune_session_13
09 intel v_tune_session_1309 intel v_tune_session_13
09 intel v_tune_session_13
Vivek Singh Chandel
 
07 intel v_tune_session_10
07 intel v_tune_session_1007 intel v_tune_session_10
07 intel v_tune_session_10
Vivek Singh Chandel
 
02 asp.net session02
02 asp.net session0202 asp.net session02
02 asp.net session02
Vivek Singh Chandel
 
01 asp.net session01
01 asp.net session0101 asp.net session01
01 asp.net session01
Vivek Singh Chandel
 
16 asp.net session23
16 asp.net session2316 asp.net session23
16 asp.net session23
Vivek Singh Chandel
 
15 asp.net session22
15 asp.net session2215 asp.net session22
15 asp.net session22
Vivek Singh Chandel
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Vivek Singh Chandel
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Vivek Singh Chandel
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking drivers
Vivek Singh Chandel
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using Thoughts
Vivek Singh Chandel
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Vivek Singh Chandel
 

Recently uploaded (20)

Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 

Complete C programming Language Course

  • 2. www.cyberlabzone.com Topics for C Language 1.Introduction to C language 2.Programming Languages 3.Data Types 4.Basic Input/Output (I/O) 5.Control Constructs 6.Array 7.Fuctions 8.Program Design Example 9.Pointers 10.Structures & Unions 11.File Operation in C 12.The C Preprocessor 13.Computational Complexity
  • 3. www.cyberlabzone.com Introduction to C languages C is a traditional, Procedural language,i.e. one that requires the programmer to provide step-by-step instructions for the processor (i.e., the main logic unit of a computer). The great success of C is due to its simplicity, efficiency, flexibility and small memory requirements. It is also due to the portability of programs that are written in it, i.e., the ability to be easily adapted to new platforms (i.e., operating systems and processors). C's great portability is in very large part a result of the fact that compilers and libraries are available for numerous platforms. A compiler is a specialized computer program that converts source code (i.e., the original, human-readable form of a program typed into a computer by a programmer in a programming language) into another language, usually machine language (also called object code or machine code) so that it can be directly understood by processors. A library is a collection of routines (also called subprograms, procedures or functions) that perform operations which are commonly required by programs.
  • 4. www.cyberlabzone.com Programming Languages Programming Languages classified as ”Low Level/High Level” 1.Low Level •Machine Language (binary-based code; machine dependent) • Assembly Language (mnemonic form of machine language) 2.High Level Closer to natural languages. Generally, machine independent Usually, several machine instructions are combined into one high- level instruction. Examples: FORTRAN, COBOL,BASIC, Java, Pascal, Ada, PL/I, Lisp, C GPSS,C++, Matlab
  • 5. www.cyberlabzone.com Processing a High-level Language Program Programs written in high-level languages must be converted to machine language. Two approaches: (1) Compilation used with C, C++, Fortran,... (2) Interpretation Used with Matlab, Visual Basic,...
  • 6. www.cyberlabzone.com STEP 1) Use Dos Prompt to create a “Directory”. In this Directory We write and save all Programme name source files with a suffix “.c”. STEP 2)In Dos Prompt to compile the desired Programme we use “Ctrl +F9” to get a desired result While programme is on the monitor . STEP 3) Check the error if any caught by compiler, remove that error and go back to step 2,repeat whole process again. STEP 4) Run the program by using “Ctrl+F9” and for OUTPUT we use “Alt+F5” in the Dos prompt. Compilation (In Window Environment)
  • 7. www.cyberlabzone.com C Program Examples 1. Requirements Specification (Problem Definition) Write a simple C program to request the users’ SSN and print the message “Hello (SSN)!” (where SSN is the value the user supplied) to the screen of the computer monitor. 2. Analysis---Refine, Generalize, Decompose the problem definition (i.e., identify sub problems, I/O, etc.) Input = SSN Output= A prompt for the SSN then “Hello (SSN)!” 3. Design---Develop Algorithm Pseudo-code Algorithm print “Enter SSN (no dashes)” read SSN print “Hello (SSN) !” 4. Implementation --- Write the "Program" (Code)
  • 8. www.cyberlabzone.com C Examples /* C Program to greet the user */ #include <stdio.h> /* makes the function printf “known” */ /* to the C compiler */ void main(void) { int ssn; /* variable ssn declared */ printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); /* read the SSN */ printf(”Hello %d !n”,ssn); /* print the message */ }
  • 9. www.cyberlabzone.com Main Function #include ... /* preprocessor directive */ . . . void main(void) /*function header*/ { . . /* function body */ . } In the following set of slides we will define the component parts of the main function.
  • 10. www.cyberlabzone.com Preprocessor Directives #include ... /* preprocessor directive */ . . . void main(void) { . . . } Statements beginning with the symbol # are called preprocessor directives. The #include directives allow the C program to access libraries of functions that are not available directly in C. These libraries are referred to as header files: stdio.h standard input-output functions math.h math functions stdlib.h a “standard” library of functions
  • 11. www.cyberlabzone.com Main Function Header #include ... . . . void main(void) /*function header*/ { . . . } The “initial” input is any value(s) passed at initial execution, e.g. >a.out 1.0 3.5 Typing the above at the Unix prompt attempts to pass the values 1.0 and 3.5 to main. At this point we will not do this. The header for the programs in some C programs is of the form: int main(void) and there is a corresponding statement in the function body: return (0); main has no “initial” input values. (see below) main function returns no value
  • 12. www.cyberlabzone.com Main Function (body) #include ... . . . void main(void) { . . /* function body */ . } • The body of a function is all the declarations and executable statements between the braces (in the block). The declarations must precede the executable statements in this block. • When you run a program, the first statement executed is the first (from the top of the file) executable statement in main. The execution of statements proceeds until the terminating “}” right brace is encountered or a return statement is executed. a “block” in C is defined by a set of curly braces.
  • 13. www.cyberlabzone.com Declaration #include <stdio.h> void main(void) { int ssn; /* variable ssn declared */ printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); printf(”Hello %d !n”,ssn); } One form of a declaration in C : data-type variable_name ;
  • 14. www.cyberlabzone.com Data Types Fixed Point(Integers) Floating Point Character short float char int double long long double
  • 15. www.cyberlabzone.com Variable Names Variable Names - reference to memory locations storing data values. A variable name is one example of an identifier in C. An identifier can use a combination of letters, numerical digits, and the underscore ( _ ) that starts with a letter. Only the first 31 characters of an identifier are recognized by most compilers. Identifiers cannot be the same as a reserved word or keyword, such as void, float, or return. Examples: x sum force2 rate_Of_Change Examples of invalid variable names (why?): 2force rate-of-change x.5 return C case-sensitive, so that the following three names all represent different variables (i.e., different storage locations): time Time TIME
  • 16. www.cyberlabzone.com #include <stdio.h> void main(void) { int ssn; printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); printf(”Hello %d !n”,ssn); } The printf and scanf functions appear in ‘expression’ statements. 1st executable statement 3rd executable statement 2nd executable statement Executable Statements
  • 17. www.cyberlabzone.com Executable Statements Statements are grouped by their type: expression statement do-while and while statements for statement if and if-else statements return statement switch statement assignment statement Every executable statement in C must be followed by a “ ; “ semicolon.
  • 18. www.cyberlabzone.com Assignment Statement •Interpretation: compute the value on the right-hand-side of the = and put this value in memory at location named (or tagged) by the name variable . • an expression can be a constant, a variable or operators with operands. variable = expression;
  • 19. www.cyberlabzone.com Constants Literal Constants(examples) Numeric: 3 6.248 -7.25 1.5e4 (=15000) Single Character: 'A' 'a' '9' '+' ' ' Character String: “Enter a positive number: ” Symbolic Constants(example) #define PI 3.14159265 /* preprocessor directive */ By default, constants declared in #define are of type double. Standard practice is to use all upper-case letters for the constant name, to avoid confusion with a variable name. A “constant” means you cannot change the value, e.g. PI = 3.0; will generate a compiler error from gcc.
  • 20. www.cyberlabzone.com Arithmetic Operators - for integer arithmetic, the / operator yields an integer result, and % gives the remainder after dividing two integers. E.g., 5 / 3 1 5 / 6 0 5 % 3 2 5 % 6 5 (Note: division by 0 creates an "overflow" run-time error.) - use arithmetic operators, with parentheses for grouping; e.g., (a - b) / (2 * c) e.g, without parentheses, the example above would evaluate b/2 first, then do the multiplication, then the subtraction. +, - , * , / , % (modulus) (no ^ operator as in Matlab)
  • 21. www.cyberlabzone.com Rules of Precedence ( ) Higher *, /, % (left to right for tie) +, - (left to right for tie) Lower Examples, : x = 3 + 2 * 3; /* x now has the value 9 */ y = 3 * 2 % 3; /* y now has the value 0 */ - Precedence Order for Arithmetic Operators:
  • 22. www.cyberlabzone.com Understanding the Assignment statement • Example int time; . . . time = 0; . 0time 1200 Main Memory Memory map after the assignment statement time = 0 is executed . unknowntime 1200 Main Memory Memory map before the assignment statement time = 0 is executed
  • 23. www.cyberlabzone.com Understanding the Assignment statement • Example double force; force = 5.0; . . . force = force * 3.0; . 15.0force 1400 Main Memory Memory map after the assignment statement force = force * 3.0; is executed . 5.0force 1400 Main Memory Memory map before the assignment statement force = force * 3.0; but after force = 5.0; is executed
  • 24. www.cyberlabzone.com Character Values Individual characters may be assign to variables of data-type char. Example: Write a program to prompt the user for a Y/ N response. Print the users response to the screen. #include <stdio.h> void main(void) { char letter; printf(“Please enter a response (Y/N):”); scanf(“%c”,&letter); printf(“Your response was: %c n”,letter); }
  • 25. www.cyberlabzone.com Expression Statements One form of a expression statement in C : function(argument list) ; Scanf function accepts input from standard input device, usually a keyboard scanf("format string", &var1, &var2, ...); The number of conversion specifiers should match the number of variables that follow the “format string”. %i,%d - decimal integer (d=decimal) %f - float %lf - double(where lf="long float") %Lf - long double %c - character where “format string” is the string of conversion specifiers for the various data types in the variable list. e.g.,
  • 26. www.cyberlabzone.com Basic Input/Output (I/O) sends output to standard output device, usually a video monitor printf("format string", output-list); where ”format string” can contain characters to be output and the conversion specifiers indicating type and position of the output values. For output, we specify formats conversion specifiers) a little differently than we do for input. For example: %i, %d -decimal integer %o -octal integer %x, %X -hex integer (use X for caps A - F) %f -float, double %c -character %s -character string Printf function
  • 27. www.cyberlabzone.com Output Control: Special characters Each is represented by an escape sequence, which is a backslash () and an escape character. Examples are: " - output double quotes b – backspace ? - output question-mark character (?) - output backslash character () n - new line
  • 28. www.cyberlabzone.com Output Control: Field Width The number of print positions to be used in the output of display values. For floating-point numbers, we can also specify the number of digits to be displayed after the decimal point. Examples: %3d - display an integer using 3 print positions. %7.3f - display a floating-point number (float, or double) using a total field width of 7 and with 3 places after the decimal point.
  • 29. www.cyberlabzone.com Printf and scanf Examples Example: scanf("%i %f %lf %c", &n, &a, &x, &code); Example: printf("The sum of %i values is %f.n“,numValues, sum); printf("%sn", "Temperature Variations"); printf("The output is: n");
  • 30. www.cyberlabzone.com Comments Comments in C are of the general form: /* . . . */ Comments can be inserted anywhere you can put a space (blank). Comments are ignored by the C compiler and not included in the executable file. The */ can be on the next line but then every character between the /* and the */ is ignored by the C compiler.
  • 31. www.cyberlabzone.com Programming Errors Syntax Errors Run-time Errors Logical Errors The gcc compiler will catch these errors and give you Error messages. Example: x + 1 = x; (should be x = x+1; for a valid assignment statement) The gcc compiler will not catch these errors. Example: User enters the value 0 and your code reads this value into variable x, and then computes 1/x . The gcc compiler will not catch these errors. Program will run and not generate any error messages but results outputted by the program are incorrect. Example: User programs solution using the wrong formula.
  • 32. www.cyberlabzone.com 1. Problem Definition Write a program that reads a number and computes the square root if the number is non-negative. 2. Refine, Generalize, Decompose the problem definition (i.e., identify subproblems, I/O, etc.) Input = real number Output=real number 3. Develop Algorithm (processing steps to solve problem) C problem examples
  • 33. www.cyberlabzone.com C problem Example Flowchart Print “enter value” Read value value >= 0.0 Print sqrt(value) TrueFalse
  • 34. www.cyberlabzone.com C program Example /* C Program to compute the square root of a positive number */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ printf(”Please enter a non-negative number :”); /* request user input */ scanf("%lf", &value); /* read value */ /* Output the square root. */ if (value >= 0.0) printf(”square_root(%f) = %f n", value,sqrt(value)); }
  • 35. www.cyberlabzone.com Selection Structures Decision statements if(expression) statement; • if expression evaluates to true, the statement is executed; otherwise execution passes to the next statement in the program. • if Selection Structure if(value >= 0.0); printf(”square_root(%f) = %f n", value,sqrt(value)); /* Error! Don’t put semicolon here */ /* This is an example of a logical error */ 1. Problem Definition Modify the previous program to notify the user when the input is invalid.
  • 36. www.cyberlabzone.com C Program Examples (Modified) Flowchart Print “enter value” Read value value >= 0.0 Print sqrt(value); TrueFalse Print “invalid input”
  • 37. www.cyberlabzone.com C Program Examples (Modified) /* C Program to compute the square root of a positive number */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ printf(”Please enter a non-negative number :”);/*request user input*/ scanf("%lf", &value); /* read value */ /* Output the square root. */ if (value >= 0.0) printf(”square_root(%f) = %f n", value,sqrt(value)); else printf(“invalid user input, please enter non-negative valuen”); }
  • 38. www.cyberlabzone.com Math Library in C - in header file math.h Arguments (parameters) for each of the following functions are assumed to be of type double. If not, a type double copy is made for use in the function. To compile a program that contains math functions you need to use the -lm (Lm not 1m )option for gcc. > gcc file.c -lm See next slide
  • 39. www.cyberlabzone.com fabs (x) - |x| sqrt (x) - square root of x pow (x, a) - x to the power ‘a’ exp (x) - e to the power ‘x’ (e = 2.718281828 …) log (x) - ln x = loge x log10 (x) - log10 x sin (x) - sine function (x in radians) cos (x) - cosine function (x in radians) tan (x) - tangent function (x in radians) fmod (a, b) - remainder of a/b in floating-point ceil (x) - smallest integer >= x floor (x) - largest integer <= x
  • 40. www.cyberlabzone.com If- else Selection Structure if (expression) statement1; else statement2; -if expression evaluates to true, statement1 is executed and execution skips statement2 -If expression evaluates to false, execution skips statement1 , statement2 is executed Control Constructs
  • 41. www.cyberlabzone.com We can also execute multiple statements when a given expression is true: if (expression) { if-statement1; if-statement2; if-statementn; } Example - if(b < a){ temp = a; a = b; b = temp; } or ... if (expression) { if-statement1; if-statement2; if-statementn; } else { else-statement1; else-statement2; else-statementm; } (what does this code accomplish?) ... ... If-else Selection Structure
  • 42. www.cyberlabzone.com C Problem Example 1. Problem Definition Modify the previous program to compute the following: You must check that the value is legal, i.e. value >= 1.0 or value <= -1.0 0.1 2 value
  • 43. www.cyberlabzone.com C Problem Example Flowchart Print “enter value” Read value value >= 1.0 or value <= - 1.0 Print sqrt(value*value - 1.0); TrueFalse Print “invalid input”
  • 44. www.cyberlabzone.com /* C Program to compute the square root of */ /* value*value -1.0 */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ /* request user input*/ printf(”Please enter value >= 1.0 or <= -1.0 :”); scanf("%lf", &value); /* read value */ /* Output the square root. */ if ((value >= 1.0) || (value <= -1.0)) printf(”square_root(%f) = %f n", value,sqrt(value*value - 1.0)); else { printf(“invalid user inputn”); printf(“input should be a value >= 1.0 or <= -1.0 n”); } } C Problem Example (Modified)
  • 45. www.cyberlabzone.com Logical Expression (Relational Operator) In logical expressions (which evaluate to true or false), we can use the following Relational operators: Relational Operator Type of Test == equal to (don’t use =) != not equal to > greater than >= greater than or equal to < less than <= less than or equal to
  • 46. www.cyberlabzone.com Logical Expression (Relational Operations) Logical(Boolean) Operators && and (true if both true) || or (true if at least one is true) ! not (a unary operator) Operation In logical expressions (which evaluate to true or false), we can use the following Logical operators:
  • 47. www.cyberlabzone.com Logical Expressions int ans, x = 3, y = 4; ans = (x < 5)||(y >= 5); /* ans now has the value 1 */ ans = (x < 5)&&(y >= 5); /* ans now has the value 0 */ In C the value for False is represented by the value zero and True is represented by any nonzero value. The value False can be any zero value such as the number 0 or 0.0 or null character ‘ 0 ’ or the NULL pointer. Example 2: int x = 0; /* x declared as an integer variable */ /* and initialized to the value 0 */ if (x = 0) /* note the error, == should be used */ printf(“ x is zeron”); /*message not printed, why?*/ Example 1: Caution: Avoid testing floating- point numbers for equality! Why?
  • 48. www.cyberlabzone.com Nested if- else Selection Structure 1. Problem Definition Write a program that returns a letter grade based on a quiz score. The input will be the integer score from a 10 point quiz. The letter grades are assigned by: 9 - 10 “A” 7 - 8 “B” 5 - 6 “C” 3 - 4 “D” < 3 “F” 2. Refine, Generalize, Decompose the problem definition (i.e., identify subproblems, I/O, etc.) Input = integer score Output=character “grade” 3. Develop Algorithm (processing steps to solve problem)
  • 49. www.cyberlabzone.com C Problem Example Flowchart Print “enter score” Read score score == 10 || score == 9 Print “A” TrueFalse (continued on next slide) (skip else part of statement)
  • 50. www.cyberlabzone.com C Problem Example False score == 8 || score == 7 Print “B”; True (skip else part of statement) (continued on next slide) False
  • 51. www.cyberlabzone.com C Problem Example False score == 6 || score == 5 Print “C”; True (skip else part of statement) (continued on next slide) False
  • 52. www.cyberlabzone.com C Problem Example False score == 4 || score == 3 Print “D” True False Print “F”
  • 53. www.cyberlabzone.com C Problem Example /* C Program to compute the letter grade for a quiz. */ #include <stdio.h> void main(void) { int score; /* Declare variables. */ printf(”Please enter a score :”); /* request user input */ scanf("%i", &score); /* read value */ /* Output the grade */ /* continued on the next slide */
  • 54. www.cyberlabzone.com C Problem Example if ((score == 10) || (score == 9)) printf(“An”); else if ((score == 8) || (score == 7)) printf(“Bn”); else if ((score == 6) || (score == 5)) printf(“Cn”); else if ((score == 4) || (score == 3)) printf(“Dn”); else printf(“Fn”); } /* end of program */ Unless { } are used the else matches the first if in the code above.
  • 55. www.cyberlabzone.com Switch Selection structure 1. Problem Definition Redo the previous problem by using a switch statement rather than the nested if-else statement. Pseudo-code Algorithm print “enter score” read score switch score score = 9,10 print “A” score = 7,8 print “B” score = 5,6 print “C” score = 3,4 print “D” otherwise print “F”
  • 56. www.cyberlabzone.com C Program Example /* C Program to compute the letter grade for a quiz. */ #include <stdio.h> void main(void) { int score; /* Declare variables. */ /* request user input */ printf(”Please enter a score :”); scanf("%i", &score); /* read value */ /* Output the grade */ /* continued on the next slide */
  • 57. www.cyberlabzone.com C Program Example switch (score) { case 10: case 9: printf(“An”); break; case 8: case 7: printf(“Bn”); break; case 6: case 5: printf(“Cn”); break; case 4: case 3: printf(“Dn”); break; default: printf(“Fn”); } /* end of switch */ } /* end of program */
  • 58. www.cyberlabzone.com Switch Selection Structure The switch structure can be used when we have multiple alternatives based on a value of type int or type char (but not floating point). This structure has the general form: switch (controlling expression) { case label1: statements1; case label2: statements2; default: default statements; } (controlling expr. must evaluate to an integer or a character value; each case should end with a break stmt.) ...
  • 59. www.cyberlabzone.com 1. Problem Definition Use a while statement to read a list of integers from a file and compute the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input.dat” Output=real number representing the arithmetic average =(sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) C problem Example
  • 60. www.cyberlabzone.com Flowchart while EOF != scanf value total = total + value; count = count + 1; TrueFalse total = 0; count = 0; printf total/(double) count (double) is a cast see slide #14 C problem Example
  • 61. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count = 0; /*Why are total and count set to zero?*/ while (EOF != scanf("%i", &value)) { /* read value */ total = total + value; count = count + 1; } /* end of while loop */ /* Output the average. */ printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C problem Example
  • 62. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem1.c , and make sure to save the file. 2. Use xemacs to create an input file input.dat and enter in integers into this file. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem1.c C problem Example-Execution
  • 63. www.cyberlabzone.com 4. Run the program using Unix redirection < a.out < input.dat 5. What happens if you type a.out < input.dat > output.dat Note: if you do this a second time it will fail because Unix will not let you over-write an existing file. 6. To append the results to the existing file output.dat a.out < input.dat >> output.dat C problem Example-I/O Redirection
  • 64. www.cyberlabzone.com A second form of a declaration in C : data-type variable_name = initializer; /*Why are total and count initialized to zero?*/ Answer: Un-initialized variables have unknown (garbage) values. int value,total = 0,count = 0; Assignment statement
  • 65. www.cyberlabzone.com while(expression) statement; • if expression evaluates to true, the statement is executed and then execution loops up and re-evaluates expression; otherwise execution passes to the next statement in the program. • while statement format while(value >= 0.0); /* Error! Don’t put semicolon here */ /* This is an example of a logical error*/ while (EOF != scanf("%i", &value)) { /* read value */ total = total + value; count = count +1; } /* end of while loop */ While-loop Statement
  • 66. www.cyberlabzone.com We can also execute multiple statements when a given expression is true: while (expression) { while-statement1; while-statement2; while-statementn; } • if expression evaluates to true, all the statements are executed and then execution loops up and re-evaluates expression; otherwise execution passes to the next statement in the program. While-General Format
  • 67. www.cyberlabzone.com { statement1; statement2; . . . statementn; } A sequence of statements surrounded by a pair of curly braces is called a block or compound statement 1) From outside, the compound statement looks like a single statement. A compound statement can go where any single C statement can go. (e.g. a branch of if-else, body of a for loop, ...) What is a Compound statement?
  • 68. www.cyberlabzone.com What is all this fuss about blocks? A block is any compound statement that may include variable declaration(s). 1.As a compound statement, from outside, the block looks like a single C statement. A block can go where any single C statement can go. 2.The importance of a block is that, the curly braces of the block delimit the Scope (i.e. the region of validity) of the variables declared in the block. 3. The concept of Scoping lies at the heart of Structured Programming, as will be discussed in a future lecture on Modularity.
  • 69. www.cyberlabzone.com The program makes use of the fact that the scanf function returns and integer value representing the number of successful conversions. For example in the code fragment: Example: int number,value1,value2,value3; number = scanf(“%d%d%d”,&value1,&value2,&value3); the variable number could take the value 0,1,2 or 3. EOF is a built-in constant in C(usually assigned -1). If you are checking for End-of-File then use this constant. EOF != scanf("%i", &value) Scanf-Revisited
  • 70. www.cyberlabzone.com To fix the above use the cast operator where data_type is a valid C data type. float result; int total = 10 , count = 4 ; result = total / (float) count; /* result now has the value 2.5 */ Example, float result; int total = 10 , count = 4 ; result = total / count; /* result has the value 2.0 */ ( data_type ) printf(”Average of the %i numbers = %fn“,count, total/(float)count ); Arithmetic Conversions-Cast
  • 71. www.cyberlabzone.com data_type1 x; data_type2 result; result = x; If x and result have different data types then an automatic conversion takes place. Data could be lost. Example, float x = 3.1416; int result; result = x; /* result now has the value 3 */ 1) Conversion of assigned values Arithmetic Conversions
  • 72. www.cyberlabzone.com +, - , * , /x op y ; where op is If x and y have different (mixed) data types then C automatically converts data from the lower rank to the higher rank and then performs the computation. Note: % (modulus) is only defined on integers. The ranking is given by the following table. long double Higher double float long integer integer short integer Lower 2) Conversion of values with mixed data types in an expression using arithmetic operators Arithmetic Conversions
  • 73. www.cyberlabzone.com Example, float result , x = 3.1416; int y = 3; result = x + y; /* result now has the value 6.1416 */ Example, int x = 2.5; float result, y; y = x; result = 1 / y; /* result now has the value .5 */ Arithmetic Conversions
  • 74. www.cyberlabzone.com 1. Problem Definition Write a program that reads a file of characters one character at a time and writes out each non-blank character to another file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = characters in a file “input2.dat” Assume this file is non-empty. Output=Non-blank characters from input2.dat are output to the file output2.dat 3. Develop Algorithm (processing steps to solve problem) C Problem Example
  • 75. www.cyberlabzone.com Flowchart while EOF != scanf c TrueFalse scanf c if c != ‘ ‘ /* a blank */ printf c C Problem Example
  • 76. www.cyberlabzone.com /* C Program to remove the blanks from a text file. */ #include <stdio.h> void main(void){ char c; scanf("%c",&c); do { if (c != ' ') printf("%c",c); } while(EOF != scanf("%c",&c)); } C Problem Example
  • 77. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem2.c , and make sure to save the file. 2. Use xemacs to create an input file input2.dat and enter in any number of lines of text including blanks. Save and exit this file. 3. Compile the problem2.c code by typing gcc problem2.c 4. Run the program using Unix redirection < and > a.out < input2.dat > output2.dat 5. View the contents of output2.dat more output2.dat C Problem Example-Execution
  • 78. www.cyberlabzone.com do statement; while(expression); • The statement is executed first. Then if expression evaluates to true, execution loops up and the statement is executed again; otherwise execution passes to the next statement in the program. The general form of the do-while statement is: • do/while statement format do { while-statement1; while-statement2; while-statementn; } while (expression); C Problem Example
  • 79. www.cyberlabzone.com 1. Problem Definition Use a for statement to read a list of integers from a file and compute the average. The first number in the list gives the count of the numbers to be read. This first value is not used in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input3.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm Use a counter controlled loop. (processing steps to solve problem) C Problem Example
  • 80. www.cyberlabzone.com Flowchart for i = 1 ; i <= count; i=i+1 scanf value total = total + value; TrueFalse total = 0; scanf count printf total/(double) count C Problem Example
  • 81. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count; int i; /* loop counter */ scanf(“%i”,&count); for(i=1;i<=count;i=i+1) { scanf(“%i”,&value); /* read value */ total = total + value; } /* end of for loop */ /* Output the average. */ printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C Problem Example
  • 82. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem3.c , and make sure to save the file. 2. Use xemacs to create an input file input3.dat and enter in integers into this file .The first integer is the count of integers to be averaged. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem3.c 4. Run the program using Unix redirection < a.out < input3.dat C Problem Example-Execution
  • 83. www.cyberlabzone.com for(init. expressions ; expression ; update stmnts. ) statement1; C allows more than one initialization expression or update statement but these statements or expressions must be separated by a comma not a semicolon. Also, if there is more than one init. expression or update statement then the order of execution is from left to right. The initialization expressions are executed once (and only once) . If expression evaluates to true, statement1 is executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program. The following order of must be observed … init. expressions; expression ; update stmnts for-loop Statement
  • 84. www.cyberlabzone.com for(init. expressions ; expression ; update stmnts. ){ statement1; statement2; . . . statementn; } The initialization expressions are executed once (and only once) , next: if expression evaluates to true, the statements statement1,... ,statementn are executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program. for-General Format
  • 85. www.cyberlabzone.com Write a code fragment to add the integers from 1 to 100. int i,total; total = 0; for(i=1;i<=100;i=i+1) total = total + i; The above code could be re-written as: int i,total; for(i=1, total = 0; i<=100; total=total+i, i=i+1); but not as: int i,total; for(i=1, total = 0; i<=100; i=i+1, total=total+i); Why not? The order of the statements is critical! for-Examples
  • 86. www.cyberlabzone.com 1. Problem Definition Use a for statement to read a list of integers from a file and compute the average. Read the integers until the sentinel value of -999 occurs. Do not use the sentinel value in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input4.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) C Problem Example-Revisited
  • 87. www.cyberlabzone.com Flowchart for i = 1 ; ; i=i+1 scanf value if value == -999 break; total = total+value; TrueFalse total = 0; printf total/(float) (i-1) C Problem Example-Revisited
  • 88. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count; int i; /* loop counter */ for(i=1; ;i=i+1) { scanf(“%i”,&value); /* read value */ if (value == -999) /* -999 is the sentinel value */ break; total = total + value; } /* end of for loop */ /* Output the average. */ count = i-1; printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C Problem Example-Revisited
  • 89. www.cyberlabzone.com Omitting the logical expression in a for statement means that the for statement executes as an infinite loop. for(i=1; ;i=i+1) { As with the switch statement the break statement causes the termination of the loop but not the program. Break Statement
  • 90. www.cyberlabzone.com A one dimensional array is a list of data values, with all values having the same data type(the base type), such as: • integer • float • double • char Technically, an array is a uniform data structure. Individual array elements are referenced using the array name and a subscript that identifies the element position in the array. What is an Array? Array
  • 91. www.cyberlabzone.com For a one dimensional array, we specify the array name, its base data type, and the number of storage locations required using declarations such as int a[25]; float x[100], y[100]; which specifies 25 integer locations for a and 100 floating- point locations for arrays x and y. Storage for array elements are in contiguous locations in memory, referenced by subscript(or index) values starting at 0. Thus for array a above, the storage is . . . a[0] a[1] a[24] RAM Declaring an Array
  • 92. www.cyberlabzone.com We can initialize array elements in declaration statements; e.g., int counts[5] = {1, 2, 3, 4, 5}; int evens[] = {2, 4, 6, 8}; The array size could also be specified using a symbolic constant: #define ARRAY_SIZE 25 int a[ARRAY_SIZE]; . . . /* evens has 4 elements */ We cannot specify more initial values than there are array elements, but we can specify fewer initial values, and the remaining elements will be initialized to 0. e.g., int b[10] = {2}; double x[250] = {0}; Declaring and initializing an Array
  • 93. www.cyberlabzone.com Note: when referencing a particular element of an array use square brackets, not parenthesis or curly braces. Given that the array x is declared as: int x[250]; To initialize a large array to a nonzero value - say 10, we can use a loop. e.g., for (k = 0; k <= 249; k = k+1) x[k] = 10; k is a subscript Arrays-Subscripting
  • 94. www.cyberlabzone.com A subscript value for an array element can be specified as any integer expression. For example, given the following declarations: double y[4] = {-1.0, 12.0, 3.5, 3.2e-2}; int c = 2; the following statement would assign the value of 5.5 to y[1] y[2 * c - 3] = 5.5; Arrays-Subscripting
  • 95. www.cyberlabzone.com Given an integer value n, we can use the following code to compute and store the first n Fibonacci numbers in an array: 1. Problem Definition Write a program “fib” that prompts the user for an integer n. The program prints the first n Fibonacci numbers. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = n - the count of Fibonacci Numbers to be printed Output= Fib Numbers printed to screen. 3. Develop Algorithm Use the formula: fib0= 1, fib1 =1 and for k > 1 fibk = fibk-1 + fibk-2 Example-Fibonacci Numbers
  • 96. www.cyberlabzone.com #include <stdio.h> /* C program to print the first n Fibonacci Numbers. */ void main(void){ int k,n; int fib[100] = {1,1}; /* note: n must be <= 100 , why ? */ printf(“How many Fibonacci number do you want listed?”); scanf(“%i”,&n); for (k = 2; k < n; k++) /* the ++ is the increment operator */ fib[k] = fib[k-1] + fib[k-2]; /* print the results, four per line */ for (k = 0; k < n;++k){ if (k % 4 == 0) printf(“n”); printf("%8i", fib[k]); /* that’s 8 ints */ } /* end of for loop */ printf(“n”); } /* end of main */ (For large values of parameter n, we would need more space for each print column. Also, even with data type long , the calculated values may become too large for the allocated storage space.)
  • 97. www.cyberlabzone.com : . Since incrementing and decrementing (negative increments) are common programming operations, the C language provides shortcut Increment / Decrement operators. ++k Increment k by 1 and use incremented value in expression containing ++k. k++ Use the current value of k then increment by 1. --k Decrement k by 1 and use decremented value in expression containing --k. k-- Use current value of k then decrement by 1. ++k; Increment and Decrement Operators
  • 98. www.cyberlabzone.com ++k; /*C statement k = k + 1; */ int x,z; int y = 1; int a = 2; x = y + a++; /* now x = 3 , y = 1 , a = 3 */ z = x + --a; /* now a = 2, z = 5, x = 3, y = 1 */ z = --x * ++y; /* now x = 2, y = 2, z = 4, a = 2 */ x = a++ / --y; /* now y = 1, x = 2, a = 3, z = 4 */ Note: The increment/decrement operators can be applied only to single variables. They cannot be applied to expressions. Increment and Decrement Operators-Examples
  • 99. www.cyberlabzone.com Given an integer value n, we can use the following code to compute and store the first n Fibonacci numbers in an array: 1. Problem Definition Write a program that inputs a list of numbers into an array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = list of reals in a file “input.dat” . We will use Unix redirection to read values from this file. Output= The average and the list of differences. Example-Average and difference List
  • 100. www.cyberlabzone.com int counter,k; double datVal[500]; /* 500 element max */ double datAve; double sum = 0.0; /* read the file and compute the average */ counter = 0; while (EOF != scanf("%lf", &datVal[counter])){ sum += datVal[counter]; /* += is an assignment operator */ counter++; } /* compute and print the average */ datAve = sum /counter; printf(“The average is:%lf n", datAve); /* compute and print the diff list */ for(k=0;k<counter;++k) printf(“%lfn", datVal[k]-datAve); Example-Average and difference List
  • 101. www.cyberlabzone.com - a shortcut method for writing assignment statements of the form var1 = var1 op expression; Using an "assignment operator", we can rewrite the above as var1 op= expression; where op can be any one of the arithmetic binary operators: + - * / % sum += datVal[counter]; Assignment-operators
  • 102. www.cyberlabzone.com sum += datVal[counter]; or sum = sum + datVal[counter]; k += 5; or k = k +5; n -= 4; or n = n -4; a *= 2.0; or a = a*2.0; x /= b; or x = x/b; remainder %= 6; or remainder = remainder % 6; newValue += (a-b)/(2*c); or newValue = newValue + (a-b)/(2*c); Assignment-operators-Examples
  • 103. www.cyberlabzone.com Unlike many other languages, there is no data type for character strings in C. But we can reference a string as a one dimensional array of characters. That is, each element of the array is a single character. Character Arrays
  • 104. www.cyberlabzone.com char aString[5] = "Zip!"; char atomic[ ] = "hydrogen"; char aString[] = {'Z', 'i', 'p', '!', '0'}; Declaring a string array with character constants Declaring character arrays with a string constant IMPORTANT!!! In C, you must always terminate a character array with the NULL character, ‘0’ . Therefore, the array size of your character array should be one plus the maximum length of the string you want to store. Example: In the declaration char atomic[ ] = "hydrogen"; “atomic” is an array of nine elements, the last being ‘0’ Declaring a Character Array
  • 105. www.cyberlabzone.com char atomic[ ] = "hydrogen"; You may declare and initialize a character arrays with a string constant as in, but you cannot assign an array in the same manner, e.g. atomic = "hydrogen"; not legal in C! One of the mysteries of C! Declaring a Character Array
  • 106. www.cyberlabzone.com Use the %s conversion specifier to read in a string of characters. Any blanks will be skipped. There should not be any blank character input such as in the string “Hello World”, since a blank signals an end of input for the string. Again, don’t forget to declare the array size as one more than the length of the longest string that you want to read in order to accommodate the NULL character. char strArray [10]; printf("Input a string with at most nine characters ”); printf("with no blanks in the string: n"); scanf("%s", strArray); /* Notice: No & is used for an array argument! */ printf(“n%s", strArray); Input and output of Strings
  • 107. www.cyberlabzone.com You can use the %c conversion specifier to output the string character by character. k = 0; while (strArray[k] != NULL) printf("%c", strArray[k++]); NULL is a built-in constant (‘0’). You must have #include <stdio.h> in your file to be able to use NULL. Outputing a String
  • 108. www.cyberlabzone.com • strlen(str) - string length, not counting NULL char. • strcpy(str1, str2) - copy string2 to string1. • strcmp(str1, str2) - returns a negative , zero or positive int depending on whether str1 is lexicographically less than, equal or greater than str2 respectively. • strncmp(str1,str2,n) - like strcmp but just the first n characters of str1 are compared to str2. #include <string.h> Arguments str1 and str2 in the following functions can be character array names, string pointers(discussed in a future lecture), or string constants. See Chapter 13.3 for examples. There are many other string functions (see Appendix G p. 1036 for a complete list). String.h Library Functions
  • 109. www.cyberlabzone.com 1. Problem Definition Write a C program that converts a Morse code string into alphabet. (Morse code is a sequence of dots and dashes). If the input is not a valid string (see table on next slide) then a message is output to the user. You will do a variation of this program in a future lab assignment. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = a single string of characters. Output= A single letter A-Z. Example-Morse Code
  • 110. www.cyberlabzone.com A .- , N -. B -... O --- C -.-. P .--. D -.. Q --.- E . R .-. F ..-. S ... G --. T - H .... U ..- I .. V ...- J .--- W .-- K -.- X -..- L .-.. Y -.-- M -- Z --..
  • 111. www.cyberlabzone.com #include <stdio.h> #include <string.h> typedef char string[5]; void main(void){ string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
  • 112. www.cyberlabzone.com char alphabet[26] = {'A','B','C','D','E','F','G','H','I','J','K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; char input[5]; int i; int flag = 0; /* flag = 0 means match not found , flag = 1 means match found */ printf("Please enter a Morse code string:"); scanf("%s",input); /* no & for array */
  • 113. www.cyberlabzone.com /* loop through the Morse array to find a match */ for(i=0;i<26;++i) if (strcmp(input,morse[i]) == 0) { printf("%cn",alphabet[i]); flag = 1; break; /*terminate for loop */ } if (flag == 0) printf("Input not a valid Morse character.n"); } /* end of main */
  • 114. www.cyberlabzone.com The typedef mechanism in C enables a programmer to create a “custom” data-type. Examples of the use of typedef are typedef int blah; /* don’t do this !!!!! */ typedef char string[5]; In the first example we give another name or alias to the data-type int . In the second example we create a new data-type named string. typedef
  • 115. www.cyberlabzone.com To declare a variable of data-type blah , blah x; this declaration is equivalent to int x; To declare a variable of data-type string , string var =“init”; /* declare and initialize */ scanf(“%s”,var); /* we can read in a string of chars */ var = “next”; But we can’t do this!!! The declaration string morse[26]; declares morse as an array of 26 elements. Each element has data-type string. typedef
  • 116. www.cyberlabzone.com The declaration and initialization: string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.. " }; declares morse as an array of 26 elements with morse[0] = “.-” morse[1] = “-...” and so on... typedef
  • 117. www.cyberlabzone.com - Two dimensional arrays are declared similarly to one dimensional arrays: char t[20][10]; (and referred to as a matrix, or as a "table") The first subscript gives the row number, and the second subscript specifies column number. Two-Dimensional Arrays
  • 118. www.cyberlabzone.com We can also initialize a two-dimensional array in a declaration statement; E.g., int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; which specifies the elements in each row of the array (the interior braces around each row of values could be omitted). The matrix for this example is        654 321 m Declaration and Initialization
  • 119. www.cyberlabzone.com Specification of the number of rows could be omitted. But other subscript specifications can not be omitted. So, we could also write the initialization as int m[ ][3] = {{1, 2, 3}, {4, 5, 6}}; Declaration and Initialization
  • 120. www.cyberlabzone.com int a[2][3]= {1,2,3,4,5,6}; specifies 6 integer locations. Storage for array elements are in contiguous locations in memory in row major order (unlike column major order in Fortran), referenced by subscripts(or index) values starting at 0 for both rows and columns. a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] RAM 1 2 3 4 5 6 Memory Storage for a Two dimensional Array
  • 121. www.cyberlabzone.com 1. Problem Definition Assume we have a file “in.dat” (located in the pwd) consisting of 10 rows of 10 integers per row (100 integers total). Write a C program which reads from the file and stores the numbers in a two dimensional array named ‘mat’, computes the largest of all of these numbers and prints the largest value to the screen. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = from file “in.dat” Output= Largest of the 100 integers printed to screen. 3. Develop Algorithm Use Unix redirection to read file “in.dat”. Use nested for loop to go through two dimensional array to find the largest value. Example-Maximum Value
  • 122. www.cyberlabzone.com #include <stdio.h> void main(void){ int row, col, maximum; /* Declare a 2-D array called ‘mat’ which can hold a 10-by-10 */ /* matrix of integers */ int mat[10][10]; /* Write code here to read from the file ‘in.dat’ */ for(row=0;row<10;++row) for(col=0;col<10;++col) scanf(“%d”,&mat[row][col]); /* Write code to find the largest value in the array ‘mat’ */ maximum = mat[0][0]; /* why ??? */ for(row=0;row<10;++row) /* How does this work??? */ for(col=0;col<10;++col) if (mat[row][col] > maximum) maximum = mat[row][col]; /* Print the largest value to the screen */ printf(“ max value in the array = %dn”,maximum); }
  • 123. www.cyberlabzone.com Another example of the use of typedef is: typedef double matrix[size][size]; In this example we create a new data-type named matrix. We can declare a variable of data-type matrix by matrix a; this declaration is equivalent to double a[size][size]; Typedef Revisited
  • 124. www.cyberlabzone.com Standard (ANSI) C allows up to 12 dimension. But more computation is required by the system to locate elements in multi-subscripted arrays. Therefore, in problems involving intensive numerical calculations, we should use arrays with fewer dimension. We can also use 3, 4, … dimensional arrays, e.g., threeDArray [i][j][k]; Higher Dimensional Arrays
  • 125. www.cyberlabzone.com In slides 2-15 and 11-15 we discussed a method for creating programs. In step three “Develop the Algorithm”, the nature of the programming problem may suggest that we use top down programming (as opposed to bottom-up programming , ...) An analogy for top-down design is the following: Suppose a general contractor was hired to construct a commercial building. The contractor would need to know where to build and what are the blue- prints. Then the contractor would hire various sub-contractors to dig foundation, install electric, plumbing, frame, roof. That is, the large job would be broken into smaller jobs, however these jobs must be performed in some sequence and not at random. Function-”Top Down Design”
  • 126. www.cyberlabzone.com In top-down design for programming, we specify the first function to be invoked (the top function or “general contractor”). In C the top function is called “main”. The programmer then refines “main” into its component functions (sub-contractors), which may in turn be refined into further functions, and so on. Function-”Top Down Design”
  • 127. www.cyberlabzone.com 1. Problem Definition Write a program that inputs a list of numbers into an array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = list of reals in a file “input.dat” . We will use Unix redirection to read values from this file. Output= The average and the list of differences. Example-Average and difference List
  • 128. www.cyberlabzone.com #include <stdio.h> int read(double datVal[]); /* prototype for read function */ double ave(int counter,double datVal[]); /* prototype for ave function */ void diff(double datAve, int counter, double datVal[]); /* prototype for diff function */ void main(void){ int counter,k; double datVal[500]; /* 500 element max */ double datAve; counter = read(datVal); /* read file into datVal */ datAve = ave(counter,datVal); /* compute & print average */ printf(“The average is:%f n", datAve); diff(datAve,counter,datVal); /* compute diff list */ for(k=0;k<counter;++k) /* print the diff list */ printf(“%lfn", datVal[k]); } /* end of main */
  • 129. www.cyberlabzone.com /* read function */ int read(double array[]) { int count = 0; while (EOF != scanf("%lf", &array[count])){ ++count; } return count; } /* end of read function */ /* ave function */ double ave(int count,double array[]){ int i; double sum = 0.0; for (i=0;i<count;++i) sum += array[i]; return sum/count; } /* end of ave function */ /* diff function */ void diff(double average, int count, double array[]){ int i; for (i = 0;i<count;++i) array[i] -= average; } /* end of diff */
  • 130. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem1.c , and make sure to save the file. 2. Use xemacs to create an input file input.dat and enter in integers into this file. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem1.c 4. Run the program using Unix redirection < a.out < input.dat C Problem Example-Execution
  • 131. www.cyberlabzone.com Example: If the file input.dat has the values: 1.0 2.0 3.0 4.0 5.0 Then the program would execute as follows: dclsn70> a.out < input.dat The average is:3.000000 -2.000000 -1.000000 0.000000 1.000000 2.000000 dclsn70> C Problem Example-Execution
  • 132. www.cyberlabzone.com #include <stdio.h> /* include statements */ int read(double datVal[]); /* prototype for read function */ void main(void) /* definiton of the main function */ { /* C code here */ } /* end of main */ int read(double array[]) /* function definition */ { /* more C code here */ } /* end of read */ One method to code the function “read”in C : Functions-Prototypes Functions
  • 133. www.cyberlabzone.com In the latest versions of standard C ("ANSI C"), the function prototype is used to define the data type to be returned by the function, the number and data type of function parameters, and the order of the function parameters. This info is used by the C compiler to validate calls to the function. A general principle in C is that you must declare or define the variable or function before you use them. Functions-Prototypes
  • 134. www.cyberlabzone.com The actual variable or array name is not needed in the function prototype. Examples: Instead of the following prototypes int read(double datVal[]); double ave(int counter,double datVal[]); void diff(double datAve, int counter, double datVal[]); we could have used int read(double []); double ave(int ,double []); void diff(double , int , double []); Functions-Prototypes
  • 135. www.cyberlabzone.com #include <stdio.h> /* include statements */ /* Since the definition of read occurs before it is */ /* used (called) by main, we don’t need a prototype.*/ int read(double array[]) /* function definition */ { /* C code for read here */ } /* end of read */ void main(void) /* definiton of the main function */ { /* C code for main function here */ } /* end of main */ Another method to code the function “read ” in C without using a prototype : Functions-Prototypes
  • 136. www.cyberlabzone.com • The function definition in C is of the form: return-type function-name(parameter-list) { /* function code */ return (value); /* parenthesis optional */ } • The “value” can be a single variable, constant, or any C expression. • The data type of “value” should be of type “return-type”, if not then a conversion of the “value” to the “return-type” is specified by the C compiler. • If the “return-type is void then the programmer can omit the return statement or code: return ; /* return nothing */ Function- definition
  • 137. www.cyberlabzone.com /* function called */ int x = 1; float y = 2.0; float value; double z = 5.0; value = sum(x,y,z+4.0); /* more code here */ /* sum adds an integer a float and a double and returns */ /* a double */ double sum(int a, float b, double c) { double result; result = a + b + c; return result; } Data-types agree! Since value has type float and sum returns a double, a conversion takes place. Function Type Checking
  • 138. www.cyberlabzone.com • A function that does not return a value is declared to be of type void. e.g., void printFunction (int, int); • If a function takes no parameters, we specify the parameter list as void. e.g., void printPageHeading (void); It is also possible to specify an "empty" parameter list: void myFunction ( ); - argument checking is "turned off", so that anything can be passed to myFunction. Best to avoid this in C. Function Type Checking
  • 139. www.cyberlabzone.com • By default , if you omit the data type of the return value, C assumes that the function returns an int value (not void). Therefore the following function header: main(void) int main(void) is equivalent to: Function Type Checking
  • 140. www.cyberlabzone.com • A function may be called from any function (including itself) in C. • A call is of the form: function-name(argument-list) • To “call” or invoke a function, you must pass the same number of arguments for which the function has been defined. The order of the arguments is important!!! • If the data types in the argument list do not match the data types in the parameter list, a conversion(or coercion) takes place. Function Call
  • 141. www.cyberlabzone.com . . . int x = 1; double y = 2.0; float result; /* function called */ result = F1(x,x+1,sin(y)); /* argument list */ . . . } /* end main */ /* data types match */ float F1(int var1, int var2, double var3){ /*parameter list */ /* function code */ return (value);} Example-Function Type Checking
  • 142. www.cyberlabzone.com • Arrays are passed as call-by-reference. counter = read(datVal); . . . int read(double array[]) { int count = 0; while (EOF != scanf("%lf", &array[count])){ ++count; } return count; } 2.0 1.0 1200 Main Memory after call unknowndatVal[0] datVal[1] datVal[2] 1200 Main Memory before call datVal[0] datVal[1] datVal[2] . . . . . . . . . . . . The parameter “array” can be considered as a pseudonym or alias for “datVal”. There is only one array in memory. Passing arguments in a function Call
  • 143. www.cyberlabzone.com For two dimensional arrays, we could omit specification of the number of rows in function prototype and header. But we must include size declaration for the number of columns. (see example on next slide) Two-Dimensional Arrays Function Parameters
  • 144. www.cyberlabzone.com #define ROWS 10 #define COLS 5 void doSumpin(int [][COLS]); int main (void) { int a[ROWS][COLS] = {{0}}; doSumpin (a); } void doSumpin(int b[][COLS]){ /* array passed by reference */ ... } /* function prototype */ /* function call */ Examples of passing 2-D arrays
  • 145. www.cyberlabzone.com We can replace any 2-D array with an equivalent 1-D array. For instance the following 2-D array int A[2][3]= {1,2,3,4,5,6}; A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] RAM 1 2 3 4 5 6 can be replaced with the equivalent 1-D array, int a[6]= {1,2,3,4,5,6}; however a[0][0] , a[0][1] , … is not defined. Alternative to 2-D arrays
  • 146. www.cyberlabzone.com In order to reference A[0][0] , A[0][1] , … with a[ ] we use the following formula, int a[]= {1,2,3,4,5,6}; A[row][col] = a[row*3 + col] A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] RAM 1 2 3 4 5 6 a[0] a[1] a[2] a[3] a[4] a[5] Alternative to 2-D arrays
  • 147. www.cyberlabzone.com 1. Problem Definition Write a function that performs matrix – vector multiplication. Assume that the matrix is passed as a 1-D array using the formula on the previous slide. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = A matrix and vector of reals . Output= The vector that results from the matrix - vector multiplication. Alternative to 2-D arrays
  • 148. www.cyberlabzone.com /* The function mvmult works with any size matrix a. */ /* This function assumes that the number of Cols of a is */ /* equal to the number of Rows of invec */ /* a is 1-D version of matrix A[Rows][Cols] */ void mvmult(double a[], int Rows, int Cols, double invec[], double outvec[]){ int row, col; /* A[row][col] = a[row*cols + col] */ for(row=0;row<Rows;++row){ outvec[row] = 0.0; for(col=0;col<Cols;++col) outvec[row] += a[row*Cols +col] * invec[col]; } } /* end of mvmult */
  • 149. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file mvmult.c , and make sure to save the file. 2. Use xemacs to create a file test.c and write the main function that calls the mvmult function. Don’t forget the prototype! 3. Compile the code in the two files mvmult.c and test.c by typing, gcc test.c mvmult.c -o mult 4. Run the program mult C Problem Example-Execution
  • 150. www.cyberlabzone.com #include <stdio.h> #define ROWS 2 #define COLS 3 mvmult(double [], int , int double [] , double []); /* prototype */ void main(void){ double a[ROWS*COLS] = {1,2,3,4,5,6}; double invec[COLS] = {1,1,1}; double outvec[ROWS]; int row,col; mvmult(a,ROWS,COLS,invec,outvec); /* call mvmult */ for(row=0;row<ROWS;++row) /* print the values of a */ for(col=0;col<COLS;++col) printf("a[%i][%i] = %lfn",row,col,a[row*COLS+col]); for(row=0;row<COLS;++row) /* print invec */ printf("invec[%i] = %lfn",row,invec[row]); for(row=0;row<ROWS;++row) /* print outvec */ printf("outvec[%i] = %lfn",row,outvec[row]); }
  • 151. www.cyberlabzone.com eesn23> mult a[0][0] = 1.000000 a[0][1] = 2.000000 a[0][2] = 3.000000 a[1][0] = 4.000000 a[1][1] = 5.000000 a[1][2] = 6.000000 invec[0] = 1.000000 invec[1] = 1.000000 invec[2] = 1.000000 outvec[0] = 6.000000 outvec[1] = 15.000000 eesn23> C Problem Example-Execution
  • 152. www.cyberlabzone.com • Non-arrays are passed as call-by-value. datAve = ave(counter,datVal); . . . double ave(int count,double array[]){ int i; double sum = 0.0; for (i=0;i<count;++i) sum += array[i]; return sum/count; } 1196 Main Memory while executing ave 5 counter 1196 Main Memory before call counter . . . The value of the parameter “counter” is copied into the memory location for the variable “count”. Therefore any change to “count” would have no affect on “counter”. 1192count 5 55 Passing arguments in a function Call
  • 153. www.cyberlabzone.com 1. Problem Definition Write a function “sinc” that computes the value of sin(x)/x . If x is zero return 1.0. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = One real number of type double. Output= sin(x)/x as a double if x is not zero else 1.0. 3. Develop Algorithm Use an if statement to check for a non-zero value. But since the user could input 1.0e-600 , this may cause an overflow when the value 1/x is computed so we will actually not check for equality with zero but will check if the input value is close to zero. Example-Call-by-value
  • 154. www.cyberlabzone.com #include <stdio.h> #include <math.h> double sinc (double); /* function prototype */ void main(void){ double x, y; printf("Enter a number: "); scanf("%lf", &x); y = sinc(x); /* function call */ printf(“n sinc(%f) = %f n”, x, y); } double sinc (double x){ /* function header */ if (fabs(x) < 1.0e-15) return 1.0; else return sin(x) / x; } /* notice that sinc calls sin */ Example: function sinc(x)=sin(x)/x
  • 155. www.cyberlabzone.com Using Xemacs, user-defined functions can be typed into the same file as “main”. Functions may be typed into a separate file. For example, suppose “main” is in the file test.c and the user defined function “sinc” is entered into the file func.c then to compile both “main” and “sinc” you would type (at the Unix prompt) gcc test.c func.c -lm Note the use of the “-lm” option The -lm option is needed only if you use a math library function in “main” or “sinc”. Don’t forget that if you put the function “sinc” into a separate file, then you must still put the prototype for “sinc” in the same file as main. The prototype for “sinc” must precede the function main. Example: Location of user-defined functions
  • 156. www.cyberlabzone.com We present some methods to debug C programs. We can categorize errors as A) compile errors B) run-time errors C) Logical errors Logical errors are the most difficult since they may involve using the incorrect formula. This has nothing to do with C so we will not discuss these types of errors any further. Debugging
  • 157. www.cyberlabzone.com We present some methods to debug C programs. A) compile errors If your program doesn’t compile. 1) Check the line number that gcc returns for the error. Note: a warning message is not an error. If you only have warning messages gcc will go ahead and compile your code. 2) Sometimes the line number of the error is not where the actual error occurred. An error on one line can produce errors messages for subsequent lines. Therefore it is best in general to fix the errors occurring on the earliest line numbers first. Also, if you can’t find an error on the line specified by gcc then look at the preceding lines. Compiler Errors
  • 158. www.cyberlabzone.com A) compile errors(continued) 3) If you can’t find the error specified by gcc then try removing some code by using the #ifdef feature of C. This is a preprocessor command that will optionally compile (or not compile) a group of statements. Or gcc allows you to use the characters // at the beginning of a line to comment out that line of code. Compiler Errors
  • 159. www.cyberlabzone.com Example: On slide 25 add a semicolon to the which contains the code: if (fabs(x) < 1.0e-15); When you compile you get an error message. The error message states the problem is before line 15 but the actual problem occurred on line 13. dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' test.c: In function `sinc': test.c:15: parse error before `else' dclsn70> Compiler Errors
  • 160. www.cyberlabzone.com Example: Use #ifdef to have the compiler skip compiling line(s) of code. From the previous problem add the #ifdef as follows: double sinc (double x){ /* function header */ if (fabs(x) < 1.0e-15); #ifdef foo return 1.0; #endif else return sin(x) / x; } /* notice that sinc calls sin */ Compiler Errors
  • 161. www.cyberlabzone.com From the above we can see that the code now compiles without errors. The reason for this is that the if-else statement is now a valid statement. If the condition is true do nothing else return sin(x)/x . Even if you don’t see the extra semicolon, at this point you know that your if-else statement was the source of your previous compile error. dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> Compiler Errors
  • 162. www.cyberlabzone.com B) run-time errors If your program compiles without errors but you get incorrect values or a message like “Segmentation fault”. 1) Use the statement: fprintf(stderr, “format string”,variable-list); Run-time Errors
  • 163. www.cyberlabzone.com On slide 25 remove the “&” symbol to obtain the following line: scanf("%lf", x); When you compile and run a.out you get the run-time error “Segmentation Fault”, dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> a.out Enter a number: 3.14159 Segmentation fault dclsn70> Run-time Errors
  • 164. www.cyberlabzone.com Example: Use the fprintf statement to debug your code. void main(void){ double x, y; printf("Enter a number: "); fprintf(stderr,“Before scanfn”); scanf("%lf", &x); fprintf(stderr,”After scanf x = %lfn”,x); y = sinc(x); /* function call */ fprintf(stderr,“After sincn”); printf(“n sinc(%f) = %f n”, x, y); } Run-time Errors
  • 165. www.cyberlabzone.com dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> a.out Before scanf Enter a number: 3.14159 Segmentation fault dclsn70> Since only “Before scanf” prints to the screen (specified by stderr). This indicates that the problem occurs in the scanf statement. Run-time Errors
  • 166. www.cyberlabzone.com 1. Problem Definition Write a function “swap” that has two integer input arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm temp = a; a = b; b = temp; Example-call-by-value
  • 167. www.cyberlabzone.com /* C Function to swap values. */ #include <stdio.h> void swap(int, int); /* prototype for swap */ void main(void){ /* function header */ int x = 1; int y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int a , int b){ int temp = a; a = b; b = temp; return; } Example-bad Swap!!!
  • 168. www.cyberlabzone.com x 1000 Main Memory before call 1 The swap function will successfully swap the values of the variables a and b. But, since non-arrays are passed by value the swap of the values for a and b will not have any affect on the variables x and y. It is important to note that even if we had used the variable names x and y rather than a and b the swap function would still not work. See the next slide... y 2 Main Memory while executing swap, but before the return statement x 1000 1 y 2 a 2 b 1 3000 Why swap doesn’t work.
  • 169. www.cyberlabzone.com /* Modified function to swap values. */ #include <stdio.h> void swap(int, int); void main(void){ int x = 1; int y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int x , int y){ /* we now use x and y */ int temp = x; x = y; y = temp; return; } Example-bad Swap!!!
  • 170. www.cyberlabzone.com x 1000 Main Memory before call 1 The C compiler will keep track of the variables x and y declared in main and the variables x and y declared in swap. The x in main is a different variable than the x in swap. Similarly for the y variable. The reason that the x variable in main is different than the x variable in swap is that two declarations of x occur in different blocks. That is the scope of the x in main is different than the scope of x in swap. One solution to the problem is to use pointer variables. We will discuss pointer variables in a future lecture. y 2 Main Memory while executing swap, but before the return statement x 1000 1 y 2 x 2 y 1 3000 Why the modified swap doesn’t work.
  • 171. www.cyberlabzone.com An identifier is a name that is composed of a sequence of letters, digits, and the ‘_’ underscore character. Variable names are identifiers and so are function names and symbolic constant names. The scope of an identifier is the portion of the program in which the identifier is visible or accessible. Both variables and functions have two attributes: type and storage class. The scope of a variable or function is related to its storage class. Scope of Identifiers
  • 172. www.cyberlabzone.com •Local Variables - are declared within a block and cannot be referenced by outside the block; i.e., each function is assigned its own "local" storage areas. •Global Variables - declared outside any block and are known to all blocks in the same file . By default, global variables are "static” storage class. In the examples on the following slides, drawing a picture of memory is helpful in understanding how scoping works. Scope of Variable Names
  • 173. www.cyberlabzone.com int globalVar = 1; /* global variable */ int myFunction(int); /* function prototypes */ void main(void){ /* local variable: result, in main */ int result; result = myFunction(globalVar); /* call myFunction */ printf(“%d”,result); /* prints “2” */ printf(“%d”,globalVar); /* prints “2” */ printf(“%d”,x); /* compile error! x not known in main */ } int myFunction(int x){ /* Local variable x */ ++x; printf(“%d”,x); /* prints value “2” */ printf(“%d”,globalVar); /*prints value“1” */ ++globalVar; return x; } Example1:Scope of Variables Program Design Example
  • 174. www.cyberlabzone.com globalVar 1000 Main Memory before call to Myfunction 1 result ??? Main Memory while executing MyFunction, but before ++globalVar; 1000 1 x 2 3000 ??? globalVar result Example1:Scope of Variables
  • 175. www.cyberlabzone.com globalVar 1000 Main Memory after call to Myfunction 2 result 2 Main Memory while executing MyFunction, but before return(x); 1000 2 ??? x 2 3000 globalVar result Example1:Scope of Variables
  • 176. www.cyberlabzone.com int globalVar = 1; /* global variable */ int myFunction(int); /* function prototypes */ void main(void){ /* local variable: result, in main */ int result; result = myFunction(globalVar); /* call myFunction */ printf(“%d”,result); /* prints “2” */ } int myFunction(int x){/* Local variables: x, globalVar */ int globalVar; /* new “local” variable */ printf(“%dn”,globalVar);/* prints ??? */ return x + 1; } Example2:Scope of Variables
  • 177. www.cyberlabzone.com int myFunction(int); /* function prototypes */ void main(void){ /* local variables: x,result in main */ int result, x = 2; result = myFunction(x); /* call myFunction */ printf(“%d”,result); /* prints “3” */ printf(“%d”,x); /* prints “2” WHY??? */ } int myFunction(int x){/* Local variable: x */ x = x + 1; printf(“%dn”,x);/* prints “3” */ return x; } Example3:Scope of Variables
  • 178. www.cyberlabzone.com /* C Function to swap values.This doesn’t work!!!! */ #include <stdio.h> int x; /* x is a global variable */ int y; /* y is a global variable */ void swap(int, int); /* prototype for swap */ void main(void){ x = 1; /* note that x and y are not declared here!!! */ y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int x , int y){ int temp = x; x = y; y = temp; return; } Example4:Scope of Variables
  • 179. www.cyberlabzone.com A function can be called by any other function, provided that either the function definition or its prototype is in the same file as the calling function and precedes the function call. If no prototype is specified for a function, its header serves as the function prototype. Note: Functions cannot be defined within each other Scope of Function Names
  • 180. www.cyberlabzone.com - Determines the storage duration and scope of identifiers, and also linkage between files. auto - creates storage for variables when the block that declares them is entered, and deletes the storage when the block is exited. Local variables have "auto" storage by default. e.g.,typing auto float a, b, c; is equivalent to typing float a, b, c; Storage Classes-auto
  • 181. www.cyberlabzone.com static - creates and initializes storage for variables when the program begins execution. Storage continues to exist until execution terminates. If an initial value is not explicitly stated, a static variable is initialized to 0. We can retain values of local variables by declaring them to be static. In the following example, the static variable sum is initialized to 1. static int sum = 1; The initialization takes place only once. If the above declaration appears in a user defined function , the first time the function is called, the variable sum is initialized to 1. The next time the function (containing the above declaration) is executed sum is not reset to 1. Storage Classes-static
  • 182. www.cyberlabzone.com extern - used to reference identifiers in another file. Function names are extern by default. e.g., extern int foreignVar; Storage Classes-extern
  • 183. www.cyberlabzone.com 1. Problem Definition Write a function “sum”that keeps a running total of the sum of every value passed to “sum”. To test this function, modify the previous program of slide 15 -3 that compute the average of values in a file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) Example-static variable
  • 184. www.cyberlabzone.com Flowchart for main while EOF != scanf value total = sum(value); ++count; TrueFalse count = 0; printf total/(double) count Example-static variable
  • 185. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> int sum(int); /* function protoype */ void main(void) { int value,total,count = 0; while (EOF != scanf("%i", &value)) { /* read value */ total = sum(value); ++count; } /* end of while loop */ printf(”Average of the %i numbers = %f n“,count,total/(double)count); } int sum(int val){ /* function header */ static int total_val = 0; /* static variable, */ total_val += val; return total_val; } Example-static variable
  • 186. www.cyberlabzone.com Pointer variables are variables that store memory addresses. Pointers variables are useful in passing storage addresses in function calls (call-by-reference) and for applications involving dynamic data structures (e.g., linked lists) Example: int *intPtr; float *floatPtr; declares intPtr to be a pointer variable to an object of type integer. and floatPtr to be a pointer variable to an object of type float. Pointers
  • 187. www.cyberlabzone.com We can write the pointer variable declaration as int* intPtr; or as int * intPtr; Note that when we declare more than two pointer variables in one line each pointer name requires an asterisk: int *ptr1, *ptr2; otherwise we are just declaring a regular variable , not a pointer variable. Pointer Declaration-syntax
  • 188. www.cyberlabzone.com There are two C operators that are necessary when using pointer variables. & - the address operator returns the address of a variable x 1000 3 ptrX 1000 ptrX holds the address of x. We say ptrX “points” to x. We will apply the & operator only to variables, e.g. &77 or &(x+1) are not valid. The declaration of ptrX initializes the variable ptrX = &x; Example: int x = 3; int * ptrX = &x; 1004 & Operator
  • 189. www.cyberlabzone.com Example: int x; int * pt; pt = &x; /* another way to assign an address to a pointer variable */ Suppose the address of the variable x is 9640 Then, the effect of pt = &x; will be: x pt Address 9640 9640 & Operator
  • 190. www.cyberlabzone.com int x; int * pt; pt = &x; To assign the value “3” to the variable x in C: x = 3; We can use the “ * ” operator to indirectly reference x. We can assign “3” to x by: *pt = 3; Here we use the fact that “pt” points to integer values. x pt Address 9640 96403 * - means "a pointer to" and is called an indirection operator or dereferencing operator, since a pointer "indirectly" references a value in a storage location. Example: *Operator
  • 191. www.cyberlabzone.com double *ptr; ptr = NULL; Assigning a NULL value (zero) to a pointer A null pointer points to nothing. We often depict it as ptr /*called a null pointer*/ Null Pointer
  • 192. www.cyberlabzone.com 1. Problem Definition Write a function “swap” that has two input integer arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm Pass the addresses of the variables and not their values. In the swap function the parameters that hold the addresses are pointers. Use the indirection operator to swap the values. Example-call-by-Reference
  • 193. www.cyberlabzone.com /* C Function to swap values. */ #include <stdio.h> void swap(int * , int *); void main(void){ /* function header */ int x = 1; int y = 2; swap(&x,&y); /* pass the addresses of x and y */ printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */ } void swap(int *ptrX , int *ptrY){ /* pointer variables */ int temp = *ptrX; *ptrX = *ptrY ; *ptrY = temp; return; } Example-good Swap
  • 194. www.cyberlabzone.com x 1000 Main Memory before call to swap 1 y 2 Main Memory while executing swap, after temp = *ptrX; but before *ptrX = *ptrY ; 10001 ptrX 1000 3000 2 x y 1004 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 195. www.cyberlabzone.com x y Main Memory while executing swap, after *ptrX = *ptrY ; but before *ptrY = temp; 10002 ptrX 1000 3000 2 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 196. www.cyberlabzone.com x y Main Memory while executing swap, after *ptrY = temp; but before return; 10002 ptrX 1000 3000 1 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 197. www.cyberlabzone.com The array name in C is assigned the address of the first element of the array. The following code will assign the address of xArray[0] to xArrayPtr : float xArray[50]; float * xArrayPtr; xArrayPtr = xArray; The assignment statement above is equivalent to: xArrayPtr = &xArray[0]; Array Names are Constant Pointers
  • 198. www.cyberlabzone.com A string literal (e.g. “A – your course graden”) is actually represented in C by a pointer to an address in memory that holds the first byte of the array of characters. Therefore the following declaration of the pointer variable “string” is valid: char * string = “A – your course graden”; and to print the value of “string” , use the “%s” conversion specifier, printf(“%s”,string); Although a pointer can be used as an array name, we cannot modify the values of “string” by using the square brackets of array notation. string[0] = ‘B’; /* error !!! */ The error is due to the fact that the literal “A – your course graden” is stored in a location in memory that cannot be accessed by pointers. String Literal is pointer to an array
  • 199. www.cyberlabzone.com One use of char * pointers is ragged arrays. In slide 15-24 we used the following code fragment in the “Morse Code” example to declare and initialize the array “morse” as : typedef char string[5]; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; An alternative would be the use of a ragged “morse” array declared as: typedef char * string; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; String Literal is Pointer to an Array
  • 200. www.cyberlabzone.com The later declaration of the array “morse” is called ragged since each element of the array , morse[0], morse[1], … takes up exactly the number of bytes necessary in memory to hold the initialized strings whereas in the previous declaration of “morse” each element of the array takes exactly five character values in memory no matter what length of the initializing string. As discussed on slide 15, we cannot change the values of the ragged “morse” array. But in the “Morse Code” problem we know that the morse strings should never be changed. Ragged Arrays
  • 201. www.cyberlabzone.com To sort means to put in place or rank according to kind, class or nature. For example, consider a herd of cows. We can sort the cows by weight, age, amount of milk produced, etc. . The sort can be in ascending or descending order. Note that we could not include a lizard in among the sort if we were sorting with respect to amount of milk produced. That is, the items we want to sort must have the same nature. In C we will use arrays to do our sorting. Since the data-type(kind, class or nature) for each element of the array must be the same we are able to compare any two elements in the array (no lizards in the array of milk producing cows). Why sort? Sorting
  • 202. www.cyberlabzone.com One method of sorting is called “selection sort”. The algorithm: find the smallest element in the list and swap the first item in the list with the smallest value. For example, suppose you are given the values(below): 5 3 7 2 4 ( 2 is the smallest value ) step 1 2 3 7 5 4 ( swap 2 with 5, now 3 is the smallest element) step 2 2 3 7 5 4 ( 3 is in place don’t swap, now 4 is the smallest element) step 3 2 3 4 5 7 ( swap 4 with 7, now 5 is the smallest element) step 4 2 3 4 5 7 ( 5 is in place don’t swap, 7 is in place )
  • 203. www.cyberlabzone.com Another method of sorting is called “insertion sort”. You use insertion sort when you sort a hand of cards. For example, suppose you are given the five cards (below): 5 3 7 2 4 (cards in Right hand) empty (cards in Left hand) step 1 3 7 2 4 (Right hand) 5 (Left hand) step 2 7 2 4 ( R ) 3 5 ( L ) step 3 2 4 ( R ) 3 5 7 ( L ) step 4 4 ( R) ) 2 3 5 7 ( L ) step 5 empty ( R ) 2 3 4 5 7 ( L ) ( the cards are now sorted )
  • 204. www.cyberlabzone.com 1. Problem Definition Write a program that sorts the values in an array in ascending order. Use the built-in function ‘qsort’ to do the work of sorting. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Array of integers. Output= Sorted array of integers (ascending order) is printed. Qsort-Sorting an array
  • 205. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> int compare(int *ptr1, int *ptr2) { if ( *ptr1 > *ptr2) return 1; else if ( *ptr1 < *ptr2) return -1; else return 0; } void main(void) { int numbers[100]; int k,i=0; printf(“Enter an array of no more than 100 integers.n”); while (EOF != scanf(“%d”,&numbers[i])) ++i; qsort(numbers, i, sizeof(numbers[0]), compare); for (k=0; k<i; k++) printf("%d ", numbers[k]); printf(“n”); }
  • 206. www.cyberlabzone.com Execution: dclsn67>./a.out Enter an array of no more than 100 integers. 3 4 2 1 5 (hit Enter and then Control-d to signal EOF) 1 2 3 4 5 (this is the output the program produces) dclsn67> Qsort-Sorting an array
  • 207. www.cyberlabzone.com arrayname - is the name of an existing array. This array can have any data-type. It can even be an array of pointers. We will refer to the array’s type as datatype . elts is the number of elements of array. qsort(arrayname,elts,size_of_elts,compare_function) The qsort function is a built-in C function that sorts values in an array. The algorithm behind qsort is called “Quick Sort” . In CS101 we are interested only in how to call this function. The general format of the qsort function is: Sorting Example-qsort
  • 208. www.cyberlabzone.com size_of_elts is the size in bytes of each element in the array. Use the built-in operator sizeof that returns an integer value representing the number of bytes a variable or data-type takes up in RAM. Example: sizeof(integer) returns the value 4 on the Lab machines. sizeof(numbers[0]) returns the number of bytes the variable numbers[0] takes up in RAM, which is 4 since numbers is an integer array. compare_function is the name of the user defined function that actually does the comparison. qsort(arrayname,elts,size_of_elts,compare_function) Sorting Example-qsort
  • 209. www.cyberlabzone.com The general format of the header for the user defined compare function is: int compare_function( datatype * ptr1,datatype * ptr2) qsort will call the compare_function and pass two pointers ptr1 and ptr2 . Both ptr1 and ptr2 “point” to values in the array arrayname (see previous slide). The user must code the function compare_function so that it returns an integer value back to qsort (the function that called compare_function) . qsort will use this integer to determine whether or not to swap the values in the array. To sort in ascending order the return value is: 0 if the elements *ptr1 and *ptr2 of the array are equal positive if *ptr1 > *ptr2 (i.e. swap the array values) negative if *ptr1 < *ptr2 (i.e. don’t swap the array values) Sorting Example- compare_function
  • 210. www.cyberlabzone.com Writing the code for compare_function depends on the data-type datatype and whether the data is sorted in ascending order, descending order, ... or by some other rule. Therefore it’s not possible to write one version of compare_function that does all. Sorting Example- compare_function
  • 211. www.cyberlabzone.com The datatype in the sorting example is int . Therefore the header for the compare_function has the form: int compare( int * ptr1,int * ptr2) where ptr1 and ptr2 are pointers to values in the array numbers . As an example of how qsort works with compare see the pictures of memory in the following slides. Sorting Example
  • 212. www.cyberlabzone.com ptr1 ptr2 numbers[0] numbers[1] numbers[4] 3 4 Address 2000 2004 … 20042000 2 1 5 . . . Suppose qsort called the compare function and *ptr1 is “3” and *ptr2 is “4”. The picture above shows this situation. In this example, we want to tell qsort to sort 3 before 4(don’t swap the values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 < *ptr2 ( 3 < 4) we return a -1 value to qsort. That’s why we have the code(slide 20): else if ( *ptr1 < *ptr2) { return -1; Sorting Example
  • 213. www.cyberlabzone.com ptr1 ptr2 numbers[1] numbers[2] numbers[4] 3 4 Address 2000 2004 2008… 20082004 2 1 5 . . . Now suppose qsort called the compare function and *ptr1 is “4” and *ptr2 is “2”. The picture above shows this situation. In this example, we want to tell qsort to sort 2 before 4( swap the values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 > *ptr2 ( 4 > 2) we return +1 value to qsort. That’s why we have the code(slide 20): if ( *ptr1 > *ptr2) { return 1; } Sorting Example
  • 214. www.cyberlabzone.com The previous code works correctly but will generate a warning message. We can avoid the error messages if we obey the rules that qsort expects the compare_function to observe. The code on the next slide will sort the numbers as before but gcc will not display any warning messages. In the compare function (on the next slide), note the use of the void pointer data-type and the use of the cast operators on the pointer variables. const int x = 1; x = 2; /* illegal */ Compiler Warning Messages
  • 215. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> int compare(const void *ptr1, const void *ptr2) { if ( *(int *)ptr1 > *(int *)ptr2) return 1; else if ( *(int *)ptr1 < *(int *)ptr2) return -1; else return 0; } void main(void) { int numbers[100]; int k,i=0; printf(“Enter an array of no more than 100 integers.n”); while (EOF != scanf(“%d”,&numbers[i])) ++i; qsort(numbers, i, sizeof(numbers[0]), compare); for (k=0; k<i; k++) printf("%d ", numbers[k]); printf(“n”); }
  • 216. www.cyberlabzone.com #include <stdio.h> void main(void){ int z = 3; float w = 4.0; void * ptr; ptr = &z; /* add one to z */ *(int *)ptr = *(int *)ptr + 1; /* cast ptr */ ptr = &w; /* add 1.0 to w */ *(float *)ptr = *(float *)ptr + 1.0; /* cast ptr */ printf("z = %i n",z); /* prints 4 */ printf("w = %f n",w); /* prints 5.000 */ }
  • 217. www.cyberlabzone.com 1. Problem Definition Write a program that creates a new data type named “vector”. A “vector” represents a 2 dimensional vector v =<x,y> in the plane. The values of v are of type double. Along with this new data-type, create functions add, sub, and dot which will add , subtract and take the vector dot product of two vectors. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) We first define a new data type “vector”. Then in main we will declare v1,v2,v3 of data type “vector”. We will assign values to these vectors and then perform addition, subtraction and the dot product. Input = None Output= The values of v1,v2 will be printed along with the results from add, sub and dot. Example-Defining a 2D “vector data type”
  • 218. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> typedef struct { /* user defined data-type called vector */ double x; /* this is a definition*/ /* no variables are declared */ double y; /* location is outside any block */ } vector; vector add(vector vec1, vector vec2) ; /* prototype */ vector sub(vector vec1, vector vec2) ; /* prototype */ double dot(vector vec1, vector vec2) ; /* prototype */ /* see explanation of the above in subsequent slides */ void main(void){ vector v1,v2,v3 ={1.0,2.0}; /* three variables of type vector*/ /* v3 initialized to {1.0,2.0} */ v1.x = 2.5; /* use the . to access individual fields */ v1.y = -1.5; v2 = v3; /* can assign all the values with one statement */ /* continued on next slide */
  • 219. www.cyberlabzone.com printf(“v1 = [%f,%f]n”,v1.x,v1.y); printf(“v2 = [%f,%f]n”,v2.x,v2.y); v3 = add(v1,v2); printf(“add(v1,v2) = [%f,%f]n”,v3.x,v3.y); v3 = sub(v1,v2); printf(“sub(v1,v2) = [%f,%f]n”,v3.x,v3.y); printf(“dot(v1,v2) = %fn”,dot(v1,v2)); } /* end of main */ vector add(vector vec1, vector vec2){ vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y}; return v4; } /* end of add */ vector sub(vector vec1, vector vec2){ vector v4 = {vec1.x - vec2.x, vec1.y - vec2.y}; return v4; } /* end of sub */ double dot(vector vec1, vector vec2){ return (vec1.x * vec2.x) + (vec1.y * vec2.y); } /* end of dot */
  • 220. www.cyberlabzone.com > a.out v1 = [2.500000,-1.500000] v2 = [1.000000,2.000000] add(v1,v2) = [3.500000,0.500000] sub(v1,v2) = [1.500000,-3.500000] dot(v1,v2) = -0.500000 Example-Execution
  • 221. www.cyberlabzone.com To set up a structure in C, we need to (1) Define a structure type. There are several ways to do this in C. In general, we will use the typedef mechanism to do this. (2) Declare variables to be of that type. Note: The built-in data types (e.g. int, float, char,…) can be used to declare variables in the C language. These data types don’t have to be defined by the user. Structures provide the user with the means to define custom designed data types. Structures & Union -How it Works Structures & Union
  • 222. www.cyberlabzone.com Structures & Union -How it Works Union is same as the structure. As the structure contains members of different data types. In the structure each member has its own memory location. Whereas members of Unions has same memory location. we can assign values to only one member at a time, so assigning value to another member that time has no meaning. When a union is declared, Compiler automatically allocates a memory locations to hold the largest largest data type of members in the Union. Thus the Union is used for saving memory. The concept of union is useful when it is not necessary to assign the values to all the members of the union at a time. Union can be declared as Union union_name { member1 member2 …………. ………… } variable_name
  • 223. www.cyberlabzone.com You can use the typedef mechanism in C to create an alias for a structure. The code above names “vector” as a synonym for, typedef struct { double x; double y; } vector; struct { double x; double y; }; Structures & Union -How it Works
  • 224. www.cyberlabzone.com Structure definitions do not reserve storage, they are used to define a new data type. For example, the code above doesn’t allocate any storage. It doesn’t reserve memory for the variables x or y --- the fields or members of the structure. Also, no variable of type vector is declared yet. typedef struct { double x; double y; } vector; Structures & Union -How it Works
  • 225. www.cyberlabzone.com Once you have defined a new data type, or a synonym for this type, you can declare variables of this data type as in, The variables v1, v2, and v3 are declared to be of data type “vector” where “vector” is a synonym for the structure, struct { double x; double y; }; vector v1,v2,v3 ={1.0,2.0}; Structure variables, like v3 above, are initialized in the same way you initialize an array. Structures & Union -How it Works
  • 226. www.cyberlabzone.com struct Vector_2D v1,v2,v3 ={1.0,2.0}; A second, alternative method in using structures in C is to code the following immediately after the preprocessor directives as in slide 4, struct Vector_2D{ double x; double y; }; The name Vector_2D is called a “tag name”. And in your functions, declare variables by Structures & Union -How it Works
  • 227. www.cyberlabzone.com A third, alternative method in using structures in C is to combine the struct and declaration of the variable in one statement. struct Vector_2D{ double x; double y; } v1,v2,v3 ={1.0,2.0}; Structures & Union -How it Works
  • 228. www.cyberlabzone.com We have seen primitive built-in single variable data types such as int, float, char. These data types can also be applied uniformly to an array. All elements of the array have the identical data type. Structures provide the mechanism in C for grouping values of different data types. Example: typedef struct { int employeeID; float salary; int departmentID; char name[30]; /* same as char * name;??? */ } Employee; Structure can have members of different data-type
  • 229. www.cyberlabzone.com Accessing(storing and fetching) values from/to fields in the structure is accomplished with the "dot operator" (.), also called the "structure member operator ". Example: (From slide 4) v1.x = 2.5; /* use the . to access individual fields */ v1.y = -1.5; Example: (From the previous slide) Employee emp1; /* declare a variable of type Employee */ emp1.employeeID = 1004; /* initialize the variable */ emp1.salary = 45123.50; Structure-Accessing Fields
  • 230. www.cyberlabzone.com scanf(“%f”,&emp1.salary); /* you can also use scanf */ emp1.departmentID = 37; strcpy(emp1.name,“John”);/* strcpy function */ scanf(“%s”,emp1.name); /* this is ok, no & needed */ emp1.name[0] = ‘J’; /* this also works */ emp1.name[1] = ‘o’; emp1.name[2] = ‘h’; emp1.name[3] = ‘n’; emp1.name[4] = ‘0’; Structure-Accessing Fields
  • 231. www.cyberlabzone.com v3 = add(v1,v2); vector add(vector vec1, vector vec2){ Function calls with an argument having a structure data-type are implement as call-by-value. In this regard structures differ from arrays in that arrays are passed as call-by-reference. For example, in slide 5, function add is called with arguments v1 and v2 of data-type vector. The header for the function add has two parameters, vec1 and vec2. The variables vec1 and vec2 are “local” in scope to the function add. In call-by-value the values of v1 and v2 are copied into vec1 and vec2 respectively. Structure-passed as cal-by-value
  • 232. www.cyberlabzone.com v3 = add(v1,v2); Functions can return values of structure data-type. For example, in slide 5, function add is called The header for the function add indicates it returns a value of data-type vector (a structure). vector add(vector vec1, vector vec2){ vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y}; return v4; } Functions can return values of structure data-type
  • 233. www.cyberlabzone.com 1. Problem Definition Write a program that reads in data for the elements in the periodic system, (e.g. Hydrogen, Helium,...) the name as a string , symbol as a string, atomic number as an int and atomic weight as a double. After the elements have been entered they are sorted using qsort in ascending alphabetical order and then printed back to the terminal. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) We have four values per atomic element: name,symbol,atomicNum and atomicWt Rather than using five separate arrays of 102 elements we will use one array AtomicElement of 102 elements. The data-type of AtomicElement is a user-defined structure named Element. Input = Input data from keyboard as above. Output= Sort the elements by atomic name, using qsort. Structure-Accessing Fields Example-Sort an array of structures
  • 234. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> typedef struct { /* user defined data-type called Element */ char name[15]; /* this is a definition, no variables are declared */ char symbol[3];/* location of this definition is outside any block */ int atomicNum; double atomicWt; } Element; int cmpnames(Element * ptr1, Element * ptr2) ; /* prototype */ /* see explanation of the above in subsequent slides */ void main(void){ int num, i; Element AtomicElement[102]; /* AtomicElement is an array */ printf(“How many elements are you going to enter?”); scanf(“%d”,&num); for(i=0;i<num;++i){ scanf(“%s”,AtomicElement[i].name); scanf(“%s”,AtomicElement[i].symbol); scanf(“%d”,&AtomicElement[i].atomicNum); scanf(“%lf”,&AtomicElement[i].atomicWt); }
  • 235. www.cyberlabzone.com /* sort the arrays by name */ qsort(AtomicElement, num, sizeof(AtomicElement[0]), cmpnames); /* print the sorted array */ printf(“n”); for (i=0;i<num;++i){ printf(“%s ”,AtomicElement[i].name); printf(“%s ”,AtomicElement[i].symbol); printf(“%d ”,AtomicElement[i].atomicNum); printf(“%.5lf ”,AtomicElement[i].atomicWt); printf(“n”); /* print one element per line */ } /* end of for */ } /* end of main */ int cmpnames(Element * ptr1, Element * ptr2) { return strcmp(ptr1->name, ptr2->name); /* why arrow and not dot??? */ } /* end of cmpnames */
  • 236. www.cyberlabzone.com > a.out How many elements are you going to enter?4 Hydrogen H 1 1.00794 Beryllium Be 4 9.01218 Gold Au 79 196.96655 Carbon C 6 12.0107 Beryllium Be 4 9.01218 Carbon C 6 12.01070 Gold Au 79 196.96655 Hydrogen H 1 1.00794 input output Example-Execution
  • 237. www.cyberlabzone.com strcmp(ptr1->name, ptr2->name) If the string ptr1->name < ptr2->name (alphabetically) then strcmp(ptr1->name, ptr2->name) has a negative value else if ptr1->name > ptr2->name then strcmp(ptr1->name, ptr2->name) has a positive value else if ptr1->name == ptr2->name then strcmp(ptr1->name, ptr2->name) has the value 0. These are the correct values we want to return to qsort and we do this by From Lecture 15 slide 21: strcmp(str1, str2) - returns a negative , zero or positive int depending on whether str1 is alphabetically less than, equal or greater than str2 respectively. qsort calls our function cmpnames and passes two addresses which are assigned to the pointer variables, ptr1 and ptr2. return strcmp(ptr1->name, ptr2->name); Strcmp
  • 238. www.cyberlabzone.com Address 2030 prt1 ptr2 AtomicElement[0] “Beryllium” Address 2000 20302000 “Be” 4 9.01218 “Hydrogen” “H” 1 1.00794 AtomicElement[1] When qsort calls ‘cmpnames’ Sorting Example
  • 239. www.cyberlabzone.com Address 2030 prt1 ptr2 AtomicElement[0] “Hydrogen” Address 2000 20302000 “H” 1 9.01218“Beryllium” “Be” 4 1.00794 AtomicElement[1] After qsort calls ‘cmpnames’ Since ‘cmpnames’ function returns a positive value to the function ‘qsort’. The function ‘qsort’ does the work of swapping the 30 bytes of AtomicElement[0] with the 30 bytes of AtomicElement[1]. Sorting Example
  • 240. www.cyberlabzone.com We can declare an array of the struct data type Autopart. AutoPart structArray[50]; declares structArray as an array which contains 50 cells (in memory) of type AutoPart. typedef struct { int id; char name[30]; } AutoPart; Given the data-type definition: Arrays of Structure data-type
  • 241. www.cyberlabzone.com We can access the field in the structure with pointers and arrow operator “ -> ” (also called the indirect component selection operator ). The general format of the use of the arrow operator is: (see example on next slide) pointer_to_structure -> member_name Pointer to variables of structure data-type
  • 242. www.cyberlabzone.com typedef struct { int employeeID; float salary; int departmentID; char name[30]; } Employee; Employee emp1; Employee *empPtr; /* pointer to data-type Employee */ emp1.employeeID = 1004; emp1.salary = 45123.50; emp1.departmentID = 37; empPtr = &emp1; /* empPtr now points to emp1 */ printf(“emplayeeID is %d in department %d n”, empPtr->employeeID, empPtr->departmentID); Pointer to variables of structure data-type
  • 243. www.cyberlabzone.com Rather than use the arrow operator we could use “ * ” the dereferencing operator. From the last example: printf(“emplayeeID is %d in department %d n”, (*empPtr).employeeID, (*empPtr).departmentID); However, do not write: printf(“emplayeeID is %d in department %d n”, *empPtr.employeeID, *empPtr.departmentID); because in C this means (see operator precedence rules) printf(“emplayeeID is %d in department %d n”, *(empPtr.employeeID), *(empPtr.departmentID)); and these expressions are not equivalent. Why? Therefore, it may be “safer” to use the arrow operator, so that we don’t make the mistake shown above. Why use the arrow “”?
  • 244. www.cyberlabzone.com So far, we have seen that one way to manipulate files in a program is to redirect the standard input and output. E.g. in UNIX command line a.out < input.dat > output.dat We redirect standard input as the file, input.dat (not a keyboard) And standard output as the file, output.dat(not screen) This method works for one input file and one output file. In this lecture we will consider an alternative, using FILE pointers. File Input/Output (I/O) File Operation in C
  • 245. www.cyberlabzone.com 1. Problem Definition Write a program that computes the average of a list of integers. The program should prompt the user for the name of both the input and output files and then read the values from the input file and print the average value in the output file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = String naming the file of integers to be read and a string naming the output file. Also, the integers in the file. Output = The average value is written to the output file. Example-Compute the Average value of a File of Integers
  • 246. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count = 0; /* fileptrIn and fileptrOut are variables of type “FILE *” */ FILE * fileptrIn, * fileptrOut; char filenameIn[100],filenameOut[100]; printf(“Please enter an input filename (use path if needed):”); scanf(“%s”,filenameIn); printf(“Please enter an output filename (use path if needed):”); scanf(“%s”,filenameOut); /* open files to read “r” and write “w” */ fileptrIn = fopen(filenameIn,”r”); fileptrOut = fopen(filenameOut,”w”); /* check to see if program found file */ if ((fileptrIn == NULL) || (fileptrOut == NULL)) { printf(“file not opened, program terminated.n”); return; } Example-Computing the Average value
  • 247. www.cyberlabzone.com /* fscanf */ while( EOF != fscanf(fileptrIn,"%i", &value)){ total += value; ++count; } /* end of while loop */ /* Write the average value to the file. fprintf */ fprintf(fileptrOut,”Ave of %i numbers = %f n“ ,count,total/(double)count); fclose(fileptrIn); fclose(fileptrOut); }
  • 248. www.cyberlabzone.com /* fscanf */ while( EOF != fscanf(fileptrIn,"%i", &value)){ total += value; ++count; } /* end of while loop */ /* Write the average value to the file. fprintf */ fprintf(fileptrOut,”Ave of %i numbers = %f n“ ,count,total/(double)count); fclose(fileptrIn); fclose(fileptrOut); } Example-Compute the Average value of a File of Integers
  • 249. www.cyberlabzone.com After the above program is compiled execution from the Unix prompt: > more input.dat 1 2 3 4 5 > ./a.out Please enter an input filename (use path if needed):input.dat Please enter an output filename (use path if needed):output.dat > more output.dat Ave of 5 numbers = 3.000000 > Execution-How it Works
  • 250. www.cyberlabzone.com FILE (all caps) is a structure defined in <stdio.h>. In CS101 we will only use this data type in the declaration of pointer variables. Examples: FILE *ptrFileIn; FILE *ptrFileOut; declares ptrFileIn and ptrFileOut as pointer variables. They both “point” to values of data-type FILE. We must have #include <stdio.h> in our source file to use FILE pointers. File-data-type
  • 251. www.cyberlabzone.com fprintf function is in <stdio.h>. It is the same as the printf function except that the first argument for fprintf is a file pointer: fprintf(ptrFileOut, ctrlString, expression(s)); where ctrlString contains the format specifiers, and expression(s) can contain one or more variable names and constants. Examples: fprintf(ptrFileOut, "%d ", intVlaue); fprintf(ptrFileOut, "%f ", a + 5.0 * b); fprintf
  • 252. www.cyberlabzone.com fscanf function is also in <stdio.h>. It is the same as the scanf function except that the first argument for fscanf is a file pointer; i.e., fscanf(ptrFileIn, ctrlString,address(es)); Examples - fscanf(ptrFileIn, "%lf", &dataValue); fscanf(ptrFileIn, "%c%s%d", &ch, str, &num); - returns an int value equal to number of items successfully read from file (e.g., 0, 1, 2, 3 in last example), or returns the value of EOF if end of file is encountered before any values are read in. Thus, fscanf can be used as an input check just like scanf. fscanf
  • 253. www.cyberlabzone.com To use fscanf and fprintf you must first open a file, we use the library function fopen (defined in <stdio.h>.) For example, to open the file input.dat for reading, we write FILE *fileIn; fileIn = fopen(“infile.dat”, “r”); The first argument “infile.dat” is a string that names the file to be read. The second argument the mode, “ r ”, stands for “reading” mode only. If the file cannot be opened, fopen returns NULL. (e.g. file doesn’t exit) fopen returns a pointer to the file(in this case infile.dat). The file pointer is the handle to the file, once the file is opened with fopen a programmer can manipulate the file with this pointer. fopen
  • 254. www.cyberlabzone.com FILE *fileOut; fileOut = fopen(“output.dat”, “w”); The first argument “output.dat” is a string that names the file to be read. The second argument the mode, “ w ”, stands for “write” mode only. fopen returns a pointer to the file(in this case (output.dat). Example: If an already existing file is opened with mode “w” the old contents are discarded. fopen
  • 255. www.cyberlabzone.com FILE *fileOut; fileOut = fopen(“out.dat”, “a”); The first argument “out.dat” is a string that names the file the you to which you want to write . The writing takes place at the end of the original file. If the file out.dat already exists it will not be destroyed as in the case for “w” mode. fopen returns a pointer to the file(in this case (out.dat). Example: fopen
  • 256. www.cyberlabzone.com When we open a file such as infile.dat we need to specify in advance whether we want to read from the file, write to the file, append to the file. A file can be opened in one mode, closed and then reopened in another mode. Mode If the file exists If the file doesn’t exist “r” Opens the file for reading Error “w” Opens a new file for writing Create a new file “a” Opens a file for appending (writing at the end of the file) Create a new file Fopen-mode
  • 257. www.cyberlabzone.com To close a file that is opened, you must use fclose. The function expects one argument, a pointer to FILE. The function fclose returns zero if it successfully closes the file and EOF otherwise.(e.g file doesn’t exist) FILE *fileIn; fileIn = fopen(“infile.dat”, “r”) … fclose(fileIn); When a program terminates, all open files are automatically closed. fclose
  • 258. www.cyberlabzone.com 1. Problem Definition Write a program that reads a list of real numbers into an array from the keyboard (or a file using Unix redirection). The array can be of arbitrary length but the user must first specify the length of the array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Since the length of the array is specified at run-time we must use Dynamic Memory Allocation. This is accomplished in C by the use of the built-in function calloc (or malloc). Use data-type double to hold the values. Output= The average and the list of differences. Example-DMA example
  • 259. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> void main(void){ int k,num; double * datValptr; /* pointer used in DMA */ double datAve; double sum = 0.0; /* prompt the user for the number of array elements */ printf(“Please enter the number of array elements:”); scanf(“%d”,&num); /* use calloc to allocate a block of memory */ datValptr = calloc(num,sizeof(double)); /* verify that calloc was successful */ if (datValptr = = NULL){ printf(“Memory not allocated!n”); return; } (continued on next slide)
  • 260. www.cyberlabzone.com /* read the values and compute the average */ k = 0; for(k=0;k<num;++k){ scanf("%lf", &datValptr[k]);/* use pointer as array name */ sum += datValptr[k]; } /* compute the average */ datAve = sum /num; printf(“The average is:%f n", datAve); /* compute and print the diff list */ for(k=0;k<num;++k){ printf(“%fn", datValptr[k]-datAve); } /* end of for*/ /* free up any memory that was dynamically allocated */ free(datValptr); } /* end of main */
  • 261. www.cyberlabzone.com dclsn75> ./a.out Please enter the number of array elements:5 1 2 3 4 5 The average is:3.000000 -2.000000 -1.000000 0.000000 1.000000 2.000000 dclsn75> Execution
  • 262. www.cyberlabzone.com In C, we can dynamically allocate storage with either of the following two functions (both are in <stdlib.h>). • malloc(numberOfBytes) • calloc(numberOfItems, itemSize) Both functions return a pointer to the address of the block of storage that has been allocated. If no memory is available, a NULL value will be returned. Function calloc returns a contiguous block of locations that are initialized to 0 and that can be referenced as array locations, using pointer operations. Calloc and malloc
  • 263. www.cyberlabzone.com In both cases above (calloc or malloc) return memory locations to the system ("memory manager") with: free (ptr); Example: Declare ptr as a pointer variable to data- type double and use dynamic memory allocation (calloc or malloc) to allocate 100 elements of data- type double. double * ptr; ptr = calloc(100,sizeof(double)); or ptr = malloc(100*sizeof(double)); free
  • 264. www.cyberlabzone.com Lecture 19 slide 8 mentioned that array names are constant pointers. Conversely, pointer variables can be used as array names. Example: int x[5] ={2,4,6,8,10}; int * ptr; ptr = x; /* or ptr = &x[0] , that is ptr points to x-array*/ ptr[0] = 3; /* is the same as x[0] = 3 */ printf(“%d”,ptr[1]); /* prints 4 */ Pointer Variables can be Used as Array Names
  • 265. www.cyberlabzone.com 1. Problem Definition Read a file “input.dat” that has employee data(“records”). Read the records into an array (using dynamic memory allocation) of data-type Employee (defined below) and then sort the employee data alphabetically by name. Write the sorted data to the file “output.dat”. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Use the structure typedef struct { int employeeID; float salary; int departmentID; char fname[30]; char lname[30]; } Employee; Output= The employee records in alphabetic order. Example-Sorting Employee Records
  • 266. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> typedef struct { int employeeID; float salary; int departmentID; char fname[30]; char lname[30]; } Employee; int cmpnames(Employee *ptr1,Employee *ptr2) /* prototype */ void main(void){ FILE * fileptrIn; FILE * fileptrOut; int i, num; char filenameIn[100]; char filenameOut[100]; Employee * ptr; /* ptr is a pointer variable */ Employee temp; (continued on next slide)
  • 267. www.cyberlabzone.com /* prompt user and get the name of employee input */ /* and output file */ printf("Enter the file name that contains the records. n"); scanf("%s",filenameIn); printf("Enter the output file name. n"); scanf("%s",filenameOut); /* open file for reading */ fileptrIn = fopen(filenameIn,”r”); /*open file for writing */ fileptrOut = fopen(filenameOut,”w”); /* verify that files were successfully opened */ if (fileptrIn == NULL){ printf(“Input file not found.n”); return; /* terminate program */ } if (fileptrOut == NULL){ printf(“Output file not opened.n”); return; /* terminate program */ } (continued on next slide)
  • 268. www.cyberlabzone.com /* find the number of Employee records by reading the */ /* input file. Then reset the file to read from the */ /* beginning of the file again. */ num = 0; while ( (EOF !=fscanf(fileptrIn,"%d",&temp.employeeID))&& (EOF !=fscanf(fileptrIn,"%f",&temp.salary))&& (EOF !=fscanf(fileptrIn,"%d",&temp.departmentID))&& (EOF !=fscanf(fileptrIn,"%s",temp.fname))&& (EOF !=fscanf(fileptrIn,”%s”,temp.lname))) ++num; rewind(fileptrIn); /* calloc is a built-in C function that performs DMA*/ ptr = calloc(num,sizeof(Employee)); (continued on next slide)
  • 269. www.cyberlabzone.com /* read the records into the area in memory pointed to */ /* by ptr. See the previous statement ptr = calloc(… */ /* Use ptr as the “name” of an array */ for(i = 0;i<num;++i){ fscanf(fileptrIn,"%d",&ptr[i].employeeID); fscanf(fileptrIn,"%f",&ptr[i].salary); fscanf(fileptrIn,"%d",&ptr[i].departmentID); fscanf(fileptrIn,"%s",ptr[i].fname); fscanf(fileptrIn,"%s",ptr[i].lname); } /* use qsort to sort the records by employee name */ qsort(ptr,num,sizeof(Employee),cmpnames); /* write the records to the output file */ /* note the space after the conversion specifiers */ for(i = 0;i<num;++i){ fprintf(fileptrOut,"%d ",ptr[i].employeeID); fprintf(fileptrOut,"%.2f ",ptr[i].salary); fprintf(fileptrOut,"%d ",ptr[i].departmentID); fprintf(fileptrOut,"%s ",ptr[i].fname); fprintf(fileptrOut,"%sn",ptr[i].lname); } (continued on next slide)
  • 270. www.cyberlabzone.com /* free up dynamic memory */ free(ptr); /* close all files before you terminate the program */ fclose(fileptrIn); fclose(fileptrOut); } /* end of main */ /* cmpnames is called by qsort */ int cmpnames(Employee *ptr1,Employee *ptr2){ return strcmp(ptr1->lname, ptr2->lname); } How would you modify the cmpnames function above to sort the array by if the last names were the same? How would you modify the compare function to sort by employeeID, or by departmentID, or by salary ?
  • 271. www.cyberlabzone.com Given that the input file “input.dat” has the following data: 12345 34500.00 24 Brad Pitt 12346 28888.00 23 Jennifer Aniston 12347 47595.00 24 Britney Spears 12348 55675.00 23 Jim Carey The program described in the previous slides produces the output shown on the next slide. Example-Execution
  • 272. www.cyberlabzone.com dclsn75> ./a.out Enter the file name that contains the records. input.dat Enter the file name that contains the records. output.dat dclsn75> more output.dat 12346 28888.00 23 Jennifer Aniston 12348 55675.00 23 Jim Carey 12345 34500.00 24 Brad Pitt 12347 47595.00 24 Britney Spears dclsn75> Example-Execution
  • 273. www.cyberlabzone.com fclose(fileptrIn); fileptrIn = fopen(filenameIn,”r”); In slide 13 we used the built-in C function rewind. To illustrate the meaning of rewind, consider the following example: If the data was written on a magnetic tape, then the rewind command causes the tape to be rewound back to the beginning of the tape. So the next read command would begin reading from the beginning of the file. In the program in slides 10-15 we could replace the code: rewind(fileptrIn); by the following code: Rewind
  • 274. www.cyberlabzone.com C has the special feature of preprocessor directive which makes it different from other languages (which hasn’t this type of facility). C preprocessor provides the facility to programmers to make program more efficient (for Understanding and modification of program). The preprocessor processes the C source code before it passes to the compiler preprocessor directives are executed before the C source code passes through the compiler. The preprocessor directives usually written at the beginning of the C program. These directives are preceded with the # symbol and there is no semicolon at the end. This is not necessary to write the preprocessor directives at the beginning of the program, These can be written anywhere in the program but they are generally written before main function or other functions. The preprocessor directives are as given below:- # define, #ifdef, #ifndef, #else, #elif,#if #error, #endif, #undef, #line, #pragma Stringizing operator # Token pasting operator ## The C Preprocessor
  • 275. www.cyberlabzone.com Recursive functions are defined in terms of themselves; i.e., a function is recursive if it contains calls back to itself or to another function that calls the original function. Recursive programming usually requires more memory and runs more slowly than non-recursive programs. This is due to the cost of implementing the “stack”. However, recursion is often a natural way to define a problem. Recursive Functions
  • 276. www.cyberlabzone.com 1. Problem Definition Write a factorial function. 0! = 1 and n! = n*(n-1)!. Use “recursion” to implement the factorial function. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Non-negative integers as input. Output= return the factorial of the input value. Note: that 69! = 1.711224524... x 1098 so our function will only work for small integer values. It would be better to return a value of data-type double (Why?) Example-Factorial function
  • 277. www.cyberlabzone.com double fact(int n) { if (n = =0 || n = =1) return 1.0; else return (n * fact(n - 1)); /* recursive call */ } In main we can call the factorial function by the following command: printf(“%lf”, fact(6)); or by (if x is of data-type int and y is of data-type double) : x = 5; y = fact(x); Example-(Recursive) Factorial function
  • 278. www.cyberlabzone.com double fact(int n) { if (n = =0 || n = =1) return 1.0; else return (n * fact(n - 1)); /* recursive call */ } When we call the factorial function with fact(2) we “stop” executing the factorial function at the line: return ( 2 * fact(1)); (n = 2) (values are substituted for the variables). We cannot return a value because we must first compute fact(1), so this statement is put on hold or “pushed on the stack” until fact(1) is computed. A second call to factorial function is made, i.e. fact(1) and we execute, (continued on the next slide) Example-How it Works
  • 279. www.cyberlabzone.com and since n = = 1 is true then the following executes: return 1.0; (n = 1) But to where does the value 1.0 return ? From where fact was last called , the fact function(see previous slide). So when this call to fact terminates (at return 1.0;) the statement return ( 2 * fact(1)); (n = 2) is “popped” from the stack and fact(1) gets the value 1.0, that is, we can now execute this statement which (effectively) says return ( 2 * 1.0); double fact(int n) (n = 1) { if (n = =0 || n = =1) return 1.0; else return (n * fact(n - 1)); /* recursive call */ } Example-How it Works
  • 280. www.cyberlabzone.com Note the contents of the “stack” when we execute a call fact(3) from main.: (push) return ( 3 * fact(2)); (n = 3) (push) return ( 2 * fact(1)); (n = 2) return 1.0; (n = 1) (pop) return ( 2 * 1.0); (n = 2) (pop) return ( 3 * 2.0); (n = 3) return ( 3 * fact(2)); (n = 3) return ( 2 * fact(1)); (n = 2) return ( 3 * fact(2)); (n = 3) (STACK) The “stack” contains “stack frames” see FER 21.2.1. Example-fact(3)
  • 281. www.cyberlabzone.com 1. Problem Definition Write a solve_maze function. Read the maze from a file, “maze.txt” and display one path that traverses the maze. Use “recursion” to implement the maze function. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = The file “maze.txt” contains the following ********** * * **** * *O* * * *** * * *X* * ** *** * * * * * *** ** * * * * ********** Your program will have to find its way through a 10x10 maze where the symbols “ * ” , “O” and “X” denote: “ * ” are solid walls through which you cannot travel "O" denotes the starting position, "X" is the exit for which you are looking for Example-Traversing a Maze
  • 282. www.cyberlabzone.com * * * * * * * * * * * * * * * * * * O * * * * * * * * * X * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  • 283. www.cyberlabzone.com 2. Refine, Generalize, Decompose the problem definition Input (continued): Read the maze into the 2D array, ********** * * **** * *O* * * *** * * *X* * ** *** * * * * * *** ** * * * * ********** char maze[NUMROWS][NUMCOLS]; where NUMROWS and NUMCOLS are constants with value 10. The upper left-hand corner of the maze has the value maze[0][0] . If we want to test whether the cell in the fourth row and fourth column contains a wall then it's enough to use an if statement like this: if (maze[3][3] == ‘ * ') Example-Traversing a Maze
  • 284. www.cyberlabzone.com 2. Refine, Generalize, Decompose the problem definition Output : Display a solution as follows: ********** * OOOOO* ****O* *O* * *O* *** * *O* *X* * **O***O* * OO *O* * ***O**O* * * OOOO* ********** Example-Traversing a Maze
  • 285. www.cyberlabzone.com 3. Develop Algorithm (processing steps to solve problem) Step 1 Read in the “maze” and find the starting Row and Column (the position of the “O”). Use variables “curRow” and “curCol” to keep track of the current position as we traverse through the maze (the 2D matrix “maze”). Step 2 Display the maze. Step 3 Check to see if current position is an “X” then we are done. Otherwise first try to go up and if not then down and if not then left and if not then right and if you can go up/down/left/right then go back to Step 2. Otherwise, go back to the previous position [curRow,curCol] and try another direction. Example-Traversing a Maze
  • 286. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> #define NUMROWS 10 #define NUMCOLS 10 /* prototypes */ int read_maze (char[][], int *, int *); void display_maze (char[][]); void solve_maze (char[][], int, int);
  • 287. www.cyberlabzone.com void main (void) { int startRow, startCol; /* Starting point in maze. */ char maze[NUMROWS][NUMCOLS]; /* Stores maze read from input file. */ if (read_maze(maze, &startRow, &startCol) == 0) { printf ("Error reading maze from file maze.txt!n"); return; } solve_maze(maze, startRow, startCol); } /*end of main */
  • 288. www.cyberlabzone.com void solve_maze(char maze[][NUMCOLS], int curRow, int curCol){ int i; display_maze(maze); /* Check if solution found. */ if ((maze[curRow - 1][curCol] == 'X') || (maze[curRow + 1][curCol] == 'X') || (maze[curRow][curCol + 1] == 'X') || (maze[curRow][curCol - 1] == 'X')) exit (0); /* Recurse in each possible direction that is empty. */ /* Move up */ if (maze[curRow - 1][curCol] == ' ') { maze[curRow - 1][curCol] = 'O'; solve_maze(maze, curRow - 1, curCol); maze[curRow - 1][curCol] = ' '; } /* continued on next slide */
  • 289. www.cyberlabzone.com /* Move down */ if (maze[curRow + 1][curCol] == ' ') { maze[curRow + 1][curCol] = 'O'; solve_maze (maze, curRow + 1, curCol); maze[curRow + 1][curCol] = ' '; } /* Move left */ if (maze[curRow][curCol - 1] == ' ') { maze[curRow][curCol - 1] = 'O'; solve_maze (maze, curRow, curCol - 1); maze[curRow][curCol - 1] = ' '; } /* Move right */ if (maze[curRow][curCol + 1] == ' ') { maze[curRow][curCol + 1] = 'O'; solve_maze (maze, curRow, curCol + 1); maze[curRow][curCol + 1] = ' '; } return; }
  • 290. www.cyberlabzone.com /* Display the maze passed as a parameter to standard output. */ void display_maze (char maze[ ][NUMCOLS]) { int i, row, col; for (row = 0; row < NUMROWS; row++) { for (col = 0; col < NUMCOLS; col++) { printf ("%c", maze[row][col]); } printf ("n"); } usleep (600000); printf ("n"); }
  • 291. www.cyberlabzone.com int read_maze (char maze[ ][NUMCOLS], int *sRow, int *sCol){ FILE *fpMaze; int row, col; char endofline; /* end of line character */ /* Open maze text file, make sure it opens OK. */ if ((fpMaze = fopen ("maze.txt", "r")) == NULL) return 0; for (row = 0; row < NUMROWS; row++){ /* Loop through the rows. */ for(col=0;col<NUMCOLS;++col){/* Loop through columns */ fscanf(fpMaze,"%c",&maze[row][col]); if (maze[row][col] == 'O') { /*Check if this is the starting position.*/ *sRow = row; *sCol = col; } } /* end of for(col=... loop */ fscanf(fpMaze,"%c",&endofline); } /* end of for(row=... loop */ fclose(fpMaze); return 1; }
  • 292. www.cyberlabzone.com According to legend, in the great temple of Benares, beneath the dome which marks the center of the world, rests a brass plate on which are fixed three diamond needles. On one of these needles at creation, there were placed 64 discs of pure gold, the largest disc resting on the brass plate and the others getting smaller up to the top one. This is the TOWERS OF HANOI. Day and night, the people on duty move the discs from one needle to another, according to the two following laws: Law 1: Only one disc at a time may be moved. Law 2: A larger disc may never rest on a smaller disc. The workers labor in the belief that once the tower has been transferred to another needle there will be heaven on earth, so they want to complete the task in the least number of moves. Towers of Hanoi
  • 293. www.cyberlabzone.com Actually, the Tower of Hanoi puzzle was invented in 1883 by the French mathematician Edouard Lucas (1842-1891), who made up the legend to accompany it. Towers of Hanoi
  • 294. www.cyberlabzone.com An elegant and efficient way to solve this problem is to think recursively. Suppose that you, somehow or other, have found the most efficient way possible to transfer a tower of n-1 disks one by one from one pole to another obeying the restriction that you never place a larger disk on top of a smaller one. Then, what is the most efficient way to move a tower of n disks from one pole to another? Towers of Hanoi
  • 295. www.cyberlabzone.com Assume we know how to move n-1 disks from one peg to another.Then can we move n disks from peg 1 to peg 3 ? 1. Move n-1 disks from peg 1 to peg 2, peg 3 is just a temporary holding area 2. Move the last disk(the largest) from peg 1 to peg 3 3. Move the n-1 disks from peg 2 to peg 3, peg 1 is just a temporary holding area. 1 2 3 n disks Pseudo-code
  • 296. www.cyberlabzone.com Click on Picture to start game 1 2 3 Example-Animation
  • 297. www.cyberlabzone.com /* function prototype*/ void hanoi( int origin, int dest, int spare, int how_many); void main(void){ int how_many; printf(“ntHow many disks initially on peg1?”); scanf(“%d”, &how_many); hanoi(1, 3, 2, how_many); } Example-Towers of Hanoi
  • 298. www.cyberlabzone.com void hanoi( int origin, int dest, int spare, int how_many){ int new_origin, new_dest, new_spare; if(how_many == 1){ printf(“nntMove top disk from peg %d to peg %d.”, origin, dest); return; } new_origin = origin; new_dest = spare; new_spare = dest; hanoi(new_origin, new_dest, new_spare, how_many - 1); printf(“nnt Move top disk from peg %d, to peg %d.”, origin, dest); new_origin = spare; new_dest = dest; new_spare = origin; hanoi(new_origin, new_dest, new_spare, how_many - 1) ; } Example-Towers of Hanoi
  • 299. www.cyberlabzone.com Going back to the legend, suppose the priests work rapidly and move one disk every second. As shown earlier, the minimum sequence of moves must be : The minimum number of moves needed to transfer a tower of n disks from peg1 to peg3 The minimum number of moves needed to transfer n-1 disks from peg1 to peg2 The minimum number of moves needed to transfer the n th disk from peg1 to peg3 The minimum number of moves needed to transfer n-1 disks from peg2 to peg3 on top of the n th disk Therefore, the recurrence relation is moves(n) = 2*moves(n-1) + 1 and initial case is moves(1) = 1 second. For example, moves(2) = 2*moves(1) + 1 = 3, moves(3) = 2*moves(2) + 1 = 7, moves(4) = 2*moves(3) + 1 = 15. Then, the time to move all 64 disks from one peg to the other, and end the universe would be moves(64) seconds or 584.5 billion years!! = + + Computational Complexity