Tuesday, August 27, 2019

Looping in C Language

Looping in C Language

Almost all programming language provide the concept of loops. A loop is a sequence of instructions that is continuously performed until a specific condition met.
It is a way using which we can perform instructions again and again.
Ex: Suppose we want to print “Hello” 5 times on output screen. We can write “Hello” 5 times in printf() function or we can write printf(“Hello\n”) statement 5 times.

(1)
#include <conio.h>
#include <stdio.h>
void main()
{
    clrscr();
    printf("Hello\nHello\nHello\nHello\nHello\n");
    getch();
}

(2)
#include <conio.h>
#include <stdio.h>
void main()
{
    clrscr();
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
    getch();
}


Output


Hello
Hello
Hello
Hello
Hello


Both Example (1) or (2) are giving same output. But when it comes to do a big task we have to write a lot of code.
What if, we write printf() statement once and it’ll repeat itself 5 times. That’s what a loop does.
#include <conio.h>
#include <stdio.h>
void main()
{
    clrscr();
    int i;
    for(i=1;i<=5;i++)
    {
        printf("Hello\n");
    }
    getch();
}


In given example we used for loop to do the same work. By doing a minor change we can print “hello” 50 times, 100 times and more.

Advantages:-


It helps to write same statements many times.
Reduces our time, code & efforts.
Reduces code complexity.

Types:-


There are three loops:-
While loop
Do-while loop
For loop
Here I’ll discuss about only for loop because it is most used loop in programming language.

Syntax:-

    for( initializationStatement; conditionExpression; updateStatement )
    {
// codes
    }


How does for loop work:-


The initialization statement is executed first and it executes only once. This step allows declaring and initializing the variables that will control our loop (control loop variable).

Now, the Condition expression is evaluated and compiler checks given condition is true or false. If, the given condition is true (non zero), codes inside the code of for loop is executed but if condition is false (Zero), the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.

If the body of for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables by incrementing or decrementing it.

After updating the control variable condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop  update statement  condition). After the condition becomes false, for loop terminates.

Note: -

To use for loop we have to use 2 semicolons (;) if we skip any or increase them it’ll give a compilation error. We can skip any of three statements but we can’t skip any semicolon (;).

Flow chart of for loop:-

 Looping in c language


// Example of for loop in C language
// Program to print table of an entered number.
#include <stdio.h>
#include <conio.h>
void main()
{
    int n, i, t;
    printf("Enter a number: ");
    scanf("%d",&n);
    for (i=1; i<=10; i++)
    {
t=n*i;
        printf("%d X %d = %d \n", n, i, t);
    } 
    getch();
}


Output:-


Enter a number: 5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50


Explanation:-


First it will ask user to enter a number which will store in a variable named n.

Now control comes to for loop and initializes variable i = 1.

After that compiler will check the condition whether the current value of i is less than or equals to
10. Value of i is 1 which is less than 10 so the condition is true.

Now the value of t will be calculated and then the values of n, i & t will get printed.

After this flow of control jumps back up to the update statement which is i++. This will increment
the value of i by 1.

Now the value of i is 2, Again compiler will check the condition, execute the codes of body and increment the value of i with 1. This process iterates itself until the given condition is true.

Once the condition is found false, compiler will terminate for loop and jumps to the next statement after loop.

Note: - 

During whole process compiler checked condition 11 times, where 1 to 10 times condition was true and when the value of i became 11 the condition was false.

Different forms of for loop in C:-


In above example I have used i as program counter and also for calculating values of t.
1. We can skip initialization part from the loop, the variable is intialzed before for loop. Even though we can skip initialization part but semicolon (;) before condition is must, without which you will get compilation error.
int i=1;
for (; i<=10; i++)


2. I used i++,  instead of it I can also use i=i+1, Both are same.

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

3. Like initialization, we can also skip update statement part but the semicolon (;) must be there after condition expression.
for (i=1; i<=10;)
{
// code
i++;
}


4. This is also possible, we can skip initialize variable before loop and update it inside the body.
int i=1;
for (; i<=10;)
{
// code
i++;
}


Nested for loop in C:-


In programming there exist situations where you need to iterate single or a set of repetitive statement for a number of times. For such conditions we can use nested loops.
A for loop inside another loop is called a nested for loop. C supports nesting of one loop inside another. We can define any number of loops inside another loop. We can also have any number of nesting level. We can put any type of loop in another type. Consider a nested loop where the outer loop runs n times and the inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

Syntax of Nested loops:-


Outer-Loop
{
// Body of Outer-loop
Inner-Loop
{
//Body of inner-loop
}
… … … …
}


As we can see, the outer loop encloses the inner loop. The inner loop is a part of the outer loop and must start and finish within the body of outer loop.
On each iteration of outer loop, the inner loop is executed completely.
for( initializationStatement; conditionExpression; updateStatement )
{
// Codes
for( initializationStatement; conditionExpression; updateStatement )
    {
// Codes
  }
     … … … …
}


Example:-


#include <stdio.h>
int main()
{
   for (int i=0; i<2; i++)
   {
for (int j=0; j<4; j++)
{
   printf("%d, %d\n",i ,j);
}
   }
   return 0;
}


Output:-


0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3


Multiple initializations inside for loop in C:-


We can also initialize multiple variables in for loop:
for (int i=1, int j=1;i<10 && j<10; i++, j++)

1. Here, I’ve initialized two variables (I & j) and both are separated by comma (,).

2. It has two test conditions joined together using logical AND (&&) operator. But you cannot use multiple test conditions separated by comma, you must use logical operator such as && or || to join conditions.

3. It has two variables in update statement part. This must be separated by comma.

Example of Multiple initialization inside for loop in C:-


#include <stdio.h>
#include <conio.h>
void main()
{
   int i,j;
   for (i=1,j=1 ; i<3 || j<5; i++,j++)
   {
printf("%d, %d\n",i ,j);
   }
   getch();
}

Output:-


1, 1
2, 2
3, 3
4, 4

Another example of for loop:-


// Example of for loop with break statement in C language
// Program to find an entered number is a prime number or not
#include<stdio.h>
#include<conio.h>
void main()
{
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    for(i=2; i<=n/2; ++i)
    {
        // condition for nonprime number
        if(n%i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (n == 1)
    {
      printf("1 is neither a prime nor a composite number.");
    }
    else
    {
        if (flag == 0)
          printf("%d is a prime number.", n);
        else
          printf("%d is not a prime number.", n);
    }
    getch();
}


Output 1st Time:-


Enter a positive integer: 17
17 is a prime number.


2nd Time:-


Enter a positive integer: 1
1 is neither a prime nor a composite number.


3rd Time:-


Enter a positive integer: 10
10 is not a prime number.



No comments:

Post a Comment