For loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use 'for' loop.
Syntax:
for(initialization;condition;increment/decrement)
{
//block of statements
//increment or decrement
}
Program: Program to illustrate for loop
#include<stdio.h>
int main()
{
int i;
for (i = 1; i <= 5; i++)
{
//print the number
printf("\n %d", i);
}
return 0;
}
Output:
12345
Explanation:
The loop repeats for 5 times and prints value of 'i' each time. 'i' increases by 1 for every cycle of loop. while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present.
Example:
#include<stdio.h>
int main()
{
int i = 0, flag = 0;
int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 };
//This loop is repeated until the condition is false.
while (flag == 0)
{
if (a[i] == 54)
{
//as element is found, flag = 1,the loop terminates
flag = 1;
}
else
{
i++;
}
}
printf("Element found at %d th location", i);
return 0;
}
Output:
Element found at 5th location
Explanation:
Here flag is initialized to zero. 'while' loop repeats until the value of flag is zero, increments i by 1. 'if' condition checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop terminates.
Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Search Content
Popular Article
Basic Courses
Advance Courses