Solved

Nested Loop

Posted on 2001-08-01
14
2,010 Views
Last Modified: 2011-09-20
#include<iostream.h>
#define VIEW '*'
main()

{     int i,j,k;
     for(i=1; i<=6; i++)
     {
          for (j=1; j<=6-i; j++)
               cout<<" ";
          for (k=1; k<=2*i-1; k++)
               cout<<VIEW;
               cout<<"\n";
     }
return 0;

}

I need to understand this program. Basically the result will appear as pyramid. But how does this program work. I need to know. Can someone explain in depth???

0
Comment
Question by:chwankok
  • 4
  • 3
  • 3
  • +3
14 Comments
 
LVL 4

Accepted Solution

by:
IainHere earned 10 total points
Comment Utility
cout << "X";

displays X on the screen.  In this program, there are spaces, stars and newlines being written, in order to build up the pattern you see.  

for(i=1; i<=6 ; i++)
{
...
}

starts off by making i=1, and goes through each of the instructions between { and }.  Then it increases i by one [i++], and continues until i is greater than 6.  From those instructions you should be able to follow through what happens and why the pattern is produced.

A couple of points: the main() function in a C++ program must return an int.  The '\n' is a newline character (makes the following stuff appear on the next line), and should be replaced with endl.  

#define VIEW '*' would be better written as
const char VIEW('*');

#include <iostream.h> is an old version of that header (not guaranteed to exist in C++ in the future), and you should always use
#include <iostream>
which puts everything in the std namespace:

#include<iostream>
const char VIEW('*');

int main()
{    
int i,j,k;
    for(i=1; i<=6; i++)
    {
         for (j=1; j<=6-i; j++)
              std::cout<<" ";
         for (k=1; k<=2*i-1; k++)
              std::cout<<VIEW;
              std::cout<<endl;
    }
return 0;
}
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
This is at least a 50 point question....
0
 
LVL 4

Expert Comment

by:IainHere
Comment Utility
In the other for(;;) loops, because they don't have { } enclosing the following statements, it is only the next statement that is carried out by the loop.

for (k=1; k<=2*i-1; k++)
             std::cout<<VIEW;
             std::cout<<endl;

is therefore the same as

for (k=1; k<=2*i-1; k++)
{
       std::cout<<VIEW;
}
std::cout<<endl;

0
 
LVL 6

Expert Comment

by:Triskelion
Comment Utility
lainHere is correct, adding the braces in the proper places will help a lot (for clarity) even though the are not absolutely necessary.
Example:
int main(void) /* main function declaration */
{
     int i,j,k;/*the counters are defined here*/
     for(i=1; i<=6; i++)/*count number of rows*/
          {
          for (j=1; j<=6-i; j++)/*number of spaces before the star*/
               {/*loops 5 times, then 4 then 3, etc*/
         cout<<" ";/*prints a space*/
               }
          for (k=1; k<=2*i-1; k++)
               {
               cout<<VIEW; /* prints the star */
               }
          cout<<"\n"; /* prints a carriage return */
          }
     return 0;/* satisfy the return value type of int for main()*/
}
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
Hi chwankok,

nietod is right.  This is at least a 50 point question.
Furthermore, I see you have the following grading record:

C A A B A C B C C A

This is a poor grading record.

If you don't have that many points, many experts would still be glad to help you, if they see that you have a good grading record.

When you have a bad grading records, some experts will not help you even if you assign adequate points to the question.

Usually an 'A' grade is given to most questions, unless the expert does not make an honest effort to help you.

Remember that these experts do not get paid for helping you.  The least that you can do to show your gratitude is to give them a decent grade.

Please be considerate of the experts who are trying to help you, and give them the grades that they deserve.

Thank you
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
0
 
LVL 1

Expert Comment

by:The_Brain
Comment Utility
Well if you ask me he's no older than 14/15 by the looks of his question.  Give him a break -_-

anyway, the thing is simply saying

#include<iostream.h>   //includes input output streams
#define VIEW '*'       //defines VIEW as character *
void main()                 //main procedure
                // (don't forget to say void!!!!! one day you might use int or something for multithreading @.@)
{                          //opening brace so that the compiler knows where to start
                           //it NEEDS NEEDS an opposing brace to signify the end of the body    
 int i,j,k;                //defines variables i j k as integers
    for(i=1; i<=6; i++)    // for loop.  starts i=1 every loop, i increases by 1, (i++ is short for i= i+1)
    {                      //another opening brace for a new body namely the loop
         for (j=1; j<=6-i; j++)   //another for loop, j=1 and increments to till 6-i
              cout<<" ";          //outputs a 'space'
         for (k=1; k<=2*i-1; k++) // another for loop
              cout<<VIEW;         // outputs * remember #define?
              cout<<"\n";         // outputs line break. "\n" moves to next line
    }                             //oposing brace of the first Loop
return 0;                         //not REALLY REALLY needed but extremely good practice to return 0 to a void procedure

}                                 //I'd keep you guessing but this is the main's closing brace :)


now what this loop means


  for(int i=1; i<=6; i++)  //this will loop what EVER IS IN THE BRACES of this LOOP -- 6 times!!
      {  //beginning of the 6 loop
         for (j=1; j<6-i; j++)   this loop in the FIRST time it goes here (when i=1) it will loop 6-1 times (5 for the mathematically challenged)  so it's gonna output 5 spaces =)
cout<<" ";
       }
   next after that loop happened 5 times, this one happens
       for(k=1; k<2*i-1; k++)
         cout<<"*";   //remebmer it's still when i=1 so, this will loop from 1 -> 2*i - 1 ( 1 -> 1)
hence it's gonna only run ONCE and leave
//        so guess what, only gonna output ONE *
          NEXT LINE IS IMPORTANT!!!!!!!!!!! it's NOT NOT NOT NOT NOT NOT PART of the last loop... SO SO many ppl make this mistake! :.(

for EVERYLOOP in GOOD practice say   for(i=something; condition here; increment here)
                                       { <---- ALWAYS even just one line, because ONE day you're gonna add something to your loop where there was only one line, and it's NOT gonna work and you're gonna wonder why, and spend 5 more points askin why  =P lol

and the line break is not part of that last loop and puts a break.


The 'i' Loop runs again the MAIN loop.  And i = 2;  here's a hint, STEP through your code, I hope this helps :p
it took enough time to type this lol ;p
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 4

Expert Comment

by:IainHere
Comment Utility
The only thing still bothering me is the meaning of these:

@.@
=)
:.(
=P
lol
;p

>>don't forget to say void!!!!!
Surely you mean int?  The standard says int, and sooner or later someone will rely on your program (OK, probably not this one) returning something, and that will cause corruption or confusion.  And you might even find a compiler enforcing it.
0
 

Author Comment

by:chwankok
Comment Utility
Axter, i have awarded those questions you listed.
Many thanks to IainHere, The_Brain  and Triskelion. Basicailly, i knew the program how it works. As Triskelion highlighted the bracket is important. i have another question

After the First For Loop there is a bracket. What is the use of bracket after the First for Loop. Another word, before the 2nd for loop. It know i will affect this program without this open bracket and close bracket.
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
the for and while statemetns cause only the next statement after the loop to be executed as part of the loop.  for example

for(i=1; i<=6; i++)
   cout << i;  // this statement is part of the loop.
   cout << endl;  // this statement is not part of the loop.

Note how the first cout statement is part of the loop, since it is right after the condition.  But the 2nd statement is NOT part of the loop.  That "endl" executes only one time  , not 6 times.   The fact that the 2nd cout is indetned is missleading.  it really should be

for(i=1; i<=6; i++)
   cout << i;  // this statement is part of the loop.
cout << endl;  // this statement is not part of the loop.


But what if you have 2 statements you do what to be p[art of the loop?  Well, then you need to make them into one statement.  The { }s do that.  for example

for(i=1; i<=6; i++)
{
   cout << i;  // this statement is part of the loop.
   cout << endl;  // this statement IS part of the loop.
}
0
 
LVL 4

Expert Comment

by:IainHere
Comment Utility
chwankok,

I don't mean to grumble, but I did answer that very question in my second post.

<tries not to cry>
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
...and a few more things.  for 5 points.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
>>Axter, i have awarded those questions you listed.
Thank you
0
 

Author Comment

by:chwankok
Comment Utility
Thank you guys !!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now