C++ bootcamp · Lab 28

Star triangle

easyNested Loops10 minLesson: Nested Loops

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 a right triangle of asterisks with n rows.

Row i has i stars and no extra spaces.

Input. One line: an integer n ≥ 1.

Output. n lines of *, **, ***, …

Constraints

  • 1 ≤ n ≤ 20

Examples

Example 1
Input
3
Output
*
**
***
Hint
  1. std::string(i, '*') builds a row of i stars.
  2. Or nest two for loops.
Show correct code

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

#include <iostream>
#include <string>

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