0% found this document useful (0 votes)
56 views

Loops PDF

The document discusses loops and repetition statements in C programming. It describes the three types of loops in C - while, for, and do-while loops. It provides examples of how to use while and for loops to repeatedly request input from the user until a condition is met, and to iterate a certain number of times. It also covers the break and continue statements, which allow skipping iterations or terminating the loop early.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Loops PDF

The document discusses loops and repetition statements in C programming. It describes the three types of loops in C - while, for, and do-while loops. It provides examples of how to use while and for loops to repeatedly request input from the user until a condition is met, and to iterate a certain number of times. It also covers the break and continue statements, which allow skipping iterations or terminating the loop early.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Loops / Repetition Statements

•  Repetition statements allow us to execute a


statement multiple times
•  Often they are referred to as loops
•  C has three kinds of repetition statements:
§  the while loop
§  the for loop
§  the do loop

•  The programmer should choose the right kind of


loop for the situation

Example 1: Fixing Bad Keyboard Input


•  Write a program that refuses to accept a negative
number as an input.

•  The program must keep asking the user to enter a


value until he/she enters a positive number.

•  How can we do this?

1
Try to solve it using if-else statement
•  Example program that continuously asks for
positive number as input:
int n;
printf (“Please enter a positive number:”);
scanf(“%d”,&n);
if (n < 0){
printf (“Enter positive number, BE POSITIVE!\n”);
scanf(“%d”, &n);
}
if (n < 0){
printf (“Enter positive number, BE POSITIVE!\n”);
scanf(“%d”, &n);
}
………
………

Example 2: Grade of several students


•  Write a program that continuously calculates the
grade of all students’ marks and stop when the
user wants.

•  After calculating one student’s grade (from his


marks) the program must keep asking the user
whether he likes to continue or not.

•  How can we do this?

2
while Loop

যতkন যিদ
while if ( condition )
statement;

if condition is satisfied execute the statement(s)

while condition is satisfied execute the statement(s)

Logic of an if statement

condition
evaluated

true
false

statement

3
Logic of a while Loop
if logic The while Loop

condition condition
evaluated evaluated

true false
true
false
statement statement

The while Statement formally


•  A while statement has the following syntax:
while ( condition ){
while ( condition )
statement1;
statement;
statement2;
……
}
•  If the condition is true, the statement or a
block of statements is executed

•  Then the condition is evaluated again, and if it is


still true, the statement/block is executed again

•  The statement/block is executed repeatedly until


the condition becomes false

4
The while Statement
•  Example program that continuously asks for
positive number as input:
int n;

printf (“Please enter a positive number:”);


scanf(“%d”,&n);
while(n
if (n < 0){
printf (“Enter positive number, BE POSITIVE!\n”);
scanf(“%d”, &n);
}

Some examples
• Print “The sky is the limit!” 10 times.
main(){
printf (“The sky is the limit”);
}

5
Some examples
• Print “The sky is the limit!” 10 times.
main(){
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);

Some examples
• Print “The sky is the limit!” 100 times.
main(){
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);
printf (“The sky is the limit”);

6
Some examples
• Print “The sky is the limit!” n times. n will be user
input

scanf(“%d”,&n);
int count = 1;
while (count <= n)
{
printf (“The sky is the limit”);
count++;
}
•  If the condition of a while loop is false initially, the
statement is never executed
•  Therefore, the body of a while loop will execute
zero or more times

Some examples
• Print first n natural numbers.
q  Upwards
q  Downwards
• Print odd numbers up to n.
• Print even numbers up to n.
• Print summation of first n numbers.
• Print summation of all odd numbers up to n.
• Print summation of all even numbers up to n.
•  Print second largest of a series of natural numbers
(at least two) given as input. STOP when the user
enters 0. Natural numbers are 1, 2, 3, 4……

7
x y x

4 21 36 14 62 91 8 22 7 81 77 10

x x x

secL = 4 largest = 21
secL largest
Third element
x

x > largest secL < x <= largest x <= secL

secL = largest secL = t ignore


largest = t

Summary of a while statement


•  A while loop is functionally equivalent to the
following structure:

initialization;
while ( condition )
{
statement;
increment;
}

8
initialization;
while ( condition )
{
statement;
increment;
}

•  A for statement has the following syntax:

The initialization The statement is


is executed once executed until the
before the loop begins condition becomes false

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at


the end of each iteration

Logic of a for loop


for ( initialization ; condition ; increment )
statement;

initialization

condition
evaluated
false
true

statement

increment

9
The for Statement
1 ≤ count ≤ n
•  An example of a for loop: 1 ≤ count and count ≤ n
for (count=1; count <= n; count++)
printf (“%d\n”, count);

for (count=n; count >= 1; count--)


printf (“%d\n”, count);

•  The initialization section can be used to declare a


variable. The variable disappears right after loop.

•  Like a while loop, the condition of a for loop is


tested prior to executing the loop body

•  Therefore, the body of a for loop will execute zero


or more times

The for Statement


•  The increment section can perform any calculation
int num;
for (num=100; num > 0; num -= 5)
printf (“%d\n”, num);

•  A for loop is well suited for executing statements


a specific number of times that can be calculated
or determined in advance

10
The break and coninue Statement
•  Sometimes we need:
§  to skip some statements inside the loop (continue)
§  or terminate the loop immediately without checking the
test condition (break).

•  In such cases, break and continue statements are


used.

The break Statement


The break statement terminates the loop immediately when it is
encountered

11
Example: break Statement
//  Program  to  calculate  the  sum  of  maximum  of  10  numbers    
//  If  negative  number  is  entered,  loop  terminates,  sum  is  displayed    
main(  )  {    
 int  i;    
 double  number,  sum  =  0.0;    
 for(i=1;  i  <=  10;  ++i)  {    
   printf("Enter  n%d:  ",i);          
   scanf("%lf",  &number);    
//  If  user  enters  negative  number,  loop  is  terminated    
   if(number  <  0.0)  {    
     break;    
   }    
   sum  +=  number;  
 }    
 printf("Sum  =  %.2lf",sum);  
}  

The continue Statement

The continue statement skips statements after it inside the loop.

12
Example: continue Statement
//  Program  to  calculate  the  sum  of  maximum  of  10  +ve  numbers    
//  If  negative  number  is  entered,  it  is  ignored  
main(  )  {    
 int  i;    
 double  number,  sum  =  0.0;    
 for(i=1;  i  <=  10;  ++i)  {    
   printf("  Enter  n%d:  ",  i);          
   scanf("%lf",  &number);    
//  If  user  enters  negative  number,  skip  it    
   if(number  <  0.0)  {    
     continue;    
   }    
   sum  +=  number;  
 }    
 printf("Sum  =  %.2lf",sum);  
}  

Some example problems


•  Write down a program to find the summation of the following
series:
t1 t2 tn

1 + 2 + 3 + 4 + ...... + up to n

i =1 i =2 i =n

int main(){
int i, n,t,s = 0;
t=i scanf("%d",&n);
for(i = 1; i <= n; i++){
t = i;
s = s + t;
}
printf("%d",s);
}

13
Some example problems
•  Write down a program to find the summation of the following
series:
t1 t2 tn

12 − 2 2 + 32 − 4 2 + ......up to n 2
i =1 i =2 i =n
int main(){
int i, n,t,s = 0;
t = i2 when i is odd scanf("%d",&n);
for(i = 1; i <= n; i++){
t = -i2 when i is even if(i%2 == 0)
t = i*i;
else
t = -i*i;
s = s + t;
}
printf("%d",s);
}

Some example problems


•  Write down a program to find the summation of the following
series: t1 t2 tn

…………….. N terms
i =n
int main(){
i =1 i =2 int i, n;
float x,t,r,s = 0;
scanf("%f%d",&x, &n);
Power of x à 2i+1 x = 22.0*x/(7*180);
s = t = x;
r à -x2 / (2i×(2i+1)) for(i = 1; i < n; i++){
r = -x*x/(2*i*(2*i+1));
tnew à r×tprev t = r*t;
s = s + t;
}
printf("%f",s);
}

14
Some example problems
•  Print factorial of n:

t1 t2 tn

n! = 1 × 2 × 3 × 4 × ...... × up to n

i =1 i =2 i =n

int main(){
int i, n,t,p = 1;
t=i scanf("%d",&n);
for(i = 1; i <= n; i++){
t = i;
p = p * t;
}
printf("%d",p);
}

Some example problems


•  Print xn:

t1 t2 tn

x n = x × x × x × x × .............. × x total n terms

i =1 i =2 i =n
int main(){
int i,x,n,t,p = 1;
t=x scanf("%d%d",&x,&n);
for(i = 1; i <= n; i++){
t = x;
p = p * t;
}
printf("%d",p);
}

15
Some example problems
•  Show all factors of a number n
•  Candidates 1, 2, 3, 4 ………. n

int main(){
int i,n;
scanf("%d",&n);
for(i = 1; i <= n; i++){
if(n%i == 0)
printf("%d ",i);
}
}

Some example problems


•  Show smallest factor of a number n (other than 1)
•  Candidates 1, 2, 3, 4 ………. n
•  Break on first candidate that becomes a factor

int main(){
int i,n;
scanf("%d",&n);
for(i = 2; i <= n; i++){
if(n%i == 0){
printf("%d",i);
break;
}
}
}

16
Some example problems
•  Show largest factor of a number n (other than n)
•  Candidates 1, 2, 3, 4 ………. n
•  Break on first candidate that becomes a factor
•  Number = largest factor * smallest factor
•  largest factor = Number/smallest factor
•  Example 28 à factors 2, 4, 7, 14, smallest 2, largest 14
int main(){
int i,n;
scanf("%d",&n);
for(i = 2; i <= n; i++){
if(n%i == 0){
printf("%d",n/i);
break;
}
}
}

Some example problems


•  Show how many factors of a number n has
•  Candidates 1, 2, 3, 4 ………. n
•  Increment a counter whenever you get a candidate
which is a factor

int main(){
int i,n,c=0;
scanf("%d",&n);
for(i = 1; i <= n; i++){
if(n%i == 0)
c++;
}
printf("Number of factors: %d",c);
}

17
Some example problems
•  Primality testing: determine whether a number n is prime or
not
•  Candidates 1, 2, 3, 4 ………. n
•  Increment a counter whenever you get a candidate
which is a factor
•  Prime numbers always have two factors.

int main(){
int i,n,c=0;
scanf("%d",&n);
for(i = 1; i <= n; i++){
if(n%i == 0)
c++;
}
if(c == 2)
printf("Prime Number");
else printf("Not a Prime Number");
}

Some example problems


•  Primality testing: determine whether a number n is prime or
not
•  Candidates 1, 2, 3, 4 ………. n
•  Increment a counter whenever you get a candidate
which is a factor
•  Prime numbers always have two factors.

int main(){ Increase


int i,n,c=0;
efficiency by
scanf("%d",&n);
for(i = 1; i*i <= n; i++){ going up to the
if(n%i == 0) square root
c++;
}
if(c == 1 && n != 1)
printf("Prime Number");
else printf("Not a Prime Number");
}

18
Some example problems
•  Perfect number testing: determine whether a number n is perfect
or not
•  If a number can be made out of its factors
•  For example 6 à 1, 2, 3 à 1+ 2 +3 = 6
•  Another example 28 à 1,2,4,7,14 à 1+2+4+7+14
•  Candidates 1, 2, 3, 4 ………. n
•  Add to sum whenever you get a candidate which is a factor
int main(){
int i,n,s=0;
scanf("%d",&n);
for(i = 1; i < n; i++){
if(n%i == 0)
s = s + i;
}
if(s == n)
printf("Perfect Number");
else printf("Not a Perfect Number");
}

Some example problems


•  GCD of two numbers (Normal way)
•  GCD(24,54) = 6
•  Factors of 24 à 1, 2, 3, 4, 6, 8, 12, 24
•  Factors of 54 à 1, 2, 3, 6, 9, 18, 27, 54
•  Common Factors 1, 2, 3, 6
•  Greatest Common Factor 6
int main(){
int i,a,min,b,gcd=1;
scanf("%d%d",&a,&b);
if(a == 0 || b == 0) gcd = a+b;
else{
min = (a < b)? a : b;
for(i = 1; i <= min; i++){
if(a%i == 0 && b%i == 0)
gcd = i;
}
}
printf("GCD: %d",gcd);
}

19
Some example problems
•  GCD of two numbers (Efficient way)
•  gcd(a,b) = gcd (b, a%b) for b > 0
•  gcd(54,24) à gcd(24,6) à gcd(6,0) à 6

int main(){
int i,a,b;
scanf("%d%d",&a,&b);
while(b != 0){
c = a%b;
a = b;
b = c;
}
printf("GCD: %d", a);
}

Fibonacci Series

20
Fibonacci Series Generation

1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ……….

1 2 3 4 5 6 7 8 9

Write down a program that will


print n-th Fibonacci number where
n will be input to your program.
n=4 output à 3
n=7 output à13

Fibonacci Series Generation

1, 1, 2, 3, 5, 8, 13, 21, 34, 55 …

p1 p2 next nextnext nextnextnext

int main(){
int p1,p2,next,n;
scanf("%d",&n);
p1 = 1;
p2 = 1;
next = p1 + p2;
nextnext = p2 + next;
nextnextnext = next + nextnext;
…..
….
}

21
p1 p2 next

1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ..

p1 p2 next

int main(){
int p1,p2,next,n;
scanf("%d",&n);
p1 = 1;
p2 = 1;
for(i = ; i <= ; i++){
next = p1 + p2;
p1 = p2;
p2 = next;
}

p1 p2 next

1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ..

p1 p2 next

int main(){
int p1,p2,next,n;
scanf("%d",&n);
p1 = 1;
p2 = 1;
for(i = 3; i <= n; i++){
next = p1 + p2;
p1 = p2;
p2 = next;
}
if(n <= 2) printf("%d", p1);
else printf("%d", next);
}

22
The for Statement
•  Each expression in the header of a for loop is
optional

•  If the initialization is left out, no initialization is


performed

•  If the condition is left out, it is always considered


to be true, and therefore creates an infinite loop

•  If the increment is left out, no increment operation


is performed

Infinite Loops
•  The body of a while loop eventually must make
the condition false

•  If not, it is called an infinite loop, which will


execute until the user interrupts the program

•  This is a common logical error

•  You should always double check the logic of a


program to ensure that your loops will terminate
normally

23
Infinite Loops
•  An example of an infinite loop:
int count = 1;
while (1 == 1){
printf (“%d\n”, count);
count = count - 1;
}

int count = 1;
for(; ;){
printf (“%d\n”, count);
count = count - 1;
}

•  This loop will continue executing until interrupted


(Control-C) or until an underflow error occurs

The do Statement
•  A do statement has the following syntax:

do{
statement;
}
while ( condition );

•  The statement is executed once initially, and then


the condition is evaluated

•  The statement is executed repeatedly until the


condition becomes false

24
Logic of a do-while Loop

statement

true

condition
evaluated

false

The do Statement
•  An example of a do loop:

int count = 1;
do{
printf(“%d\n”, count);
count++;
} while (count <= 5);

•  The body of a do loop is executed at least once

25
The do Statement
•  An example of a do loop:

int n;
do{
printf(“Enter a positive number: ”);
scanf(“%d”,&n);
} while (n < 0);

•  The body of a do loop is executed at least once

Comparing while and do


The while Loop The do Loop

statement
condition
evaluated
true

condition
true false
evaluated

statement
false

26
Example: Printing reverse of a number
•  Write down a program that prints the digits of a
number in reverse.

•  For example: scanf(“%d”,&n);


do{
•  input: 6457 a = n%10;
printf(“%d”,a);
n = n/10;
•  output: 7546 } while (n != 0);

Relevant Problem: counting number of


digits of a number
•  Write down a program that prints number of digits
of a number n.
scanf(“%d”,&n);
c = 0;
•  For example: do{
n = n/10;
•  input: 6457 c++;
} while (n != 0);
printf(“%d”,c);
•  output: 4

27
Nested Loops

Nested Loops
•  Similar to nested if statements, loops can be
nested as well

•  That is, the body of a loop can contain another


loop

•  For each iteration of the outer loop, the inner loop


iterates completely

28
Nested Loops
•  What will be the output?

Outer loop
for(i=1; i <= 3; i++){
for(j=1; j <= 2; j++){
Inner loop printf(“Sky is the limit\n”);
}
printf(“The world is becoming smaller\n”);
}

Output
for(i=1; i <= 3; i++){
for(j=1; j <= 2; j++){
printf(“Sky is the limit\n”);
}
printf(“The world is becoming smaller\n”);
}

Sky is the limit


Sky is the limit
The world is becoming smaller

29
Output
for(i=1; i <= 3; i++){
for(j=1; j <= 2; j++){
printf(“Sky is the limit\n”);
}
printf(“The world is becoming smaller\n”);
}

Sky is the limit


Sky is the limit
The world is becoming smaller
Sky is the limit
Sky is the limit
The world is becoming smaller

Output
for(i=1; i <= 3; i++){
for(j=1; j <= 2; j++){
printf(“Sky is the limit\n”);
}
printf(“The world is becoming smaller\n”);
}

Sky is the limit


Sky is the limit
The world is becoming smaller
Sky is the limit
Sky is the limit
The world is becoming smaller
Sky is the limit
Sky is the limit
The world is becoming smaller

30
Output
for(i=1; i <= 3; i++){
for(j=1; j <= 2; j++){
printf(“%d %d\n”,i,j);
}
}

1 1
1 2
2 1
2 2
3 1
3 2

Nested Loops
•  How many times will the string "Here" be printed?

count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
printf ("Here \n");
count2++;
}
count1++;
} 10 * 20 = 200

31
Analogy for Nested Loops

Inner Loop

Outer Loop

Some more Examples


•  Write a program that prints all prime numbers up to
x. The integer x will be input to your program.

•  Write down a program that will take an integer x as


input and will count and print the number of prime
numbers up to x.

•  Write a program that prints all perfect numbers up to


x. The integer x will be input to your program.

•  Write a program that prints all prime factors of a


number x given as input.

32
Example: Stars
•  Write a program that prints the following. The total
number of lines will be input to your program.

*
**
***
****
*****
******
*******
********
*********
**********

Example: Stars
•  Write a program that prints the following. The total
number of lines will be input to your program.

*
**
***
****
*****

33

You might also like