1 a What happens when you place a semicolon immediately afte
1 a) What happens when you place a semicolon immediately after the condition, as in this example:
if (cond);
statement;
b) In the following if/else statement, there is an error. What is it? What is the result of executing this statement? What is the fix for it?
if (input = 2)
cout << “Input is even.” << endl;
else
cout << “Input is odd.” << endl;
c) What is wrong with the following switch statement?
switch (temp)
{
case temp < 0: cout << “Temp is negative\ ”;
break;
case temp == 0: cout << “Temp is zero\ ”;
break;
Case temp > 0: cout << “Temp is positive\ ”;
break;
}
d) Write a \"for\" statement for each of the following cases:
i) Use a counter named i that has an initial value of 1, a final value of 20, and an increment of 1
ii) Use a counter named j that has an initial value of 20, a final value of 1, and an increment of -2.
Solution
1 a) What happens when you place a semicolon immediately after the condition, as in this example:
if (cond);
statement;
Answer : It treated as empty statement that is if condition is true the empty statement will execute.
b) In the following if/else statement, there is an error. What is it? What is the result of executing this statement? What is the fix for it?
if (input = 2)
cout << “Input is even.” << endl;
else
cout << “Input is odd.” << endl;
Answer : the above code prints \"Input is even.\"
in the statement if (input = 2) yields (input = 2 is assignment not condition, but if(condition) is the syntax) if(2) that is true,
the correct code is
if (input == 2)
cout << “Input is even.” << endl;
else
cout << “Input is odd.” << endl;
c) What is wrong with the following switch statement?
switch (temp)
{
case temp < 0: cout << “Temp is negative\ ”;
break;
case temp == 0: cout << “Temp is zero\ ”;
break;
Case temp > 0: cout << “Temp is positive\ ”;
break;
}
Answer : \'temp\' cannot appear in a constant-expression in the case statement
switch(constant){
case constant-expression:
statement;
break;
}
d) Write a \"for\" statement for each of the following cases:
i) Use a counter named i that has an initial value of 1, a final value of 20, and an increment of 1
ii) Use a counter named j that has an initial value of 20, a final value of 1, and an increment of -2
Answer :
i) for(int i=1;i<=20;i++)
ii) for(int j=20;j>=1;j-=2)

