Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print numbers from 1 to 5 using a loop.
C++
#include <iostream> int main() { for(int i = 1; i [1] 5; i++) { std::cout << i << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i < 5' will stop the loop at 4, missing 5.
Using 'i > 5' or 'i >= 5' will not run the loop as expected.
✗ Incorrect
The loop should continue while i is less than or equal to 5 to print numbers 1 through 5.
2fill in blank
mediumComplete the code to stop the loop when the variable 'count' reaches 10.
C++
#include <iostream> int main() { int count = 0; while(count [1] 10) { std::cout << count << std::endl; count++; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' will run the loop until count is 10, which may be unintended.
Using '>' or '>=' will cause the loop not to run.
✗ Incorrect
The loop should run while count is less than 10, stopping before count reaches 10.
3fill in blank
hardFix the error in the loop condition to avoid an infinite loop.
C++
#include <iostream> int main() { int x = 0; while(x [1] 5) { std::cout << x << std::endl; // Missing increment causes infinite loop x++; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '>=' will cause the loop not to run at all.
Using '<=' may cause the loop to run one extra time if not careful.
✗ Incorrect
Using 'x < 5' ensures the loop runs while x is less than 5 and stops before x reaches 5, preventing infinite loops.
4fill in blank
hardFill both blanks to create a loop that prints even numbers from 2 to 10.
C++
#include <iostream> int main() { for(int num = [1]; num [2] 10; num += 2) { std::cout << num << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 will print odd numbers.
Using '<' will stop before printing 10.
✗ Incorrect
Start from 2 and continue while num is less than or equal to 10 to print even numbers up to 10.
5fill in blank
hardFill all three blanks to create a loop that sums numbers from 1 to 5.
C++
#include <iostream> int main() { int sum = 0; for(int i = [1]; i [2] 5; i[3]) { sum += i; } std::cout << sum << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 will add an extra number.
Using '<' will miss adding 5.
Forgetting to increment i causes an infinite loop.
✗ Incorrect
Start i at 1, continue while i is less than or equal to 5, and increment i by 1 each loop to sum numbers 1 through 5.