int mysteryFunction(int number){
return number*number;
}
squares the number that was passed in
int n = 10;
while (n > 0) {
cout << n << " ";
n--;
for (int i = 0; i <= 9; i += 3){
cout << i << " ";
}
0 3 6 9
Which of the following is the correct syntax for a while loop?
A. while (i < 10) { cout << i; }
B. while i < 10 { cout << i; }
C. while (i < 10); cout << i;
D. loop (i < 10) { cout << i; }
A
T/F: a for loop can always be replaced with a while loop.
True
int x = 5;
while (x > 0) {
cout << x << " ";
x--;
}
counts down from 5
int x = 1;
while (x < 100) {
cout << x << " ";
x *= 2;
}
64
Which of these creates an infinite loop?
A. for (int i = 0; i < 10; i--)
B. for (int i = 0; i < 10; i++)
C. for (int i = 10; i > 0; i--)
D. for (int i = 0; i != 10; i++)
A
How many times will this loop run?
int i = 10;
while (i < 5) {
cout << i;
i++;
}
0 times
T/F: a while loop can always be replaced with a for loop.
True
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
cout << sum;
adds up numbers 1-5
int count = 1;
while (count != 10) {
cout << count << " ";
count += 2;
}
This loop is infinite.
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << i;
Compilation error — i is out of scope
void mystery5() {
int x = 1;
while (x < 30) {
cout << x << " ";
x *= 3;
}
}
1 3 9 27
What is the difference between for loops and while loops?
for loops are count based, while loops are condition based.
int count = 0;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
count++;
}
}
cout << count;
prints out how many numbers are in a 2*3 grid
for (int i = 5; i > 0; i -= 2) {
cout << i << " ";
}
5 3 1
for (int i = 5; i < 0; i++) {
cout << i << " ";
}
This loop never starts
int mystery10() {
int i = 1;
int count = 0;
while (i < 50) {
i *= 2;
count++;
}
return count;
}
count = 6
You want to find every instance of the letter 'g' in a string.
for loop.
int n = 1234;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << sum;
prints out the sum of the digits
for (int i = 0; i < 10; i++) {
if (i == 4){
break;
}
cout << i << " ";
}
0 1 2 3
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
cout << i << "," << j << " ";
}
}
1,1 1,2 2,1 2,2 3,1 3,2
int mystery8(int n) {
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + (n % 10);
n /= 10;
}
return reversed;
}
this function reverses the digits of n
you want to add numbers until you reach 1000.
while loop