• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 281
  • Last Modified:

while loop

I am trying to solve this problem :

*****
*****
*****
*****
*****

and another one should look like this :
*****
*    *
*    *
*    *
*****

This is what i am trying but getting only this result :
*****
*
*
*
*

Please help me out with this:
#include<iostream>
using namespace std;

int main()
{

int i=0;
while (i<4)
{
cout<<'*';
i++;
}
int j=0;
while (j<5)
{
cout<<'*';
j++;
cout<<endl;
i++;
}
return 0;
}
0
shahedny
Asked:
shahedny
  • 12
  • 10
  • 3
  • +4
1 Solution
 
sunnycoderCommented:
I would have expected you to get

****
*****

You are basically setting up two loos - 0 to 3 and 0 to 4 and printing * in each iteration

For
*****
*****
*****
*****
*****
You need two nested loops each from 0 to 4. Outer loop would be responsible for printing a line and inner loop will print the *

nested loops means loop within loop ... something like

while (...)
{
     while(...)
     {
        ....
     }
}
0
 
sstone55423Commented:
Nest your i loop (while) inside the j loop, not sequentially.
0
 
sstone55423Commented:
I would  type it out, but then, is it ethical for us to do your homework for you?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
shahednyAuthor Commented:
ofcourse it is not.Let me try what you have just said and see if i can do this.
0
 
silemoneCommented:
i had to figure this one out...i even still have the solution because it was a homework assignment for me...lol...but my solution was in java...but since i know c++, the looping in java and c++ are the same...what part are you having trouble with?  we can't give direct solutions for homework...
0
 
shahednyAuthor Commented:
i am having problem with the nested loop. i am only getting till this part
*****
*
*
*
*
0
 
shahednyAuthor Commented:
i have wrote this-
#include<iostream>
using namespace std;
         
int main()
         
{
        int i=0;
        int j=0;  
        while (i<4)
        {
        cout<<'*';
        i++;
        }
        while (j<5)
        {
        cout<<'*';
        j++;
        cout<<endl;
        i++;
        }
return 0;
}

---Where is my mistake?please tell me as i am not getting this-
*****
*****
*****
*****
*****
0
 
sunnycoderCommented:
You did not nest the loops ... Nesting means one loop within another


while (...)
{
     while(...) // This while begins before the previous while has ended
     {
        ....
     }
}

Open in new window

0
 
shahednyAuthor Commented:
i tried nesting the loop the way you said it-
#include<iostream>
using namespace std;
       
int main()
       
{
        int i=0;  
        int j=0;
        while (i<4)
        {
        cout<<'*';
        i++;
        while (j<5)
        {
        cout<<'*';
        j++;
        cout<<endl;
        i++;
        }
}
return 0;
}
__it is giving me only one line
*
*
*
*
*

0
 
sunnycoderCommented:
PLs set the indentation right ... it makes the code readable

int main()
{
        int i=0;  
        int j=0;
        while (i<4)
        {
            cout<<'*'; //you want to print * in the inner loop - Inner loop is supposed to print *, outer loop is supposed to print newlines. Basically outer loop moves you to different lines.
            i++;  //remove this. Generally loop counters are incremented towards end of the loop.
            while (j<5)
            {
                cout<<'*';
                j++;
                cout<<endl; // this needs to be part of outer loop - near end of it
                i++; //why are you incrementing i here? Increment it at the end of outer loop
            }
        }
        return 0;
}

Open in new window

0
 
shahednyAuthor Commented:
my code looks like this now-
#include<iostream>
using namespace std;
int main()
{
        int i=0;
        int j=0;
        while (i<4)
        {
            cout<<endl;

            while (j<5)
            {
                cout<<'*';
                j++;

            }
        cout<<endl;
        i++;
        }
return 0;
}
--- this code generates this result
****
##What am i doing wrong?
             
0
 
sunnycoderCommented:
Reset j in outer loop ... basically once the value of j has reached 5 in the inner loop, it stays at 5 and inner loop never runs again. Hence you see only one line of *. You need to reset it to 0 to print * in subsequent lines. Move the j=0 to inside the outer loop.
Also you have two endl being printed in inner loop. You would need only one. Delete the first one.
0
 
CSecurityCommented:
I think 3 years ago I coded this and maybe can help you
works as you want and  it is dynamic ;)
<code removed by sunnycoder>

Open in new window

0
 
CSecurityCommented:
I know agreement and help pages, I wasn't aware it's homework.... Just that... Not needed to go so far
0
 
CSecurityCommented:
Not needed, it's ok
0
 
shahednyAuthor Commented:
excellent bro.i got the first part which is
*****
*****
*****
*****
*****
but now i need to do it like this
*****
*    *
*    *
*    *
*****
this is the code i have put in-

#include<iostream>
using namespace std;
int main()
{
        int i=0;
       while (i<5)

        {
        int j=0;
                while (j<5)
                {
                cout<<'*';
                j++;
                }
                cout<<endl;
                i++;
                }

        while (j<5)
    {
        if (j==1)||(j==5);
        cout<<'*';
        else
        cout<<" ";
        j++;
        }
        return 0;
}
__but this is giving me this error-
123.cpp: In function `int main()':
123.cpp:18: error: `j' was not declared in this scope
123.cpp:21: error: expected primary-expression before '||' token
123.cpp:23: error: expected primary-expression before "else"
123.cpp:23: error: expected `;' before "else"
0
 
sunnycoderCommented:
Pls get the indentation right. When you declare a variable, its scope/visibility is limited to the pair of braces that enclose it ... Here you declared j inside a while loop - so it is limited in scope to this loop. You cannot use it the second while loop.
If you need to use a variable in both the loops, declare it before first loop.

Code for second output would similar to first one except that instead of printing all * in all lines, you need to print only the first and last * in all but first and last lines :-)
0
 
shahednyAuthor Commented:
now i tried this-
#include<iostream>
using namespace std;
int main()
{
        int i=0;
       while (i<5)
        {
        int j=0;
                while (j<5)
                {
                cout<<'*';
                j++;
                }
                cout<<endl;
                i++;

        //int j=0;
        j=0;
        while (j<5)
    {
        if
        ((j==0)||(j==5))
        cout<<'*';
        else
        cout<<" ";
        j++;
        }  
        }
    return 0;
}
     this is giving me this picture-
*****
*    *****
*    *****
*    *****
*    *****



0
 
sunnycoderCommented:
your current code organization is
while()
{
    while()
    {
    }
     while()
     {
     }
}

What you need is
while()
{
    while()
    {
    }
}
while()
{
    while()
    {
    }
}

Get your code indentation right. It is a strain to read unindented code.
0
 
peprCommented:
As sunnycoder asked repeatedly, PLEASE DO SOMETHING WITH YOUR INDENTATION. You may think that it is not important. However, you will not make the things clear in your head if they do not cry to you from the source code.  This is important especially for beginners. After that, you will see your errors. Put some short comments to the end of important lines.

Use 4 spaces for each indentation level or use some decent editor which supports automatic indentation for C++.
0
 
peprCommented:
Well, sunnycoder asked again :)) Do listen to him. The indentation is one of the things that makes or readable or obscure code.
0
 
shahednyAuthor Commented:
i thought there is only 3 while loop :(
where am i going to get the 4th one
0
 
shahednyAuthor Commented:
This is what i have now -

#include<iostream>
using namespace std;
int main()  
{
       
         int i=0;
         while (i<5)
         {
         int j=0;
         while (j<5)
         {
         cout<<'*';
         j++;
         }
         cout<<endl;
         i++;

                while (j<5)
                {
                if
                ((j==0)||(j==5))
                cout<<'*';
                else
                cout<<" ";
                j++;}
                }

        return 0;
}

But no change in result --
*****
*****
*****
*****
*****
stays the same
0
 
sunnycoderCommented:
solution to 2nd problem is structured exactly like the first one.
So you have the outer loop that handles lines and inner loop that handles printing *
0
 
sunnycoderCommented:
In this code, third loop never gets executed - by the time control reaches third loop, value of j is 5.

Use the exactly same loop setup that you used for first problem. Only printing of * is different and you already have that "nearly" right ;-) ... nearly because your loop condition is j<5 and inside loop you have a check for j == 5.
0
 
shahednyAuthor Commented:
so on second loop instead of J<5 i should put ((j==0)||j==5)) ??
0
 
sunnycoderCommented:
loop condition is correct .. it is the if check that needs to be modified. Value of j can never b 5 inside the loop. It is controlled by the loop and will range from 0 to 4.
0
 
sunnycoderCommented:
It will be good practice if you start dry running your code .. i.e. sit with a pen and paper and trace the execution of the program by hand. This will give you clarity about role and impact of each statement.
0
 
shahednyAuthor Commented:
where exactly is the problem?because i am tired of trying hundreds of ways
    while (j<5)  //here??
                {
                if
                ((j==0)||(j==5))    //or here??
                cout<<'*';
                else
                cout<<" ";
                j++;}
                }
0
 
Infinity08Commented:
>> because i am tired of trying hundreds of ways

May I offer a small bit of advice ? Instead of trying/guessing, try to understand what is going on in the code. Follow what the code does step by step (for every iteration of every loop), draw the output on a piece of paper. And you'll find it a lot easier to modify the code to do what you want.

Remember that a large part of writing code is thinking about what you will write (how you'll solve the problem, and how that solution can be expressed in code). Actually writing the code should come last (once you've figured it all out).
0
 
shahednyAuthor Commented:
hmm other people are also telling me that but i get even more confused that way :(
0
 
Infinity08Commented:
>> but i get even more confused that way :(

Just take your time for it. Take things one step at a time - rushing things causes confusion.
0
 
peprCommented:
It often help with solving such a  problem to approach it "as if you were doing it on paper with pencil in your hand". In other words, you will not solve it programmatically if you cannot find regularities in the process when doing it by hand.

Say you want to do draw

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

You probably do it line by line by writing the numerals one by one, right? Now, the regularity is "start at the first line, write the 1, move to the next position, write 2, etc.; now next line, write 1, ...; write so much lines that you need.

In the terms of programming: writing the line which length is prescribed by some value means "loop i times and write the numeral and move to the next position; write the end of line". And writing the j lines means "loop j times and write the line (using the above loop).

In your case, you or replace all the numerals by the stars (the filled rectangle) or you write stars for all 1's and 5's  and for all positions on the first line and the last line.

Now, as Infinity08 said ... one simple step at a time.

1) A program that displays one star (simple, you know it).
2) Add the loop to the 1) that writes n stars plus the end of line.
3) Modify the previous step so that you write the star only at the first and last positions by adding some test and writing star and space alternatively.
4) Modify the 3) so that you enhance the test by adding condition on j (to add stars for all positions for the first and last line). Just assign the j in front of the single loop you wrote so far -- test if you know how to write one line.

Now you know how to write whatever line. The last simple step is...

5) Write the outer loop through j. (Now you do not fill the j by assigning explicitly in front of your i-loop. It will be filled by the outer loop.

You have done all of the steps. However, you did not combine them well. Having this in your mind, try to find what the steps in your older solution are bad, strange, misplaced...
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 12
  • 10
  • 3
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now