Question: Is there any example for which the following two loops will not work the same way?
C
for (<init - stmnt>;<boolean - expr>;<incr - stmnt>) {
<body-statements>
}
<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;
}
|
Example: using the “while” loop
Syntax:
while(condition)
{
//code for execution
}
C
#include<stdio.h>
int main()
{
int no=1, sum=0;
while (no<=5)
{
sum=sum+no;
no++;
}
printf ( "SUM = %d" , sum);
return 0;
}
|
Please write comments if you want to add more solutions to the above question.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Jun, 2022
Like Article
Save Article