These are the notes for C++ Coding Questions, episode 1, the first episode of SyntaxPilot's placement-practice series for people who finished the C++ course. Pattern printing: a right-angle star triangle, a number pyramid and a hollow square, plus the C++ shortcuts string(i, '*') and setw.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real. The compiler stops a program after 8 seconds (Time Limit Exceeded), like an online judge.
Real-life picture: a school assembly
| At the assembly | In C++ |
|---|---|
| row after row of students | the outer loop (i): one turn per row |
| students standing in one row | the inner loop (j): one turn per character |
| the teacher says "next row!" only when a row is full | cout << "\n" after the inner loop |
The 3-question plan for any pattern
- How many rows? That is the outer loop.
- In row
i, what is printed, and how many of each? Those are the inner loops. - When does the line end? After the inner loops: one
"\n"per row.
Then write a small table for n = 4 and read the formulas off the table. Never guess a formula.
Q1: Right-angle star triangle
Problem. Read n and print n rows; row i has exactly i stars.
*
**
***
****
Edge cases: n = 1 (one star), n = 0 (print nothing).
Think out loud. Rows: i from 1 to n. Row i: i stars. Then end the line.
Attempt 1: endl inside the inner loop
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << "*" << endl;
}
return 0;
}
Input 3:
*
*
*
*
*
*
Six lines with one star each. Why: endl means end the line now. Inside the inner loop it ends the line after every star, like a teacher shouting "next row" after every student. The line must end once per row, after the inner loop.
"\n" vs endl: both start a new line; endl also flushes the output (pushes it out immediately), which makes big loops slower. In coding questions, use "\n".
Attempt 2: the off-by-one error
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < i; j++)
cout << "*";
cout << "\n";
}
return 0;
}
Input 4:
*
**
***
The first row is empty and the last row has 3 stars, not 4. No error, no warning: just a wrong answer.
Why: j starts at 1 and stops before i, so the inner loop runs i - 1 times. Being wrong by exactly one is an off-by-one error (the fence-post mistake: a 4 m fence with a post every metre needs 5 posts, not 4). Always check the first and the last turn of a loop.
The fix: j <= i
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << "*";
cout << "\n";
}
return 0;
}
Input 4:
*
**
***
****
Input 1:
*
Input 0:
(nothing printed)
With n = 0 the outer condition 1 <= 0 is false from the start, so nothing is printed, which is correct.
C++ shortcuts: string(i, '*') and setw
string(i, '*')builds a string oficopies of the character'*'(header<string>).setw(w)(header<iomanip>) prints the next item in a fieldwcharacters wide, padded with spaces on the left, so the text is right-aligned. It only affects the very next item printed.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cout << string(i, '*') << "\n";
for (int i = 1; i <= n; i++)
cout << setw(n) << string(i, '*') << "\n";
return 0;
}
Input 4:
*
**
***
****
*
**
***
****
Interviews often say "use loops", so know both ways.
Q2: Number pyramid
Problem. Read n (1 to 9). Row i counts up from 1 to i, then down to 1, centred.
1
121
12321
1234321
Edge cases: n = 1; n bigger than 9 (two-digit numbers).
The obvious attempt: no leading spaces
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << j;
for (int j = i - 1; j >= 1; j--)
cout << j;
cout << "\n";
}
return 0;
}
Input 4:
1
121
12321
1234321
The numbers are right, but the rows lean on the left wall.
Why: we skipped the plan table. For n = 4:
Row i |
Spaces | Up | Down |
|---|---|---|---|
| 1 | 3 | 1 | – |
| 2 | 2 | 12 | 1 |
| 3 | 1 | 123 | 21 |
| 4 | 0 | 1234 | 321 |
The spaces column is n - i.
The fix: n - i spaces first
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cout << string(n - i, ' ');
for (int j = 1; j <= i; j++)
cout << j;
for (int j = i - 1; j >= 1; j--)
cout << j;
cout << "\n";
}
return 0;
}
Input 4:
1
121
12321
1234321
And with n = 12:
Input 12:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
12345678910987654321
123456789101110987654321
1234567891011121110987654321
The bottom rows break the shape: 10, 11 and 12 are two characters wide, so those rows are longer than the spaces allow. The problem said 1 to 9, so we validate the input:
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
if (n < 1 || n > 9) {
cout << "n must be 1 to 9\n";
return 0;
}
for (int i = 1; i <= n; i++) {
cout << string(n - i, ' ');
for (int j = 1; j <= i; j++)
cout << j;
for (int j = i - 1; j >= 1; j--)
cout << j;
cout << "\n";
}
return 0;
}
Input 12:
n must be 1 to 9
Input 9:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Input 1:
1
Q3: Hollow square
Problem. Read n and print an n × n square: stars on the border, spaces inside.
****
* *
* *
****
Edge cases: n = 1 (one star), n = 2 (no inside at all).
The obvious attempt: "first row or first column"
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || j == 1)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Input 4:
****
*
*
*
An L: only the top and the left sides. Why: a border has four sides: top i == 1, bottom i == n, left j == 1, right j == n. A cell is on the border if any one is true, so join them with || (or).
Typing the fix too fast: j = n
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j = n)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
g++ says:
main.cpp: In function 'int main()':
main.cpp:9:44: error: lvalue required as left operand of assignment
9 | if (i == 1 || i == n || j == 1 || j = n)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
= assigns, == compares. || is done before =, so g++ reads everything to the left of = as one condition and tries to store n into it. You can only assign into something that has a place in memory, like a variable; C++ calls that an lvalue. Hence the error.
The fix
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Input 4:
****
* *
* *
****
Input 1:
*
Input 2:
**
**
Complexity summary
Time complexity describes how the work grows when n grows; space complexity describes how the extra memory grows.
| Program | Time | Extra space |
|---|---|---|
| star triangle (loops): 1 + 2 + … + n = n(n+1)/2 stars | O(n²) | O(1) |
star triangle with string(i, '*') |
O(n²) | O(n): one row's string |
| number pyramid: about n² characters | O(n²) | O(n) with string(n - i, ' '), O(1) with a loop |
| hollow square: n × n cells | O(n²) | O(1) |
O(n²) means: double n, and the work grows about four times. O(1) means: a fixed number of variables, whatever n is.
Common mistakes (and the real results)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
cout << "*" << endl; inside the inner loop |
one star per line | the line ends after every star | "\n" after the inner loop |
for (int j = 1; j < i; j++) |
empty first row, a star missing in every row | runs i - 1 times (off by one) |
j <= i |
| no leading spaces | a left-aligned pile | the spaces column was skipped | string(n - i, ' ') |
| two-digit numbers in a digit pyramid | the shape breaks | 10 is two characters wide | validate 1 <= n <= 9 |
only i == 1 \|\| j == 1 |
an L shape | a border has four sides | add i == n, j == n |
j = n in a condition |
error: lvalue required as left operand of assignment |
= assigns |
j == n |
string(i, "*") |
error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(int&, const char [2])' |
"*" is a string, not a char |
string(i, '*') |
setw(4) << a << b |
only a is padded |
setw affects the next item only |
setw(4) << a << setw(4) << b |
The string(i, "*") mistake for real:
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cout << string(i, "*") << "\n";
return 0;
}
g++ says:
main.cpp: In function 'int main()':
main.cpp:9:30: error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(int&, const char [2])'
9 | cout << string(i, "*") << "\n";
| ^
In file included from /usr/include/c++/13/string:54,
from /usr/include/c++/13/bits/locale_classes.h:40,
from /usr/include/c++/13/bits/ios_base.h:41,
from /usr/include/c++/13/ios:44,
from /usr/include/c++/13/ostream:40,
from /usr/include/c++/13/iostream:41,
from main.cpp:1:
/usr/include/c++/13/bits/basic_string.h:619:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, size_type, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; size_type = long unsigned int]' (near match)
619 | basic_string(const _CharT* __s, size_type __n,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:619:7: note: conversion of argument 2 would be ill-formed:
main.cpp:9:27: error: invalid conversion from 'const char*' to 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-fpermissive]
9 | cout << string(i, "*") << "\n";
| ^~~
| |
| const char*
/usr/include/c++/13/bits/basic_string.h:795:9: note: candidate: 'template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with <template-parameter-2-2> = _Tp; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
795 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:795:9: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/13/bits/move.h:37,
from /usr/include/c++/13/bits/exception_ptr.h:41,
from /usr/include/c++/13/exception:164,
from /usr/include/c++/13/ios:41:
/usr/include/c++/13/type_traits: In substitution of 'template<bool _Cond, class _Tp> using std::enable_if_t = typename std::enable_if::type [with bool _Cond = false; _Tp = void]':
/usr/include/c++/13/bits/basic_string.h:144:8: required by substitution of 'template<class _CharT, class _Traits, class _Alloc> template<class _Tp, class _Res> using std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::_If_sv = std::enable_if_t<std::__and_<std::is_convertible<const _Tp&, std::basic_string_view<_CharT, _Traits> >, std::__not_<std::is_convertible<const _Tp*, const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>*> >, std::__not_<std::is_convertible<const _Tp&, const _CharT*> > >::value, _Res> [with _Tp = int; _Res = void; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
/usr/include/c++/13/bits/basic_string.h:792:30: required from here
/usr/include/c++/13/type_traits:2610:11: error: no type named 'type' in 'struct std::enable_if<false, void>'
2610 | using enable_if_t = typename enable_if<_Cond, _Tp>::type;
| ^~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:783:9: note: candidate: 'template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, size_type, size_type, const _Alloc&) [with <template-parameter-2-2> = _Tp; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
783 | basic_string(const _Tp& __t, size_type __pos, size_type __n,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:783:9: note: template argument deduction/substitution failed:
main.cpp:9:30: note: candidate expects 4 arguments, 2 provided
9 | cout << string(i, "*") << "\n";
| ^
/usr/include/c++/13/bits/basic_string.h:760:9: note: candidate: 'template<class _InputIterator, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(_InputIterator, _InputIterator, const _Alloc&) [with <template-parameter-2-2> = _InputIterator; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
760 | basic_string(_InputIterator __beg, _InputIterator __end,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:760:9: note: template argument deduction/substitution failed:
main.cpp:9:30: note: deduced conflicting types for parameter '_InputIterator' ('int' and 'const char*')
9 | cout << string(i, "*") << "\n";
| ^
/usr/include/c++/13/bits/basic_string.h:664:7: note: candidate: 'template<class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(size_type, _CharT, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
664 | basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc())
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:664:7: note: template argument deduction/substitution failed:
main.cpp:9:27: note: cannot convert '"*"' (type 'const char [2]') to type 'char'
9 | cout << string(i, "*") << "\n";
| ^~~
/usr/include/c++/13/bits/basic_string.h:641:7: note: candidate: 'template<class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
641 | basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:641:7: note: template argument deduction/substitution failed:
main.cpp:9:24: note: cannot convert 'i' (type 'int') to type 'const char*'
9 | cout << string(i, "*") << "\n";
| ^
/usr/include/c++/13/bits/basic_string.h:716:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&&, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
716 | basic_string(basic_string&& __str, const _Alloc& __a)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:716:35: note: no known conversion for argument 1 from 'int' to 'std::__cxx11::basic_string<char>&&'
716 | basic_string(basic_string&& __str, const _Alloc& __a)
| ~~~~~~~~~~~~~~~^~~~~
/usr/include/c++/13/bits/basic_string.h:711:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
711 | basic_string(const basic_string& __str, const _Alloc& __a)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:711:40: note: no known conversion for argument 1 from 'int' to 'const std::__cxx11::basic_string<char>&'
711 | basic_string(const basic_string& __str, const _Alloc& __a)
| ~~~~~~~~~~~~~~~~~~~~^~~~~
/usr/include/c++/13/bits/basic_string.h:706:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::initializer_list<_Tp>, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
706 | basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc())
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:706:45: note: no known conversion for argument 1 from 'int' to 'std::initializer_list<char>'
706 | basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc())
| ~~~~~~~~~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/13/bits/basic_string.h:677:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
677 | basic_string(basic_string&& __str) noexcept
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:677:7: note: candidate expects 1 argument, 2 provided
/usr/include/c++/13/bits/basic_string.h:599:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, size_type, size_type, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; size_type = long unsigned int]'
599 | basic_string(const basic_string& __str, size_type __pos,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:599:7: note: candidate expects 4 arguments, 2 provided
/usr/include/c++/13/bits/basic_string.h:581:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, size_type, size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; size_type = long unsigned int]'
581 | basic_string(const basic_string& __str, size_type __pos,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:581:7: note: candidate expects 3 arguments, 2 provided
/usr/include/c++/13/bits/basic_string.h:564:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, size_type, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; size_type = long unsigned int]'
564 | basic_string(const basic_string& __str, size_type __pos,
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:564:40: note: no known conversion for argument 1 from 'int' to 'const std::__cxx11::basic_string<char>&'
564 | basic_string(const basic_string& __str, size_type __pos,
| ~~~~~~~~~~~~~~~~~~~~^~~~~
/usr/include/c++/13/bits/basic_string.h:547:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
547 | basic_string(const basic_string& __str)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:547:7: note: candidate expects 1 argument, 2 provided
/usr/include/c++/13/bits/basic_string.h:535:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
535 | basic_string(const _Alloc& __a) _GLIBCXX_NOEXCEPT
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:535:7: note: candidate expects 1 argument, 2 provided
/usr/include/c++/13/bits/basic_string.h:522:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
522 | basic_string()
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:522:7: note: candidate expects 0 arguments, 2 provided
/usr/include/c++/13/bits/basic_string.h:176:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(__sv_wrapper, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
176 | basic_string(__sv_wrapper __svw, const _Alloc& __a)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/basic_string.h:176:33: note: no known conversion for argument 1 from 'int' to 'std::__cxx11::basic_string<char>::__sv_wrapper'
176 | basic_string(__sv_wrapper __svw, const _Alloc& __a)
| ~~~~~~~~~~~~~^~~~~
(g++ also prints several "candidate" notes after this; the first error line is the one to read.)
Your turn: Floyd's triangle (solution)
Row i has i numbers and the counting never restarts. Keep one counter outside both loops, and use setw(4) so two-digit numbers stay in line.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n;
int k = 1; // one counter, outside both loops
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << setw(4) << k++;
cout << "\n";
}
return 0;
}
Input 4:
1
2 3
4 5 6
7 8 9 10
Input 5:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time O(n²), extra space O(1).
Practice questions (with solutions)
1. Inverted star triangle. Row 1 has n stars, the last row has 1.
Solution
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = n; i >= 1; i--) { // rows count down
for (int j = 1; j <= i; j++)
cout << "*";
cout << "\n";
}
return 0;
}
Input 4:
****
***
**
*
2. Diamond of stars for odd n. The middle row has n stars. Plan: the distance d of row i from the middle row gives d spaces and n - 2d stars.
Solution
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
int n;
cin >> n;
if (n < 1 || n % 2 == 0) {
cout << "n must be odd and positive\n";
return 0;
}
int mid = n / 2;
for (int i = 0; i < n; i++) {
int d = abs(mid - i); // distance from the middle row
cout << string(d, ' ') << string(n - 2 * d, '*') << "\n";
}
return 0;
}
Input 5:
*
***
*****
***
*
Input 4:
n must be odd and positive
3. Hollow right-angle triangle. Stars on the first column, the diagonal and the last row.
Solution
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
// border: first column, the diagonal (j == i), or the last row
if (j == 1 || j == i || i == n) cout << "*";
else cout << " ";
}
cout << "\n";
}
return 0;
}
Input 5:
*
**
* *
* *
*****
Mini project: a pattern menu
Read pairs choice n until the input ends: 1 = triangle, 2 = pyramid, 3 = hollow square. Each pattern is its own function.
#include <iostream>
#include <string>
using namespace std;
void triangle(int n) {
for (int i = 1; i <= n; i++) cout << string(i, '*') << "\n";
}
void pyramid(int n) {
for (int i = 1; i <= n; i++) {
cout << string(n - i, ' ');
for (int j = 1; j <= i; j++) cout << j;
for (int j = i - 1; j >= 1; j--) cout << j;
cout << "\n";
}
}
void hollow(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cout << ((i == 1 || i == n || j == 1 || j == n) ? '*' : ' ');
cout << "\n";
}
}
int main() {
int choice, n;
while (cin >> choice >> n) {
if (n < 1 || n > 9) { cout << "n must be 1 to 9\n"; continue; }
if (choice == 1) triangle(n);
else if (choice == 2) pyramid(n);
else if (choice == 3) hollow(n);
else cout << "choose 1, 2 or 3\n";
cout << "--\n";
}
return 0;
}
Input 1 3 / 2 3 / 3 4 / 4 2 / 2 12:
*
**
***
--
1
121
12321
--
****
* *
* *
****
--
choose 1, 2 or 3
--
n must be 1 to 9
Quick quiz
#include <iostream>
using namespace std;
int main() {
int n = 4, count = 0;
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j++)
count++;
cout << count << "\n";
return 0;
}
(A) 10 (B) 16 (C) 6 (D) 4
Answer
(A) 10. j starts at i: row 1 runs 4 times, row 2 runs 3, row 3 runs 2, row 4 runs 1. 4 + 3 + 2 + 1 = 10.
Output:
10
Interview questions
- How do you approach any pattern question? Count the rows (outer loop), decide what row
iprints and how many of each (inner loops), end the line after the inner loops, and check with a table for smalln. - Difference between
endland"\n"? Both start a new line;endlalso flushes the stream, which is slower in loops. - What is an off-by-one error? A loop that runs one time too many or too few, like
j < iinstead ofj <= i. Test the first and the last turn. - What does
setwdo, and how long does it last? It sets the width of the next item printed (padding on the left by default); it resets after one item. - Time complexity of printing an n × n pattern? O(n²): there are n² characters to print.
- Why is
if (x = 5)dangerous? It assigns 5 and is always true; with-Wall, g++ warns "suggest parentheses around assignment used as truth value". In our square,a || b = nwas a hard error instead. - What is an lvalue? Something with a place in memory that can be assigned to, such as a variable.
- How would you print a pattern without nested loops? Build each row as a string, for example
string(i, '*'), or withsetw.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Pattern question | Print a shape made of characters | a star triangle |
| Nested loop | A loop inside another loop | rows × columns |
| Outer loop | The loop that runs once per row | for (int i = 1; i <= n; i++) |
| Inner loop | The loop that prints the characters of one row | for (int j = 1; j <= i; j++) |
endl |
New line and flush | cout << endl; |
"\n" |
New line only | cout << "\n"; |
| Flush | Pushing buffered output out to the screen right away | endl flushes |
| Off-by-one error | A loop that runs one time too many or too few | j < i instead of j <= i |
| Fence-post problem | The classic off-by-one puzzle: posts vs gaps | a 4 m fence needs 5 posts |
| Plan table | A small table of rows vs counts used to find formulas | spaces = n - i |
string(k, c) |
A string of k copies of the character c |
string(3, '*') is "***" |
setw(w) |
Print the next item w characters wide, padded on the left |
setw(4) << 7 prints 7 |
<iomanip> |
The header that has setw |
#include <iomanip> |
| Right alignment | Text pushed to the right edge of its field | setw |
| Input validation | Checking the input is in the allowed range | if (n < 1 \|\| n > 9) |
\|\| (or) |
True if at least one side is true | i == 1 \|\| j == 1 |
= vs == |
Assignment vs comparison | j == n compares |
| lvalue | Something with a place in memory that can be assigned to | a variable |
| Compilation error | g++ refuses to build the program | lvalue required |
| Edge case | A small or extreme input that often breaks code | n = 0, n = 1 |
| Time complexity | How the work grows with the input | O(n²) |
| Space complexity | How the extra memory grows with the input | O(1) |
| O(n²) | Work grows with n × n: double n, about 4× the work | an n × n square |
| O(1) | A fixed amount, whatever n is | three int variables |
| Floyd's triangle | Rows of consecutive numbers: 1 / 2 3 / 4 5 6 | the "your turn" question |
Summary
- Plan every pattern as rows (outer loop) and characters (inner loops), and end the line after the inner loops.
endlinside the inner loop puts every star on its own line; prefer"\n"in loops.j < ivsj <= i: test the first and last turn of every loop (off-by-one errors give no error message).- Write the plan table first: the pyramid needs
n - ispaces; validate the input range when wider numbers would break the shape. - A border has four sides;
=in a condition giveslvalue required as left operand of assignment. - C++ shortcuts:
string(i, '*')andsetw(n). All three patterns are O(n²) time.
Next episode: Number questions I: reverse a number, palindrome number and sum of digits, with negative numbers and the overflow trap.