Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   using loops to print half_diamond (http://www.go4expert.com/forums/using-loops-print-halfdiamond-t19745/)

waqasanjum86 12Oct2009 14:36

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()
{
int row,column,limit=4;// limit is the maximum no of stars to be printed before //decrementing stars
row=1;

for(;row<=limit;row++) //This loop will run 4 times
{
  for(column=1;column<=row;column++)//this loop will prnt stars
  cout<<"*";

cout<<endl;

  if (column==(limit+1)) //To check when stars will be decremented
  {
    int i=limit-1;
    for(;i > 0;i--)
    {
        for(int j=1;j<=(limit-1);j++)
        cout<<"*";

    cout<<endl;
    limit--;
    }
  }

}

return 0;
}


xpi0t0s 13Oct2009 12:55

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;

for (int row=??; ??; ??)
{
  int numStars=??;
  for (int i=??; ??; ??)
  {
    cout<<"*";
  }
  cout<<endl;
}

So the way ahead is to find appropriate values for ??.
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.

xpi0t0s 13Oct2009 13:03

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;

for (int star=??; ??; ??)
{
  cout<<"*";
  if (??)
    cout<<endl;
}

So what this does is to print stars in a single loop, and the if statement just works out where to place the line breaks.

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 21:57.