Skip to main content

Control Statements: Loops in C programming

Loops are used when we want to execute a part of program or block of statement several times. So, a loop may be defined as a block of statements which are repeatedly executed for a certain number of times or until a particular condition is satisfied. There are three types of loop statements in C:

1. For
2. While
3. Do...while

Each loop consists of two segments, one is k/a the control statement and the other is the body of the loop. The control statement in loop decides whether the body is to be executed or not. Depending on the position of control statement in the loop, loops may be classified either entry_controlled loop or exit_controlled loop. While and For are entry_controlled loops where as do...while is exit_controlled loop.

For Loop:

For loops is useful to execute a statement for a number of times. When the number of repetitions is known in advance, the use of this loop will be more efficient. Thus, this loop is also known as determinate or definite loop.
The general syntax

for (counter initialization ; test condition ; increment or decrement)
{
| * body of loop * |
}



 
  (Fig : Flowchart of For Loop)


For example:

|* Calculate the factorial of a number *|
    #include<stdio.h>
    main()
    {
    int num, i
    long fact = 1
    printf (“ln Enter a number whose factorial is to be calculated : “) ;
    scanf (“%d”, &num) ;
    for (i=1 ; i<=num ; i++)
    fact * = i ; |* fact = fact*i *|
    printf (“\n The factorial is : %d”, fact ) ;
    }

    Output:
      Enter a number whose factorial is to be calculated: 5
      The factorial is: 120

 



While Loop:
The while statement can be written as
while(condition)                                  while(condition)
statement ;                                           {
statement ; | * bed of the loop *|
statement ;
- - - - - - -
}
First the condition is evaluated; if it is true then the statements in the body of loop are executed. After the execution, again the condition is checked and if it is found to be true then again the statements in the body of loop are executed. This means that these statements are executed continuously till the condition is true and when it becomes false, the loop terminates and the control comes out of the loop. Each execution of the loop body is called iteration.
             |* Program to print the sum of digits of any num *|
            #include<stdio.h>
            main()
            {
            int n, sum = 0, rem ;
            printf (“Enter the number :”) ;
            scanf (%d”, &n) ;
            while (n>0)
            {
            rem = n%10 ; |* taking last digit of number *|
            sum+ = rem ; |* sum = sum + rem * |
            n/ = 10 ; |* skipping last digit *|
            } |*n = n/10 *|
            printf (“Sum of digits = %d \n”, sum) ;
            }
            Output:
            Enter the number : 1452
            Sum of digits = 12

 
 




















do...while loop:
The do...while statement is also used for looping. The body of this loop may contain a single statement or a block of statements. The general syntax is :
do                                                        do
statement ;                                           {
while(condition) ;                               Statement 1 ;
Statement 2 ;
- - - - - - - -
Statement n ;}
while(condition) ;

Here firstly the segments inside the loop body are executed and then the condition is evaluated. If the condition is true, then again the loop body is executed and this process continues until the condition becomes false. Unlike while loop, here a semicolon is placed after the condition. In a ‘while’ loop, first the condition is evaluated and then the statements are executed whereas in do while loop, first the statements are executed and then the condition is evaluated. So, if initially the condition is false the while loop will not execute at all, whereas the do while loop will always execute at least once.
                   |* program to print the number from 1 to 10 using do while *|
                 #include <stdio.h>
                 main()
                 {
                  int i = 1 ;
                  do
                  {
                  printf (“%dlt”, i) ;
                  itt ;
                  } while (i<=10) ;
                  printf(“ln”) ;
                  }
                Output : 1 2 3 4 5 6 7 8 9 10

 
 















Differences between while loop and do while loop:
while                                                                                                        
  1. while loop is entry controlled loop i.e. test condition is evaluated first and body of loop  is executed only if this test is true.
  2. The body of the loop may not be executed  at all if the condition is not satisfied at the  very first attempt.
  3. syntax :
   while (condition)
{    body of the loop }
      4. Draw flowchart
do...while
1. do...while loop is exit controlled loop i.e. the body of the loop is executed first without checking condition and at the end of body of loop, the condition is evaluated.
2. The body of the loop is always executed at least once.
3. syntax :
do
{
body of the loop
} while (condition)
4. Draw flowchart


Nesting of loops:
When a loop is written inside the body of another loop, then it is k/a nesting of loops. Any type of loop can be nested inside any other type of loop. For example, a for loop may be nested inside another for loop or inside a while or do...while loop. Similarly, while and do while loops can be nested.
| * program to understand nesting in for loop * |
#include<stdio.h>
main()
{
int i,j ;
for (i = 1 ; i<=3 ; itt) |* Outer loop *|
{
printf (“i=%d|n”, i)
for (j=1 ; j<=4 ; j++) |* inner loop *|
printf (“j=%d\t”,j) ;
printf (“\n”) ;
}
}

Output:
i = 1
j = 1 j = 2 j = 3 j = 4
i = 2
j = 1 j = 2 j = 3 j = 4
i = 3

j = 1 j = 2 j = 3 j = 4

Comments

Popular posts from this blog

What is manipulator in C++?

Answer: Manipulators are special functions that can be included in the I/O statement to alter the format parameters of a stream. Table-2 shows some important manipulator functions that are frequently used. To access these manipulators, the file < iomanip.h > should be included in program.                               Table-2               Manipulators                                                    Equivalent ios function               set...

Database Management System(DBMS)

Data and Information  Data is an unprocessed raw fact which does  not give complete meaning about any object,person, entity etc. But when various inter-related data arranged in a row, it gives a complete meaning which is referred to as information. For Example: ID Name Address Program 1101 Ram Shrestha Biratnagar BScIT         is information of a specific person. Database Database is a repository(storage) for the organized collection of related information  of data items. It Consist of meaningful arrangement of data, relationship, constraints, schema etc. In modern days we define database as a computerized record-keeping system used to store information and allows users to retrieve and update these information on their request. Some example of databases are telephone directory, data of SLC result, student and employee records etc. Database Management System(DBMS) Database is the softw...

What is Java Applets?

An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Java-compatible web browser. Furthermore, an applet is downloaded on demand, without further interaction with the user. If the user clicks a link that contains an applet, the applet will be automatically downloaded and run in the browser. Applets are intended to be small programs. They are typically used to display data provided by the server, handle user input, or provide simple functions, such as a loan calculator, that execute locally, rather than on the server. In essence, the applet allows some functionality to be moved from the server to the client.