Control Statements: Autumn Semester 2009 Programming and Data Structure 1
Control Statements: Autumn Semester 2009 Programming and Data Structure 1
Some applications may also require that a set of instructions be executed repeatedly, possibly again based on some condition.
This is called looping.
Examples
count <= 100 (math+phys+chem)/3 >= 60 (sex==M) && (age>=21) (marks>=80) && (marks<90) (balance>5000) | | (no_of_trans>25) ! (grade==A) ! ((x>20) && (y<16))
Non-zero
Indicates TRUE. Typically the condition TRUE is represented by the value 1.
Example
#include <stdio.h> main() { int a,b,c; scanf (%d %d %d, &a, &b, &c); if ((a>=b) && (a>=c)) printf (\n The largest number is: %d, a); if ((b>=a) && (b>=c)) printf (\n The largest number is: %d, b); if ((c>=a) && (c>=b)) printf (\n The largest number is: %d, c); }
true
print Failed
print Passed
if-else syntax
if ( expression ) { statement1; statement2; . statement_n; } if ( expression ) { statement_1; statement_2; . statement_n; } else { Statement_1; . Statement_m; }
if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n"); Programming and Data Structure 11
Rule to be remembered:
An else clause is associated with the closest preceding unmatched if.
12
Example
#include <stdio.h> main() { int a,b,c; scanf (%d %d %d, &a, &b, &c); if (a>=b) if (a>=c) printf (\n The largest number is: %d, a); else printf (\n The largest number is: %d, c); else if (b>=c) printf (\n The largest number is: %d, b); else printf (\n The largest number is: %d, c); }
Autumn Semester 2009 Programming and Data Structure 15
Example
#include <stdio.h> main() { int a,b,c; scanf (%d %d %d, &a, &b, &c); if ((a>=b) && (a>=c)) printf (\n The largest number is: %d, a); else if (b>c) printf (\n The largest number is: %d, b); else printf (\n The largest number is: %d, c); }
16
Dangerous error
Does not ordinarily cause syntax errors Any expression that produces a value can be used in control structures Nonzero values are true, zero values are false
Example:
if ( payCode == 4 ) printf( "You get a bonus!\n" ); Checks paycode, if it is 4 then a bonus is awarded
Equality check improper Equality check proper if ( payCode = 4 ) if ( payCode == 4 ) printf( "You get a bonus!\n" ); printf( "You get a bonus!\n" );
Autumn Semester 2009 Programming and Data Structure 17
j=1
18
m=2; t=2;
m=2; t=1;
19
Takes three arguments (condition, value if true, value if false) Returns the evaluated value accordingly. grade >= 60 ? printf( Passed\n ) : printf( Failed\n ); (expr1)? (expr2): (expr3); Example: interest = (balance>5000) ? balance*0.2 : balance*0.1; Returns a value
Autumn Semester 2009 Programming and Data Structure 21
true case a false true case b false . . . case b action(s) break case a action(s) break
23
Example
switch ( letter ) { case 'A': printf("First letter\n"); break; case 'Z': printf("Last letter\n"); break; default : printf("Middle letter\n"); break; }
24
Example
switch (choice = toupper(getchar())) { case R: case G: case B: default: } printf (RED \n); break; printf (GREEN \n); break; printf (BLUE \n); break; printf (Invalid choice \n);
25
Example
switch (choice = getchar()) { case r: case R: case g: case G: case b: case B: default: }
Autumn Semester 2009 Programming and Data Structure 26
printf (RED \n); break; printf (GREEN \n); break; printf (BLUE \n); break; printf (Invalid choice \n);
With respect to switch, the break statement causes a transfer of control out of the entire switch statement, to the first statement following the switch statement.
27
Counter-controlled repetition
Definite repetition - know how many times loop will execute Control variable used to count repetitions
Sentinel-controlled repetition
Indefinite repetition Used when number of repetitions not known Sentinel value indicates "end of data"
28
Counter-Controlled Repetition
Counter-controlled repetition requires
name of a control variable (or loop counter). initial value of the control variable. condition that tests for the final value of the control variable (i.e., whether looping should continue). increment (or decrement) by which the control variable is modified each time through the loop. int counter =1; //initialization
while (counter <= 10) { //repetition condition for (counter=1;counter<=10;counter++) printf( "%d\n", counter ); printf(%d\n,counter); ++counter; //increment }
Autumn Semester 2009 Programming and Data Structure 29
int counter;
while Statement
while (condition) statement_to_repeat; while (condition) { statement_1; ... statement_N; } int digit = 0;
while (digit <= 9) printf (%d \n, digit++);
Autumn Semester 2009 Programming and Data Structure 30
/* Weight loss program */ while ( weight > 65 ) { printf("Go, exercise, "); printf("then come back. \n"); printf("Enter your weight: "); scanf("%d", &weight); }
C true statement(s)
31
do-while Statement
do { statement-1 statement-2 . . statement-n } while ( condition ); At least one round of exercise ensured.
Autumn Semester 2009 Programming and Data Structure 32
/* Weight loss program */ do { printf("Go, exercise, "); printf("then come back. \n"); printf("Enter your weight: "); scanf("%d", &weight); } while ( weight > 65 ) ;
C true
false
for Statement
for (initial; condition; iteration) statement_to_repeat;
for (initial; condition; iteration) { statement_1; ... statement_N; fact = 1; /* Calculate 10 ! */ } for ( i = 1; i < =10; i++) fact = fact * i;
34
How it works?
expression1 is used to initialize some variable (called index) that controls the looping action. expression2 represents a condition that must be true for the loop to continue. expression3 is used to alter the value of the index initially assigned by expression1.
int digit; for (digit=0; digit<=9; digit++) printf (%d \n, digit);
Autumn Semester 2009 Programming and Data Structure 35
How it works?
expression1 is used to initialize some variable (called index) that controls the looping action. expression2 represents a condition that must be true for the loop to continue. expression3 is used to alter the value of the index initially assigned by expression1.
36
int digit;
expression1
false
37
"Increment" may be negative (decrement) If loop continuation condition initially false Body of for structure not performed Control proceeds with statement after for structure
38
for :: Examples
int fact = 1, i; for (i=1; i<=10; i++) fact = fact * i; int sum = 0, N, count; scanf (%d, &N); for (i=1; i<=N, i++) sum = sum + i * i; printf (%d \n, sum);
39
40
41
break Statement
Break out of the loop { } can use with while do while for switch does not work with if {} else {}
Causes immediate exit from a while, for, do/while or switch structure 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 structure
Autumn Semester 2009 Programming and Data Structure 42
A Complete Example
#include <stdio.h> main() { int fact, i; fact = 1; i = 1; while ( i<10 ) { /* run loop break when fact >100*/ fact = fact * i; if ( fact > 100 ) { printf ("Factorial of %d above 100", i); break; /* break out of the while loop */ } i ++ ; } }
43
continue Statement
continue Skips the remaining statements in the body of a while, for or do/while structure
Proceeds with the next iteration of the loop
for structure
Increment expression is executed, then the loopcontinuation test is evaluated.
44
45
46
Venue:
Syllabus
Variables and constants Number system Assignments Conditional statements Loops Simple input/output
48
Some Examples
49
50
More efficient??
#include <stdio.h> main() { int n, i=3; scanf (%d, &n); while (i < sqrt(n)) { if (n % i == 0) { printf (%d is not a prime \n, n); exit; } i = i + 2; } printf (%d is a prime \n, n); }
Autumn Semester 2009 Programming and Data Structure 51
52
53
Shortcuts in Assignments
Additional assignment operators:
+ =, =, * =, / =, %=
55
56
The control string consists of individual groups of characters, with one character group for each input data item. % sign, followed by a conversion character.
Autumn Semester 2009 Programming and Data Structure 57
We can also specify the maximum field-width of a data item, by specifying a number indicating the field width before the conversion character.
Example: scanf (%3d %5d, &a, &b);
58
59
Examples:
printf (The average of %d and %d is %f, a, b, avg); printf (Hello \nGood \nMorning \n); printf (%3d %3d %5d, a, b, a*b+2); printf (%7.2f %5.1f, x, y);
String I/O:
Will be covered later in the class.
Autumn Semester 2009 Programming and Data Structure 60