Google

C programming questions puzzles

The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.


#include<stdio.h>


 


#define TOTAL_ELEMENTS (sizeof(array) /
sizeof(array[0]))


int
array[] = {23,34,12,17,204,99,16};


int
main()
{

int
d;


for(d=-1;d
<= (TOTAL_ELEMENTS-2);d++)

printf("%d\n",array[d+1]);


return
0;
}

Find out what's going wrong.


 

I thought the following program was a perfect C program. But on compiling, I found a silly mistake. Can you find it out (without compiling the program :-) ?

#include<stdio.h>


 

void
OS_Solaris_print()

{


printf("Solaris - Sun Microsystems\n");

}


 

void
OS_Windows_print()

{


printf("Windows - Microsoft\n");


 

}

void
OS_HP-UX_print()

{


printf("HP-UX - Hewlett Packard\n");

}


 

int
main()

{


int
num;


printf("Enter the number (1-3):\n");


scanf("%d",&num);


switch(num)

{


case
1:


OS_Solaris_print();


break;


case
2:


OS_Windows_print();


break;


case
3:


OS_HP-UX_print();


break;


default:


printf("Hmm! only 1-3 :-)\n");


break;

}


 


return
0;

}


 

What's the expected output for the following program and why?

enum {false,true};


 

int
main()

{


int
i=1;


do

{


printf("%d\n",i);


i++;


if(i
<
15)


continue;

}while(false);


return
0;

}


 

The following program doesn't "seem" to print "hello-out". (Try executing it)


#include <stdio.h>


#include <unistd.h>


int
main()
{

while(1)
{

fprintf(stdout,"hello-out");

fprintf(stderr,"hello-err");

sleep(1);
}

return
0;
}

What could be the reason?

 

 


#include <stdio.h>


#define f(a,b) a##b


#define g(a) #a


#define h(a) g(a)


 


int
main()
{

printf("%s\n",h(f(1,2)));

printf("%s\n",g(f(1,2)));

return
0;
}

Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the program you get it as:
bash$ ./a.out
12
f(1,2)
bash$

Why is it so?