Predict the output of below programs.
Question 1
#include<stdio.h> int main() { int n; for(n = 7; n!=0; n--) printf("n = %d", n--); getchar(); return 0; } |
Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked.
Question 2
#include<stdio.h> int main() { printf("%x", -1<<1); getchar(); return 0; } |
Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.
Question 3
# include <stdio.h> # define scanf "%s Geeks For Geeks " main() { printf(scanf, scanf); getchar(); return 0; } |
Output: %s Geeks For Geeks Geeks For Geeks
Explanation: After pre-processing phase of compilation, printf statement will become.
printf("%s Geeks For Geeks ", "%s Geeks For Geeks ");
Now you can easily guess why output is %s Geeks For Geeks Geeks For Geeks.
Question 4
#include <stdlib.h> #include <stdio.h> enum {false, true}; int main() { int i = 1; do { printf("%d\n", i); i++; if (i < 15) continue; } while (false); getchar(); return 0; } |
Output: 1
Explanation: The do wile loop checks condition after each iteration. So after continue statement, control transfers to the statement while(false). Since the condition is false ‘i’ is printed only once.
Now try below program.
#include <stdlib.h> #include <stdio.h> enum {false, true}; int main() { int i = 1; do { printf("%d\n", i); i++; if (i < 15) break; } while (true); getchar(); return 0; } |
Question 5
char *getString() { char *str = "Nice test for strings"; return str; } int main() { printf("%s", getString()); getchar(); return 0; } |
Output: “Nice test for strings”
The above program works because string constants are stored in Data Section (not in Stack Section). So, when getString returns *str is not lost.
Recommended Posts:
- Output of C Programs | Set 2
- Output of C Programs | Set 3
- Output of C Programs | Set 4
- Output of C Programs | Set 5
- Output of C Programs | Set 6
- Output of C Programs | Set 7
- Output of C Programs | Set 9
- Output of C Programs | Set 11
- Output of C Programs | Set 12
- Output of C Programs | Set 14
- Output of C Programs | Set 13
- Output of C Programs | Set 16
- Output of C++ programs | Set 50
- Output of C programs | Set 29
- Output of Java Programs | Set 12
- Output of Java programs | Set 10 (Garbage Collection)
- Output of C++ programs | Set 21
- Output of Java programs | Set 13 (Collections)
- Output of C programs | Set 30 (Switch Case)
- Output of C++ programs | Set 22

