CBCP2202 E-Tutorial 3 Repetition Control Structure
CBCP2202 E-Tutorial 3 Repetition Control Structure
Repetition Control
Structure
E-TUTORIAL 3
Learning Outcomes
1. Implement C programs using repetition structure such as for, while and do-
while statements;
2. Differentiate between for, while and do-while statements
3. Use continue and break statements to jump instruction
4. Write nested loops depending on the problem given.
While statement
While statement is used to perform repetition on a few statements when the
expression is true.
Syntax:
initialisation;
while (expression)
{
statement;
counter;
}
While loop: Code 1
Question: Display numbers 1 to 10 using while loop:
#include <stdio.h>
int main()
{
int x = 1;
while (x <= 10) Output:
{ 1 2 3 4 5 6 7 8 9 10
printf("%d\t", x);
x++;
}
return 0;
}
While loop: Code 2
Question: Add all numbers from 1 to n which is input by the user
#include <stdio.h>
int main()
{
int num, x = 1, total = 0;
printf("Input number: ");
scanf("%d", &num); Output:
while (x <= num)
{ Input number: 5
total += x; Total of numbers from 1 to 5 is 15.
x++;
}
printf("Total of numbers from 1 to %d is %d.\n", num, total);
return 0;
}
Answers to Activity 2.1 (a)
int x=2;
while (x <=20)
{
printf("%d\t", x);
x = x + 2;
}
Question:
i) why must start at x=2?
ii) what if the x=x+2 is left out?
Answers to Activity 2.1 (b)
int x=1;
printf("Enter a number: ");
scanf("%d", &x);
if (x > 0) Questions:
{ i) Why must start with x = 1?
while (x!=0) ii) What does the condition x!=0 mean?
iii) Why is there 2 input statements?
{
printf("Enter a number: ");
scanf("%d", &x);
}
}
Do-While Statement
This statement is similar to the while statement because it too has initialisation,
expression, statements, and counter.
Syntax:
initialisation;
do
{
statement;
counter;
}while (expression);
Do While Statement...
Similar to the while statement, expression can be made up of a relational or a
logical expression that has the value true or false.
Initialisation always has a variable and its value will be tested at the end.
Update the counter to ensure that the expression value becomes false eventually
so that the do-while statement can end.
do-while loop: Code 1
Question: Display numbers 1 to 10 using do-while loop:
#include <stdio.h>
int main()
{
int x = 1;
do Output:
{ 1 2 3 4 5 6 7 8 9 10
printf("%d\t", x);
x++;
}while (x <= 10);
return 0;
}
do-while loop: Code 2
Question: Adding all positive numbers being input until 0 is entered
#include <stdio.h>
int main() Output:
{ Input a positive number to add, 0 to stop: 1
int num, total = 0; Input a positive number to add, 0 to stop: 2
do Input a positive number to add, 0 to stop: 3
{ Input a positive number to add, 0 to stop: 4
printf("Input a positive number to add, 0 to stop: "); Input a positive number to add, 0 to stop: 5
scanf("%d", &num); Input a positive number to add, 0 to stop: 0
total += num; Total of positive numbers entered: 15
} while (num!=0);