COMPUTER PROGRAMMING
NCSV101, Monsoon 24-25
LOOPS
Pranav Bisht
Assistant Professor,
CSE, IIT(ISM) Dhanbad
Loops
⚫ Group of statements that are executed repeatedly while some
condition remains true
⚫ Each execution of the group of statements is called an
iteration of the loop
⚫ How loops are controlled
⚫ Counter controlled
⚫ Condition controlled
⚫ Sentinel controlled
Counter Controlled
Start
• Read 5 integers
and display the Counter=0, Sum=0
their sum
• Read 100 integers
and display their Counter<5
sum
• Read 10,00,000
integers and Take input n
display their sum
Counter=Counter+1, Output Sum
Sum=Sum+n;
Stop
Example
Given an exam marks as input, display the appropriate message based
on the rules below:
⚫ If marks is greater than 49, display “PASS”, otherwise display “FAIL”
⚫ However, for input outside the 0-100 range, display “WRONG INPUT”
and prompt the user to input again until a valid input is entered
Condition controlled
Start
Input m
FALSE
m<0 || m >100
TRUE
TRUE
Wrong Input m>45 PASS
FALSE
FAIL
Take input m
Stop
Sentinel -controlled
Sentinel-controlled repetition is sometimes called indefinite repetition
because it is not known in advance how many times the loop will be
executed.
Example: Receive a number of positive integers and display the summation and average
of these integers.
A negative or zero input indicates the end of input process
Sentinel controlled
Start
Input m
Count=0, Sum=0
FALSE
m>0
TRUE
Sum=Sum+m
Count=Count+1 Average=SUM/count
SUM
Take input m
Average
Stop
Looping: while statement
while (expression)
Statement;
while (expression) {
Block of statements;
}
The condition to be tested is any expression enclosed in parentheses. The expression is
evaluated, and if its value is non-zero, the statement is executed. Then the expression is
evaluated again and the same thing repeats. The loop terminates when the expression
evaluates to 0.
Looping: while statement
while (expression)
FALSE
Statement; Expression
TRUE
while (expression) {
Block of statements;
} Statement (loop body)
Looping: while statement
Initialize
Initialize loop counter;
while (test loop counter) FALSE
Statement; Expression
Initialize loop counter; TRUE
while (test loop counter) {
Statement 1; Statement (loop body)
Statement 2;
Increment
} Increment or decrement
Example 1
int x, count=0;
int n;
scanf(“%d”, &n);
while (count < n) {
scanf(“%d”, &x);
printf(“Number is %d”, x);
sum=sum+x;
count=count+1;
}
printf(“Sum of n Numbers %d”, sum);
Example 2
int x, count=0, sum=0, Average=0;
scanf(“%d”, &x);
while (x >0) {
printf(“Natural number %d”, x);
sum=sum+x;
count=count+1;
scanf(“%d”, &x);
}
Average=sum/count;
printf(“Average =%d, Sum=%d”, Average, sum);
Example 3
1. Sum of 12 + 22 + 32 .....+n2
2. Find the sum of digits of a number
3. Convert decimal to binary (after we cover number systems)
Looping: for statement
Initialize
for ( expr1; expr2; expr3) expr1
Statement; expr2
Expression
FALSE
TRUE
for ( expr1; expr2; expr3)
{
Statement (loop body)
Statement 1;
Statement 2;
Increment
} Increment or decrement exp3
Equivalence of for and while
for(expr1; expr2; expr3)
statement
Expr1;
while(expr2)
{
Statement
Expr3;
}
The comma operator
• Separates expressions
• Syntax: expr-1, expr-2, ...,expr-n
• expr-1, expr-2,...are all expressions
for (fact=1, i=1; i<=10;++ i)
fact = fact * i;
for (sum=0, i=1; i<=N; ++i)
sum = sum + i * i
Looping: do-while statement
Initialize
do
statement; Statement (loop body)
while (expression);
Increment or decrement
do {
Block of statements; TRUE FALSE
} while (expression); Expression
Example:
Prompt user to input “month” value, keep
prompting until a correct value of month is given
as input
Example:
Prompt user to input “month” value, keep
prompting until a correct value of month is given
as input
do {
printf (“Please input month {1-12}”);
scanf (“%d”, &month);
} while ((month < 1) || (month > 12));
The break Statement
Break out of the loop body { }
⚫ can use with
➢ while, do while, for, switch
⚫ does not work with
➢ if, else
⚫ Causes immediate exit from a while, do/while, for or switch
structure
⚫ Program execution continues with the first statement after the
structure
Find smallest n such that n! exceeds 100
void main() {
int fact, i;
fact = 1; i = 1;
while ( i<10 )
{ /* run loop –break when fact >100*/
fact = fact * i;
if ( fact > 100 )
{
printf ("Factorial of %d above 100", i);
break; /* break out of the while loop */
}
++i;
}}
Test if a number is prime or not
void main() {
int n, i=2;
scanf (“%d”, &n);
while (i < n) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
break;
}
++i;
}
if (i == n) printf (“%d is a prime \n”, n);
The Continue Statement
Skips the remaining statements in the body of a while, for or do/while
structure
• Proceeds with the next iteration of the loop
• while and do/while loop
• Loop-continuation test is evaluated immediately after the continue
statement is executed
• for loop
• expr3 is evaluated, then expr2 is evaluated
continue and break
void main() {
int fact = 1, i = 1;
while (1)
{
fact = fact * i;
++i;
if ( i <=10 ){
continue; /* not done yet ! Go to loop and perform next iteration*/
}
printf(“I am outside the if condition\n”);
break;
}
printf(“fact is %d”, fact);
}
Problem- continue and break
Add positive numbers until a 0 is typed, but ignore any negative
numbers typed
Solution
int main() {
int sum = 0, next;
while (1)
{
scanf(“%d”, &next);
if (next < 0)
continue;
else if (next == 0)
break;
sum = sum + next;
}
printf (“Sum = %d\n”, sum) ;
return 0; }
Nested Loops
How would you print the following diagram?
*****
*****
*****
What if the number of rows and columns are very large?
Example
const int ROWS = 3; while (row <=ROWS) {
const int COLS = 5; col = 1;
... while (col <=COLS) {
row = 1; printf (“* “);
col++;
}
printf(“\n”);
++row;
}
Nested Loops
How would you print the following diagram?
*
**
***
****
*****
Example
const int ROWS = 3; while (row <=ROWS) {
const int COLS = 5; col = 1;
... while (col <=ROWS) {
row = 1; printf (“* “);
col++;
}
printf(“\n”);
++row;
}
continue and break in Nested Loop
For nested loops, break and continue are matched with the nearest loops
(for, while, do- while)
while (i < n) {
for (k=1; k < m; ++k) {
if (k % i == 0)
break;
printf(“Inside for loop\n”);
}
i = i + 1;
}
Thanks
Any Questions?