Difference between for and while in c
For loop in c
Program: Program to illustrate for loop
#include
int main(){
int i:
for (i=1:<=5:i++)
{
//print the number
printf("\n%d",i);
}
return 0;
}
output: 1 2 3 4 5
Attention: The loop repeats for 5 times and prints value of 'i' each time .'i' increases by 1 for every cycle of loop.
while loop in c
Syntax:
Program 02
#include
int main(){
int i = 0,flag = 0;
int a [10]={0,1,4,6,89,54,25,635,500};
//this loop ie repeated until the condition is false.
while (flag==0){
if(a[1]==54){
//as element is found,flag = 1,the loop terminates
falg = 1;
}
else{
i++;
}
}
printf("Element found at %d th location",i);
return 0;
}
output: Here flag is initialized to zero.' while loop repeats until the valuer of the 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.
Further Reading:
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!