CS31 Worksheet 2
CS31 Worksheet 2
This worksheet is entirely optional, and meant for extra practice. Some problems will be more
challenging than others and are designed to have you apply your knowledge beyond the examples
presented in lecture, discussion or projects. All exams will be done on paper, so it is in your best
interest to practice these problems by hand and not rely on a compiler.
Concepts
Logical Expressions, If Statements, Loops, Switch Statements
Reading Problems
1. If x = -2, y = 5, z = 0 , and t = -4, what is the value of each of the following logical expressions?
a) x + y < z + 1
b) x - 2 * y + y < z * 2 / 3
d) t > 5 || z < 2
e) x * y < 10 || y * z < 10
6. i is an even number
a) if (y >= x)
y = z;
cout << x << " " << y << " " << z << endl;
b) if (y >= x)
{
y = z;
cout << x << " " << y << " " << z << endl;
}
c) if (z < y)
temp = x;
x = z;
z = temp;
cout << x << " " << y << " " << z << endl;
d) if (z > y)
{
temp = x;
x = z;
z = temp;
}
cout << x << " " << y << " " << z << endl;
e) if (x >= 6)
cout << x + y << endl;
cout << x + y << endl;
int a = 10;
int b = 22;
while (a / 2 >= 1) {
a--;
cout << a << endl;
if ((a + b) % 2 == 0) {
a--;
cout << a << endl;
b /= 2;
}
}
5. This code snippet tries to print all prime numbers between 3 and a given input n. It has a number
of bugs. Fix them and replace the inner while loop with a for loop.
int n, x;
cin >> n;
int candidate = 3;
while (candidate < n) {
bool isPrime = true;
x = 2;
while (x < n) { // replace with a for loop…
if (candidate % x = 0){
isPrime = false;
}
x = x + 1;
}
if (isPrime) {
cout << n << “ “;
}
candidate = candidate + 1;
}
Programming Problems
1) Write a program that takes in an integer N where N > 0, and outputs a comma-separated list
of all the factors of N.
Sample input:
12
Sample output:
1,2,3,4,6,12
2. Write a program that reads in exactly four numbers and outputs the sum of the even numbers
that have been entered. Write the solution once without any loops at all. Then write the
solution again using a for loop. Write the solution again using a while loop. Write the solution
again using a do-while loop.
Sample output:
Enter a number: 2
Enter a number: 9
Enter a number: -3
Enter a number: 6
Result: 8
3) Write a program that reads two integers and determines whether or not these two integers
are palindromes of one another. A palindrome number is a value that reads the same forwards
and backwards. HINT: Use % and / to break the value into its different digits.
Sample input:
62 26
Sample output:
true
Sample input:
154 451
Sample output:
true
Sample input:
25 56
Sample output:
false