While Loop Simulation
Category: Simulation
Author: Marty Stepp
Book Chapter: 5.1
Problem: While Loop Simulation
For each call below to the following method, write the value that is returned:
public static int mystery(int x) {
int a = 1;
int c = 0;
while (x > 0) {
a = x % 2;
if (a == 1) {
c++;
}
x = x / 2;
}
return c;
}
1) mystery(2);
2) mystery(-1);
3) mystery(7);
4) mystery(18);
5) mystery(43);