0% found this document useful (0 votes)
19 views43 pages

Chap 4 Control Structures

This document discusses various control structures in programming including sequence, selection, and iteration structures. It provides examples and explanations of different types of control flow statements like if, if-else, else-if, switch-case statements and loops. Specific topics covered include understanding the syntax and use of if statements, if-else statements with blocks of code, else-if statements for multiple choices, switch-case statements for selecting cases, and using break and continue statements within loops.

Uploaded by

French Kaptain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views43 pages

Chap 4 Control Structures

This document discusses various control structures in programming including sequence, selection, and iteration structures. It provides examples and explanations of different types of control flow statements like if, if-else, else-if, switch-case statements and loops. Specific topics covered include understanding the syntax and use of if statements, if-else statements with blocks of code, else-if statements for multiple choices, switch-case statements for selecting cases, and using break and continue statements within loops.

Uploaded by

French Kaptain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 43

Control structures

Objectives
 Understand the sequence structure
 Understand selection structures; if, if..else statements
 Select paths with the switch..case statement
 Understand loop structures; for loop, do..while loop
and do..while loop
 Use break to exit a loop
 Know when to use the continue statement
 Understand the goto statement
 Nest if statements
 Create nested loops

Jane Kuria 08/15/23 Inoorero


University
Introduction
2

 A statement is an element within a program which


you can apply control flow to; control flow is how
you specify the order in which the statements in
your program are executed.
 Three structures control program execution:
 Sequence
 Selection or decision structure
 Iteration or looping structure

Jane Kuria Inoorero University 08/15/23


Sequence…
3

 These consist of execution of statements one at a


time in the sequences they appear.

Jane Kuria Inoorero University 08/15/23


Selection or decision structure
4

 A logical test using logical and relational operators may


require to be used in order to determine which actions
to take (subsequent statements to be executed)
depending on the outcome of the test.
 This is selection.
 For example:
  
 if (score >= 50)
 printf(“Pass”);
 else
 printf(“Fail”);

Jane Kuria Inoorero University 08/15/23


Iteration or looping structure
5

 These are a group of statements in a program may


have to be executed repeatedly until some
condition is satisfied.
 This is known as looping. Suppose you were
asked to display "Hello World!" five times on the
screen.
 How would you write the above program?

Jane Kuria Inoorero University 08/15/23


If statement
6

 We can say that the syntax of an if statement is:


 if( expression )
 statement
 where expression is any expression and statement
is any statement.
1. if(x > max)
2. max = x;
 what happens here is that if x is greater than max, x
gets assigned to max.
Jane Kuria Inoorero University 08/15/23
if statement examples…
7

 (i) if (x<y)
 printf(“x is less that y”);
  
 (ii) if (salary >500)
 tax-amount = salary * 1.5;
  
 (iii) if(balance<1000 || status =’R’)
 print (“Balance = %f”, balance);

Jane Kuria Inoorero University 08/15/23


If statement…
8

 The statement in the if structure can be a single statement or a block


(compound statement).
 If the statement is a block (of statements), it must be marked off by braces.

 if(expression)
 {
 block of statements;
 }
 You may write a series of statements enclosed by braces. (You do not
need to, and should not, put a semicolon after the closing brace, because
the series of statements enclosed by braces is not itself a simple expression
statement.)

Jane Kuria Inoorero University 08/15/23


If ….else statement
9

 The if else statement lets the programmer choose


between two statements as opposed to the simple if
statement which gives you the choice of executing a
statement (possibly compound) or skipping it.
  
 The general form is:
 if (expression)
 statement1;
 else
 statement2;

Jane Kuria Inoorero University 08/15/23


If…else…example
10

1. if(n > 0)
2. average = sum / n;
3. else
4. {
5. printf("can't compute average\n");
6. average = 0;
7. }

Jane Kuria Inoorero University 08/15/23


If..else…
11

 The first statement or block of statements is executed


if the condition is true, and the second statement or
block of statements (following the keyword else) is
executed if the condition is not true.
 In this example, we can compute a meaningful
average only if n is greater than 0;
 Otherwise, we print a message saying that we cannot
compute the average. The general syntax of an if
statement is therefore

Jane Kuria Inoorero University 08/15/23


Else… if statement
12

 This is use when many choices are involved.


  
 The general form is:
  
 if (expression)
 statement;
 else if (expression)
 statement;
 else if (expression)
 statement;
 else
 statement;
  
 (Braces still apply for block statements)

Jane Kuria Inoorero University 08/15/23


Else..if example
13

1. if(sale_amount>=10000)
2. Disc=sal_amt*0.10; /*ten percent/
3. else if (sal_amt>=5000&&sal_amt<1000 )
4. printf(“The discount is %f”,sal_amt*0.07 ); /*seven percent */
5. else if(sal_amt=3000&&sal_amt<5000)
6. {
7. Disc = sal_amt * 0.05; /* five percent */
8. printf ( “ The discount is %f “ , Disc ) ;
9. }
10. else
11. printf(“The discount is 0”) ;

Jane Kuria Inoorero University 08/15/23


Exercises.
14

 Suppose we have a variable grade containing a


student's numeric grade, and we want to print out
the corresponding letter grade.
 Write the program to do just that. Use the JKUAT
grading system.

Jane Kuria Inoorero University 08/15/23


Switch..case
15

 The switch..case statements can be used in place of the if - else statements when
there are several choices to be made.

 The structure of a switch..case statement is as follows:


  
 switch (integer expression)
 {
 case constant 1:
 statement; optional
 case constant 2:
 statement; optional
 default: (optional)
 statement; (optional)
 }

Jane Kuria Inoorero University 08/15/23


Switch case…
16

1. #include<stdio.h>
2. main()
3. {
4. int choice;
5. printf(“Enter a number of your choice ”);
6. scanf(“ %d”, &choice);
7. if (choice >=1 && choice <=9) /* Range of choice numbers */
8. switch (choice)
9. { /* Begin of switch */
10. case 1: /* label 1 */
11. printf(“\n You typed 1”);
12. break;
13. case 2: /* label 2 */
14. printf(“\n You typed 2”);

Jane Kuria Inoorero University 08/15/23


Switch case..
17

1. break;
2. case 3: /* label 3 */
3. printf(“\n You typed 3”);
4. break;
5. case 4: /* label 4 */
6. printf( “ \n You typed 4”);
7. break;
8. default:
9. printf(“There is no match in your choice”);
10. } /* End of switch */
11. else
12. printf(“Your choice is out of range”);
13. return (0);
14. } /* End of main */

Jane Kuria Inoorero University 08/15/23


Explanation of program…
18

 The expression in the parenthesis following the switch is evaluated. In the


example above, it has whatever value we entered as our choice.
  
 Then the program scans a list of labels (case 1, case 2,…. case 4) until it
finds one that matches the one that is in parenthesis following the switch
statement.
  
 If there is no match, the program moves to the line labeled default,
otherwise the program proceeds to the statements following the switch.

 The break statement causes the program to break out of the switch and
skip to the next statement after the switch. Without the break statement,
every statement from the matched label to the end of the switch will be
processed.

Jane Kuria Inoorero University 08/15/23


Switch case continued…
19

 Remove all the break statements from the program and then
run the program using the number 3. What is the result?
   Note

 The switch labels (case labels) must be type int (including


char) constants or constant expression.
  
 You cannot use a variable for an expression for a label
expression.
  
 The expressions in the parenthesis should be one with an
integer value. (again including type char)

Jane Kuria Inoorero University 08/15/23


Looping
20

 C supports three loop versions:


  
 while loop
 do while loop
 for loop.

  

Jane Kuria Inoorero University 08/15/23


The ‘while’ loop
21

 The while statement is used to carry out looping


instructions where a group of instructions executed
repeatedly until some conditions are satisfied.
  
 General form:
 while (expression)
 statement;
  
 The statement will be executed as long as the
expression is true. The statement can be a single or
compound.

Jane Kuria Inoorero University 08/15/23


Example ‘while’ loop
22

1. /* counter.c */
2. /* Displays the digits 1 through 9 */
3. main()
4. {
5. int digit=0; /* Initialisation */
6. while (digit<=9)
7. {
8. printf(“%d \n”, digit);
9. digit++;
10. }
11. return 0;
12. }

Jane Kuria Inoorero University 08/15/23


Example: Calculating the average of
23
n numbers using a ‘while’ loop
 Algorithm:
1. Initialise an integer count variable to 1. It will be used as a loop counter.
2.  
3. Assign a value of 0 to the floating-point sum.
4.  
5. Read in the variable for n (number of values)
6.  
7. Carry out the following repeatedly (as long as the count is less or equal to n).
1. Read in a number, say x.
2. Add the value of x to current value of sum.
3. Increase the value of count by 1.
8.  
9. Calculate the average: Divide the value of sum by n.
10.  
11. Write out the calculated value of average.

Jane Kuria Inoorero University 08/15/23


The ‘do .. while’ loop
24

 It is used when the loop condition is executed at the end of each


loop pass.
  
 It takes the form:
 do
 statement;
 while(expression);
  
 The statement (simple or compound) will be executed repeatedly as
long as the value of the expression is true. (i.e. non zero).

 Notice that since the test comes at the end, the loop body
(statement) must be executed at least once.

Jane Kuria Inoorero University 08/15/23


Example of ‘do…while’
25

 Rewriting the program that counts from 0 to 9, using the do while loop:
  
1. /* counter1.c */
2. /* Displays the digits 1 through 9 */
3. main()
4. {
5. int digit=0; /* Initialisation */
6. do
7. {
8. printf(“%d \n”, digit);
9. digit++;
10. } while (digit<=9);
11. return 0;
12. }

Jane Kuria Inoorero University 08/15/23


The ‘for’ loop
26

 This is the most commonly used looping statement


in C.
  
 It takes the form:
  
 for (expression1;expression2;expression3)
 statement;
 where:

Jane Kuria Inoorero University 08/15/23


The ‘for’ loop
27

 expression1 is used to initialize some parameter (called


an index). The index controls the loop action. It is
usually an assignment operator.
  
 expression2 is a test expression, usually comparing the
initialized index in expression1 to some maximum or
minimum value.
  
 expression3 is used to alter the value of the parameter
index initially assigned by expression and is usually a
unary expression or assignment operator;

Jane Kuria Inoorero University 08/15/23


Examples of ‘for’ loop
28

 Example 
 for(int k=0;k<=5; k++)
 printf(k = %d \n”, k); The code should print integers 0 through to 5, each on a
different line.
  
 Example: Counting 0 to 9 using a ‘for’ loop
  
 /* Displays the digits 1 through 9 */
 #include<stdio.h>
 main()
 {
 int digit;
 for(digit=0;digit<=9; digit++)
 printf(“%d \n” , digit);
 return 0;
 }

Jane Kuria Inoorero University 08/15/23


Example: Table of cubes
29

1. / Using a loop to make a table of cubes */


2. #include<stdio.h>
3. main()
4. {
5. int number;
6. printf(“n n cubed “);
7. for(num=1; num<=6;num++)
8. printf(“%5d %5d \n”, num, num*num*num);
9. return 0;
10. }

Jane Kuria Inoorero University 08/15/23


Note….
30

 Also note the following points about the for


structure.
 You can count down using the decrement operator
 You can count by any number you wish; two’s
threes, etc.
 You can test some condition other than the number
of operators.
 A quantity can increase geometrically instead of
arithmetically.
Jane Kuria Inoorero University 08/15/23
Using break and continue
31
statements in loops
 The break statement allows you to exit a loop from any
point within its body, bypassing its normal termination
expression.
 When the break statement is encountered inside a loop,
the loop is immediately terminated, and program control
resumes at the next statement following the loop.
 The break statement can be used with all three of C's
loops. You can have as many statements within a loop as
you desire.
 It is generally best to use the break for special purposes,
not as your normal loop exit. break is also used with
case statements as explained earlier.

Jane Kuria Inoorero University 08/15/23


Example: break statement
32

1. #include <stdio.h>
2.  
3. main()
4. {
5. int t ;
6.  
7. for ( ; ; )
8. {
9. printf(“Value of t: “);
10. scanf("%d" , &t) ;
11. if ( t==10 )
12. break ;
13. }
14. printf("End of an infinite loop...\n");
15.  
16. }

Jane Kuria Inoorero University 08/15/23


Continue statement
33

 The continue statement is somewhat the opposite of


the break statement.
 It forces the next iteration of the loop to take place,
skipping any code in between itself and the test
condition of the loop.
 In while and do-while loops, a continue statement will
cause control to go directly to the test condition and
then continue the looping process.
 In the case of the for loop, the increment part of the
loop continues.
 One good use of continue is to restart a statement
sequence when an error occurs.
Jane Kuria Inoorero University 08/15/23
Example : continue statement
34

 Only even integers between 0 and 100 are printed.


  
1. #include <stdio.h>
2. main()
3. {
4. int x ;
5. for (x=0 ; x<=100 ; x++){
6. if(x%2==0) continue;
7. printf("%d\n" , x);
8. }
9. }

Jane Kuria Inoorero University 08/15/23


The ‘goto’ statement
35

 This is another control flow statement. It takes the


form goto labelname;
  
 Example
 goto part2;
 part2: printf(“programming in c”\n”;)
 In principle you never need to use goto in a C
statement. The if construct can be used in its place
as shown below.

Jane Kuria Inoorero University 08/15/23


Example of ‘goto’
36

 Alternative 1 Alternative 2
  
 if (a>14) if (a>14)
 goto a; sheds=3;

 sheds=2; else
 goto b; sheds=2;

 a: sheds=3; k=2*sheds;
 b: k=2 * sheds;

Jane Kuria Inoorero University 08/15/23


Nesting statements
37

 It is possible to embed (place one inside another)


control structures, particularly the if and for
statements.

Jane Kuria Inoorero University 08/15/23


Nested ‘if’ statement
38

 It is used whenever choosing a particular selection


leads to an additional choice.
  
 Example
  
 if (number>6)
 if (number<12)
 printf(“You are very close to the target!”);
 else
 printf(“Sorry, you lose!”);

Jane Kuria Inoorero University 08/15/23


Nested ‘for’ statement
39

 Suppose we want to calculate the average of


several consecutive lists of numbers, if we know in
advance how many lists are to be averaged.
  
 Example: Nested ‘for’ statements

Jane Kuria Inoorero University 08/15/23


Example
40

1. /* Calculate the averages of several different lists of number */


2. #include<stdio.h>
3. main()
4. {
5. int n, count, loops, loopcount;
6. float x, average, sum;
7. /*Read in the number of loops */
8. printf(“How many lists? “);
9. scanf(“%d”, &loops);
10. /*Outer loop processes each list of numbers */
11. for (loopcount=1; loopcount<=loops; loopcount++)
12. {
13. /* initialise sum and read in a value of n */
14. sum=0.0;
15. printf(“List number %d \n How many numbers ? “,loopcount);
16. scanf(“%d”, &n);

Jane Kuria Inoorero University 08/15/23


Example continued…
41

1. /*Read in the numbers */


2. for(count=1;count<=n; count++)
3. {
4. printf(“x = “);
5. scanf(“%f”, &x);
6. sum+=x;
7. } /* End of inner loop */
8. /* Calculate the average and display the answer */
9. average = sum/n;
10. printf(“\n The average is %f \n”, average);
11. } /*End of outer loop */
12. return 0;
13. }

Jane Kuria Inoorero University 08/15/23


Exercises
42

 Using a nested if statement, write a program that prompts the user for a
number and then reports if the number is positive, zero or negative.
 
 Write a while loop that will calculate the sum of every fourth integer,
beginning with the integer 3 (that is calculate the sum 3 + 7 +11 + 15 + ...)
for all integers that are less than 30.
 
 Write a program that prints only the odd numbers between 1 and 100. Use
a for loop that looks this: 
for(i=1; i<101; i++)....
Use a continue statement to avoid printing even numbers.
 
 

Jane Kuria Inoorero University 08/15/23


Exercises
43

 Write a program that computes the area of a circle,


rectangle or triangle using an if..else if ladder.

 Write a program that requests two numbers and


then displays their sum or product, depending upon
what the user selects.

 Write a program that asks the user for an integer


and then tells the user if that number is even or
odd. (Hint: Use C’s modulus operator %)
Jane Kuria Inoorero University 08/15/23

You might also like