Control Statements 6.2 BRANCHING: If - Else Statement
Control Statements 6.2 BRANCHING: If - Else Statement
The statement is executed only if the expression is true. if (expression-is-true) statement; When there are only two options, use the else clause if (expression-is-true) statement 1; else statement 2; When there are more than two options, use the if else clause if (expression1-is-true) statement 1; else if (expression2-is-true) statement 2; .. else statement n; Example Read mark (0-100) and assign grade according to the following table: Mark 80 100 70 79 60 69 0 59 #include <stdio.h> main () { float mark; char grade; scanf(%f, &mark); if (mark >= 80 ) grade = A; else if (mark >=70) grade = B; else if (mark >=60) grade = C else grade = F; } Grade A B C F
6.3
The statement is executed repeatedly, as long as the expression is true (i.e. nonzero value). while (expression-is-true) statement; Example Display consecutive digits 0, 1, 2, . , 9 with one digit on each line. #include <stdio.h> main() { int digit = 0; while (digit <=9) { printf(%d\n, digit); digit = digit + 1; } } The program can be written concisely as #include <stdio.h> main() { int digit = 0; while (digit <=9) printf(%d\n, digit + +); } 6.4 LOOPING: do while Statement
Can be written as
+ + digit
The general expression is: do statement; while (expression-is-true); Example Display consecutive digits 0, 1, 2, . , 9 with one digit on each line. #include <stdio.h> main() { int digit = 0; do printf(%d\n, digit + +); while (digit<=9); }
6.5
The for statement is the most commonly used looping statement in C. General form is for (expression1; expression2; expression3) {statement1; statement2;} expression1 used to initialize some parameter (called index) that controls the loop expression2 a condition that must be true to continue the loop expression3 used to alter the value of parameter initialized by expression1.
Example - Display consecutive digits 0, 1, 2, . , 9 with one digit on each line. #include <stdio.h> main() { int digit ; for (digit=0; digit <=9; digit=digit+1) printf(%d\n, digit); } 6.6 Nested Control Structures true false
Example Generate a multiplication table 1X1=1 . 11 X 12 = 121 12 X 12 = 144 #include <stdio.h> main() { int i, j; for (i=1; i<=12; i=i+1) for (j=1; j<=12; j=j+1) printf(%d X %d = %d \n, j, i, j*i); } There are 2 loops: the inner loop (index j) and the outer loop (index i). The inner loop is executed for j = 1,2, ,12 for each value of the outer loop index (i=1,2, ,12).