I am not looking for an explicit answer to this question, and I have googled/searched this site for hours trying to find an example to work off of. What I can't figure out is how to write a nested "for loop" that will allow the user to input one number and will produce a square and two triangles of equal length and height that look like this:

So if 5 was entered the output would be:
*****
*****
*****
*****
*****

*
**
***
****
*****

----*
---**
--***
-****
*****

I've figure out the first two shapes without much problem but the second requires the same-ish code format but will input spaces at one point (marked here by dashes) and asterisks at another. I've been starring at this for days, know it's a relatively simple fix, but cant come up with the syntax. I would appreciate a walk through of how to write what I think should be the nested for loops switching spaces for stars. I've got bubkiss.

this is my code so far:

#include <iostream>
using namespace std;
int main()
{
	int length_stars=0;
	cout << "enter the length of the shapes that your would like to make:";
	cin >> length_stars;

	for (int r = 1; r <= length_stars; r++){
		for (int c = 1; c <=length_stars; c++){
			cout << "*";
	}
		cout <<endl;
	}

cout <<endl;

	for (int r=0; r<=length_stars-1; r++){
		for (int c=0; c<=r; c++){
			cout << "*";
		}
		cout <<endl;
	}

	cout <<endl;

	for(int i=1; i<length_stars; i++) {
		for (int j=1; j<length_stars-i; j++) {
		cout << " ";
	}
	for (int h=1; h<= i; h++) {
	cout << "*";
	}
	}

	return 0;
}

Recommended Answers

All 3 Replies

1) In lines 27 and 28 change < to <=

2) Remember to output an endl at the end of the outer for-loop

for(int i=1; i<=length_stars; i++) {
	for (int j=1; j<=length_stars-i; j++) {
		cout << " ";
	}
	for (int h=1; h<= i; h++) {
		cout << "*";
	}
	cout << endl;
}

I guess you can try std::setfill('-') for the last question.
It is declared in <iomanip>
Or you can just use loop to generate '-'.

1) In lines 27 and 28 change < to <=

2) Remember to output an endl at the end of the outer for-loop

for(int i=1; i<=length_stars; i++) {
	for (int j=1; j<=length_stars-i; j++) {
		cout << " ";
	}
	for (int h=1; h<= i; h++) {
		cout << "*";
	}
	cout << endl;
}

....of course it was that simple...[beats head against wall]. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.