Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print numbers from 0 to 4 using a for loop.
C++
#include <iostream> int main() { for (int i = 0; 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 '>=' instead of '<' causes the loop not to run.
Using '<=' prints one extra number.
✗ Incorrect
The loop should run while i is less than 5 to print numbers 0 to 4.
2fill in blank
mediumComplete the code to sum numbers from 1 to 5 using a for loop.
C++
#include <iostream> int main() { int sum = 0; for (int i = 1; i [1] 5; i++) { 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
Using '<' excludes 5 from the sum.
Using '>=' causes the loop not to run.
✗ Incorrect
The loop should include 5, so use '<=' to sum numbers 1 through 5.
3fill in blank
hardFix the error in the for loop condition to count down from 5 to 1.
C++
#include <iostream> int main() { for (int i = 5; i [1] 1; 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 '<' or '<=' causes the loop not to run.
Using '>' excludes 1 from the output.
✗ Incorrect
To count down from 5 to 1, the loop should run while i is greater than or equal to 1.
4fill in blank
hardFill both blanks to create a for loop that prints even numbers from 2 to 10.
C++
#include <iostream> int main() { for (int i = [1]; i [2] 10; i += 2) { std::cout << i << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 prints odd numbers.
Using '<' excludes 10 from the output.
✗ Incorrect
Start at 2 and continue while i is less than or equal to 10 to print even numbers.
5fill in blank
hardFill all three blanks to create a for loop that prints squares of numbers from 1 to 4.
C++
#include <iostream> int main() { for (int [1] = 1; [2] [3] 5; i++) { std::cout << i * i << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causes errors.
Using '<=' prints one extra square.
✗ Incorrect
Use 'i' as the variable, and loop while i is less than 5 to print squares from 1 to 4.