For loop

Write a C++ program that asks the user to enter an integer N and display N lines as
follows. On line i, display i dollars ($), followed by a single pound (#)
character. For example, line 0 will have 0 dollars signs followed by a pound sign.
Line 1 will have 1 dollar sign followed by a pound sign. As an example, for N= 6, the
pattern should look as follows.
#
$#
$$#
$$$#
$$$$#
$$$$$#
$$$$$$#

I've gotten this far, but i don't know how to set it to add the $ signs. I think I need to use a nessted for loop, but I can't figure it out. Any help would be greatly appreciated.

#include <iostream>
using namespace std;
int main ()
{
int i,x;

cout<<"Enter a number: ";
cin>>x;
cout<<endl;

for(i=0;i<=x;i++){

cout<<i<<"#"<<endl;
}
return 0;
}
Yes. You will want to add a nested for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main ()
{
	int x;

	cout << "Enter a number: ";
	cin >> x;
	cout << endl;

	for(int i = 0;i < x; i++)
	{
		for(int j = 0; j<i; j++)
		{
			cout << "$";
		}
		cout<< "#" <<endl;
	}
	return 0;
}


First, you create an outer for loop like the one you have but have i < x. Inside that loop, create another.

On the first loop: i = 0, j = 0, j isn't less than i so the nothing happens. Print #.
Second loop: i = 1, j = 0, the loop prints $ once. Print #.
Third loop: i = 2, j = 0, the loop prints $ twice. Print #.
etc etc etc

Side note:

You should initialize i inside the for loop so that once the loop ends, the i is deleted. Otherwise, the i still exists after you're done with it. I've done that here. Also, use the [code] marks! It will make your pasted code a lot prettier.
Last edited on
Thank you so much, I was having so much trouble because I didn't realize you simply "cout<<"$";". And just out of curiosity, why do most people tend to use "i" and "j"? Every problem I find similar, thats what people use and i'm just curious.
And just out of curiosity, why do most people tend to use "i" and "j"? Every problem I find similar, thats what people use and i'm just curious.


Hi,

I prefer not to use i and j. They look too similar, and I have seen problems that stem from this, especially when there are i and j everywhere.

I prefer to call them what they are: Row and Col, as an example. That way a logical error like Table[i][i] becomes Table[Row][Row] which is much easier to spot, even better much harder to make the error in the first place.
And just out of curiosity, why do most people tend to use "i" and "j"?


Maybe this will answer your question -
http://programmers.stackexchange.com/questions/86904/why-do-most-of-us-use-i-as-a-loop-counter-variable
Topic archived. No new replies allowed.