For Versus While
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.
Recommended Posts:
- typedef versus #define in C
- calloc() versus malloc()
- Scope Resolution Operator Versus this pointer in C++?
- Slack Bytes in Structures : Explained with Example
- Difference between Iterators and Pointers in C/C++ with Examples
- C program to count number of vowels and consonants in a String
- Nested Loops in C with Examples
- Hello World Program : First program while learning Programming
- Difference between Argument and Parameter in C/C++ with Examples
- Implicit Type Conversion in C with Examples
- <cfloat> float.h in C/C++ with Examples
- C/C++ #include directive with Examples
- C/C++ if else statement with Examples
- Internal static variable vs. External static variable with Examples in C


