WHILE LOOP IN C LANGUAGE …

WHAT ARE LOOPS?

Suppose we want to print integer numbers from 1 to 10. Here we have to use printf statement 10 times which is a long and time taking process. For making it easy we use loops. Loops in C language provide us to repeat a piece of code again and again until our condition is not satisfied.
Loops in C language are -:
1.)While loop
2.) do-while loop
3.) for loop
Let’s understand them one by one with a bunch of examples

1.) While loop

The syntax of while loop is
while(condition)
{
do this;
}
Here condition in while loop is checked first and if it is true control enters in while loop and code written get executed. Once all codes are executed than again compiler goes to while and condition is checked. Until and unless condition inside while is false, statements inside loop will continuously get executes. When condition becomes false compiler exit through loop and statement next to loop is executed.
Let’s take an example of printing numbers 1 to 10 using while loop.

EXAMPLE -: PRINTING NUMBERS FROM 1 TO 10 USING WHILE LOOP.
CODING-:

#include<stdio.h>

int main()
{
int n=1;
while(n<=10)
{
printf(“%d\n”,n);
n++;
}
}

How it worked -:
Here we initialized n from 1 and raised a condition in while. Compiler check whether n is less than or equal to 10, if yes control will enter in the loop and it will print the value of n i.e., 1. Now it’s most important step to increase the value of n (n++ operator is used) because when next time condition is checked n becomes 2. Again Compiler checks the condition, if true then control enters in while and value of n gets printed i.e., 2. This process goes on until the value of n becomes greater than 10.

EXAMPLE -: PRINTING ALL EVEN NUMBERS UP TO A NUMBER ENTERED BY USER.
CODING-:

#include<stdio.h>
int main()
{
    int n;
    int i=1;
    scanf(“%d”,&n);
    printf(“Enter any number\n”);
      while(i<=n)
     {
       if(i%2==0)
       {
         printf(“%d”,i);
         printf(” is even\n”);
       }
       i++;
     }
}

Leave a comment

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started