C coding
C coding
2
Introduction
to C Programming
OBJECTIVES
In this chapter you will learn:
To write simple computer programs in C.
To use simple input and output statements.
The fundamental data types.
Computer memory concepts.
To use arithmetic operators.
The precedence of arithmetic operators.
To write simple decision-making statements.
1
3
2.1 Introduction
2.2 A Simple C Program: Printing a Line of Text
2.3 Another Simple C Program: Adding Two Integers
2.4 Memory Concepts
2.5 Arithmetic in C
2.6 Decision Making: Equality and Relational Operators
2.1 Introduction
C programming language
– Structured and disciplined approach to program design
Structured programming
2
1 /* Fig. 2.1: fig02_01.c 5
2
3
A first program in C */
#include <stdio.h>
Outline
/* and */ indicate comments – ignored by compiler
4
5 /* function main begins program execution */ #include directive tells C to load a
6 int main( void ) particular file
7 { ‘{‘ Left brace declares beginning of fig02_01.c
8 printf( "Welcome to C!\n" ); main function
9 Statement tells C to perform an
10 action
return 0; /* indicate that program ended successfully */
return statement ends the
11
12 } /* end function main */ function
‘}’ Right brace declares end of main
function
Welcome to C!
Code output
3
7
Welcome to C!
4
9
"Welcome to C!“
2007 Pearson Education, Inc. All rights reserved.
10
Welcome to C!
return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally. When you return 0, you tell the caller (OS in case of
main) that the status of your program was successful.
5
1 /* Fig. 2.3: fig02_03.c 11
2
3
Printing on one line with two printf statements */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig02_03.c
7 {
printf statement starts printing from
8 printf( "Welcome " );
9 printf( "to C!\n" ); where the last statement ended, so the
10 text is printed on one line.
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */
Welcome to C!
Welcome to C!
6
1 /* Fig. 2.4: fig02_04.c 13
2
3
Printing multiple lines with a single printf */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
Newline characters move the cursor to the fig02_04.c
7 {
8 printf( "Welcome\nto\nC!\n" );next line
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
Welcome
to
C!
Q1
* *
* *
* *
Code is:
printf ( "* *\n* *\n* *" );
7
Q1
* *
* *
* *
Code is:
printf ( "*\t*\n*\t*\n*\t*" );
Declaring Variables
int x; // Declare x to be an
// integer variable;
float radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
Assignment Statements
x = 1; // Assign 1 to x;
8
Declaring and Initializing in One Step
int x = 1;
float d = 1.4;
double f = 1.4;
9
19
same definition
int integer1;
int integer2;
int sum;
– Definitions appear before executable statements
- If an executable statement references an undeclared variable it
will produce a syntax (compiler) error
20
10
21
22
11
23
24
12
25
26
13
27
– Similar to scanf
- %d means decimal integer will be printed
- sum specifies what integer will be printed
– Calculations can be performed inside printf
statements
printf("Sum is %d\n", integer1 + integer2);
28
spaces
14
29
30
int integer1;
interger1 = 45;
After executing the above statement
Fig. 2.6 | Memory location showing the name and value of a variable.
15
31
interger1 = 45;
interger2 = 72;
32
interger1 = 45;
interger2 = 72;
sum = interger1 + interger2;
16
33
34
Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
17
35
36
Equality operators
== x == y x is equal to y
18
37
int main()
{
printf("3==3 results %d\n",3==3);
printf("3==4 results %d\n",3==4);
printf("3<4 results %d\n",3<4);
printf("3!=3 results %d\n",3!=3);
printf("3>4 results %d\n",3>4);
return 0;
}
Result is:
3==3 results 1
3==4 results 0
3<4 results 1
3!=3 results 0
3>4 results 0
19
39
No space
40
20
41
42
if control statement
if control statement
– Simple version in this section, more detail later
if (condition) {
body statements
}
21
1 /* Fig. 2.13: fig02_13.c 43
2
3
Using if statements, relational
operators, and equality operators */
Outline
4 #include <stdio.h>
5
6 /* function main begins program execution */
fig02_13.c
7 int main( void )
8 {
9 int num1; /* first number to be read from user */
(1 of 3 )
10 int num2; /* second number to be read from user */
11
12 printf( "Enter two integers, and I will tell you\n" );
13 printf( "the relationships they satisfy: " );
14
15 scanf( "%d%d", &num1, &num2 ); /* read two integers */
16
17 if ( num1 == num2 ) { Checks if num1 is equal to num2
18 printf( "%d is equal to %d\n", num1, num2 );
19 } /* end if */
20
21 if ( num1 != num2 ) { Checks if num1 is not equal to num2
22 printf( "%d is not equal to %d\n", num1, num2 );
23 } /* end if */
24
25 if ( num1 < num2 ) { Checks if num1 is less than num2
26 printf( "%d is less than %d\n", num1, num2 );
27 } /* end if */
28
22
45
Outline
46
Operator precedence
– Some arithmetic operators act before others
Operators Associativity
() left to right
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
= right to left
Fig. 2.14 | Precedence and associativity of the operators discussed so far.
23
47
Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Q1
24
Q1
50
Identify and correct the errors in each of the following
statements. (Note: There may be more than one error per
statement.)
25
51
Identify and correct the errors in each of the following
statements. (Note: There may be more than one error per
statement.)
52
26
53
system("Pause");
return 0; /* successful termination */
}
2007 Pearson Education, Inc. All rights reserved.
54
27
55
system("Pause");
return 0; /* successful termination */
}
56
28
57
58
29
1
3
Structured Program
Development in C
OBJECTIVES
In this chapter you will learn:
To develop algorithms through the process of
top-down, stepwise refinement.
To use the if selection statement and if...else
selection statement to select actions.
To use the while repetition statement to execute
statements in a program repeatedly.
Counter-controlled repetition and sentinel-controlled
repetition.
Structured programming.
The increment, decrement and assignment operators.
1
3
2
Example:
Write an algorithm to determine a student’s final grade and
indicate whether it is passing (>60) or failing. The final grade
is calculated as the average of four marks.
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 60
Print “FAIL”
else
Print “PASS”
3
Example:
Draw the flowchart of an algorithm which finds the sum of two numbers
N and M
Example:
Draw the flowchart of an algorithm which finds the sum of the first 50
numbers
4
9
– Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed
10
If condition true
– Print statement executed and program goes on to next
statement
– If false, print statement is ignored and the program
goes onto the next statement
5
The if selection statement
General Form: if the condition is true then statement 1 is executed. If
the condition is false then statement 1 is skipped.
If there is only one statement inside the
if (condition) block, there is no need to use braces. Curly
statement 1; braces show the borders of the compound
statement or block.
if (condition) Example
{
statement 1; if (a < 50)
statement 2; {
… count=count +1;
statement n; sum =sum + a;
} }
Example:
if (a < 50)
{
count=count +1;
sum = sum + a;
if (b > a)
b = 0;
}
6
13
7
The if…else selection statement
Example:
if (x > y)
if (y < z)
k++;
else
m++;
else
j++;
(same) (same)
8
What is the output of the following code? Q
#include <stdio.h>
int main()
{
int x=1, y=2, z=3, k=0, j=0;
if (x > y){
if (y < z)
k++;}
else
j=j+1;
Write a program that reads in four integers from the keyboard and
then calculates the sum of the numbers which are positive. The screen
Q
dialogue should appear as follows:
Input four different integers: 14 8 11 -8
The sum of the positive numbers is: 25
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1, x2, x3, x4;
int sum=0;
9
Ternary conditional operator (?:)
Takes three arguments (condition, value if true, value if false)
Condition
Example:
printf( "%s\n", grade >= 60 ? "Passed" : "Failed" );
OR
OR
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
Write a program (by using ternary operator) that reads in one integer Q
from the keyboard and then prints out a message whether integer is
greater than zero or not. The screen dialogue should appear as follows:
Input one integer: 14
Greater than zero
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1;
system("Pause");
return 0; /* successful termination */
}
10
21
– Pseudocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
22
Counter-Controlled Repetition
Counter-controlled repetition
– Loop repeated until counter reaches a certain value
– Definite repetition: number of repetitions is known
if number of repetitions is known a counter is used to
control repetition
11
23
12
25
13
23 /* loop while sentinel value not yet read from user */ 27
24 while ( grade != -1 ) {
25 total = total + grade; /* add grade to total */
26 counter = counter + 1; /* increment counter */ while loop repeats until user
27 enters a value of -1
28 /* get next grade from user */
29 printf( "Enter grade, -1 to end: " ); /* prompt for input */
30 scanf("%d", &grade); /* read next grade */
31 } /* end while */
32
33 /* termination phase */
34 /* if user entered at least one grade */ Ensures the user entered at least
35 if ( counter != 0 ) {
one grade
36
37 /* calculate average of all grades entered */
38 average = ( float ) total / counter; /* avoid truncation */
39
Converts total to
40 /* display average with two digits of precision */ float type
41 printf( "Class average is %.2f\n", average );
42 } /* end if */ Prints result with 2 digits
43 else { /* if no grades were entered, output message */ after decimal point
44 printf( "No grades were entered\n" );
45 } /* end else */
46
47 return 0; /* indicate program ended successfully */
48
49 } /* end function main */
2007 Pearson Education,
Inc. All rights reserved.
28
14
29
Performance Tip
30
Assignment Operators
c = c + 3;
Assignment operator
The form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
can be abbreviated as
c += 3;
using the addition assignment operator
15
31
d -= 4; is equal to (d = d - 4)
e *= 5; is equal to (e = e * 5)
f /= 3; is equal to (f = f / 3)
g %= 9; is equal to (g = g % 9)
32
16
33
34
17
35
5
6
6
2007 Pearson Education,
Inc. All rights reserved.
18
37
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1, x2, x3, x4;
x1=x2=x3=x4=1;
x1=x1+1; %1st
x2+=1; %2nd
x3++; %3th
++x4; %4th
printf("The results are: %d, %d, %d, %d\n",x1,x2,x3,x4);
system("Pause");
return 0; /* successful termination */
}
19
What is the expected output of each of the following? Q
int i=3;
printf( "%d ", (--i + 3) );
printf( "%d", (i++ + 10) );
Answer:
5 12
What is the value of i now?
20
1
4
C Program
Control
OBJECTIVES
In this chapter you will learn:
The essentials of counter-controlled repetition.
To use the for and do...while repetition statements to
execute statements in a program repeatedly.
To understand multiple selection using the switch
selection statement.
To use the break and continue program control statements
to alter the flow of control.
To use the logical operators to form complex conditional
expressions in control statements.
To avoid the consequences of confusing the equality and
assignment operators.
1
3
4.1 Introduction
This chapter introduces
– Additional repetition control structures
- for
- do…while
– switch multiple selection statement
– break statement
- Used for exiting immediately and rapidly from certain control
structures
– continue statement
- Used for skipping the remainder of the body of a repetition
structure and proceeding with the next iteration of the loop
2
5
– The statement
int counter = 1;
- Names variable as counter
- Defines it to be an integer
- Reserves space for it in memory
- Sets it to an initial value of 1
3
1 /* Fig. 4.1: fig04_01.c 7
2
3
Counter-controlled repetition */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_01.c
7 {
8 int counter = 1; /* initialization */ Definition and assignment are
9
performed simultaneously
10 while ( counter <= 10 ) { /* repetition condition */
11 printf ( "%d\n", counter ); /* display counter */
12 ++counter; /* increment */
13 } /* end while */
14
15 return 0; /* indicate program ended successfully */
16
17 } /* end function main */
1
2
3
4
5
6
7
8
9
10
Counter-Controlled Repetition
Condensed code
– C Programmers would make the program more concise
– Initialize counter to 0
- int counter = 0;
- while ( ++counter <= 10 )
printf("%d\n", counter );
4
9
Fig. 4.4 |
Flowcharting a
typical for
repetition statement.
10
5
11
6
13
14
Arithmetic expressions
– Initialization, loop-continuation, and increment can contain
arithmetic expressions.
7
15
Error-Prevention Tip
Sum is 2550
8
1 /* Fig. 4.6: fig04_06.c 17
2
3
Calculating compound interest */
#include <stdio.h>
Outline
4 #include <math.h> additional header
5
6 /* function main begins program execution */
fig04_06.c
7 int main( void )
8 {
9 double amount; /* amount on deposit */
(1 of 2 )
10 double principal = 1000.0; /* starting principal */
11 double rate = .05; /* annual interest rate */
12 int year; /* year counter */
13
14 /* output table column head */
15 printf( "%4s%21s\n", "Year", "Amount on deposit" );
16
17 /* calculate amount on deposit for each of ten years */
18 for ( year = 1; year <= 10; year++ ) {
19
20 /* calculate new amount for specified year */
21 amount = principal * pow( 1.0 + rate, year ); pow function calculates the value
22 of the first argument to the power
23 /* output one table row */
of the second argument
24 printf( "%4d%21.2f\n", year, amount );
25 } /* end for */
26 double pow(double x, double y);
27 return 0; /* indicate program ended successfully */
28
29 } /* end function main */
18
Year Amount on deposit Outline
1 1050.00
2 1102.50
3 1157.63
4 1215.51 fig04_06.c
5 1276.28
6 1340.10 (2 of 2 )
7 1407.10
8 1477.46
9 1551.33
10 1628.89
%f format specifier prints 6 digits after
the decimal point by default.
9
19
switch ( value ) {
case '1':
actions
if ‘value’ is equal to ‘2’, the code is swithed to
case '2':
the ‘case 2’. Then, statements under ‘case 2’
actions
are executed.
default:
actions
} if ‘value’ is not equal to ‘1’ and ‘2’, the code is
swithed to the ‘default’. Then, statements
under ‘default’ is executed.
20
case 1
action
case 2
action
case 3
action
default
action
10
The break statement
Syntax: break;
22
getchar() function
The C library function
getchar()
reads only one character (an unsigned char) from
standart input (keyboard).
#include <stdio.h>
int main () {
char k;
k = getchar();
return(0);
11
1 /* Fig. 4.7: fig04_07.c 23
2
3
Counting letter grades */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_07.c
7 {
8 int grade; /* one grade */
9 int aCount = 0; /* number of As */
(1 of 4 )
10 int bCount = 0; /* number of Bs */
11 int cCount = 0; /* number of Cs */
12 int dCount = 0; /* number of Ds */
13 int fCount = 0; /* number of Fs */
14
15 printf( "Enter the letter grades.\n" );
16 printf( "Enter the EOF character to end input.\n" );
17
18 /* loop until user types end-of-file key sequence */
19 while ( ( grade = getchar() ) != EOF ) { EOF stands for “end of file;” this character
20 varies from system to system
21 /* determine which grade was input */
22 switch ( grade ) { /* switch nested in while */
23 switch statement checks each of its
24 case 'A': /* grade was uppercase A */ nested cases for a match
25 case 'a': /* or lowercase a */
26 ++aCount; /* increment aCount */
27 break; /* necessary to exit switch */
28
12
54 default: /* catch all other characters */ 25
55
56
printf( "Incorrect letter grade entered." );
printf( " Enter a new grade.\n" );
Outline
57 break; /* optional; will exit switch anyway */ default case occurs if none of
58 } /* end switch */
the cases are matched
59
fig04_07.c
60 } /* end while */
61
62 /* output summary of results */
(3 of 4 )
63 printf( "\nTotals for each letter grade are:\n" );
64 printf( "A: %d\n", aCount ); /* display number of A grades */
65 printf( "B: %d\n", bCount ); /* display number of B grades */
66 printf( "C: %d\n", cCount ); /* display number of C grades */
67 printf( "D: %d\n", dCount ); /* display number of D grades */
68 printf( "F: %d\n", fCount ); /* display number of F grades */
69
70 return 0; /* indicate program ended successfully */
71
72 } /* end function main */
26
Enter the letter grades.
Enter the EOF character to end input. Outline
a
b
c
C
A fig04_07.c
d
f
C (4 of 4 )
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
^Z
13
27
28
Portability Tip
14
29
30
int counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);
15
31
do {
printf( "%d ", counter );
} while (++counter <= 10);
32
16
1 /* Fig. 4.9: fig04_09.c 33
2
3
Using the do/while repetition statement */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_09.c
7 {
8 int counter = 1; /* initialize counter */
9
10 do {
11 printf( "%d ", counter ); /* display counter */
12 } while ( ++counter <= 10 ); /* end do...while */ increments counter then checks if
13
it is less than or equal to 10
14 return 0; /* indicate program ended successfully */
15
16 } /* end function main */
1 2 3 4 5 6 7 8 9 10
34
17
1 /* Fig. 4.11: fig04_11.c 35
2
3
Using the break statement in a for statement */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_11.c
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, terminate loop */
14 if ( x == 5 ) {
15 break; /* break loop only if x is 5 */
break immediately ends for
16 } /* end if */ loop
17
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nBroke out of loop at x == %d\n", x );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4
Broke out of loop at x == 5
36
18
1 /* Fig. 4.12: fig04_12.c 37
2 Using the continue statement in a for statement */
Outline
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
fig04_12.c
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, continue with next iteration of loop */
14 if ( x == 5 ) {
15 continue; /* skip remaining code in loop body */
continue skips to end of
16 } /* end if */ for loop and performs next
17 iteration
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nUsed continue to skip printing the value 5\n" );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
38
Logical Operators
&& ( logical AND )
– Returns true if both conditions are true
|| ( logical OR )
– Returns true if either of its conditions are true
! ( logical NOT, logical negation )
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
19
39
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Fig. 4.13 | Truth table for the && (logical AND) operator.
40
|| ( logical OR )
– Returns true if either of its conditions are true
0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1
20
41
expression !expression
0 1
nonzero 0
42
Performance Tip
In expressions using operator &&, make the
condition that is most likely to be false the leftmost
condition.
In expressions using operator ||, make the
condition that is most likely to be true the leftmost
condition.
21
43
44
22
45
23
1
5
C Functions
OBJECTIVES
In this chapter you will learn:
To construct programs modularly from small pieces
called functions.
The common math functions available in the C
Standard Library.
To create new functions.
The mechanisms used to pass information between
functions.
Simulation techniques using random number
generation.
How to write and use recursive functions, i.e., functions
that call themselves.
1
3
Introduction
Why functions?
• Break longer jobs into conceptually smaller jobs which
are precisely defined.
• A C program generally consists of many small functions.
• A piece of a code which repeats at many places can be
written only once and used again and again.
• Debugging and maintenance is easy
Functions in C
C standard library has a wide variety of functions
2
5
x
exp( x ) exponential function e exp( 1.0 ) is 2.718282
exp( 2.0 ) is 7.389056
3
7
#include <math.h>
4
9
For example: If you want to use sqrt() function, the header
file <math.h> should be included.
#include <stdio.h>
#include <math.h>
int main() {
sqrt(900);
10
sqrt(900.0);
- Calls function sqrt, which returns the square root of its
argument
- All math functions return data type double
5
11
12
Portability Tip
If you use the functions in the C Standart
library, this helps your programs more
portable.
6
13
Function Definitions
if we want to define a new function
Return-value-type: data type of the result function-name: any
(default int). valid identifier
void indicates that the function returns nothing
14
Function Definitions
return-value-type function-name( parameter-list )
{
declarations and statements
function body
}
7
15
Function Definitions
// function definition
int max(int a){
int b=100;
return a>b ? a : b;
}
int main() {
int x;
x = max(5,8);
Function is called
x = max(x,7);
} // end of main function
// function definition
int max(int a, int b){ Function definition
return a>b ? a : b;
}
8
1 /* Fig. 5.3: fig05_03.c 17
2
3
Creating and using a programmer-defined function */
#include <stdio.h>
Outline
4
5 int square( int y ); /* function prototype */
6
7 /* function main begins program execution */
Function prototype indicates function
8 int main( void ) will be defined later in the program
9 {
10 int x; /* counter */
11
12 /* loop 10 times and calculate and output square of x each time */
13 for ( x = 1; x <= 10; x++ ) {
14 printf( "%d ", square( x ) ); /* function call */
15 } /* end for */
16
Call to square function
17 printf( "\n" );
18 Place a blank line between
19 return 0; /* indicates successful termination */ function definitions to separate
20 the functions and enhance
21 } /* end main */
22
program readability.
23 /* square function definition returns square of parameter */
24 int square( int y ) /* y is a copy of argument to function */ Function definition
25 {
26 return y * y; /* returns square of y as an int */
27
28 } /* end function square */
Code output
1 4 9 16 25 36 49 64 81 100
18
int main {
… }
sample_f ( parameter-list )
{
declarations and statements, calculations of x
return x;
}
9
19
int main {
… }
20
int main {
… }
return x;
}
10
21
int main {
… }
sample_f ( parameter-list )
{
declarations and statements, calculations of x
return x;
}
22
int main {
y is declared as
… }
integer
double sample_f ( double x, y )
{
declarations and statements, calculations of x
return x;
}
11
23
int main {
… }
24
12
25
26
13
1 /* Fig. 5.4: fig05_04.c 27
2
3
Finding the maximum of three integers */
#include <stdio.h>
Outline
4
5 int maximum( int x, int y, int z ); /* function prototype */
6
fig05_04.c
7 /* function main begins program execution */ Function prototype
8 int main( void )
9 {
(1 of 2 )
10 int number1; /* first integer */
11 int number2; /* second integer */
12 int number3; /* third integer */
13
14 printf( "Enter three integers: " );
15 scanf( "%d%d%d", &number1, &number2, &number3 );
16 Function call
17 /* number1, number2 and number3 are arguments
18 to the maximum function call */
19 printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24
14
29
Function Prototypes
Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after
the use in program
30
int main {
… }
15
31
unsigned int %u %u
int %d %d
unsigned short %hu %hu
short %hd %hd
char %c %c
Converting to
Fig. 5.5 | Promotion hierarchy for data types. lower data types
can lead to
Please refer to: https://en.wikipedia.org/wiki/C_data_types errors
32
int main {
… }
16
33
// function definition
int sample_f ( int x, int y )
{
declarations and statements, calculations of x
return x;
}
34
17
35
Headers
Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
36
18
37
38
1 + ( rand() % n )
1 + ( rand() % 6)
19
Computers
and Random Numbers
Computers are “deterministic” machines
Computers are not capable of true randomness
Instead, pseudo-random numbers are used
– Pseudo-random numbers are generated using a
mathematical formula
– There is a pattern in pseudo-random numbers
– The pattern is nearly impossible to observe
Advantage of Psuedo-Randomness
It would be difficult to debug programs that use truly random
numbers (can’t recreate error cases on demand)
By providing the same start-value (seed) to the generator, the same
sequence results on each run and error cases can be observed
When you are through debugging, you can use a different seed each
time.
– Often, this is done by using the system clock
20
1 /* Fig. 5.7: fig05_07.c 41
2
3
Shifted, scaled integers produced by 1 + rand() % 6 */
#include <stdio.h>
Outline
4 #include <stdlib.h>
5
6 /* function main begins program execution */
fig05_07.c
7 int main( void )
8 {
9 int i; /* counter */
10
11 /* loop 20 times */
12 for ( i = 1; i <= 20; i++ ) {
13
14 /* pick random number from 1 to 6 and output it */
15 printf( "%10d", 1 + ( rand() % 6 ) ); Generates a random number between 1 and 6
16
17 /* if counter is divisible by 5, begin new line of output */
18 if ( i % 5 == 0 ) {
19 printf( "\n" );
20 } /* end if */
21
22 } /* end for */ rand() function returns
23 same sequence for
24 return 0; /* indicates successful termination */
every function call
25
26 } /* end main */
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
21
30 case 2: /* rolled 2 */ 43
31
32
++frequency2;
break;
Outline
33
34 case 3: /* rolled 3 */
35 ++frequency3;
fig05_08.c
36 break;
37
38 case 4: /* rolled 4 */
(2 of 3 )
39 ++frequency4;
40 break;
41
42 case 5: /* rolled 5 */
43 ++frequency5;
44 break;
45
If face=6, frequency6 is
46 case 6: /* rolled 6 */
incremented by one.
47 ++frequency6;
48 break; /* optional */
49 } /* end switch */
50
51 } /* end for */
52
Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999
22
45
srand function
– <stdlib.h>
– Takes an integer seed and jumps to that location in its "random"
sequence
srand( seed );
– srand( time( NULL ) );/*load <time.h> */
- time( NULL )
Returns the number of seconds that have passed since
January 1, 1970
“Randomizes" the seed
23
Enter seed: 67
47
6 1 4 6 2 Outline
1 6 1 6 4
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
24
Using Time to Seed the Generator
Must include the <time.h> library: Provides function “time( )”
Enumeration
Constants
#include<stdio.h>
void main() {
Here, today is defined as a variable
enum week today;
today=TUE; and sun, mon, tue, wed, thu, fri
printf("%d day",today+1); and sat are the enumeration
} constants having values 0, 1, 2, 3, 4,
5 and 6 respectively.
25
To number the days 1 to 7, use the following enumeration:
52
26
53
54
27
1 /* Fig. 5.10: fig05_10.c 55
2
3
Craps */
#include <stdio.h>
Outline
4 #include <stdlib.h>
5 #include <time.h> /* contains prototype for function time */
6
fig05_10.c
7 /* enumeration constants represent game status */
8 enum Status { CONTINUE, WON, LOST };
enum (enumeration) assigns
(1numerical
of 4 )
9
10 int rollDice( void ); /* function prototype */ values to CONTINUE, WON and LOST
11
12 /* function main begins program execution */
13 int main( void )
14 {
15 int sum; /* sum of rolled dice */
16 int myPoint; /* point earned */
17
18 enum Status gameStatus; /* can contain CONTINUE, WON, or LOST */
19
20 /* randomize random number generator using current time */
21 srand( time( NULL ) );
22
23 sum = rollDice(); /* first roll of the dice */
24
25 /* determine game status based on sum of dice */
26 switch( sum ) {
27
Rules:
Roll two dice
7 or 11 on first throw, player wins
2, 3, or 12 on first throw, player loses
4, 5, 6, 8, 9, 10 - value becomes player's
"point"
Player must roll his point before rolling 7 to win
2007 Pearson Education,
Inc. All rights reserved.
28
49 /* while game not complete */ 57
50
51
while ( gameStatus == CONTINUE ) {
sum = rollDice(); /* roll dice again */
Outline
52
53 /* determine game status */
54 if ( sum == myPoint ) { /* win by making point */
fig05_10.c
55 gameStatus = WON; /* game over, player won */
56 } /* end if */
57 else {
(3 of 4 )
58
59 if ( sum == 7 ) { /* lose by rolling 7 */
60 gameStatus = LOST; /* game over, player lost */
61 } /* end if */
62
63 } /* end else */
64
65 } /* end while */
66
67 /* display won or lost message */
68 if ( gameStatus == WON ) { /* did player win? */
69 printf( "Player wins\n" );
70 } /* end if */
71 else { /* player lost */
72 printf( "Player loses\n" );
73 } /* end else */
74
75 return 0; /* indicates successful termination */
76
77 } /* end main */
78 58
79
80
/* roll dice, calculate sum and display results */
int rollDice( void )
Outline
81 {
82 int die1; /* first die */
83 int die2; /* second die */
fig05_10.c
84 int workSum; /* sum of dice */
85
86 die1 = 1 + ( rand() % 6 ); /* pick random die1 value */
(4 of 4 )
87 die2 = 1 + ( rand() % 6 ); /* pick random die2 value */
88 workSum = die1 + die2; /* sum die1 and die2 */
89
90 /* display results of this roll */
91 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum );
92
93 return workSum; /* return sum of dice */
94
95 } /* end function rollRice */
29
Player rolled 5 + 6 = 11 59
Player wins Outline
Player rolled 4 + 1 = 5
Point is 5
Player rolled 6 + 2 = 8 fig05_11.c
Player rolled 2 + 1 = 3
Player rolled 3 + 2 = 5
Player wins
Player rolled 1 + 1 = 2
Player loses
Player rolled 6 + 4 = 10
Point is 10
Player rolled 3 + 4 = 7
Player loses
60
Storage Classes
Every variable in C programming has two properties:
type and storage class.
30
61
Local Variable
The variables declared inside the function are local variables.
The local variables exist only inside the function in which it is declared. When
the function exits, the local variables are destroyed.
int main() {
int n; // n is a local variable to main() function
... .. ...
}
void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed
when main() exits.
62
Global Variable
Variables that are declared outside of all functions are known as global variables.
Global variables are accessible to any function.
#include <stdio.h>
void display();
int n = 5; // global variable
int main() {
++n; // variable n is not declared in the main() function
display();
return 0;}
void display() {
++n; // variable n is not declared in the display() function
printf ("n = %d", n); }
31
63
Recursion
Recursive functions
– Functions that call themselves. The function launches a new copy of
itself (recursion step) to solve what it cannot do
Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
- 5! = 5 * 4!
- 4! = 4 * 3!
- 3! = 3 * 2!
- 2! = 2 * 1!
– Can compute factorials recursively
– Solve base case (1! = 1) then plug in
- 2! = 2 * 1! = 2 * 1 = 2;
- 3! = 3 * 2! = 3 * 2 = 6;
- 4! = 4 * 3! = 4 * 6 = 24;
- 5! = 5 * 4! = 5 * 24 = 120;
32
22 /* recursive definition of function factorial */ 65
23
24
long factorial( long number )
{
Outline
25 /* base case */
26 if ( number <= 1 ) { Omitting the base case will
27 return 1;
cause infinite recursion,
28 } /* end if */
29 else { /* recursive step */ eventually exhausting
30 return ( number * factorial( number - 1 ) ); memory.
31 } /* end else */
32
33 } /* end function factorial */
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
66
33
67
34
27 /* Recursive definition of function fibonacci */ 69
28 long fibonacci( long n )
29 {
Outline
30 /* base case */
31 if ( n == 0 || n == 1 ) {
32 return n;
fig05_15.c
33 } /* end if */
34 else { /* recursive step */
35 return fibonacci( n - 1 ) + fibonacci( n - 2 );
(2 of 4 )
36 } /* end else */
37
38 } /* end function fibonacci */
Enter an integer: 0
Fibonacci( 0 ) = 0
Enter an integer: 1
Fibonacci( 1 ) = 1
Enter an integer: 2
Fibonacci( 2 ) = 1
(continued on next slide… )
Enter an integer: 4
Fibonacci( 4 ) = 3 fig05_15.c
(3 of 4 )
Enter an integer: 5
Fibonacci( 5 ) = 5
Enter an integer: 6
Fibonacci( 6 ) = 8
(continued on next slide… )
35
(continued from previous slide…) 71
Enter an integer: 10
Fibonacci( 10 ) = 55
Outline
Enter an integer: 20
Fibonacci( 20 ) = 6765 fig05_15.c
(4 of 4 )
Enter an integer: 30
Fibonacci( 30 ) = 832040
Enter an integer: 35
Fibonacci( 35 ) = 9227465
72
36
73
Performance Tip
Avoid using recursion in performance situations.
Recursive calls take time and consume additional
memory.
37
1
6
C Arrays
OBJECTIVES
In this chapter you will learn:
To use the array data structure to represent lists
and tables of values.
To define an array, initialize an array and refer to
individual elements of an array.
To define symbolic constants.
To pass arrays to functions.
To use arrays to store, sort and search lists and
tables of values.
To define and manipulate multiple-subscripted
arrays.
1
3
6.1 Arrays
Instead of declaring individual variables (having same data type) , such as
number0, number1, ..., and number99, you declare one array variable
such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
6.1 Arrays
2
Array indexes always start at zero in C
– Examples:
int c[ 12 ];
3
7
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
int b[ 100 ], x[ 27 ];
4
9
int n[ 5 ] = { 5, 2 }
Remaining three element are 0
int n[ 5 ] = { 5, 2, 7, 9, 2, 1, 4}
If too many initializers, a syntax error occurs
10
int n[ ] = { 1, 2, 3, 4, 5 };
5
1 /* Fig. 6.3: fig06_03.c 11
2
3
initializing an array */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig06_03.c
7 {
8 int n[ 10 ]; /* n is an array of 10 integers */
9 int i; /* counter */
(1 of 2 )
10
11 /* initialize elements of array n to 0 */
12 for ( i = 0; i < 10; i++ ) { for loop initializes each array
13 n[ i ] = 0; /* set element at location i to 0 */ element separately
14 } /* end for */
15
16 printf( "%s%13s\n", "Element", "Value" );
17
18 /* output contents of array n in tabular format */
19 for ( i = 0; i < 10; i++ ) { for loop outputs all array elements
20 printf( "%7d%13d\n", i, n[ i ] );
21 } /* end for */
22
23 return 0; /* indicates successful termination */
24
Element Value
25 } /* end main */ 0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0 2007 Pearson Education,
9 0 Inc. All rights reserved.
6
1 /* Fig. 6.5: fig06_05.c 13
2 Initialize the elements of array s to the even integers from 2 to 20 */
3 #include <stdio.h>
4 #define SIZE 10 /* maximum size of array */ #define directive tells compiler to replace all
5 instances of the word SIZE with 10
6 /* function main begins program execution */
7 int main( void )
8 {
9 /* symbolic constant SIZE can be used to specify array size */
10 int s[ SIZE ]; /* array s has SIZE elements */
SIZE is replaced with 10 by the
11 int j; /* counter */ compiler, so array s has 10 elements
12
13 for ( j = 0; j < SIZE; j++ ) { /* set the values */
14 s[ j ] = 2 + 2 * j; for loop initializes each array
15 } /* end for */
16
element separately
17 printf( "%s%13s\n", "Element", "Value" );
18
19 /* output contents of array s in tabular format */
20 for ( j = 0; j < SIZE; j++ ) {
21 printf( "%7d%13d\n", j, s[ j ] );
22 } /* end for */ Element Value
23 0 2
24 return 0; /* indicates successful termination */ 1 4
25 2 6
26 } /* end main */ 3 8
4 10
fig06_05.c 5 12
6 14
7 16
8 18
2007 Pearson Education,
9 20
Inc. All rights reserved.
14
7
15
#define SIZE 10 /*
16
8
17
#define SIZE 10 /*
9
1 /* Fig. 6.7: fig06_07.c 19
2
3
Student poll program */
#include <stdio.h>
Outline
4 #define RESPONSE_SIZE 40 /* define array sizes */ #define directives create
5 #define FREQUENCY_SIZE 11 symbolic constants
6
7 /* function main begins program execution */
fig06_07.c
8 int main( void )
9 {
(1 of 2 )
10 int answer; /* counter to loop through 40 responses */
11 int rating; /* counter to loop through frequencies 1-10 */
12
13 /* initialize frequency counters to 0 */
14 int frequency[ FREQUENCY_SIZE ] = { 0 };
frequency array is
15 defined with 11 elements
16 /* place the survey responses in the responses array */
17 int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, responses array is
18 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6,
19 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
defined with 40 elements
20 and its elements are
21 /* for each answer, select value of an element of array responses initialized
22 and use that value as subscript in array frequency to
23 determine element to increment */
24 for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) {
25 ++frequency[ responses [ answer ] ]; subscript of frequency array is
26 } /* end for */ given by value in responses array
27
28 /* display results */ 20
29
30
printf( "%s%17s\n", "Rating", "Frequency" );
Outline
31 /* output the frequencies in a tabular format */
32 for ( rating = 1; rating < FREQUENCY_SIZE; rating++ ) {
33 printf( "%6d%17d\n", rating, frequency[ rating ] );
fig06_07.c
34 } /* end for */
35
36 return 0; /* indicates successful termination */
(2 of 2 )
37
38 } /* end main */
Rating Frequency
1 2
2 2
3 2
4 2
5 5
6 11
7 5
8 7
9 1
10 3
10
1 /* Fig. 6.8: fig06_08.c 22
2
3
Histogram printing program */
#include <stdio.h>
Outline
4 #define SIZE 10
5
6 /* function main begins program execution */
fig06_08.c
7 int main( void )
8 {
9 /* use initializer list to initialize array n */
10 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
11 int i; /* outer for counter for array elements */
12 int j; /* inner for counter counts *s in each histogram bar */
13
14 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
15
16 /* for each element of array n, output a bar of the histogram */
17 for ( i = 0; i < SIZE; i++ ) {
18 printf( "%7d%13d ", i, n[ i ]) ;
19
20 for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */
21 printf( "%c", '*' );
22 } /* end inner for */ Element Value Histogram
23 0 19 *******************
24 printf( "\n" ); /* end a histogram bar */ 1 3 ***
25 } /* end outer for */ 2 15 ***************
26 3 7 *******
4 11 ***********
27 return 0; /* indicates successful termination */
5 9 *********
28
6 13 *************
29 } /* end main */
7 5 *****
8 17 *****************
9 1 *2007 Pearson Education,
Inc. All rights reserved.
11
22 24
23
24
printf( "%s%17s\n", "Face", "Frequency" );
Outline
25 /* output frequency elements 1-6 in tabular format */
26 for ( face = 1; face < SIZE; face++ ) {
27 printf( "%4d%17d\n", face, frequency[ face ] );
fig06_09.c
28 } /* end for */
29
30 return 0; /* indicates successful termination */
(2 of 2 )
31
32 } /* end main */
Face Frequency
1 1029
2 951
3 987
4 1033
5 1010
6 990
Character Strings
A sequence of characters is often referred to as a character
“string”.
A string is stored in an array of type char ending with the
null character '\0 '.
12
Character Strings
A string containing a single character takes up 2 bytes of storage.
Character Strings
13
Character vs. String
14
30
It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
31
15
32
Output:
Enter name: Ali Zengin
Your name is Ali
16
1 /* Fig. 6.11: fig06_11.c 34
2
3
Static arrays are initialized to zero */
#include <stdio.h>
Outline
4
5 void staticArrayInit( void ); /* function prototype */
6 void automaticArrayInit( void ); /* function prototype */
fig06_11.c
7
8 /* function main begins program execution */
9 int main( void )
(1 of 4 )
10 {
11 printf( "First call to each function:\n" );
12 staticArrayInit();
13 automaticArrayInit();
14
15 printf( "\n\nSecond call to each function:\n" );
16 staticArrayInit();
17 automaticArrayInit();
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
17
45 36
46 /* function to demonstrate an automatic local array */
47 void automaticArrayInit( void )
Outline
48 {
49 /* initializes elements each time function is called */
50 int array2[ 3 ] = { 1, 2, 3 };
51 int i; /* counter */
automatic array is recreated every time
52 automaticArrayInit is called
53 printf( "\n\nValues on entering automaticArrayInit:\n" );
54
55 /* output contents of array2 */ fig06_11.c
56 for ( i = 0; i <= 2; i++ ) {
57 printf("array2[ %d ] = %d ", i, array2[ i ] ); (3 of 4 )
58 } /* end for */
59
60 printf( "\nValues on exiting automaticArrayInit:\n" );
61
62 /* modify and output contents of array2 */
63 for ( i = 0; i <= 2; i++ ) {
64 printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 );
65 } /* end for */
66
67 } /* end function automaticArrayInit */
37
First call to each function:
Outline
Values on entering staticArrayInit:
array1[ 0 ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0
Values on exiting staticArrayInit:
array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5 fig06_11.c
18
38
39
19
40
array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78
20
42
#include <stdio.h>
int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element by value only.
return 0;
}
Output
4
43
int main()
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}
21
1 /* Fig. 6.13: fig06_13.c 44
2
3
Passing arrays and individual array elements to functions */
#include <stdio.h>
Outline
4 #define SIZE 5
5
6 /* function prototypes */
7 void modifyArray( int b[], int size ); Function prototype indicates
8 void modifyElement( int e );
function will take an array
9
10 /* function main begins program execution */ fig06_13.c
11 int main( void )
12 { (1 of 3 )
13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */
14 int i; /* counter */
15
16 printf( "Effects of passing entire array by reference:\n\nThe "
17 "values of the original array are:\n" );
18
19 /* output original array */
20 for ( i = 0; i < SIZE; i++ ) {
21 printf( "%3d", a[ i ] );
22 } /* end for */
23
24 printf( "\n" );
25
26 /* pass array a to modifyArray by reference */
27 modifyArray( a, SIZE );
Array a is passed to modifyArray
28 by passing only its name
29 printf( "The values of the modified array are:\n" );
30
22
61 46
62 /* in function modifyElement, "e" is a local copy of array element
63 a[ 3 ] passed from main */
Outline
64 void modifyElement( int e )
65 {
66 /* multiply parameter by 2 */
fig06_13.c
67 printf( "Value in modifyElement is %d\n", e *= 2 );
68 } /* end function modifyElement */
(3 of 3 )
Effects of passing entire array by reference:
Compiling...
FIG06_14.C
fig06_14.c(24) : error C2166: l-value specifies const object
fig06_14.c(25) : error C2166: l-value specifies const object 2007 Pearson Education,
Inc. All rights reserved.
fig06_14.c(26) : error C2166: l-value specifies const object
23
48
49
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– Initializers grouped by row in braces
24
50
Result = 2
51
25
52
Fig. 6.20 | Double-subscripted array with three rows and four columns.
53
1st row
26
1 /* Fig. 6.21: fig06_21.c 54
2 Initializing multidimensional arrays */ number of columns Outline
3 #include <stdio.h>
4
5 void printArray( const int a[][ 3 ] ); /* function prototype */
6
fig06_21.c
7 /* function main begins program execution */
8 int main( void )
9 { array1 is initialized(1with
of 2 )both rows
10 /* initialize array1, array2, array3 */ full
11 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
12 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
array2 and array3 are initialized only
13 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
14 partially
15 printf( "Values in array1 by row are:\n" );
16 printArray( array1 );
17
18 printf( "Values in array2 by row are:\n" );
19 printArray( array2 );
20
21 printf( "Values in array3 by row are:\n" );
22 printArray( array3 );
23
24 return 0; /* indicates successful termination */
25
26 } /* end main */
27
27
1 /* Fig. 6.22: fig06_22.c 56
2
3
Double-subscripted array example */
#include <stdio.h>
Outline
4 #define STUDENTS 3
5 #define EXAMS 4
6
fig06_22.c
7 /* function prototypes */
8 int minimum( const int grades[][ EXAMS ], int pupils, int tests );
9 int maximum( const int grades[][ EXAMS ], int pupils, int tests );
(1 of 6 )
10 double average( const int setOfGrades[], int tests );
11 void printArray( const int grades[][ EXAMS ], int pupils, int tests );
12
13 /* function main begins program execution */
14 int main( void )
15 {
16 int student; /* student counter */
17
18 /* initialize student grades for three students (rows) */
19 const int studentGrades[ STUDENTS ][ EXAMS ] =
20 { { 77, 68, 86, 73 },
21 { 96, 87, 89, 78 }, Each row in the array corresponds
22 { 70, 90, 86, 81 } }; to a single student’s set of grades
23
24 /* output array studentGrades */
25 printf( "The array is:\n" );
26 printArray( studentGrades, STUDENTS, EXAMS );
27
28
43 /* Find the minimum grade */ 58
44 int minimum( const int grades[][ EXAMS ], int pupils, int tests )
45 {
Outline
46 int i; /* student counter */
47 int j; /* exam counter */
48 int lowGrade = 100; /* initialize to highest possible grade */
fig06_22.c
49
50 /* loop through rows of grades */
51 for ( i = 0; i < pupils; i++ ) {
(3 of 6 )
52
53 /* loop through columns of grades */
54 for ( j = 0; j < tests; j++ ) {
55
56 if ( grades[ i ][ j ] < lowGrade ) {
57 lowGrade = grades[ i ][ j ];
58 } /* end if */
59
60 } /* end inner for */
61
62 } /* end outer for */
63
64 return lowGrade; /* return minimum grade */
65
66 } /* end function minimum */
67
29
93 /* Determine the average grade for a particular student */ 60
94 double average( const int setOfGrades[], int tests )
95 {
Outline
96 int i; /* exam counter */
97 int total = 0; /* sum of test grades */
98
fig06_22.c
99 /* total all grades for one student */
100 for ( i = 0; i < tests; i++ ) {
101 total += setOfGrades[ i ];
(5 of 6 )
102 } /* end for */
103
104 return ( double ) total / tests; /* average */
105
106 } /* end function average */
107
108 /* Print the array */
109 void printArray( const int grades[][ EXAMS ], int pupils, int tests )
110 {
111 int i; /* student counter */
112 int j; /* exam counter */
113
114 /* output column heads */
115 printf( " [0] [1] [2] [3]" );
116
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
30
Break
Class assistant will be showing
example applications after the break.
31