0% found this document useful (0 votes)
3 views

C coding

This document serves as an introduction to C programming, covering basic concepts such as writing simple programs, using input/output statements, understanding data types, and arithmetic operations. It includes examples of code, explanations of functions, and best practices for writing clear and maintainable code. The chapter aims to equip readers with foundational skills necessary for programming in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C coding

This document serves as an introduction to C programming, covering basic concepts such as writing simple programs, using input/output statements, understanding data types, and arithmetic operations. It includes examples of code, explanations of functions, and best practices for writing clear and maintainable code. The chapter aims to equip readers with foundational skills necessary for programming in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 140

1

2
Introduction
to C Programming

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

2.1 Introduction
 C programming language
– Structured and disciplined approach to program design
 Structured programming

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

2.2 A Simple C Program:


Printing a Line of Text
Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
 #include <stdio.h>
– Preprocessor directive
- Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations

1 /* Fig. 2.1: fig02_01.c


2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );  2007 Pearson Education, Inc. All rights reserved.
9

3
7

2.2 A Simple C Program:


Printing a Line of Text
 int main()
– C programs contain one or more functions, exactly one of
which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
- The bodies of all functions must be contained in braces
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
 2007 Pearson Education, Inc. All rights reserved.

Good Programming Practice 2.1


Every function should be preceded by a
comment describing the purpose of the
function.
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

Welcome to C!

 2007 Pearson Education, Inc. All rights reserved.

4
9

2.2 A Simple C Program:


Printing a Line of Text
 printf( "Welcome to C!\n" );
– printf() function prints the string of characters within quotes (" ")
– Entire line is called as a statement. All statements must end with a semicolon
(;)
– Escape character (\)
- Indicates that printf should do something out of the ordinary
- \n is the newline character
Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.


\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double-quote character in a string.

printf( "\"Welcome to C!\"\n" );

"Welcome to C!“
 2007 Pearson Education, Inc. All rights reserved.

10

2.2 A Simple C Program:


Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

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.

 2007 Pearson Education, Inc. All rights reserved.

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!

Add a comment to the line containing the


right brace, }, that closes every function,
including main.

 2007 Pearson Education,


Inc. All rights reserved.

1 /* Fig. 2.3: fig02_03.c 12


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 {
8 printf( "Welcome " );
9 printf( "to C!\n" );
10
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */

Welcome to C!

Indent the entire body of each function (we


recommend three spaces) within the braces
that define the body of the function.

 2007 Pearson Education,


Inc. All rights reserved.

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!

 2007 Pearson Education,


Inc. All rights reserved.

Q1

Write a program that prints the following shape by using one


printf statement.

* *
* *
* *
Code is:
printf ( "* *\n* *\n* *" );

7
Q1

Write a program that prints the following shape by using one


printf statement. Space character is not allowed. Use tab
character to give a space between asterics (*) characters.

* *
* *
* *
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;

radius = 1.8; // Assign 1.8 to radius;


a = 'A'; // Assign 'A' to a;

8
Declaring and Initializing in One Step

int x = 1;
float d = 1.4;
double f = 1.4;

1 /* Fig. 2.5: fig02_05.c 18


2
3
Addition program */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig02_05.c
7 {
8 int integer1; /* first number to be input by user */ Definitions of
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
variables
11
12 printf( "Enter first integer\n" ); /* prompt */ scanf obtains a value from the
13 scanf( "%d", &integer1 ); /* read an integer */ user and assigns it to
14
integer1
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
Assigns a value to sum
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */
scanf uses standard input which is usually
Enter first integer
45
keyboard. When the scanf command is
Enter second integer executed the code stops and waits for an
72
Sum is 117 input from the keyboard. And assigns the
input to integer1 until the enter key is
pressed.
 2007 Pearson Education,
Inc. All rights reserved.

9
19

2.3 Another Simple C Program:


Adding Two Integers
 int integer1, integer2, sum;
– Definition of variables
- Variables: locations in memory where a value can be stored
– int means the variables can hold integers (-1, 3, 0, 47)

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

 2007 Pearson Education, Inc. All rights reserved.

20

2.3 Another Simple C Program:


Adding Two Integers
 int integer1, integer2, sum;
– Variable names (identifiers) consist of letters, digits
(cannot begin with a digit) and underscores( _ )
int i,j, k;
float _length, height14;

 Use identifiers (variable names) of 31 or fewer


characters. This helps ensure portability and can
avoid some subtle programming errors.
int integerdeneysonyeniden;

 2007 Pearson Education, Inc. All rights reserved.

10
21

Good Programming Practice 2.6


Choosing meaningful variable names
helps make a program self-documenting,
i.e., fewer comments are needed.
int measured_value;

 2007 Pearson Education, Inc. All rights reserved.

22

Good Programming Practice 2.9


Separate the definitions and executable
statements in a function with one blank line
to emphasize where the definitions end and
the executable statements begin.
1 /* Fig. 2.5: fig02_05.c
2 Addition program */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int integer1; /* first number to be input by user */
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
11
12 printf( "Enter first integer\n" ); /* prompt */
13 scanf( "%d", &integer1 ); /* read an integer */
14
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
 2007 Pearson Education, Inc. All rights reserved.
17

11
23

2.3 Another Simple C Program:


Adding Two Integers
 scanf( "%d", &integer1 );
– Obtains a value from the user
- scanf uses standard input (usually keyboard)
– This scanf statement has two arguments
- %d - indicates data should be a decimal integer
- &integer1 - location in memory to store variable

– When the scanf command is executed the code stops and


waits for an input from the keyboard.
– The user responds to the scanf statement by typing in a
number, then pressing the enter (return) key

 2007 Pearson Education, Inc. All rights reserved.

24

Good Programming Practice 2.10


Place a space after each comma (,) to
make programs more readable.

scanf( "%d", &integer1 );

 2007 Pearson Education, Inc. All rights reserved.

12
25

2.3 Another Simple C Program:


Adding Two Integers
sum = variable1 + variable2;

= is assignment operator. Assigns a value to a


variable. The sum of variable1 + variable2 is assigned
to sum.

 2007 Pearson Education, Inc. All rights reserved.

26

2.3 Another Simple C Program:


Adding Two Integers
sum = variable1 + variable2;

A binary-operator operates on two operands and


manipulates them to return a result.

‘sum’ and ‘ variable1 + variable2’


are two operands of ’=’ in this example.

‘variable1’ and ’ variable2’


are two operands of ’+’ in this example.

 2007 Pearson Education, Inc. All rights reserved.

13
27

2.3 Another Simple C Program:


Adding Two Integers
 printf( "Sum is %d\n", sum );

The value of sum will be printed in place of %d

– 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);

 2007 Pearson Education, Inc. All rights reserved.

28

Good Programming Practice 2.11


Place spaces on either side of a binary
operator. This makes the operator stand
out and makes the program more readable.
sum = variable1 + variable2;

spaces

 2007 Pearson Education, Inc. All rights reserved.

14
29

Common Programming Error 2.6


A calculation in an assignment statement
must be on the right side of the = operator.
It is a syntax error to place a calculation on
the left side of an assignment operator.
sum = variable1 + variable2;
variable1 + variable2 = sum causes syntax error

 2007 Pearson Education, Inc. All rights reserved.

30

2.4 Memory Concepts


 Variables
– Variable names correspond to locations in the computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable (through scanf, for
example), it replaces (and destroys) the previous value
– Reading variables from memory does not change them

int integer1;
interger1 = 45;
After executing the above statement

Fig. 2.6 | Memory location showing the name and value of a variable.

 2007 Pearson Education, Inc. All rights reserved.

15
31

interger1 = 45;
interger2 = 72;

After executing the above statement

Fig. 2.7 | Memory locations after both variables are input.

 2007 Pearson Education, Inc. All rights reserved.

32
interger1 = 45;
interger2 = 72;
sum = interger1 + interger2;

After executing the above statement

Fig. 2.8 | Memory locations after a calculation.

 2007 Pearson Education, Inc. All rights reserved.

16
33

2.5 Arithmetic Operators


Operator Description Example

+ Adds two operands. C =A+B


− Subtracts second operand from the C =A−B
first.
* Multiplies both operands. C =A*B
/ Divides numerator by denumerator. C =B /A
Integer division truncates remainder
7 / 5 evaluates to 1
% Modulus operator(%) returns the C=B%A
remainder
7 % 5 evaluates to 2

 2007 Pearson Education, Inc. All rights reserved.

34

Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)

Operator(s) Operation(s) Order of evaluation (precedence)


( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair is
evaluated first. If there are several pairs of
parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
* Multiplication Evaluated second. If there are several, they are
/ Division evaluated left to right.
% Remainder
+ Addition Evaluated last. If there are several, they are
- Subtraction evaluated left to right.

Fig. 2.10 | Precedence of arithmetic operators.

 2007 Pearson Education, Inc. All rights reserved.

17
35

Fig. 2.11 | Order in which a second-degree polynomial is evaluated.

 2007 Pearson Education, Inc. All rights reserved.

36

2.6 Equality and Relational Operators


The binary relational and equality operators compare their first operand to
their second operand to test the validity of the specified relationship. The
result of a relational expression is 1 if the tested relationship is true and 0
if it is false.

Standard algebraic C equality or


Example of
equality operator or relational Meaning of C condition
C condition
relational operator operator

Equality operators
 == x == y x is equal to y

 != x != y x is not equal to y


Relational operators

 > x > y x is greater than y

 < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

Fig. 2.12 | Equality and relational operators.


 2007 Pearson Education, Inc. All rights reserved.

18
37

What is the output of the following code Q


#include <stdio.h>

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

 2007 Pearson Education, Inc. All rights reserved.

Write is the output of this code Q

 2007 Pearson Education, Inc. All rights reserved.

19
39

Common Programming Error 2.16


A syntax error will occur if the two symbols
in any of the operators ==, !=, >= and <=
are separated by spaces.

No space

variable1 = = sum causes syntax error

 2007 Pearson Education, Inc. All rights reserved.

40

Common Programming Error 2.17

A syntax error will occur if the two symbols


in any of the operators !=, >= and <= are
reversed as in =!, => and =<, respectively.

 2007 Pearson Education, Inc. All rights reserved.

20
41

Common Programming Error 2.18

Confusing the equality operator == with


the assignment operator =

 2007 Pearson Education, Inc. All rights reserved.

42

if control statement
 if control statement
– Simple version in this section, more detail later

– If a condition is true, then the body of the if statement executed

if (condition) {
body statements
}

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

29 if ( num1 > num2 ) {


44
30 printf( "%d is greater than %d\n", num1, num2 ); Outline
31 } /* end if */
Checks if num1 is greater than num2
32
33 if ( num1 <= num2 ) { Checks if num1 is less than or equal to num2
34 printf( "%d is less than or equal to %d\n", num1, num2 );
35 } /* end if */
fig02_13.c
36
37 if ( num1 >= num2 ) { Checks if num1 is greater than equal to num2
(2 of 3 )
38 printf( "%d is greater than or equal to %d\n", num1, num2 );
39 } /* end if */
40
41 return 0; /* indicate that program ended successfully */
42
43 } /* end function main */
43 } /* end function main */

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

(continued on next slide… )

 2007 Pearson Education,


Inc. All rights reserved.

22
45
Outline

(continued from previous slide…)


fig02_13.c

Enter two integers, and I will tell you (3 of 3 )


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12

Enter two integers, and I will tell you


the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

 2007 Pearson Education,


Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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

Fig. 2.15 | C’s keywords.

 2007 Pearson Education, Inc. All rights reserved.

Q1

What is the result of this logic statement?

int i=5, j=10, k=20;

i > 5 * k % 3 > (k-2!=18)

 2007 Pearson Education, Inc. All rights reserved.

24
Q1

What is the result of this logic statement?


int i=5, j=10, k=20;

i > 5 * k % 3 > (k-2!=18)



i > 5 * k % 3 > (18!=18)

i>5*k%3>0

i > 100 % 3 > 0

i>1>0

1>0

1

 2007 Pearson Education, Inc. All rights reserved.

50
Identify and correct the errors in each of the following
statements. (Note: There may be more than one error per
statement.)

scanf( "d", value );


printf( "The product of %d and %d is %d"\n, x, y );
firstNumber + secondNumber = sumOfNumbers
if ( number => largest ) largest == number;
*/ Program to determine the largest of three integers /*
Scanf( "%d", anInteger );
printf( "Remainder of %d divided by %d is\n", x, y, x % y );
if ( x = y );
printf( %d is equal to %d\n", x, y );
print( "The sum is %d\n," x + y );
printf( "The value you entered is: %d\n, &value );

 2007 Pearson Education, Inc. All rights reserved.

25
51
Identify and correct the errors in each of the following
statements. (Note: There may be more than one error per
statement.)

printf( "The value is %d\n", &number );


scanf( "%d%d", &number1, number2 );
if ( c < 7 ); {
printf( "C is less than 7\n" ); }
if ( c => 7 ) {
printf( "C is equal to or less than 7\n" ); }

 2007 Pearson Education, Inc. All rights reserved.

52

Please write the following practice applications


by yourself at home.

 2007 Pearson Education, Inc. All rights reserved.

26
53

(Comparing Integers) Write a program that asks the user to


enter two integers, obtains the numbers from the user, then
prints the larger number followed by the words “is larger.” If the
numbers are equal, print the message “These numbers are
equal.” Use only the single-selection form of the if statement
you learned in this chapter.
#include <stdio.h>
#include <stdlib.h>
Input two integers: 13 27 int main()
27 is larger {
int x1;
int x2;
Input two integers: 27 27
These numbers are equal printf("Input two different integers: " );
scanf("%d%d",&x1,&x2);

if (x1 > x2) printf ("%d is larger", x1);


if (x2 > x1) printf ("%d is larger", x2);
if (x1 == x2) printf ("These numbers are equal");

system("Pause");
return 0; /* successful termination */
}
 2007 Pearson Education, Inc. All rights reserved.

54

(Multiples) Write a program that reads in two integers and


determines and prints if the first is a multiple of the second.
[Hint: Use the remainder operator.]

Input two integers: 52 13


First is multiple of the second
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1;
int x2;

printf("Input two different integers: " );


scanf("%d%d",&x1,&x2);

if (x1 % x2 == 0) printf("%d is multiple of %d\n", x1, x2);


if (x1 % x2 != 0) printf("%d is not multiple of %d\n", x1, x2);

system("Pause"); return 0; /* successful termination */


}

 2007 Pearson Education, Inc. All rights reserved.

27
55

Write a program that inputs three different integers from the


keyboard, then prints the sum, the average, the product of
these numbers. The screen dialogue should appear as follows:
#include <stdio.h>
Input three different integers: 13 27 14 #include <stdlib.h>
Sum is 54
int main()
Average is 18
{
Product is 4914
int x1;
int x2, x3;

printf("Input three different integers: " );


scanf("%d%d%d",&x1,&x2,&x3);

printf("Sum is %d\n",x1 + x2 +x3);


printf("Average is %d\n",(x1 + x2 +x3)/3);
printf("Product is %d\n",x1 * x2 * x3);

system("Pause");
return 0; /* successful termination */
}

 2007 Pearson Education, Inc. All rights reserved.

56

Write a program that inputs one five-digit number, separates


the number into its individual digits and prints the digits
separated from one another by three spaces each. [Hint: Use
combinations of integer division and the remainder operation.]
For example, if the user types in 42139, the program should
print
4 2 1 3 9
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1;

printf("Input 5 digit integer: " );


scanf("%d",&x1);

printf("%d %d %d %d %d\n", x1/10000, (x1%10000)/1000, (x1%1000)/100, (x1%100)/10,


x1%10);

system("Pause"); return 0; /* successful termination */


}
 2007 Pearson Education, Inc. All rights reserved.

28
57

 2007 Pearson Education, Inc. All rights reserved.

58

 2007 Pearson Education, Inc. All rights reserved.

29
1

3
Structured Program
Development in C

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

1
3

Software Engineering Observation


Experience has shown that the most difficult part of solving
a problem on a computer is developing the algorithm for the
solution. Once a correct algorithm has been specified, the
process of producing a working C program is normally
straightforward.

Algorithm is the step by step definition of the problem in detail.

 2007 Pearson Education, Inc. All rights reserved.

Steps in Problem Solving

First produce a general algorithm (you can use


pseudocode). Refine your steps until you get to an easy
sequence.

Pseudocode is an artificial and informal language that helps


programmers develop algorithms. Pseudocode may be an
informal English, combinations of computer languages and
spoken language. Whatever works for you.

 2007 Pearson Education, Inc. All rights reserved.

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”

Flowchart (graphical representation of an algorithm)

Basic and most common algorithm symbols are shown here.


Diamond is decision symbol. Rectangle is process symbol.
Parallelogram is input-output symbol. Cycle is the terminal symbol.

 2007 Pearson Education, Inc. All rights reserved.

3
Example:
Draw the flowchart of an algorithm which finds the sum of two numbers
N and M

 2007 Pearson Education, Inc. All rights reserved.

Example:
Draw the flowchart of an algorithm which finds the sum of the first 50
numbers

 2007 Pearson Education, Inc. All rights reserved.

4
9

Diamond symbol (decision symbol)


– Indicates decision is to be made
– Test the condition, then, follow appropriate path

Contains a test condition that can be


true or false

– Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed

 2007 Pearson Education, Inc. All rights reserved.

10

The if selection statement


 if selection structure is used to choose among alternative courses of
action
if (condition)
statement 1;

 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

 2007 Pearson Education, Inc. All rights reserved.

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.

 A compound statement or block, which is composed of a set of


statements enclosed in braces, can also be used.

if (condition) Example
{
statement 1; if (a < 50)
statement 2; {
… count=count +1;
statement n; sum =sum + a;
} }

 2007 Pearson Education, Inc. All rights reserved.

The if selection statement


 if statements can also be nested:

Example:

if (a < 50)
{
count=count +1;
sum = sum + a;
if (b > a)
b = 0;
}

Any if statement can be inside another if statement.

 2007 Pearson Education, Inc. All rights reserved.

6
13

The if…else selection statement


 if
– Only performs an action if the condition is true
 if…else
– Specifies an action to be performed both when the condition is true
and when it is false
 Psuedocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”

 2007 Pearson Education, Inc. All rights reserved.

The if…else selection statement


 The if/else statement allows to execute one set of statements if a
condition is true and a different set if the condition is false.
 General Form:
if (condition)
statement1;
else
statement2;

 Statements 1 and 2 can also be an empty statement, which is a


semicolon.
if (a < b)
; Empty statement
else
count=count +1;

 2007 Pearson Education, Inc. All rights reserved.

7
The if…else selection statement
 Example:

if (x > y)
if (y < z)
k++;
else
m++;
else
j++;

Please pay attention to the indentation usage. There is only one


statement in each block. So, there is no need to use braces. Last statement
belongs to the outer if block.

 2007 Pearson Education, Inc. All rights reserved.

The if…else selection statement


Indentation is just for style and it does not change interpretation.

if (x > y) if (x > y) if (x > y)


if (y < z) if (y < z) {
k++; k++; if (y < z)
else else k++;
j++; j++; }
else
j++;

(same) (same)

 2007 Pearson Education, Inc. All rights reserved.

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;

printf("k=%d, j=%d\n", k, j);


return 0;
}

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;

printf("Input four different integers: " );


scanf("%d%d%d%d",&x1, &x2, &x3, &x4);
if (x1>0) sum=x1;
if (x2>0) sum=sum+x2;
if (x3>0) sum=sum+x3;
if (x4>0) sum=sum+x4;

printf("The sum of the positive numbers is: %d\n",sum);


system("Pause");
return 0; /* successful termination */
}

9
Ternary conditional operator (?:)
 Takes three arguments (condition, value if true, value if false)
Condition
 Example:
printf( "%s\n", grade >= 60 ? "Passed" : "Failed" );

OR

grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n” );

OR

if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");

 2007 Pearson Education, Inc. All rights reserved.

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;

printf("Input one integer: " );


scanf("%d",&x1);

x1 > 0 ? printf("Greater than zero\n" ) : printf("Less than zero\n");

system("Pause");
return 0; /* successful termination */
}

10
21

The while repetition statement


– Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;

While loop is repeated


until condition
becomes false

– Pseudocode:
While there are more items on my shopping list
Purchase next item and cross it off my list

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

11
23

Example: Ten students took a quiz. The grades (integers in the


range 0 to 100) for this quiz are available to you. Determine the
class average on the quiz. Write pseudocode of the algorithm.

1 Set total to zero


Pseudocode of algorithm
2 Set grade counter to one
3
4 While grade counter is less than or equal to ten
5 Input the next grade
6 Add the grade into the total
7 Add one to the grade counter
8
9 Set the class average to the total divided by ten
10 Print the class average

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 3.6: fig03_06.c 24


2 Class average program with counter-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grade to be entered next */
9 int grade; /* grade value */
10 int total; /* sum of grades input by user */
Counter to control while loop
11 int average; /* average of grades */
12
13 /* initialization phase */
14 total = 0; /* initialize total */
15 counter = 1; /* initialize loop counter */ Initialize counter to 1
16
17 /* processing phase */
18 while ( counter <= 10 ) { /* loop 10 times */
while loop iterates as long as
19 printf( "Enter grade: " ); /* prompt for input */ counter <= 10
20 scanf( "%d", &grade ); /* read grade from user */
21 total = total + grade; /* add grade to total */
22 counter = counter + 1; /* increment counter */ Increment the counter
23 } /* end while */
24
25 /* termination phase */
26
27
average = total / 10; /* integer division */
Calculate the average
28 printf( "Class average is %d\n", average ); /* display result */
29
30 return 0; /* indicate program ended successfully */
31
32 } /* end function main */  2007 Pearson Education,
Inc. All rights reserved.

12
25

Sentinel Controlled Repetition


 if number of repetitions is not known a sentinel
(dummy) value is used to control repetition

 Use sentinel value


– Also called signal value, dummy value, or flag value
– Indicates “end of data entry.”
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a
regular input (such as -1 in this case)

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 3.8: fig03_08.c 26


2 Class average program with sentinel-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grades entered */
9 int grade; /* grade value */
10 int total; /* sum of grades */
11
12 float average; /* number with decimal point for average */
13
float type indicates variable
14 /* initialization phase */
can be a non-integer
15 total = 0; /* initialize total */
16 counter = 0; /* initialize loop counter */
17
18 /* processing phase */
19 /* get first grade from user */
20 printf( "Enter grade, -1 to end: " ); /* prompt for input */
21 scanf( "%d", &grade ); /* read grade from user */
22

 2007 Pearson Education,


Inc. All rights reserved.

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

Enter grade, -1 to end: 75


Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50

Enter grade, -1 to end: -1


No grades were entered

 2007 Pearson Education,


Inc. All rights reserved.

14
29

Performance Tip

Assigning value (Initializing variables )

Initializing variables when they are defined can help


reduce a program’s execution time.
int passes = 0;
int failures = 0;
int student = 1;

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

15
31

Examples of other assignment operators:

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)

 2007 Pearson Education, Inc. All rights reserved.

32

Increment and Decrement Operators


 Increment operator (++)
– Can be used instead of c+=1
 Decrement operator (--)
– Can be used instead of c-=1
 Preincrement
– Operator is used before the variable (++c or --c)
– Variable value is changed before the expression it is in is evaluated
 Postincrement
– Operator is used after the variable (c++ or c--)
– Expression executes before the variable value is changed

 2007 Pearson Education, Inc. All rights reserved.

16
33

Increment and Decrement Operators


 If c equals 5, then
printf( "%d", ++c );
– Prints 6
Variable is in an
expression
– -------------------------------------------
printf( "%d", c++ );
– Prints 5

In either case, c now has the value of 6

 2007 Pearson Education, Inc. All rights reserved.

34

Increment and Decrement Operators


 When variable not in an expression
– Preincrementing and postincrementing have the same effect
++c;
printf( “%d”, c );
– Has the same effect as
c++;
Variable is not in an
expression
printf( “%d”, c );

 2007 Pearson Education, Inc. All rights reserved.

17
35

Operator Sample expression Explanation

++ ++a Increment a by 1, then use the new value of a in the


expression in which a resides.
++ a++ Use the current value of a in the expression in which a
resides, then increment a by 1.
-- --b Decrement b by 1, then use the new value of b in the
expression in which b resides.
-- b-- Use the current value of b in the expression in which b
resides, then decrement b by 1.

Fig. 3.12 | Increment and decrement operators.

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 3.13: fig03_13.c 36


2
3
Preincrementing and postincrementing */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig03_13.c
7 {
8 int c; /* define variable */
9
10 /* demonstrate postincrement */
11 c = 5; /* assign 5 to c */
12 printf( "%d\n", c ); /* print 5 */
13 printf( "%d\n", c++ ); /* print 5 then postincrement */ c is printed, then incremented
14 printf( "%d\n\n", c ); /* print 6 */
15
16 /* demonstrate preincrement */
17 c = 5; /* assign 5 to c */
18 printf( "%d\n", c ); /* print 5 */
19 printf( "%d\n", ++c ); /* preincrement then print 6 */ c is incremented, then printed
20 printf( "%d\n", c ); /* print 6 */
21
22 return 0; /* indicate program ended successfully */
23
24 } /* end function main */
5
5
6

5
6
6
 2007 Pearson Education,
Inc. All rights reserved.

18
37

Operators Associativity Type

++ (postfix) -- (postfix) right to left postfix

+ - ( type) ++ (prefix) -- (prefix) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Fig. 3.14 | Precedence of the operators encountered so far in the text.


Post increment and decrement operators have highest precedence.
Multiplication have higher precedence than summation and subtraction.

 2007 Pearson Education, Inc. All rights reserved.

Write four different C statements that each adds 1 to Q


integer variable “x”.

#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?

What is the result of this logic statement? Q

int i=5, j=10, k=20;

i>5*k%3 Operators Associativity Type

++ (postfix) -- (postfix) right to left postfix


i > 100 % 3 + - ( type) ++ (prefix) -- (prefix) right to left unary

left to right multiplicative


i>1 * / %

+ - left to right additive

5> 1 < <= > >= left to right relational

== != left to right equality


1 ?: right to left conditional

= += -= *= /= %= right to left assignment

20
1

4
C Program
Control

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

4.2 Repetition Essentials


 Loop
– Group of instructions computer executes repeatedly while
some condition remains true
 Counter-controlled repetition
– Definite repetition: know how many times loop will execute
– Control variable used to count repetitions
 Sentinel-controlled repetition (special end of data
value)
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"

 2007 Pearson Education, Inc. All rights reserved.

2
5

4.3 Counter-Controlled Repetition


 Counter-controlled repetition requires
– The name of a control variable (or loop counter)
– The initial value of the control variable
– An increment (or decrement) by which the control variable is
modified each time through the loop
– A condition that tests for the final value of the control variable
(i.e., whether looping should continue)

int counter = 1; // initialization


while ( counter <= 10 ) { // repetition condition
printf( "%d\n", counter );
++counter; } // increment

 2007 Pearson Education, Inc. All rights reserved.

4.3 Counter-Controlled Repetition


 Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition
printf( "%d\n", counter );
++counter; // increment
}

– 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

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

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 );

 2007 Pearson Education, Inc. All rights reserved.

4
9

for Repetition Statement


 Format when using for loops
for ( initialization; loopContinuationTest; increment )
statement
 Example:
for( int counter = 1; counter <= 10; counter++ )
printf( "%d\n", counter );
– Prints the integers from one to ten

Fig. 4.4 |
Flowcharting a
typical for
repetition statement.

 2007 Pearson Education, Inc. All rights reserved.

10

for Repetition Statement


 Initialization and increment
– Can be comma-separated lists
– Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );

 2007 Pearson Education, Inc. All rights reserved.

5
11

Fig. 4.3 | for statement header components.

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 4.2: fig04_02.c 12


2
3
Counter-controlled repetition with the for statement */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_02.c
7 {
8 int counter; /* define counter */
9
10 /* initialization, repetition condition, and increment
11 are all included in the for statement header. */
12 for ( counter = 1; counter <= 10; counter++ ) { for loop begins by setting counter to
13 printf( "%d\n", counter );
1 and repeats while counter <= 10.
14 } /* end for */
15 Each time the end of the loop is
16 return 0; /* indicate program ended successfully */ reached, counter is incremented by
17
1.
18 } /* end function main */

Put a blank line before and after


each control statement to make it
stand out in a program.

 2007 Pearson Education,


Inc. All rights reserved.

6
13

Common Programming Error


Placing a semicolon immediately to the
right of a for header makes the body of
for statement empty. This is normally a
logic error. body is empty

for (int i = 0; i <= 10; i++);

Header of for loop structure

 2007 Pearson Education, Inc. All rights reserved.

14

for Statement : Notes and Observations

 Arithmetic expressions
– Initialization, loop-continuation, and increment can contain
arithmetic expressions.

– If x equals 2 and y equals 10


for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )

 Notes about the for statement:


– "Increment" may be negative (decrement)
– If the loop continuation condition is initially false
- The body of the for statement is not performed
- Control proceeds with the next statement after the for statement

 2007 Pearson Education, Inc. All rights reserved.

7
15

Error-Prevention Tip

Although the value of the control variable can


be changed in the body of a for loop, this
can lead to subtle errors. It is best not to
change it.
for (int i = 0; i <= 10; i++){
i=5;}

Body of for structure Control variable

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 4.5: fig04_05.c 16


2
3
Summation with for */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig04_05.c
7 {
8 int sum = 0; /* initialize sum */
9 int number; /* number to be added to sum */
10
11 for ( number = 2; number <= 100; number += 2 ) { Note that number has a different
12 sum += number; /* add number to sum */
13 } /* end for */ value each time when this
14 statement is executed
15 printf( "Sum is %d\n", sum ); /* output sum */
16
17 return 0; /* indicate program ended successfully */
18
19 } /* end function main */

Sum is 2550

 2007 Pearson Education,


Inc. All rights reserved.

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 */

 2007 Pearson Education,


Inc. All rights reserved.

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.

 2007 Pearson Education,


Inc. All rights reserved.

9
19

switch Multiple-Selection Statement


 switch
– Useful when a variable or expression is tested for all the values it can
assume and different actions are taken
 Format
– Series of case labels and an optional default case

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.

 2007 Pearson Education, Inc. All rights reserved.

20

if ‘value’ is equal to ‘case2’,


the code is swithed to the
‘case 2’. Then, all statements
under ‘case 2’ are executed.

case 1
action

case 2
action

case 3
action
default

action

 2007 Pearson Education, Inc. All rights reserved.

10
The break statement

 Syntax: break;

• When the break statement is executed inside a loop or switch


statement, that statement is terminated immediately
• The execution of the program will continue with the statement
following the loop-statement

 2007 Pearson Education, Inc. All rights reserved.

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;

printf("Enter character: \n");

k = getchar();

printf("%c entered", k);

return(0);

 2007 Pearson Education, Inc. All rights reserved.

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

break statement makes program skip to end of


switch  2007 Pearson Education,
Inc. All rights reserved.

29 case 'B': /* grade was uppercase B */ 24


30
31
case 'b': /* or lowercase b */
++bCount; /* increment bCount */
Outline
32 break; /* exit switch */
33
34 case 'C': /* grade was uppercase C */
fig04_07.c
35 case 'c': /* or lowercase c */
36 ++cCount; /* increment cCount */
37 break; /* exit switch */
(2 of 4 )
38
39 case 'D': /* grade was uppercase D */ if ‘grade’ is equal to ‘D’, the
40 case 'd': /* or lowercase d */
41 ++dCount; /* increment dCount */
code is swithed to the case ‘D’.
42 break; /* exit switch */ Then, statements under are
43 executed.
44 case 'F': /* grade was uppercase F */
45 case 'f': /* or lowercase f */
46 ++fCount; /* increment fCount */
47 break; /* exit switch */
break statement makes
48
49 case '\n': /* ignore newlines, */ program skip to end of
50 case '\t': /* tabs, */ switch
51 case ' ': /* and spaces in input */
52 break; /* exit switch */
53

 2007 Pearson Education,


Inc. All rights reserved.

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 */

 2007 Pearson Education,


Inc. All rights reserved.

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

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1

 2007 Pearson Education,


Inc. All rights reserved.

13
27

Fig. 4.8 | switch multiple-selection statement with breaks.

 2007 Pearson Education, Inc. All rights reserved.

28

Portability Tip

The keystroke combinations for entering


EOF (end of file) are system dependent.

 2007 Pearson Education, Inc. All rights reserved.

14
29

do…while Repetition Statement


 The do…while repetition statement
– Similar to the while structure
– Condition for repetition only tested after the body of the loop
is performed
- All actions are performed at least once
– Format:
do {
statement;
} while ( condition );

Fig. 4.10 | Flowcharting the


do...while repetition
statement.

 2007 Pearson Education, Inc. All rights reserved.

30

do…while Repetition Statement


 Example:

int counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);

– Prints the integers from 1 to 10

 2007 Pearson Education, Inc. All rights reserved.

15
31

Good Programming Practice


Some programmers always include braces in a
do...while statement even if the braces are not
necessary.
do
printf( "%d ", counter );
while (++counter <= 10);

do {
printf( "%d ", counter );
} while (++counter <= 10);

 2007 Pearson Education, Inc. All rights reserved.

32

Common Programming Error


Infinite loops are caused when the loop-continuation condition
in a while, for or do...while statement never becomes
false. To prevent this, make sure there is not a semicolon
immediately after the header of a while or for statement.

In a counter-controlled loop, make sure the control variable is


incremented (or decremented) in the loop.

In a sentinel-controlled loop, make sure the sentinel value is


eventually input.

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

34

break and continue Statements


 break
– Causes immediate exit from a while, for, do…while or
switch statement
– Program execution continues with the first statement after the
structure
– Common uses of the break statement
- Escape early from a loop
- Skip the remainder of a switch statement

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

36

break and continue Statements


 continue
– Skips the remaining statements in the body of a while, for or
do…while statement
- Proceeds with the next iteration of the loop

while and do…while


- Loop-continuation test is evaluated immediately after the
continue statement is executed
for
- Increment expression is executed, then the loop-continuation test
is evaluated

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

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

 Useful as conditions in loops


Expression Result
true && false false
true || false true
!false true

 2007 Pearson Education, Inc. All rights reserved.

19
39

 && ( logical AND )


– Returns true if both conditions are true

expression1 expression2 expression1 && expression2

0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1

Fig. 4.13 | Truth table for the && (logical AND) operator.

 2007 Pearson Education, Inc. All rights reserved.

40

 || ( logical OR )
– Returns true if either of its conditions are true

expression1 expression2 expression1 || expression2

0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1

Fig. 4.14 | Truth table for the logical OR (||) operator.

 2007 Pearson Education, Inc. All rights reserved.

20
41

 ! ( logical NOT, logical negation )


– Reverses the truth/falsity of its condition
– Unary operator, has one operand

expression !expression

0 1
nonzero 0

Fig. 4.15 | Truth table for operator ! (logical negation).

 2007 Pearson Education, Inc. All rights reserved.

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.

This can reduce a program’s execution time.

 2007 Pearson Education, Inc. All rights reserved.

21
43

Operators Associativity Type

++ (postfix) -- (postfix) right to left postfix

+ - ! ++ (prefix) -- (prefix) (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

, left to right comma

Fig. 4.16 | Operator precedence and associativity.

 2007 Pearson Education, Inc. All rights reserved.

44

Confusing Equality (==) and Assignment (=)


Operators
 Dangerous error (using = instead of ==)
– Does not ordinarily cause syntax errors
– Nonzero values are true, zero values are false

– Example using ==:


if ( payCode == 4 )
printf( "You get a bonus!\n" );

- Checks payCode, if it is 4 then a bonus is awarded

 2007 Pearson Education, Inc. All rights reserved.

22
45

Confusing Equality (==) and Assignment


(=) Operators
- Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );

This sets payCode to 4


4 is nonzero, so expression is always true.
– Logic error, not a syntax error

A simple solution is advised to this dangerous problem.


Use 4==x instead of x==4.
if you accidentally replace operator == with = the compiler gives
error messages.

 2007 Pearson Education, Inc. All rights reserved.

23
1

5
C Functions

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

Functions in C
C standard library has a wide variety of functions

 2007 Pearson Education, Inc. All rights reserved.

2
5

Math Library Functions


 Math library functions
– perform common mathematical calculations
– #include <math.h>
Function Description Example

floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0


not greater than x
floor( -9.8 ) is -10.0

pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0


pow( 9, .5 ) is 3.0

fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992


point number

sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0


(x in radians)

cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0


(x in radians)

tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0


(x in radians)

 2007 Pearson Education, Inc. All rights reserved.

Function Description Example

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0


sqrt( 9.0 ) is 3.0

x
exp( x ) exponential function e exp( 1.0 ) is 2.718282
exp( 2.0 ) is 7.389056

log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0


log( 7.389056 ) is 2.0

log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0


log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0

fabs( x ) absolute value of x fabs( 5.0 ) is 5.0


fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0

ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0


not less than x ceil( -9.8 ) is -9.0

Fig. 5.2 | Commonly used math library functions. (Part 1 of 2.)

 2007 Pearson Education, Inc. All rights reserved.

3
7

Boss asks worker to complete task, Worker gets information, does


task, returns result. Information hiding: boss does not know
details.

Fig. 5.1 | Hierarchical boss function/worker function relationship.

 2007 Pearson Education, Inc. All rights reserved.

#include <math.h>

statement adds (preprocessor directive) all the codes


(functions) from the math.h file into our code.

Therefore, all the functions which are defined in math.h


file are ready for our usage.

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() {

// If you use sqrt() function without including the <math.h>


// header file, this program will show an error.

sqrt(900);

 2007 Pearson Education, Inc. All rights reserved.

10

Format for calling functions


functionName( argument1, argument2 );
- If multiple arguments, use comma-separated list

sqrt(900.0);
- Calls function sqrt, which returns the square root of its
argument
- All math functions return data type double

Arguments may be constants, variables, or expressions

 2007 Pearson Education, Inc. All rights reserved.

5
11

Good Programming Practice

Familiarize yourself with the rich collection


of functions in the C Standard Library.

Avoid reinventing the wheel. When possible,


use C Standard Library functions instead of
writing new functions.

 2007 Pearson Education, Inc. All rights reserved.

12

Portability Tip
If you use the functions in the C Standart
library, this helps your programs more
portable.

 2007 Pearson Education, Inc. All rights reserved.

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

return-value-type function-name( parameter-list )


{
declarations and statements
}

– Parameter-list: comma separated list, declares parameters

 2007 Pearson Education, Inc. All rights reserved.

14

Function Definitions
return-value-type function-name( parameter-list )
{
declarations and statements
function body
}

- Variables can be defined inside blocks (function body)


// function definition
int max(int a){
int b=100; local variables
return a>b ? a : b;
}

 2007 Pearson Education, Inc. All rights reserved.

7
15

Function Definitions
// function definition
int max(int a){
int b=100;
return a>b ? a : b;
}

returns an integer value

 2007 Pearson Education, Inc. All rights reserved.

Function Definition Example


int max(int a, int b); Function prototype indicates function
will be defined later in the program

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;
}

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

18

Common Programming Error


Omitting the return-value-type in a function
definition is a syntax error if the function prototype
specifies a return type other than int.
double sample_f (parameter-list );

int main {
… }

sample_f ( parameter-list )
{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

9
19

Common Programming Error


Forgetting to return a value from a function that is
supposed to return a value can lead to unexpected
errors.

double sample_f (parameter-list );

int main {
… }

double sample_f ( parameter-list )


{
declarations and statements
}

 2007 Pearson Education, Inc. All rights reserved.

20

Common Programming Error


Returning a value from a function with a void
return type is a syntax error.
void means returns nothing
void sample_f (parameter-list );

int main {
… }

void sample_f ( parameter-list )


{
declarations and statements, calculations of x

return x;
}

 2007 Pearson Education, Inc. All rights reserved.

10
21

Good Programming Practice


Even though an omitted return type defaults to int,
always state the return type explicitly.
sample_f (parameter-list );

int main {
… }

sample_f ( parameter-list )
{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

22

Common Programming Error


Default data type is int. If you specify function parameters such as
double x, y instead of double x, double y, this definition might
cause errors in your programs. The parameter declaration double
x, y would actually make y a parameter of type int because int is
the default.
double sample_f (double x, y );

int main {
y is declared as
… }
integer
double sample_f ( double x, y )
{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

11
23

Good Programming Practice


Include the type of each parameter in the parameter
list, even if that parameter is of the default type int.

double sample_f (int x, int y );

int main {
… }

double sample_f ( int x, int y )


{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

24

Common Programming Error


Defining a function inside another function is a
syntax error.

Functions can not be defined inside other functions

 2007 Pearson Education, Inc. All rights reserved.

12
25

Good Programming Practice


Choosing meaningful function names and meaningful
parameter names makes programs more readable and
helps avoid excessive use of comments.

 2007 Pearson Education, Inc. All rights reserved.

26

Software Engineering Observation


Programs should be written as collections of small
functions. This makes programs easier to write,
debug, maintain and modify.

 2007 Pearson Education, Inc. All rights reserved.

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

Function prototype indicates function


will be defined later in the program

 2007 Pearson Education,


Inc. All rights reserved.

25 /* Function maximum definition */ 28


26 /* x, y and z are parameters */
27 int maximum( int x, int y, int z ) Function definition
Outline
28 {
29 int max = x; /* assume x is largest */
30
fig05_04.c
31 if ( y > max ) { /* if y is larger than max, assign y to max */
32 max = y;
33 } /* end if */
(2 of 2 )
34
35 if ( z > max ) { /* if z is larger than max, assign z to max */
36 max = z;
37 } /* end if */
38
39 return max; /* max is largest value */
40
41 } /* end function maximum */

Enter three integers: 22 85 17


Maximum is: 85

Enter three integers: 85 22 17


Maximum is: 85

Enter three integers: 22 17 85


Maximum is: 85

 2007 Pearson Education,


Inc. All rights reserved.

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

– The function with the prototype


int maximum ( int x, int y, int z );
- Takes in 3 ints
- Returns an int

 2007 Pearson Education, Inc. All rights reserved.

30

Common Programming Error


Forgetting the semicolon at the end of a function
prototype is a syntax error.
double sample_f (int x,int y ) ;

int main {
… }

double sample_f ( int x, int y )


{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

15
31

printf conversion scanf conversion


Data type
specification specification

Long double %Lf %Lf


double %f %lf higher data
float %f %f types
Unsigned long int %lu %lu
long int %ld %ld

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

 2007 Pearson Education, Inc. All rights reserved.

32

Common Programming Error


Converting from a higher data type in the promotion
hierarchy to a lower type can change the data value.
int sample_f (double x, double y );

int main {
… }

int sample_f (double x, double y );


{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

16
33

Common Programming Error


Forgetting a function prototype causes a syntax error
if the function definition appears after the function
call in the program.
int main {
sample_f (3,4); /* function call */
… }

// function definition
int sample_f ( int x, int y )
{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

34

Software Engineering Observation


A function prototype placed in a function applies only to
calls made in that function.
int main {
int sample_f (int x,int y ); function prototype
sample_f(3,4);
… }

int sample_f ( int x, int y )


{
declarations and statements, calculations of x
return x;
}

 2007 Pearson Education, Inc. All rights reserved.

17
35

Headers
 Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>

 Custom header files


– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions

 2007 Pearson Education, Inc. All rights reserved.

36

Calling Functions: Call-by-Value and Call-


by-Reference call by value
 Call by value
– Copy of argument passed to function int main {
– Changes in function do not effect original sample_f(3,4); /* function call */
– Use when function does not need to modify … }
argument
int sample_f ( int x, int y )
- Avoids accidental changes {
declarations and statements,
calculations of x
 Call by reference return x; }
– Passes original argument
– Changes in function effect original
– Only used with trusted functions

 For now, we focus on call by value

 2007 Pearson Education, Inc. All rights reserved.

18
37

Random Number Generation


 rand function
– Load <stdlib.h>
– Returns "random" number between 0 and RAND_MAX (at
least 32767)
i = rand();
– Pseudorandom
- Preset sequence of "random" numbers
- Same sequence for every function call

 2007 Pearson Education, Inc. All rights reserved.

38

To get a random number between 1 and n

1 + ( rand() % n )

- rand() % n returns a number between 0 and n - 1


- Add 1 to make random number between 1 and n

1 + ( rand() % 6)

returns number between 1 and 6

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

1 /* Fig. 5.8: fig05_08.c 42


2
3
Roll a six-sided die 6000 times */
#include <stdio.h>
Outline
4 #include <stdlib.h>
5
6 /* function main begins program execution */
fig05_08.c
7 int main( void )
8 {
9 int frequency1 = 0; /* rolled 1 counter */
(1 of 3 )
10 int frequency2 = 0; /* rolled 2 counter */
11 int frequency3 = 0; /* rolled 3 counter */
12 int frequency4 = 0; /* rolled 4 counter */
If you roll a six sided die 6000
13 int frequency5 = 0; /* rolled 5 counter */
times, this program counts how
14 int frequency6 = 0; /* rolled 6 counter */
many times you get 1, how many
15
times you get 2 and so on.. .
16 int roll; /* roll counter, value 1 to 6000 */
17 int face; /* represents one roll of the die, value 1 to 6 */
frequency1 variable is used to
18
count 1,
19 /* loop 6000 times and summarize results */
frequency2 variable is used to
20 for ( roll = 1; roll <= 6000; roll++ ) {
count 2 and so on…
21 face = 1 + rand() % 6; /* random number from 1 to 6 */
22
23 /* determine face value and increment appropriate counter */
24 switch ( face ) {
25
26 case 1: /* rolled 1 */ If face=1, frequency1 is
27 ++frequency1; incremented by one.
28 break;
29

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

53 /* display results in tabular format */ 44


54
55
printf( "%s%13s\n", "Face", "Frequency" );
printf( " 1%13d\n", frequency1 );
Outline
56 printf( " 2%13d\n", frequency2 );
57 printf( " 3%13d\n", frequency3 );
58 printf( " 4%13d\n", frequency4 );
fig05_08.c
59 printf( " 5%13d\n", frequency5 );
60 printf( " 6%13d\n", frequency6 );
61
(3 of 3 )
62 return 0; /* indicates successful termination */
63
64 } /* end main */

Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999

 2007 Pearson Education,


Inc. All rights reserved.

22
45

Random Number Generation


rand() function returns same sequence for every function call.
srand function is used to get different sequences.

 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

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 5.9: fig05_09.c 46


2
3
Randomizing die-rolling program */
#include <stdlib.h>
Outline
4 #include <stdio.h>
5
6 /* function main begins program execution */
fig05_09.c
7 int main( void )
8 {
(1 of 2 )
9 int i; /* counter */
10 unsigned seed; /* number used to seed random number generator */
11
12 printf( "Enter seed: " );
13 scanf( "%u", &seed ); /* note %u for unsigned */
14
15 srand( seed ); /* seed random number generator */ Seeds the rand function
16
17 /* loop 10 times */
18 for ( i = 1; i <= 10; i++ ) {
19
rand() function generates random
20 /* pick a random number from 1 to 6 and output it */
21 printf( "%10d", 1 + ( rand() % 6 ) ); numbers according to the given seed
22 value to srand() function
23 /* if counter is divisible by 5, begin a new line of output */
24 if ( i % 5 == 0 ) {
25 printf( "\n" );
26 } /* end if */
27
28 } /* end for */
29
30 return 0; /* indicates successful termination */
31  2007 Pearson Education,
32 } /* end main */ Inc. All rights reserved.

23
Enter seed: 67
47
6 1 4 6 2 Outline
1 6 1 6 4

Enter seed: 867


2 4 6 1 6
1 1 3 6 2

Enter seed: 67
6 1 4 6 2
1 6 1 6 4

 2007 Pearson Education,


Inc. All rights reserved.

Using Time to Seed the Generator


If you hard code the seed or allow the user to enter a seed,
simulated randomness is lost.
Most programmers use the “time” function to seed the generator.

 2007 Pearson Education,


Inc. All rights reserved.

24
Using Time to Seed the Generator
Must include the <time.h> library: Provides function “time( )”

Calling function “time( )”:


time( NULL )
Returns the current time from the system clock
Expressed in number of seconds elapsed since 00:00 hours, Jan 1, 1970
UTC

srand( time( NULL );

srand() function is called with a different seed


value at each call
 2007 Pearson Education,
Inc. All rights reserved.

Enumeration
Constants

#include<stdio.h>

enum week {SUN, MON, TUE, WED, THU, FRI, SAT};

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.

 2007 Pearson Education, Inc. All rights reserved.

25
 To number the days 1 to 7, use the following enumeration:

 enum week {SUN=1, MON, TUE, WED, THU, FRI, SAT};

 Since the first is set to 1, the remaining values are


incremented from 1, resulting in the values 1 through 7.

52

Common Programming Error


 Assigning a different value to an enumeration constant
after it has been defined is a syntax error.

 2007 Pearson Education, Inc. All rights reserved.

26
53

Good Programming Practice


 Use only uppercase letters in the names of enumeration
constants to make these constants stand out in a program
and to indicate that enumeration constants are not
variables.

 2007 Pearson Education, Inc. All rights reserved.

54

Example: A Game of Chance


 Craps simulator
– Craps is a dice game in which players bet on the outcomes
of the roll of a pair of dice
 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.

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

 2007 Pearson Education,


Inc. All rights reserved.

28 /* win on first roll */ 56


29
30
case 7:
case 11:
Outline
31 gameStatus = WON;
32 break;
33
fig05_10.c
34 /* lose on first roll */
35 case 2:
36 case 3:
(2 of 4 )
37 case 12:
38 gameStatus = LOST;
39 break;
40
41 /* remember point */
42 default:
43 gameStatus = CONTINUE;
44 myPoint = sum;
45 printf( "Point is %d\n", myPoint );
46 break; /* optional */
47 } /* end switch */
48

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 */

 2007 Pearson Education,


Inc. All rights reserved.

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 */

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

60

Storage Classes
Every variable in C programming has two properties:
type and storage class.

Storage class determines the scope and lifetime of a variable.

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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); }

 2007 Pearson Education, Inc. All rights reserved.

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;

Fig. 5.13 | Recursive evaluation of 5!.

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 5.14: fig05_14.c 64


2
3
Recursive factorial function */
#include <stdio.h>
Outline
4
5 long factorial( long number ); /* function prototype */
6
7 /* function main begins program execution */
8 int main( void )
9 {
10 int i; /* counter */
11
12 /* loop 11 times; during each iteration, calculate
13 factorial( i ) and display result */
14 for ( i = 0; i <= 10; i++ ) {
15 printf( "%2d! = %ld\n", i, factorial( i ) );
16 } /* end for */
17
18 return 0; /* indicates successful termination */
19
20 } /* end main */
21

DataType Size in memory (bytes)


char 1
int 4
short 2 integer data types
long 8
float 4
double 8
 2007 Pearson Education,
Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

66

Example Using Recursion: Fibonacci


Series
 Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
- fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}

 2007 Pearson Education, Inc. All rights reserved.

33
67

Fig. 5.16 | Set of recursive calls for fibonacci(3).

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 5.15: fig05_15.c 68


2
3
Recursive fibonacci function */
#include <stdio.h>
Outline
4
5 long fibonacci( long n ); /* function prototype */
6
fig05_15.c
7 /* function main begins program execution */
8 int main( void )
9 {
(1 of 4 )
10 long result; /* fibonacci value */
11 long number; /* number input by user */
12
13 /* obtain integer from user */
14 printf( "Enter an integer: " );
15 scanf( "%ld", &number );
16
17 /* calculate fibonacci value for number input by user */
18 result = fibonacci( number );
19
20 /* display result */
21 printf( "Fibonacci( %ld ) = %ld\n", number, result );
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */
26

 2007 Pearson Education,


Inc. All rights reserved.

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… )

 2007 Pearson Education,


Inc. All rights reserved.

(continued from previous slide…) 70


Enter an integer: 3
Fibonacci( 3 ) = 2
Outline

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… )

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

72

Software Engineering Observation

Any problem that can be solved recursively can also be


solved iteratively (nonrecursively).
A recursive approach is normally chosen due to is easier
to understand and debug.
Another reason to choose a recursive solution is that an
iterative solution may not be apparent.

 2007 Pearson Education, Inc. All rights reserved.

36
73

Performance Tip
Avoid using recursion in performance situations.
Recursive calls take time and consume additional
memory.

 2007 Pearson Education, Inc. All rights reserved.

37
1

6
C Arrays

 2007 Pearson Education, Inc. All rights reserved.

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.

 2007 Pearson Education, Inc. All rights reserved.

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.

All array elements are sequential in computer memory locations. The


lowest address corresponds to the first element and the highest address to
the last element.

 2007 Pearson Education, Inc. All rights reserved.

6.1 Arrays

Array elements are like normal variables


c[ 0 ] = -45;
printf( "%d", c[ 0 ]);

 2007 Pearson Education, Inc. All rights reserved.

2
Array indexes always start at zero in C

Seventh element of the array is


c[6]

– Examples:
int c[ 12 ];

type name number of elements

 2007 Pearson Education, Inc. All rights reserved.

Operators Associativity Type

[] () left to right highest

++ -- ! (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

, left to right comma

Fig. 6.2 | Operator precedence.

 2007 Pearson Education, Inc. All rights reserved.

3
7

6.3 Defining Arrays


 When defining arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];

– Examples:
int c[ 10 ];
float myArray[ 3284 ];

type name number of elements

 2007 Pearson Education, Inc. All rights reserved.

6.3 Defining Arrays


 Defining multiple arrays of same type
– Format similar to regular variables
– Example:

int b[ 100 ], x[ 27 ];

 2007 Pearson Education, Inc. All rights reserved.

4
9

6.4 Array Examples


 Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };

– If not enough initializers, rightmost elements become 0


int n[ 5 ] = { 0 }
All elements are 0

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

– C arrays have no bounds checking


 2007 Pearson Education, Inc. All rights reserved.

10

6.4 Array Examples


 If size omitted, initializers determine it

int n[ ] = { 1, 2, 3, 4, 5 };

Number of elements is automatically calculated.


5 initializers, therefore 5 element array.

 2007 Pearson Education, Inc. All rights reserved.

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.

1 /* Fig. 6.4: fig06_04.c 12


2
3
Initializing an array with an initializer list */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
7 { fig06_04.c
8 /* use initializer list to initialize array n */
9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
10 int i; /* counter */
11
12 printf( "%s%13s\n", "Element", "Value" );
13 initializer list initializes all array
14 /* output contents of array in tabular format */ elements simultaneously
15 for ( i = 0; i < 10; i++ ) {
16 printf( "%7d%13d\n", i, n[ i ] );
17 } /* end for */
18 Element Value
19 return 0; /* indicates successful termination */ 0 32
20 1 27
21 } /* end main */ 2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37

 2007 Pearson Education,


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

Common Programming Error 6.4


Ending a #define or #include preprocessor directive
with a semicolon. Remember that preprocessor directives
are not C statements.

#define DATA 128;

 2007 Pearson Education, Inc. All rights reserved.

7
15

Common Programming Error 6.5


Assigning a value to a symbolic constant in an executable
statement is a syntax error. A symbolic constant is not a
variable and no space is reserved for it by the compiler .

#define SIZE 10 /*

7 int main( void )


8 {
9 /* symbolic constant is not variable. */
SIZE=45; /* couses a syntax error */
….
….

 2007 Pearson Education, Inc. All rights reserved.

16

Software Engineering Observation 6.1


Defining the size of each array as a symbolic
constant makes programs more scalable.

 2007 Pearson Education, Inc. All rights reserved.

8
17

Good Programming Practice 6.1


Use only uppercase letters for all symbolic constant
names. This reminds you that these are symbolic
constants. They are not variables.

#define SIZE 10 /*

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 6.6: fig06_06.c 18


2
3
Compute the sum of the elements of the array */
#include <stdio.h>
Outline
4 #define SIZE 12
5
6 /* function main begins program execution */
fig06_06.c
7 int main( void )
8 {
9 /* use initializer list to initialize array */
10 int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
11 int i; /* counter */
initializer list initializes all
12 int total = 0; /* sum of array */
13 array elements simultaneously
14 /* sum contents of array a */
15 for ( i = 0; i < SIZE; i++ ) {
16 total += a[ i ]; for loop adds each element of
17 } /* end for */ the array to variable total
18
19 printf( "Total of array element values is %d\n", total );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */

Total of array element values is 383

 2007 Pearson Education,


Inc. All rights reserved.

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

In the given list, number of ‘1’s is counted by frequency[1],


number of ‘2’s is counted by frequency[2] and so on..
 2007 Pearson Education,
Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

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.

1 /* Fig. 6.9: fig06_09.c 23


2
3
Roll a six-sided die 6000 times */
#include <stdio.h>
Outline
4 #include <stdlib.h>
5 #include <time.h>
6 #define SIZE 7
fig06_09.c
7
8 /* function main begins program execution */
9 int main( void )
10 {
11 int face; /* random die value 1 - 6 */
12 int roll; /* roll counter 1-6000 */
13 int frequency[ SIZE ] = { 0 }; /* clear counts */
14
15 srand( time( NULL ) ); /* seed random-number generator */
16
17 /* roll die 6000 times */
18 for ( roll = 1; roll <= 6000; roll++ ) {
19 face = 1 + rand() % 6;
20 ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */
21 } /* end for */

‘1’s is counted by frequency[1], ‘2’s is counted by frequency[2]


and so on..

 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

 2007 Pearson Education,


Inc. All rights reserved.

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 '.

 2007 Pearson Education,


Inc. All rights reserved.

12
Character Strings
A string containing a single character takes up 2 bytes of storage.

 2007 Pearson Education,


Inc. All rights reserved.

Character Strings

 2007 Pearson Education,


Inc. All rights reserved.

13
Character vs. String

A string constant is a sequence of characters enclosed in double quotes.

For example, the character string:


char s1[2]="a"; //Takes two bytes of storage.
s1:
a \0
On the other hand, the character, in single quotes:
char s2= `a`; //Takes only one byte of storage.
s2:
a

 2007 Pearson Education,


Inc. All rights reserved.

Character vs. String

 2007 Pearson Education,


Inc. All rights reserved.

14
30

6.4 Array Examples


 Character arrays
char string1[] = "first";

It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

– String “first” is really a static array of characters


– Null character '\0' terminates strings
– string1 actually has 6 elements (5 characters + null character)

– Can access individual characters


string1[ 3 ] is character ‘s’

 2007 Pearson Education, Inc. All rights reserved.

31

In C, string can be initialized in a number of different


ways.

char c[] = "abcd";


OR,
char c[5] = "abcd";
OR,
char c[] = {'a', 'b', 'c', 'd', '\0'};
OR,
char c[5] = {'a', 'b', 'c', 'd', '\0'};

 2007 Pearson Education, Inc. All rights reserved.

15
32

6.4 Array Examples


Array name is the address of array, so ‘&’ is not needed for scanf
char string1[20];
scanf( "%s", string1 );

- Reads characters until whitespace encountered


Sample Code:
#include <stdio.h>
int main() {
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s", name);
return 0;
}

Output:
Enter name: Ali Zengin
Your name is Ali

Reads characters until whitespace


encountered
 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 6.10: fig06_10.c 33


2
3
Treating character arrays as strings */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */ fig06_10.c
6 int main( void )
7 {
8 char string1[ 20 ]; /* reserves 20 characters */
9 char string2[] = "string literal"; /* reserves 15 characters */
10 int i; /* counter */ string2 array is defined with
11 15 elements including null
12 /* read string from user into array string1 */
13 printf("Enter a string: ");
character /0
14 scanf( "%s", string1 ); /* input ended by whitespace character */
15
16 /* output strings */
17 printf( "string1 is: %s\nstring2 is: %s\n"
18 "string1 with spaces between characters is:\n",
19 string1, string2 );
20
21 /* output characters until null character is reached */
22 for ( i = 0; string1[ i ] != '\0'; i++ ) {
23 printf( "%c ", string1[ i ] );
24 } /* end for */
25
26 printf( "\n" );
27
28 return 0; /* indicates successful termination */
29 Enter a string: Hello there
string1 is: Hello
30 } /* end main */
string2 is: string literal
string1 with spaces between 
characters
2007 Pearson is:
Education,
H e l l o Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

23 /* function to demonstrate a static local array */ 35


24 void staticArrayInit( void )
25 {
Outline
26 /* initializes elements to 0 first time function is called */
27 static int array1[ 3 ];
static array is created only once, when
28 int i; /* counter */
29
staticArrayInit is first called fig06_11.c
30 printf( "\nValues on entering staticArrayInit:\n" );
31
(2 of 4 )
32 /* output contents of array1 */
33 for ( i = 0; i <= 2; i++ ) {
34 printf( "array1[ %d ] = %d ", i, array1[ i ] );
35 } /* end for */
36
37 printf( "\nValues on exiting staticArrayInit:\n" );
38
39 /* modify and output contents of array1 */
40 for ( i = 0; i <= 2; i++ ) {
41 printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 );
42 } /* end for */
43
44 } /* end function staticArrayInit */

The static qualifier instructs the compiler to keep a local


variable in existence during the life-time of the program.
Their default value is zero.

 2007 Pearson Education,


Inc. All rights reserved.

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 */

 2007 Pearson Education,


Inc. All rights reserved.

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

Values on entering automaticArrayInit: (4 of 4 )


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

Second call to each function:

Values on entering staticArrayInit:


array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5
Values on exiting staticArrayInit:
array1[ 0 ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10

Values on entering automaticArrayInit:


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

 2007 Pearson Education,


Inc. All rights reserved.

18
38

6.5 Passing Arrays to Functions


 Passing arrays
– To pass an array argument to a function, specify the name of the
array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
- Array size usually passed to function
– Arrays passed call-by-reference
– Name of array is address of first element
– Function knows where the array is stored
- Modifies original memory locations

 2007 Pearson Education, Inc. All rights reserved.

39

6.5 Passing Arrays to Functions


 Function prototype
void modifyArray( int b[], int arraySize );

– Parameter names optional in prototype


- int b[] could be written int []
- int arraySize could be simply int

 2007 Pearson Education, Inc. All rights reserved.

19
40

Performance Tip 6.3


Passing arrays by reference (address) is for
performance reasons.
If arrays were passed by value, a copy of
each element would be passed.

 2007 Pearson Education, Inc. All rights reserved.

1 /* Fig. 6.12: fig06_12.c 41


2
3
The name of an array is the same as &array[ 0 ] */
#include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig06_12.c
7 {
8 char array[ 5 ]; /* define an array of size 5 */
9
10 printf( " array = %p\n&array[0] = %p\n &array = %p\n",
11 array, &array[ 0 ], &array );
12
13 return 0; /* indicates successful termination */
14
15 } /* end main */

array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78

 2007 Pearson Education,


Inc. All rights reserved.

20
42

Single element of an array can be passed in similar manner as passing


variable to a function.
C program to pass a single element of an array to function:

#include <stdio.h>

void display(int age)


{
printf("%d", age);
}

int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element by value only.
return 0;
}

Output
4

 2007 Pearson Education,


Inc. All rights reserved.

43

Passing an entire one-dimensional array to a function


While passing arrays as arguments to the function, only the name of the array is passed
(,i.e, starting address of memory area is passed as argument)
#include <stdio.h>
float average(float age[]);

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;
}

float average(float age[])


{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}
 2007 Pearson Education,
Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

31 /* output modified array */ 45


32
33
for ( i = 0; i < SIZE; i++ ) {
printf( "%3d", a[ i ] );
Outline
34 } /* end for */
35
36 /* output value of a[ 3 ] */
fig06_13.c
37 printf( "\n\n\nEffects of passing array element "
38 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );
39
(2 of 3 )
40 modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */
41
42 /* output value of a[ 3 ] */ Array element is passed to
43 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
modifyElement by passing a[ 3 ]
44
45 return 0; /* indicates successful termination */
46
47 } /* end main */
48
49 /* in function modifyArray, "b" points to the original array "a"
50 in memory */
51 void modifyArray( int b[], int size )
52 {
53 int j; /* counter */
54
55 /* multiply each array element by 2 */
56 for ( j = 0; j < size; j++ ) {
57 b[ j ] *= 2;
58 } /* end for */
59
60 } /* end function modifyArray */

 2007 Pearson Education,


Inc. All rights reserved.

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:

The values of the original array are:


0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[ 3 ] is 6

 2007 Pearson Education,


Inc. All rights reserved.

1 /* Fig. 6.14: fig06_14.c 47


2
3
Demonstrating the const type qualifier with arrays */
#include <stdio.h>
Outline
4
5 void tryToModifyArray( const int b[] ); /* function prototype */
6
fig06_14.c
7 /* function main begins program execution */
8 int main( void )
9 {
(1 of 2 )
10 int a[] = { 10, 20, 30 }; /* initialize a */ const qualifier tells compiler that
11
12 tryToModifyArray( a );
array cannot be changed and is used
13 prevent the original array
14 printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] ); from being modified in the
15 function body
16 return 0; /* indicates successful termination */
17
18 } /* end main */
19
20 /* in function tryToModifyArray, array b is const, so it cannot be
21 used to modify the original array a in main. */
22 void tryToModifyArray( const int b[] )
23 {
24 b[ 0 ] /= 2; /* error */
Any attempts to modify the array
25 b[ 1 ] /= 2; /* error */
26 b[ 2 ] /= 2; /* error */ will result in errors
27 } /* end function tryToModifyArray */

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

Software Engineering Observation 6.3


The const type qualifier can be applied to an array
parameter in a function definition to prevent the
original array from being modified in the function
body.
Functions should not be given the capability to modify
an array unless it is absolutely necessary.

 2007 Pearson Education, Inc. All rights reserved.

49

6.9 Multiple-Subscripted Arrays


 Multiple subscripted arrays
– Tables with rows and columns (m by n array)
– Like matrices: specify row, then column
 Initialization 1st row 2nd row

– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– Initializers grouped by row in braces

– If not enough, unspecified elements set to zero


int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

First row and second column of array is equal to 0

 2007 Pearson Education, Inc. All rights reserved.

24
50

6.9 Multiple-Subscripted Arrays


 Referencing elements
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
printf( "%d", b[ 0 ][ 1 ] );

1st row 2nd column

Result = 2

 2007 Pearson Education, Inc. All rights reserved.

51

Common Programming Error 6.9


C interprets a[ x, y ] as a[ y ], and as such it does not
cause a syntax error.

 2007 Pearson Education, Inc. All rights reserved.

25
52

Fig. 6.20 | Double-subscripted array with three rows and four columns.

 2007 Pearson Education, Inc. All rights reserved.

53

Array in a computer memory

1st row

Number of columns in an array is important!

 2007 Pearson Education, Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

28 /* function to output array with two rows and three columns */ 55


29 void printArray( const int a[][ 3 ] )
30 {
Outline
31 int i; /* row counter */
32 int j; /* column counter */
33
fig06_21.c
34 /* loop through rows */
35 for ( i = 0; i <= 1; i++ ) {
36
(2 of 2 )
37 /* output column values */
38 for ( j = 0; j <= 2; j++ ) {
39 printf( "%d ", a[ i ][ j ] );
40 } /* end inner for */
41
42 printf( "\n" ); /* start new line of output */
43 } /* end outer for */
44
45 } /* end function printArray */

Values in array1 by row are:


1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

28 /* determine smallest and largest grade values */ 57


29
30
printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
minimum( studentGrades, STUDENTS, EXAMS ),
Outline
31 maximum( studentGrades, STUDENTS, EXAMS ) );
32
33 /* calculate average grade for each student */
fig06_22.c
34 for ( student = 0; student < STUDENTS; student++ ) {
35 printf( "The average grade for student %d is %.2f\n",
36 student, average( studentGrades[ student ], EXAMS ) );
(2 of 6 )
37 } /* end for */
38
The address of each row is given to the function
39 return 0; /* indicates successful termination */
40
41 } /* end main */
42

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

68 /* Find the maximum grade */ 59


69 int maximum( const int grades[][ EXAMS ], int pupils, int tests )
70 {
Outline
71 int i; /* student counter */
72 int j; /* exam counter */
73 int highGrade = 0; /* initialize to lowest possible grade */
fig06_22.c
74
75 /* loop through rows of grades */
76 for ( i = 0; i < pupils; i++ ) {
(4 of 6 )
77
78 /* loop through columns of grades */
79 for ( j = 0; j < tests; j++ ) {
80
81 if ( grades[ i ][ j ] > highGrade ) {
82 highGrade = grades[ i ][ j ];
83 } /* end if */
84
85 } /* end inner for */
86
87 } /* end outer for */
88
89 return highGrade; /* return maximum grade */
90
91 } /* end function maximum */
92

 2007 Pearson Education,


Inc. All rights reserved.

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

 2007 Pearson Education,


Inc. All rights reserved.

117 /* output grades in tabular format */ 61


118
119
for ( i = 0; i < pupils; i++ ) {
Outline
120 /* output label for row */
121 printf( "\nstudentGrades[%d] ", i );
122
fig06_22.c
123 /* output grades for one student */
124 for ( j = 0; j < tests; j++ ) {
125 printf( "%-5d", grades[ i ][ j ] );
(6 of 6 )
126 } /* end inner for */
127
128 } /* end outer for */
129
130 } /* end function printArray */

The array is:


[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
studentGrades[2] 70 90 86 81

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

 2007 Pearson Education,


Inc. All rights reserved.

30
Break
Class assistant will be showing
example applications after the break.

 2007 Pearson Education,


Inc. All rights reserved.

31

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy