For loop triangle

I've been searching all over the internet for a help with a triangle program that I can't make any sense of. The instructor wants the triangle to be equilateral but is only made up of odd numbers, the base of the triangle being made of the odd number input, so it should look like
* 1
*** 3
***** 5
******* 7

I can get it to go numerically with even rows, but can't fix this coding and always get weird results
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 #include <iostream>
using namespace std;
int main()
{

	int star, x, y;
    cout<<"Enter the number of stars for the base (Must be an odd number) "<<endl;
    cin>>star;
     
        if(star%2==0)
		{
			cout<<"You entered an even number, the program will now close"<<endl;
			exit(0);
		}
		
		else
		{
			

			for(y=0;y<=((star)/2);y++)
			{ 
			
			for(x=0; x>y;x++)
            {
                cout<<" ";
            }       

            for(x=1;x<=y;x++)
			{     
				cout<<"*";                   
			}   
            cout<<endl;
        }
    }
		cout<<endl;

    return 0;
}
Well to directly answer your question int division often results in a truncated answer. For example 7/2 is 3.5 in 'real life', but because it is a int the compiler will truncate the product to the nearest int. So in truth when you put in 7/2 the answer is 3 not 3.5 because the . 5 was truncated. However, this doesn't really solve your problem as 3.5 is the not the correct of rows that you need anyways. In fact it is 4 if we are using 7 as an example. So the answer really is (star + 1)/2 (at line 20) will give the correct amount of rows.

Assuming the rest of the code is correct.... this should solve your problem.
Last edited on
I can get the correct number of rows, but I can't get the correct number of stars per row, it should go like 1 star, 3 stars, 5, stars etc, getting bigger by odd number
Last edited on
My bad it looked like that was your question and I am surprised that you are getting the correct amount of rows, but, that is irreverent.

So, I am guessing int stars is the max amount of stars that are to be printed?

Then lets look at the relationship between the amount of stars printed and rows printed.

if we say use stars = 7 then we know 4 rows will be printed and the number stars printed will be 1,3,5,7 in other words with each row doesn't the amount of stars printed increase by two? So if you were write a code snippet that expressed that relationship how would you write it? (the relationship being with each row increase stars printed by two) Hint: pay attention to your second argument in one the for loop in your program.

since this appears to be assignment I am going to avoid giving you the direct answer as that would hurt more then help you. However, if you read carefully all you really need to do is translate some bad English into code.
Thank you very much I figured it out!
Topic archived. No new replies allowed.