Question: Is there any example for which the following two loops will not work same way?
/*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> } |
chevron_right
filter_none
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 for program 1
int main() { int i = 0; for(i = 0; i < 3; i++) { printf("loop "); continue; } getchar(); return 0; } |
chevron_right
filter_none
Example for program 2
int main() { int i = 0; while(i < 3) { printf("loop"); /* printed infinite times */ continue; i++; /*This statement is never executed*/ } getchar(); return 0; } |
chevron_right
filter_none
Please write comments if you want to add more solutions for the above question.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Difference between while and do-while loop in C, C++, Java
- Which will be faster while(1) or while(2)?
- Difference between while(1) and while(0) in C language
- typedef versus #define in C
- Scope Resolution Operator Versus this pointer in C++?
- Output of C programs | Set 56 (While loop)
- C/C++ while loop with Examples
- C/C++ do while loop with Examples
- Hello World Program : First program while learning Programming
- Bug Tracking System
- C Program to sort rows of the Matrix
- Advantages and Disadvantages of Array in C
- Types of C files after its compilation
- Food Ordering System in C

