Difference between for and while in c

21 Aug 2022 Balmiki Mandal 0 C Programming

For loop in c

  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 the 'for' loop.

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

When it is not necessary to do initialization.condition check and increment/decrement in a single statement of an iterative loop, while a loop could be used. In the while loop statement, only the condition statement is present.

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:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

 

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!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.