Question: Is there any example for which the following two loops will not work the same way?
C
/*Program 1 --> For loop*/ for (<init - stmnt>;<boolean - expr>;<incr - stmnt>) {
<body-statements> } /*Program 2 --> While loop*/ <init - stmnt>; while (<boolean - expr>) {
<body-statements> <incr-stmnt> } |
Solution: If the body-statements contains continue, then the two programs will work in different ways See the below examples: Program 1 will print “loop” 3 times but Program 2 will go in an infinite loop.
Example: using “for” loop
Syntax:
for(initialization ; condition ; increment/decrement) { //statement }
C
#include <stdio.h> int main()
{ int sum=0, i;
for (i=1;i<=5;i++)
{
sum=sum+i;
}
printf ( "SUM = %d" , sum);
return 0;
} |
Output
SUM = 15
Example: using the “while” loop
Syntax:
while(condition) { //code for execution }
C
// Example: #include<stdio.h> int main()
{ int no=1, sum=0;
while (no<=5)
{
sum=sum+no;
no++;
}
printf ( "SUM = %d" , sum);
return 0;
} |
Output
SUM = 15
Please write comments if you want to add more solutions to the above question.