Output of C Programs | Set 1

Predict the output of below programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
   int n;
   for(n = 7; n!=0; n--)
     printf("n = %d", n--);
   getchar();
   return 0;
}

chevron_right


Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked.

Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
   printf("%x", -1<<1);
   getchar();
   return 0;
}

chevron_right


Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.

Question 3



filter_none

edit
close

play_arrow

link
brightness_4
code

# include <stdio.h>
# define scanf  "%s Geeks For Geeks "
main()
{
   printf(scanf, scanf);
   getchar();
   return 0;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


Question 5

filter_none

edit
close

play_arrow

link
brightness_4
code

char *getString()
{
   char *str = "Nice test for strings";
   return str;
}
  
int main()
{
   printf("%s", getString());
   getchar();
   return 0;
}

chevron_right


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.



My Personal Notes arrow_drop_up


Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.