[try Beta version]
Not logged in

 
 
Loop question

Nov 19, 2015 at 11:51am
Hi!
I'm a complete beginner and have been learning C++ for a mounth or so via an internet course. It has been going fine untill we came to looping and got an assignment that goes :
"Write a program that asks a number and writes a figure depending on the number. Here is an exemple:

number: 3

A
AA
AAA

number: 5

A
AA
AAA
AAAA
AAAAA
"

And here is where i got stuck. I understand how to loop with for, while, do... while. But none of them seem to achiev this result directly. I tried searching for a way to type a character N X times but all these searches gave an answers either "you need to loop character N" or "oh, you're thinking of a diffrent language, you can't do that with C++".

I would appreciate some help before I turn to the teacher with this. Please bear in mind that this is a beginners task that has to do with loops, so the solution is probably simple. Thanks!

Nov 19, 2015 at 12:28pm
It is. However, nothing is obvious until you learn it, so don't let anyone make you feel bad.

The trick is that you need two loops, one inside the other.

The outside loop controls the number of lines printed AND the number of 'A's per line.
The inside loop prints all the 'A's on the line.

Hope this helps.
Nov 19, 2015 at 12:54pm
Nov 19, 2015 at 3:00pm
Thanks for answers! I did suspect that this requares 2 loops, but even after reading how you embed a loop into a loop, I can only manage this.

AAA
AAA
AAA
1
2
3
4
5
6
7
8
9
{
			
	for(int row=1;row<=3;row++)
			
	{
		for(int sign=1;sign<=3;sign++)
		cout<<'A';
		cout<<endl;
	}	


I can't figure out how control the amount of repeats inside the row...
Nov 19, 2015 at 6:41pm
Hint: one of those variables knows how long the inner loop must run.
Nov 19, 2015 at 7:54pm
How could i not see that x__x Thanks!
The inner loop's continue statement is controled with outers loop variable.

1
2
3
4
5
6
7
8
for(int row=1;row<=3;row++)
			
	{
	for(int sign=1;sign<=row;sign++)
	cout<<'A';
	cout<<endl;
			
	}

Problem solved
Nov 20, 2015 at 1:16am
:O)

Nothing is obvious.
Topic archived. No new replies allowed.