There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
Agree with a comment or answer? Like () to up-vote the contribution!
Outside the while loop, we have initialized int i = 0;. If you omit the increment statement, you will end up with an infinite loop because i will always remain as 0 (unless you increment it).
When making a square number system, why doesn’t it work when I key in this statement" square = square * square" because it doesn’t give the correct answer.
Consider what’s happening to square in each loop with your current code.
Loop 1: square is 0, so 0 * 0 = 0. All good there. square is incremented by 1 with square++;
Loop 2: square is 1, so 1 * 1 = 1. square is incremented by 1 with square++;
Loop 3: square is 2, so 2 * 2 = 4. square is incremented by 1 with square++;
Now things start going crazy. square is 5 after being incremented, so on the next loop… Loop 4: square is 5, so 5 * 5 = 25. square is incremented by 1 with square++;
and it just gets worse from there. After that, square starts with the value of 26.
#include
int main() {
int i = 0;
int square = 0;
// Write a while loop here:
while (i < 10 && square == i){
std::cout << i << " " << i * square << “\n”;
i++;
square++;
}
return 0;
}
Where will you assign i = 0 in the while loop?
If you assign it like this: while (int i = 0) { ... that isn’t acceptable because the while loop condition is supposed to go in between the parentheses while (\\loop condition) { ...
If you do it inside the body of the while loop like:
while (i < 10) {
i = 0;
\\ do stuff here
i++;
}
that won’t work because in every iteration of the while loop, the statements in the loop body will be executed. That means every time through, i will be set to 0, then we will do some stuff, then we will increment i to 1. Then we will check the loop condition (i < 10) which will be true. We will go to the next iteration. In the next iteration, we will again set i to 0, do some stuff and so on. We will end up with an infinite loop. Additionally if i is not initialized before the first time we reach the while loop, then the compiler will throw an error because i will be undeclared and uninitialized and therefore the condition (i < 10) can’t be evaluated. So, we must declare and initialize the loop variable before entering our while loop.