Repetition Structures: CSE115: Computing Concepts
Repetition Structures: CSE115: Computing Concepts
Repetition Structures
CSE115: Computing Concepts
An Example Problem
• Read in 10 integers and output their
sum
An Example Problem
• Read in 10 integers and output their
sum<stdio.h>
#include printf("Enter a number: ");
int main() scanf("%d",&a);
{ sum += a;
int a, sum = 0; printf("Enter a number: ");
printf("Enter a number: scanf("%d",&a);
"); sum += a;
scanf("%d",&a); printf("Enter a number: ");
sum += a; scanf("%d",&a);
printf("Enter a number: sum += a;
"); printf("Enter a number: ");
scanf("%d",&a); scanf("%d",&a);
sum += a; sum += a;
printf("Enter a number: printf("Enter a number: ");
"); scanf("%d",&a);
scanf("%d",&a); sum += a;
sum += a; return 0;
printf("Enter a number: }
");
Repetition Structure (Loop)
• Executes a number of statements more than
one time without having to write the
statements multiple times.
• Two designs of loop :
• To execute a number of instructions from the
program for a finite, pre-determined number of
time (Counter-controlled loop)
• To execute a number of instructions indefinitely
until the user tells it to stop or a special
condition is met (Sentinel-controlled loop)
Repetition Structure (Loop)
Loop
condition
cond? false
Each round of
true
the loop is called
an iteration. Some
statement(s)
loop body
Repetition Structure (Loop)
statement;
false
cond?
As long as the condition is met (the
condition expression is true), the true
statement inside the while loop (also
Loop
called loop body) will get executed. body
• When the condition is no longer met (the
condition expression is false), the
program will continue on with the next
instruction (the one after the while loop).
Repetition : while Loop
• In this example :
• (i < 5) is known as loop repetition condition (counter-controlled) .
• i is the loop counter variable.
• In this case, this loop will keep on looping until the counter variable is
equal to 4. Once i = 5, the loop will terminate.
• The printf() statement will get executed as long as the variable i is
less than 5. Since the variable i is incremented each time the loop is
executed, the loop will stop after the 5th output.
• Output:
Example:
i = 0
i = 1
int i = 0;
while (i < 5)
i = 2 {
i = 3 printf(“i = %d\n”, i);
i = 4 i++;
}
Done
printf(“Done”);
Sum of 10 Integers
#include <stdio.h>
int main()
{
int i, a, sum;
sum = 0; Initialization
i = 0;
while(i < 10) Loop
{ condition
printf("Enter a number: ");
scanf("%d", &a);
sum = sum + a;
i++;
} Increment/decrement
printf("Total is %d\n", sum); Loop
return 0; body
}
Repetition : for Loop
• Syntax :
• Sample run 4:
• Enter a number: 8711541
• 1451178
Infinite Loop
#include <stdio.h>
int main()
{
int i;
for(i = 0; i != 9; i+=2)
printf("i = %d\n", i);
return 0;
}
How many times will the loop iterate?
Infinite Loop