Jul 4, 2013 at 10:06am Jul 4, 2013 at 10:06am UTC
Hello guys,
I would like your help with a basic thing, repeating characters.
For example the program should display:
1
22
333
4444.
I can use a for loop to make it display the first and the after the loop, I increment the value.
Then,execute a loop again, but this time it should give 1 more character than the previous one. This is the part I'm stuck with.
Please don't write the code if possible just explain and I'll write it otherwise I won't learn anything. If I get stuck I'll come back.
Thanks :)
Jul 4, 2013 at 10:21am Jul 4, 2013 at 10:21am UTC
You could use the value that you increment, in the loop condition to decide how many times the loop should run.
Jul 4, 2013 at 10:22am Jul 4, 2013 at 10:22am UTC
Ir sounds like a case where nested loops could be useful.
That is, put a for-loop contained within another for loop. The important part is how the inner loop can be made dependent on the variable which is controlling the outer loop.
Jul 4, 2013 at 10:24am Jul 4, 2013 at 10:24am UTC
Thanks guys, I'll try it and post back. :)
Jul 4, 2013 at 10:39am Jul 4, 2013 at 10:39am UTC
I am showing the code because I doubt that you are able to write the same code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <iomanip>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0 - exit): " ;
size_t n = 0;
std::cin >> n;
if ( !n ) break ;
std::cout << std::endl;
for ( size_t i = 1; i <= n; i++ )
{
std::cout << std::setw( i + 1 ) << std::setfill( char ( i % 10 + '0' ) ) << '\n' ;
}
std::cout << std::endl;
}
}
Last edited on Jul 4, 2013 at 10:44am Jul 4, 2013 at 10:44am UTC
Jul 4, 2013 at 10:57am Jul 4, 2013 at 10:57am UTC
Change line 7 to either:
for (int j = 1; j <= i; ++j)
or:
for (int j = 0; j < i; ++j)
To give the first example in your code, when i=1, it prints 1 the first time, but because the second loop is still true on its second iteration (1<=1) it prints it a second time. Also, I don't think it makes a difference here, but most for loops I've seen use j++ rather than ++j.
Last edited on Jul 4, 2013 at 10:59am Jul 4, 2013 at 10:59am UTC
Jul 4, 2013 at 11:00am Jul 4, 2013 at 11:00am UTC
So, as long as the for-loop is true it will print it?
But how come it becomes 3333, 44444, 555555 later on, and not 33,44,55?
Thanks :)
Last edited on Jul 4, 2013 at 11:00am Jul 4, 2013 at 11:00am UTC
Jul 4, 2013 at 11:02am Jul 4, 2013 at 11:02am UTC
i is also increasing (in the first for loop), so for i=3, it would be true 4 times, 5 times for i=4 etc.
Last edited on Jul 4, 2013 at 11:06am Jul 4, 2013 at 11:06am UTC
Jul 4, 2013 at 11:24am Jul 4, 2013 at 11:24am UTC
But how come it becomes 3333, 44444, 555555 later on, and not 33,44,55?
Think how many times your inner loop is going to iterate, depending on the value of
i . That will explain it.
Last edited on Jul 4, 2013 at 11:24am Jul 4, 2013 at 11:24am UTC