patterncppMinor
Printing stars using nested loops
Viewed 0 times
loopsnestedprintingstarsusing
Problem
I just got back from my interview where I had to solve the following problem:
Write a C++ program that prints the following pattern using nested
Here is my solution:
I'm just curious to know if there are better solutions (any criteria for better) or just different approaches.
Write a C++ program that prints the following pattern using nested
for loops.*
***
*****
***
*Here is my solution:
int inc = 2;
for (int i = 1; i >= 1; i += inc){
for (int j = 0; j < i; j++ )
std::cout<<'*';
std::cout<<endl;
if ( i == 5 )
inc = -2;
}I'm just curious to know if there are better solutions (any criteria for better) or just different approaches.
Solution
Edit Oh well, not using nested for... Sorry about that
int inc = 2;
for (int i = 1; i >= 1; i += inc){
std::cout<<std::string(i,'*')<<endl;
if ( i == 5 )
inc = -2;
}Code Snippets
int inc = 2;
for (int i = 1; i >= 1; i += inc){
std::cout<<std::string(i,'*')<<endl;
if ( i == 5 )
inc = -2;
}Context
StackExchange Code Review Q#12465, answer score: 8
Revisions (0)
No revisions yet.