Thursday, December 3, 2020

Loops in c language.

 Learn programming for free



Loops in c language.


In c language loops is basically of three types.

  1. For loop
  2. while loop
  3. do while loop

We will learn all of them in depth with a question so that it becomes easy to learn and understand.


Question: Write a program in c language which will take input from user and print all number in between 1 to entered number?


1.For loop


#include<stdio.h>
int main()
{
int n,i=1;
printf("Enter number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
return 0;
}


Syntax of for loop is:

for(initialization;condition;increment/decrement)
{
    
        //logic

}

Explanation:

According to question user will enter a number and we need to print all number between 1 to that number.So we take input from user and inside for loop we initialize our for loop to start from 1 and go till entered number.For each iteration we increment i so that when matched conditions found it terminates for loop and comes out of loop.

And for each iteration we have printed the number.


2.While loop


#include<stdio.h>
int main()
{
int n,i=1;
printf("Enter number");
scanf("%d",&n);
while(i<=n)
{
printf("%d",i);
i++;
}
return 0;
}

While loop is also called as entry controlled loop because it first checks the conditions.If conditions found to be true then only it enters in loop otherwise it skips the loop.

So in above example we have first initialize a variable i = 1.And before entering in while loop we checked the condition since 1<=n ( suppose n=10) then it will enter into loop and print that number.

One important point that we should keep in our mind that inside our while loop we must increment our variable otherwise it will lead to infinite loop condition.


3. do-while loop


#include<stdio.h>
int main()
{
int n,i=1;
printf("Enter number");
scanf("%d",&n);
do
{
printf("%d",i);
i++;
}while(i<=n);
return 0;
}


do-while loop is called as exit-controlled loop because it first executes a statement then check conditions.If our initial condition is found to be false then also it will execute for once.That's why it is known as exit-controlled loop. 

If you want to learn c language in depth then do visit: learn c language in depth.

Share this

0 Comment to "Loops in c language."

Post a Comment

If you have any doubts then let me know.