Find the output for the following C program#include<stdio.h>void main(void){unsigned int c;unsigned x=0x3;scanf("%u",&c);switch(c&x){case 3: printf("Hello!t");case 2: printf("Welcomet");case 1: printf("To Allt");default:printf("n");}}

Showing Answers 1 - 2 of 2 Answers

manish

  • Jul 15th, 2006
 

#include<stdio.h>
void main(void)
{
unsigned int c;
unsigned x=0x3;
scanf("%u",&c);
switch(c&x)
{
case 3: printf("Hello!t");
case 2: printf("Welcomet");
case 1: printf("To Allt");
default:printf("n");
}
}

sol first of lets see the hexadecimal value assigned to x its decimal equivalent is also 3

now unsigned 3 is equivalent to

0000 0000 0000 0011

and if enter 1 at the console hance 1 is assigned to x whose binary equivalent is

0000 0000 0000 0001

Now if and both these

using table

A B A&B

0 0 0

0 1 0

1 0 0

1 1 1

that means if both are 1 then output is 1

x=        0000 0000 0000 0011

c=        0000 0000 0000 0001

c & x =  0000 0000 0000 0001 which is equivailent to decimal 1 hence case 1 is activated and  To Allt  is printed similary when we entered 2 since there is no break statement case 2 and case1 both get activated and output contains 

Welcomet To Allt and hence so on..................for value greater than 3 or less than 1 default case is activated.

  Was this answer useful?  Yes

manishsddiet

  • Jul 15th, 2006
 

hi here the solution

x is being assigned a hexadecimal value =3 its decimal equivalent is also

let we entered the value 2 at console and that value is assigned to c now in the switch clause we have bitwise operation c & x this operation is visualised as

x=3=        0000 0000 0000 0011

c=2=        0000 0000 0000 0010

c & x        0000 0000 0000 0010 which is equivalent to decimal 2 as per the and operation between x and c this will activate the case 2 since case 2 doesnt have any break statement hence output would be 

 WelcometTo Allt for any other value > 3 or < 0 default case will be activated and for values 1,2, 3 entered at console there corressponding cases will be activated

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions