For loop in C programming with examples


To run the particular block of code continuously until a required condition is fulfill is called looping. It is used to perform looping operation. When the condition will become false the execution of loop will be stopped.

Syntax


1.In for loop there are three part initialization, condition and increment/decrement.
2.Initialization part executes only once.
3.All the three parts of for loop are optional

Example 1 

#include<stdio.h>
int main()
{
for(int i=1;i<=10;i++)
{
printf("%d\n",i);
}
}

### Output ###
1
2
3
4
5
6
7
8
9
10

In the above program i is a variable which is initialized with 1,condition goes to 10 and it is incremented by 1 so the output will be 1 to 10.

Example 2

#include<stdio.h>
int main()
{
for( ; ; )
{
	printf("Hello ");
}
}
/*
### output ###
Hello Hello Hello .....Infinite times
*/

All the three parts of for loop are optional so there is no error in the above program and output will be infinite times Hello because there is no condition to stop the execution of loop.

Example 3: Check given number is prime or not

Prime number is a whole number that have only two factors 1 and the number itself. Here in this program we will take two variable one for number and other for counting factors. After taking user input of number we will count number of factors by dividing number form 1 to number itself, After counting factors we will check if factors count is 2 means number is prime otherwise not prime.
 
#include<stdio.h>
int main()
{
//variables declaration
int no,factor_count=0;
//taking user input
printf("Enter any number\n");
scanf("%d",&no);
//loop for counting factors
for(int i=1;i<=no;i++)
{
if(no%i==0)
//incrementing factor count
factor_count++;
}
//checking condition
if(factor_count==2)
printf("Prime");
else
printf("Not Prime");
}
/*
###Output###
Run 1
Enter any number
94
Not Prime
Run 2
Enter any number
53
Prime
*/

Here I am requesting if you found this post was helpful for you then let me know by your comment in below comment box and share it with your friend. Also you can contact me on Instagram @rajusunagar_

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thank you!!.......

Post a Comment

0 Comments