CECS 174 QUIZ #3
1. Here
is a collection of if and if-else statements with semicolons in various places.
Assume all variables
have been declared and initialized. Which of those are correct and are likely to
give the programmers intent?
Which are correct but unlikely to give the programmer's intent? Give the error
for the remaining.
a) if ( a > b ); a = b; else b = a; b) if ( a > b ) a = b; else; b = a; c) if ( a > b ) a = b; else b = a; d) if (a > b) a = b else b = a; Answer
a) if ( a > b ); // No semicolon
a = b;
else
b = a;
b) if ( a > b )
a = b;
else; //No semicolon
b = a;
c) if ( a > b ) //Correct
a = b;
else
b = a;
d) if (a > b)
a = b //Missing semicolon a = b;
else
b = a;
2. Use the coding below to answer the questions a and b.
int x;
if ( x> 10)
{ x = x + 10;
System.out.println(x);
}
else
System.out.println(x);
System.out.println("Done");
a. What is the output if x is equal to 20?
Answer
30
Done
b. What is the output if x is equal to 5?
Answer
5
Done
3. Use the coding below to answer the questions a and b.
int x;
if ( x> 10)
{ x = x + 10;
System.out.println(x);
}
else
{ x = x + 20;
System.out.println(x);
}
System.out.println("Done");
a. What is the output if x is equal to 20?
Answer
30
Done
b. What is the output if x is equal to 5?
Answer
25
Done
4. Use the coding below to answer the questions a and b.
int x;
if ( x> 10)
{ System.out.println("A");
System.out.println("B");
}
System.out.println("Done");
a. What is the output if x is equal to 20?
Answer
A
B
Done
b. What is the output if x is equal to 5?
Answer
Done
5. Use the coding below to answer the questions a and b.
int x;
if ( x> 10)
System.out.println("A");
System.out.println("B");
System.out.println("Done");
a. What is the output if x is equal to 20?
Answer
A
B
Done
b. What is the output if x is equal to 5?
Answer
B
Done
6. What is the output of the following C++ code?
x = 6;
if (x > 10)
System.out.println("Two");
System.out.printl("One");
Answer
One
8. Write a Java statements that will
a. print x>y if x is greater than y and print y>=x otherwise.
Answer: if (x > y)
System.out.println("x>y");
else
System.out.println("y>=y");
9. Convert the following while loop to a for loop:
int count = 0;
while(count++ < 50)
{System.out.println("A");
}
Answer
for(int count = 0; count <50; count++)
System.out.println("A");
10. Write a for loop that display
the following set of numbers:
0, 10, 20, 30, 40, 50 . . . 1000,
Answer:
for(int i=0; i <=1000;i = i + 10 )
{ System.out.print ( i + ",");
} Answer: while(x > 10)
{ x - = 2; }
12. Write a program segment that adds up the even integers from 16 through
2000, inclusive.
Answer:
int sum =0 , evenint = 16;
while ( evenint < = 2000)
{ sum + = evenint;
eventint + = 2;
}
13. What is the output of the following
code?
int i = 10;
while (i > 0)
System.out.println("A");
i = i -2;
Answer
Display many "A"
infinity loop