0% found this document useful (0 votes)
13 views53 pages

Introduction To C

Uploaded by

mborasydn
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)
13 views53 pages

Introduction To C

Uploaded by

mborasydn
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/ 53

1

4
C Program
Control

© 2007 Pearson Education, Inc. All rights reserved.


2

Not everything that can be counted counts, and


not every thing that counts can be counted.
—Albert Einstein

Who can control his fate?


—William Shakespeare

The used key is always bright.


—Benjamin Franklin

© 2007 Pearson Education, Inc. All rights reserved.


3

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.


4

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.


5

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.


6

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.


7

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.


1 /* Fig. 4.1: fig04_01.c 8
2 Counter-controlled repetition */
3 #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.
9

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.


10

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.


11

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.


12

Fig. 4.3 | for statement header components.

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 4.2: fig04_02.c 13
2 Counter-controlled repetition with the for statement */
3 #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.
14

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.


15

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.


16

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 17
2 Summation with for */
3 #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.
1 /* Fig. 4.6: fig04_06.c 18
2 Calculating compound interest */
3 #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.
19
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

25.4545 is printed

© 2007 Pearson Education,


Inc. All rights reserved.
How many times the “*” character is printed? Q

main() {
int i, j;
for (i=0; i<10; i++)
for (j=0; j<=3; j++)
printf ("*"); }

a) 13 b) 30 c) 33 d) 40 e) 44

© 2007 Pearson Education,


Inc. All rights reserved.
What is the output of the following program? Q

main() {
int i=3, j=-1;
for (i=5; i < 10; i++) {
printf ("%d", i); i++;
for (j=0; j < 2; j++) printf ("*"); } }

a) 579
b) 5**7**9
c) 5**7**9**
d) **7**9**
e) ******

© 2007 Pearson Education,


Inc. All rights reserved.
What is the output of the following program? Q

main() {
int number=13986, i;
int s=0, d=0;
for (i=1 ; i ; i=number) {
s+=number%10;
number/=10;
d++; }
printf ("%d%d", s, d); }

a) 265 b) 274 c) 275 d) 264 e) None of them

© 2007 Pearson Education,


Inc. All rights reserved.
23

switch Multiple-Selection Statement


▪ switch
– A switch statement allows a variable to be tested for equality against
a list of values. Each value is called a case, and the variable being
switched on is checked for each switch case.
– 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.


24

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.


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.


26

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.


1 /* Fig. 4.7: fig04_07.c 27
2 Counting letter grades */
3 #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 */ 28
30 case 'b': /* or lowercase b */
31 ++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.
54 default: /* catch all other characters */ 29
55 printf( "Incorrect letter grade entered." );
56 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.
30
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.
31

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

© 2007 Pearson Education, Inc. All rights reserved.


32

Portability Tip

The keystroke combinations for entering


EOF (end of file) are system dependent.

© 2007 Pearson Education, Inc. All rights reserved.


What is the output of the following program? Q

main() {
int x;
switch (x=3.2) {
case 0: printf ("zero\n"); break;
case 1: printf ("one\n"); break;
case 2: printf ("two\n"); break;
case 3: printf ("three\n"); break;
default: printf ("default\n"); break; } }

a) zero b) one c) three


d) default e) Compile-time Error

© 2007 Pearson Education,


Inc. All rights reserved.
What is the output of the following program? Q

main() {
int x=0,i;
for (i=0;i<5;i++) {
switch (i) {
case 0: x++;
case 1: x*=x; break;
case 2: x+=x;
default: x--; }
}
printf ("%d", x); }

a) -1 b) 0 c) 1 d) 2 e) 3

© 2007 Pearson Education,


Inc. All rights reserved.
35

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.


36

do…while Repetition Statement


▪ Example (letting counter = 1):

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

– Prints the integers from 1 to 10

© 2007 Pearson Education, Inc. All rights reserved.


37

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.


38

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.

while (++counter <= 10); { statements;}

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.


39

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

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 4.11: fig04_11.c 40
2 Using the break statement in a for statement */
3 #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.
41

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.


1 /* Fig. 4.12: fig04_12.c 42
Using the continue statement in a for statement */
2
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.
What is the output of the following program? Q

int i=3, j=4, k=8;


for ( ; ; i++, j++, k--) {
if (j%2) continue;
if (i>k) break; }
printf ("%d %d %d", i, j, k);

a) 6 6 4 b) 6 8 5
c) 7 8 5 d) 7 8 4 e) 8 8 5

© 2007 Pearson Education,


Inc. All rights reserved.
44

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.


45

▪ && ( 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.


46

▪ || ( 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.


47

▪ ! ( 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.


48

Performance Tip
In expressions using operator &&, make the
condition that is most likely to be false the leftmost
condition. (0 && x)
In expressions using operator ||, make the
condition that is most likely to be true the leftmost
condition. (1 ||x)

This can reduce a program’s execution time.

© 2007 Pearson Education, Inc. All rights reserved.


What will be the output of the following code segment? Q

int a=1, b=3, c=1;


if ( (a || c--) && (c && b--) ) printf ("%d", b);
printf ("%d %d %d ", a, b ,c);

a) 1 2 0 b) 21 2 0 c) 21 2 1
d) 1 3 1 e) 31 3 1

© 2007 Pearson Education,


Inc. All rights reserved.
50

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.


What is the output of the following program? Q

main() {
int i, j, a, b, c, d;
a=1; b=-4; c=2; d=-3;
if ((a>b+c&&d) == (a>(b+c)&&d)) printf ("THIS");
else if ((a>b+c&&d) == ((a>b)+c&&d)) printf ("THAT");
else if ((a>b+c&&d) == (a>b+(c&&d))) printf ("NOT");
else printf ("DOT"); }

a) THIS b) THAT c)NOT d) DOT e) 0

© 2007 Pearson Education,


Inc. All rights reserved.
52

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.


53

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.

You might also like