0% found this document useful (0 votes)
5 views34 pages

Loop

The document provides an overview of loops in computer programming, specifically focusing on counter-controlled and sentinel-controlled repetitions. It explains various looping structures in C, including 'while', 'for', and 'do-while' loops, along with examples for summation, factorial computation, and prime number checking. Additionally, it discusses control statements like 'break' and 'continue', nested loops, and common pitfalls in loop implementation.

Uploaded by

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

Loop

The document provides an overview of loops in computer programming, specifically focusing on counter-controlled and sentinel-controlled repetitions. It explains various looping structures in C, including 'while', 'for', and 'do-while' loops, along with examples for summation, factorial computation, and prime number checking. Additionally, it discusses control statements like 'break' and 'continue', nested loops, and common pitfalls in loop implementation.

Uploaded by

mehedihasan34mq
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Programming and

Data Structure (CS351)

Loop
Loops

● Group of statements that are executed repeatedly while some condition


remains true.
● The repeated execution of a group of statements is also known as Iteration.
Loops Cont...

● Counter-controlled repetition
○ Definite repetition- Know how many times loop will execute.
○ Control variable used to count repetitions.
● Sentinel-controlled repetition
○ Indefinite repetition
○ Used when number of repetitions not known.
○ Sentinel value indicates "end of data"
Finding the summation of six numbers
Counter-Controlled Repetition

● Counter-Controlled repetition requires


○ Name of a control variable (or loop count).
○ Initial value of the control variable.
○ Condition that tests for the final value of the control variable (i.e., whether loop should
continue).
○ Increment (or decrement) by which the control variable is modified each time through the
loop.
Looping: while statement
while (expression)
statement;
while (expression)
{
statement;
}

● The condition to be tested is any expression enclosed in the parentheses.


The expression is evaluated, and if the value is non-zero or TRUE, the
statement is executed. Then the expression is evaluated again and the same
thing repeats. The loop terminates when the expression evaluates to 0 or
FALSE.
Finding the summation of six numbers
int counter = 0, sum = 0, n;
while (counter < 6)
{
scanf(“%d”,&n);
sum = sum + n;
counter ++;
}
printf(“sum is %d”, sum);
}
Double your money
int main()
Suppose your Rs 100 is earning interest
at 10% per month. How many months {
until you double your money? float my_money = 100.0;
int month = 0;
while (my_money < 200.0)
{
my_money = my_money + (my_money * .1)
month ++;
}
printf(“My money will double in %d months. \n”, month);
}
Find the sum of digits of a number
int main()
{
int sum=0,n;
scanf(“%d”, &n);
while (n!=0)
{
sum = sum + (n%10);
n = n / 10;
}
printf(“Sum=%d\n”, sum);
}
Looping: for statement
● Most commonly used looping ● expr1 is used to initialize some variable
structure in C. (called index) that controls the looping
actions
● expr2 represents a condition that must be
for(expr1;expr2;expr3) true for the loop to continue.
● expr3 is used to alter the value of the index
Statement;
initially assigned by expr1.
● There is a body of the loop.
for(expr1;expr2;expr3)
{
statement ;
}
Looping: for statement
Computing factorial
int main()
{
int n, count, fact = 1;
scanf(“%d”, &n);
for(count=1;count<=n;count++)
{
fact = fact * count;
}
printf(“Factorial=%d\n”, fact);
return 0;
}
Equivalence of for and while

for(expr1;expr2;expr3) expr1;
{ while(expr2)

statement; {

} statement;
expr3;
}
Sum of first N natural numbers
int N, count=1, sum=0; int N, count, sum=0;

scanf(“%d”, &N); scanf(“%d”, &N);

while(count <= N) for(count=1; count<=N; count++)

{ {

sum = sum + count; sum = sum + count;

count++; }

} printf(“Sum=%d\n”, &sum);

printf(“Sum=%d\n”, &sum);
Some observation on for

● Initialization, loop-continuation test, and update contain arithmetic


expressions

for( k = x; k <= 4*x*x ; k += y/x )

● Update may be negative (decrement)

for( digit = 9; digit >= 0; digit - -)

● If loop continuation test is initially 0 (false)


○ Body of for structure not performed.
○ No statement executed.
○ Program proceeds with statement after for structure.
Looping: do-while statement
do
statement;
while (expression);

do
{
statement;
} while (expression);
Difference between while and do-while loop
● while loop ● do-while loop
Difference between while and do-while loop

#include<stdio.h> #include<stdio.h>

int main() int main()


{ {
int i = 5; int i = 5;
printf("While loop output:\n"); printf("Do-While loop output:\n");
while (i<5) do
{ {
printf("%d\n", i); printf("%d\n", i);
i++; i++;
} }while (i<5);
return 0; return 0;
} }
Practice problems

● Print all the natural numbers in the range 1 to N.


● Print the even numbers in the range 1 to N.
● Print the summation of all the even numbers in the range 1 to N.
● Print the average of all the even numbers in the range 1 to N.
● Print the multiplication table of a number given by the user.
Decimal to (reverse) binary conversion
int main()
{
int dec;
scanf(“%d”, &dec);
do
{
printf(“%d”, (dec%2));
dec = dec/2;
} while(dec != 0);
}
Example: Prime Number
int main()
{
int n, i=2;
scanf(“%d”, &n);
while (i < n)
{
if (n%i == 0)
{
printf(“%d is not a prime”, n);
break;
}
i++;
}
if (i == n) printf(“%d is a prime”, n);
}
Find n where n! > 100, but (n-1)! < 100.
int main()
{
int fact=1, i=1;
while (1)
{
fact = fact * i;
if (fact > 100)
{
printf(“Factorial is %d is above 100”, i);
break;
}
i++;
}
}
Computing series upto n terms
void main()
{
int n, count;
float x, term=1.0, sum=0.0;
scanf(“%f”, &x);
scanf(“%d”, &n);
for(count=1;count<=n;count++)
{
sum = sum + term;
term = term * x/count;
}
printf(“Exp(x,n)=%d\n”,sum);
}
Output ?

while (1)
{
Statements;
}
Infinite loop

while (1) for ( ; ; ) do

{ { {

statement; statement; statement;

} } } while (1);
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.
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
○ Increment/ Decrement expression is executed, then loop-continuation test is evaluated.
○ expr3 is evaluated, then expr2 is evaluated.
An example with break & continue
int main()
{
int fact, i=1;
while (1)
{
fact = fact * i;
i++;
if (i <= 10)
continue;
break;
}
printf(“%d”,fact);
}
Some pitfalls

while (sum<=NUM); for(i=0;i<=NUM;++i);


sum = sum + 2; sum = sum + i;

for( i=1 ; i != 10 ; i=i+2 )

sum = sum + i;
Nested loops: Printing 2D figure
● How to print the following? ● Approach

Repeat 3 times
*****
print a rows of 5 *’s
*****
***** OR

Repeat 5 times

print *
Nested loops
int rows = 3;
● How to print the following? int cols = 5;
int r,c;
r = 1;
***** while (r <= rows)
{
***** c = 1;
***** while (c <= cols)
{
printf(“*”);
c++;
}
printf(“\n”);
r++;
}
2D Figure with for loop
int row = 3, col = 5;
● How to print the following?
int r, c;
for(r=1; r<=row; r++)

***** {
***** for(c=1; c<=col; c++)
***** {
printf(“*”);
}
printf(“\n”);
}
2D Figure with for loop
int row = 3, col = 5;
● How to print the following?
int r, c;
for(r=1; r<=row; r++)

* {
** for(c=1; c<=r; c++)
*** {
**** printf(“*”);
***** }
printf(“\n”);
}
Uses of comma operator in for loop

● We can give several expressions separated by commas in place of expr 1


and expr 3 in a for loop to do multiple assignments for example

for(fact=1, i=1; i<=10; ++i)

fact = fact * i;

for(sum=0, i=1; i<=N; ++i)

sum=sum+i*i;

You might also like