tutorial#3 if..../if.....else/if.....else if/ switch solution

8
Tutorial#3 if..../if.....else/if.....else if/ switch Solution

Upload: arabella-murphy

Post on 22-Dec-2015

230 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

Tutorial#3if..../if.....else/if.....else if/ switch

Solution

Page 2: Tutorial#3 if..../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

Page 3: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

• 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

Page 4: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

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

Page 5: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

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

Page 6: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

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++;

Page 7: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

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

Page 8: Tutorial#3 if..../if.....else/if.....else if/ switch Solution

• 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.