tutorial#3 if..../if.....else/if.....else if/ switch solution
TRANSCRIPT
Tutorial#3if..../if.....else/if.....else if/ switch
Solution
Q1: What is the output of these code:
•Code1:
int n, k = 5;
n = (100 % k ? k + 1 : k - 1);
n=4
• Code2:
int a = 4, b = 2, c = 5;
if(a > b)
a= 5;
if(c == a)
{
a = 6;
c = 3;
}
else
a = 7;
cout << “a is : “<<a ;
cout << “c is : “<<c ;
a is: 6 c is:3
Code3 int x; int y;
x=2; y=5;
if(x = y)
{
cout <<"x is equal to y";
cout << "x+y=" << x+y<<","<<"y++="<<y++;
}
else
cout << "x is not equal to y";
x is equal to y x+y= 10 , y++=5
Code4•int x=5;
switch (x)
{
cout << “$$$$”<< endl;
case 1: x=x+2; break;case 3: x=x+1;
case 5: if (x==4)
x=x+6;
case 6: x=x+3;
break;
default: x=x-1;
}cout << x<< endl;
8
Q2: Convert the following switch statement to if statementint value = 0, input ; cin>>input;switch(input) {case 1: value+=4;break;case 2: value+=3;break;case 3: value+=2; break;default: value++;}
if(input==1)value+=4;else if(input==2)value+=3;else if(input==3)value+=2;elsevalue++;
Q3: Rewrite the following fragment using switch
if (letter == ‘R’) cout <<“Red”;
else if (letter ==‘Y’ ) cout<<“Yellow”;
else if (letter == ‘W’) cout<<“White”;
else
cout<<“ No color “;switch(letter){ case ‘R’: cout<<“Red”; break; case ‘Y’: cout<<“Yellow”; break; case ‘W’: cout<<“White”; break; default: cout<<“No color”; }
• Write a C++ program to find absolute value of negative number.
• Write a C++ program to test a number is negative number or positive number.