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++?
- Difference between C and C#
- scanf("%[^\n]s", str) Vs gets(str) in C with Examples
- time.h localtime() function in C with Examples
- Conditional or Ternary Operator (?:) in C/C++
- C program to Insert an element in an Array
- Types of Literals in C/C++ with Examples
- asctime() and asctime_s() functions in C with Examples
- time.h header file in C with Examples
- __builtin_inf() functions of GCC compiler
- Count substrings that contain all vowels | SET 2
- How can we use Comma operator in place of curly braces?



