34 Detailed Q&A for C4
1. What is a loop in C++ and why do we use it?
Answer:
A loop is like telling a computer, “Hey, do this over and over again until I say stop.”
You use loops when you want the same code to run many times — like counting from 1 to 10 or asking someone to guess a number until they get it right.
2. What are unary operators and how do they work?
Answer:
Unary means “one”. These operators only work on one thing (called an operand).
++xmeans "add 1 to x right now."x++means "use x now, then add 1 later."--xorx--subtracts 1, the same way.
Example:
int x = 5;
int y = ++x; // y = 6, x = 6
3. Why is ++x better than x++ in most cases?
Answer:
Because x++ might create a temporary copy behind the scenes, which uses a bit more memory and is slower.
So unless you have a special reason, it’s better to write ++x.
4. Can you use these unary operators with characters?
Answer:
Yes! Characters like 'A', 'B' are secretly numbers in disguise (ASCII).
So if you do:
char c = 'A';
++c;
Now c becomes 'B'!
5. What are compound assignment operators?
Answer:
These are shortcuts for doing math with the same variable.
Instead of writing:
x = x + 5;
You can just write:
x += 5;
There’s also -=, *=, /=, and %= for subtract, multiply, divide, and remainder.
6. What is operator precedence and why does it matter?
Answer:
It’s the rule of “what happens first” in math.
Like in school: multiplication happens before addition.
Example:
int result = 2 + 3 * 4; // result = 14 (not 20!)
If you want addition to happen first, use parentheses:
int result = (2 + 3) * 4; // result = 20
7. What does a while loop do?
Answer:
A while loop checks if something is true before it runs.
Example:
int i = 1;
while (i < 5) {
cout << i;
i++;
}
This prints: 1234
8. What happens if the while condition is false at the start?
Answer:
Nothing inside the loop runs.
Example:
int i = 10;
while (i < 5) {
cout << i;
}
This prints nothing because 10 < 5 is false.
9. What is block scope in loops?
Answer:
Variables you create inside a loop’s { } block disappear when the loop ends.
If you want to use them after the loop, you need to declare them before the loop starts.
10. What is an infinite loop?
Answer:
It’s a loop that never stops!
Example:
while (true) {
cout << "I will never stop!";
}
It keeps printing forever unless you press “stop” or use break.
11. What’s the difference between while and do-while loops?
Answer:
while→ checks the condition before running. Might run zero times.do-while→ runs the code first, then checks. Will run at least once.
Use do-while when you want to guarantee at least one run (like prompting user input).
12. When should I use a for loop instead of while or do-while?
Answer:
Use a for loop when you:
Know exactly how many times to loop (like counting 1 to 10).
Are using a counter that increases or decreases every time.
It keeps all loop stuff in one line, which makes it easier to read.
13. Can you have a loop with no braces {}?
Answer:
Yes — but only if the loop has one line of code.
for (int i = 0; i < 5; ++i)
cout << i;
BUT! Best practice is to always use braces, even if it’s one line — to avoid confusion and bugs.
14. What happens if I forget to update my counter inside a loop?
Answer:
The loop might become infinite (never-ending), because the condition never changes.
Example:
int i = 1;
while (i < 5) {
cout << i;
// missing: i++; ← loop never ends
}
Always make sure your loop can eventually stop!
15. How does a loop know when to stop?
Answer:
It stops when the condition you wrote becomes false.
while (i < 5)
As soon as i becomes 5 or more, the loop ends.
16. What is a sentinel value?
Answer:
It’s a special number you use to say “stop the loop now.”
Example: Entering -1 to stop entering test scores:
while (score != -1) {
// keep asking for scores
}
Sentinel values help you control when input ends.
17. What does future_value += monthly_investment; mean?
Answer:
It’s a shortcut for:
future_value = future_value + monthly_investment;
It just adds the monthly investment to the current value, updating it.
It’s a compound assignment operator, making code cleaner.
18. What is nesting loops and why use it?
Answer:
“Nesting” means putting one loop inside another loop.
Useful when:
Making tables
Working with grids (rows and columns)
Doing comparisons between multiple items
Example:
for (int row = 1; row <= 3; ++row) {
for (int col = 1; col <= 4; ++col) {
cout << "*";
}
cout << endl;
}
Prints 3 rows of 4 stars.
19. How does break work in a loop?
Answer:break; immediately jumps out of the loop, no matter what.
Example:
while (true) {
if (guess == answer) {
break;
}
}
Used to stop an infinite loop once something is true.
20. How does continue work in a loop?
Answer:continue; skips the rest of the loop code and jumps back to the top.
Useful when you want to skip bad input, or skip one round of the loop.
Example:
for (int i = 1; i <= 5; ++i) {
if (i == 3) continue;
cout << i;
}
// Prints: 1245 (skips 3)
Awesome! Let’s keep it going 💪
Here are Questions 21–30 from Chapter 4: How to Code Loops, explained in a clear, simple way:
21. How does the Test Scores program use a loop?
Answer:
It uses a while loop to keep asking the user for test scores until they enter -1.
It:
Adds up the scores
Counts how many were valid
Then shows the average
Invalid inputs like 150 or -5 are ignored with helpful messages.
22. How does the program avoid dividing by zero when calculating the average?
Answer:
Before dividing total by count, it checks:
if (count > 0)
If no valid scores were entered, this prevents a divide-by-zero crash.
23. How does the Future Value program calculate investment growth?
Answer:
It uses:
A
whileloop to keep running the program if the user wantsA
forloop inside it to calculate compound interest each month
It uses this formula inside the loop:
future_value = (future_value + monthly_investment) * (1 + monthly_rate);
24. Why do we use round() in the Future Value program?
Answer:
To round the result to 2 decimal places, like money!
Example:
future_value = round(future_value * 100) / 100;
This avoids results like $4080.5833333.
25. What happens if the user types letters (like "abc") instead of numbers?
Answer:
The program might get stuck in an infinite loop, because cin can’t handle it properly.
You’ll learn how to fix that with input validation in the next chapter.
26. When should you use a while loop vs. a for loop?
Answer:
Use
whilewhen you don’t know how many times the loop should run (like asking the user repeatedly).Use
forwhen you do know (like looping 36 times for 36 months).
27. What are nested loops used for in the Future Value Table example?
Answer:
To make a grid (or table) showing future value results for:
Different interest rates
Different number of years
Example:
for each year {
for each interest rate {
calculate and display value
}
}
This prints a neat chart.
28. Why do we use \t (tab) in the nested loop example?
Answer:
To separate columns so the table looks nice:
cout << rate << '\t';
Each tab moves the cursor to the next column.
29. Why are future values rounded to whole numbers in the table?
Answer:
To keep the columns aligned. Decimal values with different lengths would mess up the layout.
It’s for neat formatting, even though it loses some precision.
30. How does the Guess the Number game use break and continue?
Answer:
continueis used when a guess is invalid (like too big or small), to skip the rest of the loop.breakis used when the user guesses right, to end the loop and stop the game.
31. How does the Guess the Number program generate random numbers?
Answer:
It uses functions from two C++ libraries:
cstdlib→ forrand()andsrand()ctime→ fortime(nullptr)
Together they generate a different number each time:
srand(time(nullptr)); // Seed the random number
int number = rand() % 10 + 1; // Random number from 1 to 10
This way, the game feels fresh every time you play.
32. What is the purpose of the upper_limit variable in the game?
Answer:
It lets you easily change the range of guessing without hunting through your code.
Example:
int upper_limit = 10;
Now you can change it to 100, 50, etc., in one place — good for code flexibility.
33. Can the Guess the Number game work without break or continue?
Answer:
Yes! You can re-write the loop like this:
Change the
while (true)to something likewhile (guess != number)Check for invalid input with
ifstatementsDon’t use
breakorcontinue
It just takes a little extra planning. This is a great exercise for practicing better loop control.
34. What key loop terms should I remember from this chapter?
Answer:
Here are the MVPs (Most Valuable Programming terms):
Term | Meaning |
|---|---|
Unary operators | Work on one variable ( |
Compound operators | Shortcuts like |
While loop | Checks condition before running (pre-test loop) |
Do-while loop | Runs at least once before checking (post-test loop) |
For loop | Great when you know how many times to loop |
Nested loop | One loop inside another |
Sentinel value | Special input like |
Break | Stops the loop instantly |
Continue | Skips the rest of the loop and starts the next turn |
Infinite loop | Loop that never ends (on purpose or by accident) |