Difference between for and while in c
BM Balmiki Mandal 21 Aug 2022 2 views 0 comments C Programming

Difference between for and while in c

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!

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026