Solved

while loop

Posted on 2008-09-29
35
266 Views
Last Modified: 2010-07-27
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
Comment
Question by:shahedny
  • 12
  • 10
  • 3
  • +4
35 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22602508
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
 
LVL 8

Expert Comment

by:sstone55423
ID: 22602509
Nest your i loop (while) inside the j loop, not sequentially.
0
 
LVL 8

Expert Comment

by:sstone55423
ID: 22602510
I would  type it out, but then, is it ethical for us to do your homework for you?
0
 

Author Comment

by:shahedny
ID: 22602568
ofcourse it is not.Let me try what you have just said and see if i can do this.
0
 
LVL 21

Expert Comment

by:silemone
ID: 22602664
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
 

Author Comment

by:shahedny
ID: 22602697
i am having problem with the nested loop. i am only getting till this part
*****
*
*
*
*
0
 

Author Comment

by:shahedny
ID: 22602712
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22602737
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
 

Author Comment

by:shahedny
ID: 22602796
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22602876
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
 

Author Comment

by:shahedny
ID: 22602949
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
 
LVL 45

Accepted Solution

by:
sunnycoder earned 500 total points
ID: 22602957
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
 
LVL 17

Expert Comment

by:CSecurity
ID: 22605085
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
 
LVL 17

Expert Comment

by:CSecurity
ID: 22605363
I know agreement and help pages, I wasn't aware it's homework.... Just that... Not needed to go so far
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 22605466
Not needed, it's ok
0
 

Author Comment

by:shahedny
ID: 22606646
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 45

Expert Comment

by:sunnycoder
ID: 22606706
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
 

Author Comment

by:shahedny
ID: 22606816
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22606882
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
 
LVL 28

Expert Comment

by:pepr
ID: 22606964
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
 
LVL 28

Expert Comment

by:pepr
ID: 22607002
Well, sunnycoder asked again :)) Do listen to him. The indentation is one of the things that makes or readable or obscure code.
0
 

Author Comment

by:shahedny
ID: 22607290
i thought there is only 3 while loop :(
where am i going to get the 4th one
0
 

Author Comment

by:shahedny
ID: 22607318
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22607327
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22607356
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
 

Author Comment

by:shahedny
ID: 22607399
so on second loop instead of J<5 i should put ((j==0)||j==5)) ??
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22607472
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 22607517
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
 

Author Comment

by:shahedny
ID: 22608213
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
 
LVL 53

Expert Comment

by:Infinity08
ID: 22608496
>> 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
 

Author Comment

by:shahedny
ID: 22608780
hmm other people are also telling me that but i get even more confused that way :(
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 22608816
>> 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
 
LVL 28

Expert Comment

by:pepr
ID: 22612598
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
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 learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

705 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

18 Experts available now in Live!

Get 1:1 Help Now