![]() |
using loops to print half_diamond
I am beginner in C++.I write the code to print half diamond.
* ** *** **** *** ** * My Code is given below.I want your suggestion regarding code logic,No of loops used(i used 4).Or how can i further simplify keeping in mind that the concept of efficient coding. Code:
int main() |
Re: using loops to print half_diamond
You can do it with just two loops, if you can fill in the blanks in the following:
Code:
int limit=4;Essentially this depends on calculating numStars from row and limit so that numStars has the values 1,2,3,4,3,2,1. Ideally what you should aim at is to figure out the row for-loop and numStars expression to work off any limit value, so you could just change limit to 8 (and make no other changes) to get the size-8 half diamond, i.e. 1,2,3,4,5,6,7,8,7,6,5,4,3,2,1. |
Re: using loops to print half_diamond
Also you could do it with just one for loop: if you can calculate the total number of stars from limit, and where to place line breaks, you could do something like:
Code:
int limit=4;But it depends what your goal is. You mention number of for loops and efficiency, but what is your definition of efficiency - is it having the least number of for loops, or is it displaying the pattern in the smallest time? Generally you can make code faster OR smaller, but not both, and part of software engineering is determining where to make the trade-off. So if your goal is minimum time, this example probably isn't very good because the if expression is recalculated every time round the loop, whereas if you use more, simpler code then it can zip through that more quickly. |
| All times are GMT +5.5. The time now is 06:04. |