05 Control Statements in C
05 Control Statements in C
The switch
The for loop
statements
If Selection Statement
• Selection structure
• Choose among alternative courses of action Syntax:
if ( condition )
• Pseudocode example: {
If student’s grade is greater than or equal to 60 statement ;
}
Printf “Passed”
• If the condition is true
• Print statement executed, program continues to next statement
• If the condition is false
• Print statement ignored, program continues
If Structure
• Translation into C
If student’s grade is greater than or equal to 60 if ( grade >= 60 ) {
Print “Passed” printf("Passed“);}
• if structure
• Single-entry/single-exit A decision can be made on
any expression.
zero - false
true nonzero - true
grade >= 60 print “Passed”
Example:
3 - 4 is true
false
If-Else Structure FLOW Chart
• if
• Performs action if condition true False True
Test Condition
• if/else
• Different actions if conditions true or false
• Pseudocode Executable Y - Statement Executable X - Statement
printf("Passed“); else
{
else statement 2 ; (if the condition is false this statement will be executed)
printf("Failed“); }
Else-If Structure
• Nested if/else structures • Example
One inside another, test for multiple cases
Once condition met, other statements skipped
if ( grade >= 90 ) // 90 and above
if student’s grade is greater than or equal to 90
Print “A” printf("A“);
else else if ( grade >= 80 ) // 80-89
if student’s grade is greater than or equal to 80 pritnf("B“);
Print “B”
else
else if ( grade >= 70 ) // 70-79
if student’s grade is greater than or equal to 70 printf("C");
Print “C” else if ( grade >= 60 ) // 60-69
else
if student’s grade is greater than or equal to 60 printf("D“);
Print “D” else // less than 60
else printf("F“);
Print “F”
FALSE TRUE
Test Condition_1 Exec. Stat_1
FALSE
TRUE
FALSE TRUE
Test Condition_3 Exec. Stat_3
FALSE TRUE
Test Condition_n
FALSE
Syntax and Flow Chart
TRUE
EXPR==VALUE_2 Starts execution from this case
Syntax
FALSE
Switch ( expression )
{
TRUE
EXPR==VALUE_3 Starts execution from this case
case value_1: set of statements;
case value_2: Setof Statements;
FALSE
case value_3: Set of Statements;
default: Set of Statements; Flow Chart
} EXPR==VALUE_1