C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

What is the difference between 'for' and 'while' loops in C?

0 votes
102 views
asked Jan 8, 2014 by sara Guru (24,570 points)

1 Answer

0 votes
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.

Syntax:

#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.
answered Jan 8, 2014 by rajesh Guru (39,140 points)

Related questions

0 votes
1 answer 34 views
0 votes
1 answer 1,121 views
0 votes
1 answer 92 views
0 votes
0 answers 74 views
+1 vote
2 answers 5,654 views
...