Control Structure in C- controlling the program execution flow: selection, repetition and branching-
What are control structures?  Our programs so far consist of just a list of commands to be done in order  The program cannot choose whether or not to perform a command  The program cannot perform the same command more than once  Such programs are extremely limited!  Control structures allow a program to base its behavior on the values of variables 2 Prepared by: Er. Rhishav Poudyal
PROGRAM CONTROL  Program begins execution at the main() function.  Statements within the main() function are then executed from top-down style, line-by-line.  The order of the execution within the main() body may be branched.  Changing the order in which statements are executed is called program control.  Accomplished by using program control statements.  So we can control the program flows.
PROGRAM CONTROL  There are three types of program controls: 1. Sequence control structure. 2. Selection structures such as if, if-else, nested if, if-if-else, if-else-if and switch-case-break-goto. 3. Repetition (loop) such as for, while and do- while.  Certain C functions and keywords also can be used to control the program flows.
Control Structures  Statements can be executed in sequence  One right after the other  No deviation from the specified sequence 5 Prepared by: Er. Rhishav Poudyal
PROGRAM CONTROL  Take a look at the following example Jump/branch to printf() Back to main() from printf()
PROGRAM CONTROL float paidRate = 5.0, sumPaid, paidHours = 25; S1 sumPaid = paidHours * paidRate; S2 printf("Paid sum = $%.2f n", sumPaid); S3 return 0; S4  One entry point and one exit point.  Conceptually, a control structure like this means a sequence execution.
Control Structures  A selection structure can be used  Which statement is executed is selected by whether the expression is true or false 8 Prepared by: Er. Rhishav Poudyal
PROGRAM CONTROL  Program need to select from the options given for execution.  At least 2 options, can be more than 2.  Option selected based on the condition evaluation result: TRUE or FALSE. Selection Control Structure
PROGRAM CONTROL Selection: if, if-else, if-else-if  Starting from the most basic if syntax, if (condition) if (condition) statement; { statements;} next_statement; next_statement; 1.(condition) is evaluated. 2. If TRUE (non-zero) the statement is executed. 3. If FALSE (zero) the next_statement following the if statement block is executed. 4. So, during the execution, based on some condition, some codes were skipped.
Flowchart for the if statement 11 condition? statement true false Prepared by: Er. Rhishav Poudyal
PROGRAM CONTROL For example: if (hours > 70) hours = hours + 100; printf("Less hours, no bonus!n");  If hours is less than or equal to 70, its value will remain unchanged and the printf() will be executed.  If it exceeds 70, its value will be increased by 100. if(jobCode == '1') { carAllowance = 100.00; housingAllowance = 500.00; entertainmentAllowance = 300.00; } printf("Not qualified for car, housing and entertainment allowances!"); The three statements enclosed in the curly braces { } will only be executed if jobCode is equal to '1', else the printf() will be executed.
The if-else statement  The if-else statement chooses which of two statements to execute  The if-else statement has the form: if (condition) statement-to-execute-if-true ; else statement-to-execute-if-false ;  Either statement (or both) may be a compound statement  Notice the semicolon after each statement 13 Prepared by: Er. Rhishav Poudyal
Flowchart for the if-else statement 14 condition? true statement-1 statement-2 false Prepared by: Er. Rhishav Poudyal
PROGRAM CONTROL if (condition) if (condition) statement_1; { a block of statements;} else else statement_2; { a block of statements;} next_statement; next_statement; Explanation: 1. The (condition) is evaluated. 2. If it evaluates to non-zero (TRUE), statement_1 is executed, otherwise, if it evaluates to zero (FALSE), statement_2 is executed. 3. They are mutually exclusive, meaning, either statement_1 is executed or statement_2, but not both. 4.statements_1 and statements_2 can be a block of codes and must be put in curly braces.
PROGRAM CONTROL For example: if(myCode == '1') rate = 7.20; else rate = 12.50; If myCode is equal to '1', the rate is 7.20 else, if myCode is not equal to '1' the rate is 12.50. Equal/not equal is not a value comparison, but a character comparison!!!
PROGRAM CONTROL  The if-else constructs can be nested (placed one within another) to any depth.  General forms: if-if-else and if-else-if.  The if-if-else constructs has the following form (3 level of depth example), if(condition_1) if(condition_2) if(condition_3) statement_4; else statement_3; else statement_2; else statement_1; next_statement;
PROGRAM CONTROL  In this nested form, condition_1 is evaluated. If it is zero (FALSE), statement_1 is executed and the entire nested if statement is terminated.  If non-zero (TRUE), control goes to the second if (within the first if) and condition_2 is evaluated.  If it is zero (FALSE), statement_2 is executed; if not, control goes to the third if (within the second if) and condition_3 is evaluated.  If it is zero (FALSE), statement_3 is executed; if not, statement_4 is executed. The statement_4 (inner most) will only be executed if all the if statement are TRUE.  Again, only one of the statements is executed other will be skipped.  If the else is used together with if, always match an else with the nearest if before the else.  statements_x can be a block of codes and must be put in curly braces.
PROGRAM CONTROL  The if-else-if statement has the following form (3 levels example). if(condition_1) statement_1; else if (condition_2) statement_2; else if(condition_3) statement_3; else statement_4; next_statement;
PROGRAM CONTROL  condition_1 is first evaluated. If it is non zero (TRUE), statement_1 is executed and the whole statement terminated and the execution is continue on the next_statement.  If condition_1 is zero (FALSE), control passes to the next else- if and condition_2 is evaluated.  If it is non zero (TRUE), statement_2 is executed and the whole system is terminated. If it is zero (FALSE), the next else-if is tested.  If condition_3 is non zero (TRUE), statement_3 is executed; if not, statement_4 is executed.  Note that only one of the statements will be executed, others will be skipped.  statement_x can be a block of statement and must be put in curly braces.
PROGRAM CONTROL  If mark is less than 40 then grade 'F' will be displayed; if it is greater than or equal to 40 but less than 50, then grade 'E' is displayed.  The test continues for grades 'D', 'C', and 'B'.  Finally, if mark is greater than or equal to 80, then grade 'A' is displayed.
The Switch Statement  The switch statement provides another way to decide which statement to execute next  The switch statement evaluates an expression, then attempts to match the result to one of several possible cases  The match must be an exact match. 22 switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } Prepared by: Er. Rhishav Poudyal
The Switch Statement  Each case contains a value and a list of statements  The flow of control transfers to statement associated with the first case value that matches 23 switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } Prepared by: Er. Rhishav Poudyal
Switch - syntax  The general syntax of a switch statement is: switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words If expression matches value3, control jumps to here Prepared by: Er. Rhishav Poudyal 24
The Switch Statement  The break statement can be used as the last statement in each case's statement list  A break statement causes control to transfer to the end of the switch statement  If a break statement is not used, the flow of control will continue into the next case switch ( expression ){ case value1 : statement-list1 break; case value2 : statement-list2 break; case value3 : statement-list3 break; case ... } Prepared by: Er. Rhishav Poudyal 25
Switch Example  Examples of the switch statement: switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } Prepared by: Er. Rhishav Poudyal 26
Switch – no breaks!!!  Another Example: switch (option){ case 'A': aCount++; case 'B': bCount++; case 'C': cCount++; } switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } Prepared by: Er. Rhishav Poudyal 27
Switch - default  A switch statement can have an optional default case  The default case has no associated value and simply uses the reserved word default  If the default case is present, control will transfer to it if no other case value matches  If there is no default case, and no other value matches, control falls through to the statement after the switch Prepared by: Er. Rhishav Poudyal 28
The switch Statement  Switch with default case: switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: otherCount++; break; } Prepared by: Er. Rhishav Poudyal 29
switch Example switch ( day ) { case 0: printf (“Sundayn”) ; break ; case 1: printf (“Mondayn”) ; break ; case 2: printf (“Tuesdayn”) ; break ; case 3: printf (“Wednesdayn”) ; break ; case 4: printf (“Thursdayn”) ; break ; case 5: printf (“Fridayn”) ; break ; case 6: printf (“Saturdayn”) ; break ; default: printf (“Error -- invalid day.n”) ; break ; } Prepared by: Er. Rhishav Poudyal 30
Why Use a switch Statement?  A nested if-else structure is just as efficient as a switch statement.  However, a switch statement may be easier to read.  Also, it is easier to add new cases to a switch statement than to a nested if-else structure. Prepared by: Er. Rhishav Poudyal 31
To Switch or not to Switch  The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char  It cannot be a boolean value or a floating point value (float or double)  The implicit boolean condition in a switch statement is equality  You cannot perform relational checks with a switch statement Prepared by: Er. Rhishav Poudyal 32
Iterations/Loops  The purpose of a loop is to repeat the same action a number of times  We continue repeating the action until a terminating condition is satisfied.  This terminating condition is called a loop guard  The loop guard is represented by a boolean expression in the same way as the condition of an IF statement.  Before the loop starts we initialise variables involved in the loop  In C there are a number of ways to represent loops Prepared by: Er. Rhishav Poudyal 33
Repetition: The for statement  Executes a code block for a certain number of times.  The code block may have no statement, one statement or more.  The for statement causes the for loop to be executed in a fixed number of times.  The following is the for statement form, for(initial_value;condition(s);increment/decr ement) statement(s); next_statement;  initial_value, condition(s) and increment/decrement are any valid C expressions.  The statement(s) may be a single or compound C statement (a block of code). .
PROGRAM CONTROL  The for loop flow chart should be something like the following. F Stop Execute statement(s) Do increment/ decrement T Start Evaluate initial_value Evaluate condition(s)
PROGRAM CONTROL  A Simple for example, printing integer 1 to 10. #include <stdio.h> void main(void) { int nCount; // display the numbers 1 to 10 for(nCount = 1; nCount <= 10; nCount++) printf("%d ", nCount); printf("t"); } Printf(“Press any key to continue . . . “);
PROGRAM CONTROL F Stop printf("…"); nCount++ T Start nCount = 1 nCount <=10?  Its flow chart…
PROGRAM CONTROL  for loop is a very flexible construct.  Can use the decrementing counter instead of incrementing. For example, for (nCount = 100; nCount > 0; nCount--)  Can use counter other than 1, for example 3, for(nCount = 0; nCount < 1000; nCount += 3)  initial_value can be omitted if the test variable has been initialized beforehand.  However the semicolon must still be there. For example, nCount=1; for( ; nCount < 1000; nCount ++)
PROGRAM CONTROL  The condition(s) expression that terminates the loop can be any valid C expression.  As long as it evaluates as TRUE (non zero), the for statement continues to execute.  Logical operators can be used to construct more complex condition(s) expressions.
PROGRAM CONTROL  The for statement(s) can be followed by a null (empty) statement, so that task is done in the for loop itself.  Null statement consists of a semicolon alone on a line. For example, for(count = 0; count < 20000; count++) ;  This statement provides a pause (delay) of 20,000 milliseconds.
PROGRAM CONTROL  We can also create an infinite or never-ending loop by omitting all the expressions or by using a non-zero constant for condition(s) as shown in the following two code snippets, for( ; ; ) printf("This is an infinite loopn");  or for( ; 1 ; ) printf("This is an infinite loopn");  In both cases, the message "This is an infinite loop" will be printed repeatedly, indefinitely.  All the repetition constructs discussed so far can be nested to any degree.
While loops  The most basic loop in C is the while loop.  The general syntax of a while loop is while( expression ) statement The expression represents the loop guard.  While it is true repeat the statement. Terminate when the expression evaluates to false Prepared by: Er. Rhishav Poudyal 42
Repetition: The while loop  Executes a block of statements as long as a specified condition is TRUE.  The general while loop construct, while (condition) statement(s); next_statement;  The (condition) may be any valid C expression.  The statement(s) may be either a single or a compound (a block of code) C statement.
PROGRAM CONTROL  The while statement flow chart is shown below. Start Evaluate condition Execute statement(s) Stop F T
PROGRAM CONTROL // simple while loop example #include <stdio.h> int main(void) { int nCalculate = 1; // set the while condition while(nCalculate <= 12) { // print printf("%d ", nCalculate); // increment by 1, repeats nCalculate++; } // a newline printf("n"); return 0; }  A simple example
PROGRAM CONTROL  The same task that can be performed using the for statement.  But, while statement does not contain an initialization section, the program must explicitly initialize any variables beforehand.  As conclusion, while statement is essentially a for statement without the initialization and increment components.  The syntax comparison between for and while, for( ; condition; ) vs while(condition)
PROGRAM CONTROL  Just like for and if statements, while statements can also be nested.  The nested while example www.tenouk.com, ©
PROGRAM CONTROL  The nested for and while program example
Repetition: The do-while loop  Executes a block of statements as long as a specified condition is true at least once.  Test the condition at the end of the loop rather than at the beginning, as demonstrated by the for and while loops.  The do-while loop construct is, do statement(s); while (condition) next_statement;  (condition) can be any valid C expression.  statement(s) can be either a single or compound (a block of code) C statement.
PROGRAM CONTROL  A flow chart for the do-while loop Stop Evaluate condition T F Start Execute statement(s)  The statement(s) are always executed at least once.  for and while loops evaluate the condition at the start of the loop, so the associated statements are not executed if the condition is initially FALSE.
continue keyword  continue keyword forces the next iteration to take place immediately, skipping any instructions that may follow it.  The continue statement can only be used inside a loop (for, do-while and while) and not inside a switch-case selection.  When executed, it transfers control to the condition (the expression part) in a while or do-while loop, and to the increment expression in a for loop.  Unlike the break statement, continue does not force the termination of a loop, it merely transfers control to the next iteration.
 continue keyword example // using the continue in for structure #include <stdio.h> int main(void) { int iNum; for(iNum = 1; iNum <= 10; iNum++) { // skip remaining code in loop only if iNum == 5 if(iNum == 5) continue; printf("%d ", iNum); } printf("nUsed continue to skip printing the value 5n"); return 0; }
goto keyword  The goto statement is one of C unconditional jump or branching.  When program execution encounters a goto statement, execution immediately jumps, or branches, to the location specified by the goto statement.  The statement is unconditional because execution always branches when a goto statement is came across, the branching does not depend on any condition.  However, using goto statement strongly not recommended.  Always use other C branching statements.  When program execution branches with a goto statement, no record is kept of where the execution is coming from.
 Syntax goto label; ... .. ... ... .. ... ... .. ... label: statement; 54 Prepared by: Er. Rhishav Poudyal
# include <stdio.h> int main() { const int maxInput = 5; int i; double number, average, sum=0.0; for(i=1; i<=maxInput; ++i) { printf("%d. Enter a number: ", i); scanf("%lf",&number); if(number < 0.0) goto jump; sum += number; // sum = sum+number; } jump: average=sum/(i-1); printf("Sum = %.2fn", sum); printf("Average = %.2f", average); return 0; } 55 Prepared by: Er. Rhishav Poudyal
break keyword  Already discussed in switch-case constructs.  The break statement terminates the execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the terminated statement, if any.  Used with the conditional switch statement and with the do, for, and while loop statements.  In loops, break terminates execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the terminated statement, if any.  Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it.
Some loop programs  1: Read in 10 integers and output their sum  2: Read in 10 integers and output the largest of them  3: Keep reading in integers until one is input which is larger than 100 Prepared by: Er. Rhishav Poudyal 57
Sum of 10 Integers #Include <stdio.h> main() { int i, a,sum; sum = 0; for (i=0;I < 10; i++) { printf(“enter number n”); scanf(“%d”,&a); sum = sum + a; }; printf(“total is %d”,sum); } Prepared by: Er. Rhishav Poudyal 58
Largest of 10 Integers #include <stdio.h> main() { int i, a,max; printf(“enter number n”); scanf(“%d”,&a); max = a; for (i=1;I < 10; i++) { printf(“enter number n”); scanf(“%d”,&a); If (a > max) max = a; }; printf(“largest is %d”,max); Return 0; } Prepared by: Er. Rhishav Poudyal 59
Loop until one input is larger than 100 #Include <stdio.h> main() { int a, do { printf(“enter number n”); scanf(“%d”,&a); }; while (a < 100) printf(“The number which ended the loop is %d”,a); } Prepared by: Er. Rhishav Poudyal 60
While #Include <stdio.h> main() { int a, a= 0; while (a < 100) { printf(“enter number n”); scanf(“%d”,&a); } printf(“The number which ended the loop is %d”,a); } Prepared by: Er. Rhishav Poudyal 61
Example of a while loop #include <stdio.h> main() { int x x = 2; while(x < 1000) { printf("%dn", x); x = x * 2; } } This program repeatedly prints out powers of two until we generate a number greater than or equal to 1000 The terminating condition is thus when the power of two equals or exceeds 1000 Prepared by: Er. Rhishav Poudyal 62
loop questions 2: Use a Do while loop to calculate the minimum of 100 integers being read in. Prepared by: Er. Rhishav Poudyal 63
#include <stdio.h> main() {int x; x =1; while(x != 45) { printf(“enter no”); scanf(“%d", &x); } } 1: Write a program which continually reads in integers until 45 is read in Prepared by: Er. Rhishav Poudyal 64
Read until 45 #include <stdio.h> main() {int x; do { printf(“enter no”); scanf(“%d", &x); } while(x != 45) ; } Prepared by: Er. Rhishav Poudyal 65
More questions  Read in 20 integers and count the even numbers  Write a program to calculate    100 1 2 ) ( N N n n X X Prepared by: Er. Rhishav Poudyal 66
Sum of function Example #include <stdio.h> #include <math.h> main() { int n,i, fac; float enum,denom,sum; sum = 0.0; for (n=1;n <= 100; n++) { fac = 1; for (i=1, i <=n, i++) { fac = fac*i; enum = n-1; denom = fac*pow(n,2); If (denom == 0) printf(“sum not defined”) sum = sum + (enum/denom); }; printf(“total %f”,sum); } Prepared by: Er. Rhishav Poudyal 67
Remember Loops Consist of  Initialization  Terminating Condition (Guard)  Loop Body  Terminating Action  For Counted Loops Iterations use a For loop  Otherwise use a while or a do while loop Prepared by: Er. Rhishav Poudyal 68

Control Structure in C-programming with examples

  • 1.
    Control Structure inC- controlling the program execution flow: selection, repetition and branching-
  • 2.
    What are controlstructures?  Our programs so far consist of just a list of commands to be done in order  The program cannot choose whether or not to perform a command  The program cannot perform the same command more than once  Such programs are extremely limited!  Control structures allow a program to base its behavior on the values of variables 2 Prepared by: Er. Rhishav Poudyal
  • 3.
    PROGRAM CONTROL  Programbegins execution at the main() function.  Statements within the main() function are then executed from top-down style, line-by-line.  The order of the execution within the main() body may be branched.  Changing the order in which statements are executed is called program control.  Accomplished by using program control statements.  So we can control the program flows.
  • 4.
    PROGRAM CONTROL  Thereare three types of program controls: 1. Sequence control structure. 2. Selection structures such as if, if-else, nested if, if-if-else, if-else-if and switch-case-break-goto. 3. Repetition (loop) such as for, while and do- while.  Certain C functions and keywords also can be used to control the program flows.
  • 5.
    Control Structures  Statementscan be executed in sequence  One right after the other  No deviation from the specified sequence 5 Prepared by: Er. Rhishav Poudyal
  • 6.
    PROGRAM CONTROL  Takea look at the following example Jump/branch to printf() Back to main() from printf()
  • 7.
    PROGRAM CONTROL float paidRate= 5.0, sumPaid, paidHours = 25; S1 sumPaid = paidHours * paidRate; S2 printf("Paid sum = $%.2f n", sumPaid); S3 return 0; S4  One entry point and one exit point.  Conceptually, a control structure like this means a sequence execution.
  • 8.
    Control Structures  Aselection structure can be used  Which statement is executed is selected by whether the expression is true or false 8 Prepared by: Er. Rhishav Poudyal
  • 9.
    PROGRAM CONTROL  Programneed to select from the options given for execution.  At least 2 options, can be more than 2.  Option selected based on the condition evaluation result: TRUE or FALSE. Selection Control Structure
  • 10.
    PROGRAM CONTROL Selection: if,if-else, if-else-if  Starting from the most basic if syntax, if (condition) if (condition) statement; { statements;} next_statement; next_statement; 1.(condition) is evaluated. 2. If TRUE (non-zero) the statement is executed. 3. If FALSE (zero) the next_statement following the if statement block is executed. 4. So, during the execution, based on some condition, some codes were skipped.
  • 11.
    Flowchart for theif statement 11 condition? statement true false Prepared by: Er. Rhishav Poudyal
  • 12.
    PROGRAM CONTROL For example: if(hours > 70) hours = hours + 100; printf("Less hours, no bonus!n");  If hours is less than or equal to 70, its value will remain unchanged and the printf() will be executed.  If it exceeds 70, its value will be increased by 100. if(jobCode == '1') { carAllowance = 100.00; housingAllowance = 500.00; entertainmentAllowance = 300.00; } printf("Not qualified for car, housing and entertainment allowances!"); The three statements enclosed in the curly braces { } will only be executed if jobCode is equal to '1', else the printf() will be executed.
  • 13.
    The if-else statement The if-else statement chooses which of two statements to execute  The if-else statement has the form: if (condition) statement-to-execute-if-true ; else statement-to-execute-if-false ;  Either statement (or both) may be a compound statement  Notice the semicolon after each statement 13 Prepared by: Er. Rhishav Poudyal
  • 14.
    Flowchart for theif-else statement 14 condition? true statement-1 statement-2 false Prepared by: Er. Rhishav Poudyal
  • 15.
    PROGRAM CONTROL if (condition)if (condition) statement_1; { a block of statements;} else else statement_2; { a block of statements;} next_statement; next_statement; Explanation: 1. The (condition) is evaluated. 2. If it evaluates to non-zero (TRUE), statement_1 is executed, otherwise, if it evaluates to zero (FALSE), statement_2 is executed. 3. They are mutually exclusive, meaning, either statement_1 is executed or statement_2, but not both. 4.statements_1 and statements_2 can be a block of codes and must be put in curly braces.
  • 16.
    PROGRAM CONTROL For example: if(myCode== '1') rate = 7.20; else rate = 12.50; If myCode is equal to '1', the rate is 7.20 else, if myCode is not equal to '1' the rate is 12.50. Equal/not equal is not a value comparison, but a character comparison!!!
  • 17.
    PROGRAM CONTROL  Theif-else constructs can be nested (placed one within another) to any depth.  General forms: if-if-else and if-else-if.  The if-if-else constructs has the following form (3 level of depth example), if(condition_1) if(condition_2) if(condition_3) statement_4; else statement_3; else statement_2; else statement_1; next_statement;
  • 18.
    PROGRAM CONTROL  Inthis nested form, condition_1 is evaluated. If it is zero (FALSE), statement_1 is executed and the entire nested if statement is terminated.  If non-zero (TRUE), control goes to the second if (within the first if) and condition_2 is evaluated.  If it is zero (FALSE), statement_2 is executed; if not, control goes to the third if (within the second if) and condition_3 is evaluated.  If it is zero (FALSE), statement_3 is executed; if not, statement_4 is executed. The statement_4 (inner most) will only be executed if all the if statement are TRUE.  Again, only one of the statements is executed other will be skipped.  If the else is used together with if, always match an else with the nearest if before the else.  statements_x can be a block of codes and must be put in curly braces.
  • 19.
    PROGRAM CONTROL  Theif-else-if statement has the following form (3 levels example). if(condition_1) statement_1; else if (condition_2) statement_2; else if(condition_3) statement_3; else statement_4; next_statement;
  • 20.
    PROGRAM CONTROL  condition_1is first evaluated. If it is non zero (TRUE), statement_1 is executed and the whole statement terminated and the execution is continue on the next_statement.  If condition_1 is zero (FALSE), control passes to the next else- if and condition_2 is evaluated.  If it is non zero (TRUE), statement_2 is executed and the whole system is terminated. If it is zero (FALSE), the next else-if is tested.  If condition_3 is non zero (TRUE), statement_3 is executed; if not, statement_4 is executed.  Note that only one of the statements will be executed, others will be skipped.  statement_x can be a block of statement and must be put in curly braces.
  • 21.
    PROGRAM CONTROL  Ifmark is less than 40 then grade 'F' will be displayed; if it is greater than or equal to 40 but less than 50, then grade 'E' is displayed.  The test continues for grades 'D', 'C', and 'B'.  Finally, if mark is greater than or equal to 80, then grade 'A' is displayed.
  • 22.
    The Switch Statement The switch statement provides another way to decide which statement to execute next  The switch statement evaluates an expression, then attempts to match the result to one of several possible cases  The match must be an exact match. 22 switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } Prepared by: Er. Rhishav Poudyal
  • 23.
    The Switch Statement Each case contains a value and a list of statements  The flow of control transfers to statement associated with the first case value that matches 23 switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } Prepared by: Er. Rhishav Poudyal
  • 24.
    Switch - syntax The general syntax of a switch statement is: switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words If expression matches value3, control jumps to here Prepared by: Er. Rhishav Poudyal 24
  • 25.
    The Switch Statement The break statement can be used as the last statement in each case's statement list  A break statement causes control to transfer to the end of the switch statement  If a break statement is not used, the flow of control will continue into the next case switch ( expression ){ case value1 : statement-list1 break; case value2 : statement-list2 break; case value3 : statement-list3 break; case ... } Prepared by: Er. Rhishav Poudyal 25
  • 26.
    Switch Example  Examplesof the switch statement: switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } Prepared by: Er. Rhishav Poudyal 26
  • 27.
    Switch – nobreaks!!!  Another Example: switch (option){ case 'A': aCount++; case 'B': bCount++; case 'C': cCount++; } switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } Prepared by: Er. Rhishav Poudyal 27
  • 28.
    Switch - default A switch statement can have an optional default case  The default case has no associated value and simply uses the reserved word default  If the default case is present, control will transfer to it if no other case value matches  If there is no default case, and no other value matches, control falls through to the statement after the switch Prepared by: Er. Rhishav Poudyal 28
  • 29.
    The switch Statement Switch with default case: switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: otherCount++; break; } Prepared by: Er. Rhishav Poudyal 29
  • 30.
    switch Example switch (day ) { case 0: printf (“Sundayn”) ; break ; case 1: printf (“Mondayn”) ; break ; case 2: printf (“Tuesdayn”) ; break ; case 3: printf (“Wednesdayn”) ; break ; case 4: printf (“Thursdayn”) ; break ; case 5: printf (“Fridayn”) ; break ; case 6: printf (“Saturdayn”) ; break ; default: printf (“Error -- invalid day.n”) ; break ; } Prepared by: Er. Rhishav Poudyal 30
  • 31.
    Why Use aswitch Statement?  A nested if-else structure is just as efficient as a switch statement.  However, a switch statement may be easier to read.  Also, it is easier to add new cases to a switch statement than to a nested if-else structure. Prepared by: Er. Rhishav Poudyal 31
  • 32.
    To Switch ornot to Switch  The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char  It cannot be a boolean value or a floating point value (float or double)  The implicit boolean condition in a switch statement is equality  You cannot perform relational checks with a switch statement Prepared by: Er. Rhishav Poudyal 32
  • 33.
    Iterations/Loops  The purposeof a loop is to repeat the same action a number of times  We continue repeating the action until a terminating condition is satisfied.  This terminating condition is called a loop guard  The loop guard is represented by a boolean expression in the same way as the condition of an IF statement.  Before the loop starts we initialise variables involved in the loop  In C there are a number of ways to represent loops Prepared by: Er. Rhishav Poudyal 33
  • 34.
    Repetition: The forstatement  Executes a code block for a certain number of times.  The code block may have no statement, one statement or more.  The for statement causes the for loop to be executed in a fixed number of times.  The following is the for statement form, for(initial_value;condition(s);increment/decr ement) statement(s); next_statement;  initial_value, condition(s) and increment/decrement are any valid C expressions.  The statement(s) may be a single or compound C statement (a block of code). .
  • 35.
    PROGRAM CONTROL  Thefor loop flow chart should be something like the following. F Stop Execute statement(s) Do increment/ decrement T Start Evaluate initial_value Evaluate condition(s)
  • 36.
    PROGRAM CONTROL  ASimple for example, printing integer 1 to 10. #include <stdio.h> void main(void) { int nCount; // display the numbers 1 to 10 for(nCount = 1; nCount <= 10; nCount++) printf("%d ", nCount); printf("t"); } Printf(“Press any key to continue . . . “);
  • 37.
  • 38.
    PROGRAM CONTROL  forloop is a very flexible construct.  Can use the decrementing counter instead of incrementing. For example, for (nCount = 100; nCount > 0; nCount--)  Can use counter other than 1, for example 3, for(nCount = 0; nCount < 1000; nCount += 3)  initial_value can be omitted if the test variable has been initialized beforehand.  However the semicolon must still be there. For example, nCount=1; for( ; nCount < 1000; nCount ++)
  • 39.
    PROGRAM CONTROL  Thecondition(s) expression that terminates the loop can be any valid C expression.  As long as it evaluates as TRUE (non zero), the for statement continues to execute.  Logical operators can be used to construct more complex condition(s) expressions.
  • 40.
    PROGRAM CONTROL  Thefor statement(s) can be followed by a null (empty) statement, so that task is done in the for loop itself.  Null statement consists of a semicolon alone on a line. For example, for(count = 0; count < 20000; count++) ;  This statement provides a pause (delay) of 20,000 milliseconds.
  • 41.
    PROGRAM CONTROL  Wecan also create an infinite or never-ending loop by omitting all the expressions or by using a non-zero constant for condition(s) as shown in the following two code snippets, for( ; ; ) printf("This is an infinite loopn");  or for( ; 1 ; ) printf("This is an infinite loopn");  In both cases, the message "This is an infinite loop" will be printed repeatedly, indefinitely.  All the repetition constructs discussed so far can be nested to any degree.
  • 42.
    While loops  Themost basic loop in C is the while loop.  The general syntax of a while loop is while( expression ) statement The expression represents the loop guard.  While it is true repeat the statement. Terminate when the expression evaluates to false Prepared by: Er. Rhishav Poudyal 42
  • 43.
    Repetition: The whileloop  Executes a block of statements as long as a specified condition is TRUE.  The general while loop construct, while (condition) statement(s); next_statement;  The (condition) may be any valid C expression.  The statement(s) may be either a single or a compound (a block of code) C statement.
  • 44.
    PROGRAM CONTROL  Thewhile statement flow chart is shown below. Start Evaluate condition Execute statement(s) Stop F T
  • 45.
    PROGRAM CONTROL // simplewhile loop example #include <stdio.h> int main(void) { int nCalculate = 1; // set the while condition while(nCalculate <= 12) { // print printf("%d ", nCalculate); // increment by 1, repeats nCalculate++; } // a newline printf("n"); return 0; }  A simple example
  • 46.
    PROGRAM CONTROL  Thesame task that can be performed using the for statement.  But, while statement does not contain an initialization section, the program must explicitly initialize any variables beforehand.  As conclusion, while statement is essentially a for statement without the initialization and increment components.  The syntax comparison between for and while, for( ; condition; ) vs while(condition)
  • 47.
    PROGRAM CONTROL  Justlike for and if statements, while statements can also be nested.  The nested while example www.tenouk.com, ©
  • 48.
    PROGRAM CONTROL  Thenested for and while program example
  • 49.
    Repetition: The do-whileloop  Executes a block of statements as long as a specified condition is true at least once.  Test the condition at the end of the loop rather than at the beginning, as demonstrated by the for and while loops.  The do-while loop construct is, do statement(s); while (condition) next_statement;  (condition) can be any valid C expression.  statement(s) can be either a single or compound (a block of code) C statement.
  • 50.
    PROGRAM CONTROL  Aflow chart for the do-while loop Stop Evaluate condition T F Start Execute statement(s)  The statement(s) are always executed at least once.  for and while loops evaluate the condition at the start of the loop, so the associated statements are not executed if the condition is initially FALSE.
  • 51.
    continue keyword  continuekeyword forces the next iteration to take place immediately, skipping any instructions that may follow it.  The continue statement can only be used inside a loop (for, do-while and while) and not inside a switch-case selection.  When executed, it transfers control to the condition (the expression part) in a while or do-while loop, and to the increment expression in a for loop.  Unlike the break statement, continue does not force the termination of a loop, it merely transfers control to the next iteration.
  • 52.
     continue keywordexample // using the continue in for structure #include <stdio.h> int main(void) { int iNum; for(iNum = 1; iNum <= 10; iNum++) { // skip remaining code in loop only if iNum == 5 if(iNum == 5) continue; printf("%d ", iNum); } printf("nUsed continue to skip printing the value 5n"); return 0; }
  • 53.
    goto keyword  Thegoto statement is one of C unconditional jump or branching.  When program execution encounters a goto statement, execution immediately jumps, or branches, to the location specified by the goto statement.  The statement is unconditional because execution always branches when a goto statement is came across, the branching does not depend on any condition.  However, using goto statement strongly not recommended.  Always use other C branching statements.  When program execution branches with a goto statement, no record is kept of where the execution is coming from.
  • 54.
     Syntax goto label; ..... ... ... .. ... ... .. ... label: statement; 54 Prepared by: Er. Rhishav Poudyal
  • 55.
    # include <stdio.h> intmain() { const int maxInput = 5; int i; double number, average, sum=0.0; for(i=1; i<=maxInput; ++i) { printf("%d. Enter a number: ", i); scanf("%lf",&number); if(number < 0.0) goto jump; sum += number; // sum = sum+number; } jump: average=sum/(i-1); printf("Sum = %.2fn", sum); printf("Average = %.2f", average); return 0; } 55 Prepared by: Er. Rhishav Poudyal
  • 56.
    break keyword  Alreadydiscussed in switch-case constructs.  The break statement terminates the execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the terminated statement, if any.  Used with the conditional switch statement and with the do, for, and while loop statements.  In loops, break terminates execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the terminated statement, if any.  Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it.
  • 57.
    Some loop programs 1: Read in 10 integers and output their sum  2: Read in 10 integers and output the largest of them  3: Keep reading in integers until one is input which is larger than 100 Prepared by: Er. Rhishav Poudyal 57
  • 58.
    Sum of 10Integers #Include <stdio.h> main() { int i, a,sum; sum = 0; for (i=0;I < 10; i++) { printf(“enter number n”); scanf(“%d”,&a); sum = sum + a; }; printf(“total is %d”,sum); } Prepared by: Er. Rhishav Poudyal 58
  • 59.
    Largest of 10Integers #include <stdio.h> main() { int i, a,max; printf(“enter number n”); scanf(“%d”,&a); max = a; for (i=1;I < 10; i++) { printf(“enter number n”); scanf(“%d”,&a); If (a > max) max = a; }; printf(“largest is %d”,max); Return 0; } Prepared by: Er. Rhishav Poudyal 59
  • 60.
    Loop until oneinput is larger than 100 #Include <stdio.h> main() { int a, do { printf(“enter number n”); scanf(“%d”,&a); }; while (a < 100) printf(“The number which ended the loop is %d”,a); } Prepared by: Er. Rhishav Poudyal 60
  • 61.
    While #Include <stdio.h> main() { inta, a= 0; while (a < 100) { printf(“enter number n”); scanf(“%d”,&a); } printf(“The number which ended the loop is %d”,a); } Prepared by: Er. Rhishav Poudyal 61
  • 62.
    Example of awhile loop #include <stdio.h> main() { int x x = 2; while(x < 1000) { printf("%dn", x); x = x * 2; } } This program repeatedly prints out powers of two until we generate a number greater than or equal to 1000 The terminating condition is thus when the power of two equals or exceeds 1000 Prepared by: Er. Rhishav Poudyal 62
  • 63.
    loop questions 2: Usea Do while loop to calculate the minimum of 100 integers being read in. Prepared by: Er. Rhishav Poudyal 63
  • 64.
    #include <stdio.h> main() {int x; x=1; while(x != 45) { printf(“enter no”); scanf(“%d", &x); } } 1: Write a program which continually reads in integers until 45 is read in Prepared by: Er. Rhishav Poudyal 64
  • 65.
    Read until 45 #include<stdio.h> main() {int x; do { printf(“enter no”); scanf(“%d", &x); } while(x != 45) ; } Prepared by: Er. Rhishav Poudyal 65
  • 66.
    More questions  Readin 20 integers and count the even numbers  Write a program to calculate    100 1 2 ) ( N N n n X X Prepared by: Er. Rhishav Poudyal 66
  • 67.
    Sum of functionExample #include <stdio.h> #include <math.h> main() { int n,i, fac; float enum,denom,sum; sum = 0.0; for (n=1;n <= 100; n++) { fac = 1; for (i=1, i <=n, i++) { fac = fac*i; enum = n-1; denom = fac*pow(n,2); If (denom == 0) printf(“sum not defined”) sum = sum + (enum/denom); }; printf(“total %f”,sum); } Prepared by: Er. Rhishav Poudyal 67
  • 68.
    Remember Loops Consistof  Initialization  Terminating Condition (Guard)  Loop Body  Terminating Action  For Counted Loops Iterations use a For loop  Otherwise use a while or a do while loop Prepared by: Er. Rhishav Poudyal 68