C++ bootcamp · Lab 08

Squares on one line

easyFor Loop10 minLesson: For Loop

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n and print the squares of 1 through n on a single line, separated by spaces.

A trailing space at the end of the line is fine — the checker ignores trailing whitespace.

Input. One line: an integer n ≥ 1.

Output. Space-separated squares, e.g. 1 4 9 16 25 for n = 5.

Constraints

  • 1 ≤ n ≤ 20

Examples

Example 1
Input
5
Output
1 4 9 16 25
Hint
  1. Loop i from 1 to n and print i * i.
  2. Print each value followed by a space, then a newline at the end.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>

int main() {
  int n;
  std::cin >> n;
  for (int i = 1; i <= n; i++) std::cout << i * i << " ";
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.