CSC099 Week 13 Flexible Learning
CSC099 Week 13 Flexible Learning
CSC099 Week 13 Flexible Learning
break
break
4
Switch Flowchart
true
case 1 Display break;
“ONE”
false
true
Display
case 2
“TWO” break; end
false
true
Display
case 3 break;
“THREE”
false
Display “INVALID
INPUT”
5
Programming Exercise
• Text Book Page 85 1a, b, c
• Exercise Sumbit ilearn : Pg 89 3b
Repetition
7
Categories of Loop
•Common categories of loop:-
1. counter-controlled loop
– Called as definite repetition
– Know the number of iteration to be executed
– A counter controlled loop posses 3 elements:-
1. Initialize a counter/control variable to a starting value
2. Test the counter/control variable. If the counter/control variable
exceeded the maximum value, the iteration will be terminated
3. Update the counter during each iteration.
9
Example 1: while Loop
int i = 0; //the variable is initialized to 0
{
printf(“%d ”,i); //print the of i
}
• Each repetition of looping is known as iteration.
10
Sentinel-Controlled WHILE loops
• Sentinel-controlled repetition is sometimes called indefinite repetition because
the repetition is not known
• The last entry called sentinel, is a special value.
• A sentinel value is a value that is not a legitimate data value for a particular
problem (but is of proper type) that is used as a “stopping” value.
• The while loop continues to execute as long as the program has not read the
sentinel.
• General structure :
scanf(“%d”,&variable);/*get first variable value
while (variable != -1)
{
……
Sentinel Value
scanf(“%d”,&variable);/*get next variable value
11
do…while Loop
do
++j;
while( j > 100 );
printf("\nj = %2d\n", j); Test expression false at
first iteration
13
for Loop
•for loop is of type counter controlled loop.
• Each time the outer loop is repeated, the inner loops are re-
entered, their loop control expressions are re-evaluated and
all required iteration are performed.
• When working with nested loops, the outer loop changes only
after the inner loop is completely finished(or is interrupted.).
18
Nested loop – Example 1
// This program prints numbers on lines
#include <stdio.h>
int main ()
{
int i,j;
for (i=1;i<=4;i++)
{
printf(“Line %d :",i);
for (j=3;j>= 1; j--)
{
printf("%d ",j);
}
printf("\n");
} 19
Nested loop – Example 2
Find the output for the loop below.
• break
• causes a loop to terminate
• terminate only the inner loop in nested loop
22
Break- Example 1
#include <stdio.h>
int main(void)
{
int x = 5;
while (x)
{
if (x == 10 )
break;
printf("%d",x);
x++;
}
printf("\nThe value of x now is %d",x);
} 23
Continue Statement – Example 1
Use continue statement in a for statement to skip the
printf statement and begin the next iteration of the loop.
24
Continue Statement – Example 2
int i;
i = 0;
while ( i < 8 )
{
i++;
continue;
printf(“This will be printed??\n");
}
THE END