Menu

Iteration Statements (Loop Statements)

  • Iteration statements are also called loop statements.
  • Iteration or loop allows a set of instructions to be executed repeatedly based on some condition.
  • The statements which appear in the source code only once but execute many times, such kind of statements are called loops.
  • It has initialization expression, condition expression and updates expression.
  • Loop statements are divided into two:
    1. Entry Controlled Loop
    2. Exit Controlled Loop

Entry Controlled Loop

  • In the entry, controlled loop condition expression will be evaluated first.
  • If it is true the body of the loop will be executed and repeats until the condition becomes true.

Exit controlled Loop

  • In an exit controlled loop, first, the body of the loop will be executed without checking the condition.
  • The condition expression will be evaluated after the execution of loop body once.
  • Loops can be again classified as
    1. for loop
    2. while loop
    3. do-while loop

for loop

  • It is an entry controlled loop

Syntax

     for (Initialization Expression; condition Expression; Update Expression){
          body-of the-loop;
     }

Description of syntax

  • First the initialization expression will be evaluated first.
  • Then checks the condition expression.
  • If the condition expression is true, the body of the loop will be executed and update the update expession.
  • Then checks the condition of update expression. If it is true repeat steps two and three.If it is false exit from the loop.

Example

C PROGRAM TO PRINT NUMBERS FROM 1 TO 10

      #include
      main()
      {
        for(i=0;i<10;i++){ 
          printf("%d",i);
        }
      }

Output: 0123456789

Working of the program:

  • In the main function, the execution of the program starts.
  • First executes initialization expression,ie set i=0.
  • Then evaluates condition expression i<10.ie 0<10 ,it is true, so jump to the body of the loop.
  • In the body of the loop it has given to the print value of i.ie the current value of i is 0, so print 0.
  • Next, evaluate condition expession.here increment the value of i.ie i=i+1,ie i=0+1=1 .
  • Again evaluates condition expression i<10.ie 1<10 and loop body works.
  • Repeat steps 3,4,5,6 until the condition becomes false.
  • When i=10, the condition expression will not satisfy. ie 10<10 is false.so exit from the loop.

Sample Programs

  • C program to print numbers up to a given limit.
  • C program to print even numbers up to a given limit.
  • C program to print odd numbers up to a given limit.
  • C program to find the sum of even numbers and sum of odd numbers up to a given limit.
  • C program to print factorial of a number.
  • C program to print the Fibonacci series up to a limit.
  • C program to check whether a number is prime or not.
  • C program to check whether a number is a palindrome or not.
  • C program to find the sum of natural numbers up to a limit.