I've just started learning C++ and I decided to make a program that asks user for a length of a triangle's side and then draws the triangle with asterisks. This is what program looks like when executed:
Define number of signs per side of a triangle. To exit the program, enter 0.
Number of signs: 4
*
* *
* * *
* * * *
Number of signs: 2
*
* *
etc...
I want to know if there's more convenient way of doing this, using other loop types, a break... I'm here to learn, so any suggestions and corrections are more than welcome!
#include <iostream>
usingnamespace std;
int main() {
int num=1, line, sign;
cout << "Define number of signs per side of a triangle. To exit the program, enter 0.\n";
while (num != 0) { //This loop will repeat until user enters 0.
cout << "\nNumber of signs: "; cin >> num; cout << "\n";
//Line's number will decrease until 0, because number of empty spaces decreases.
for (line = num; line != 0; line--) {
sign = 1;
//The following loop will output empty spaces until line's number is reached.
for (;sign < line; sign++) cout << " ";
sign = num;
//The following loop will output asterisks until sign number decreases to line's number.
for (;sign >= line; sign--) {
if (sign > line) cout << " *";
//Outputs last asterisk and goes to new line when number of signs equals line number.
else cout << " *\n";
}
}
}
return 0;
}