Loop Question

I need to write a program that will display a user given input a user inputed amount of times.

For example,
the program will ask

"Please enter a positive integer"
"Please enter a character"

If the integer 5 is inputed and the character = is entered then the character must be printed 5 times.

=
=
=
=
=

This is given by the code.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main ()
{

//Initialization

int x = 0; //number of times the loop will run
string letter; //the character that will be displayed X number of times
int number = 0;

// Input

cout << "Please input a positive integer: " ;
cin >> x;

cout << "Please input a character: " ;
cin >> letter;

//Loop

while (number < x)
{
cout << letter << endl;
number = number + 1;
}


return 0;
}


Now, I would like to modify the program to have an output like this.

Integer = 5
Character = "="

OUTPUT:

=
==
===
====
=====
Try nesting two for loops. The actual logic of how it would work to get that desired output is actually not as easy as I thought. I do have a working program but because I suspect this is school work, I will help as much as I can without giving you the code ;)

To get
=
==
===
====
=====


you'll need at least one loop because it prints out a new line. Next, you'll need another loop to put the "\n"; or std::endl; (depending on what you prefer). HINT: I would suggest to have the outer loop create the new line, and the inner loop print out the characters.
Hello there!

I suggest that you have a loop within your loop but around cout << letter; only that runs a number + 1 number of times and has its own variable to iterate.

Also, and this is not required but suggested, but you may want to look into for loops. They improve readability. ^_^

-Albatross

EDIT: Late!
Last edited on
Thanks for the replies!

So the first loop I would change to

For (number = 1; number =< x; x++)
cout << letter << endl;


Would I use a second for loop within the first for loop?

(Yes it is homework :) I appreciate you trying to steer me in the right direction without telling me the answer)
Be careful... C++ is case sensitive. It's for /*not*/ For.

Also, yes. You would use a second loop within the first for loop. :)

-Albatross
Topic archived. No new replies allowed.