• ## Discover

1. Home >
2. All Categories >
3. Computers & Internet >
4. Programming & Design >
5. Resolved Question
Member since:
May 13, 2006
Total points:
454 (Level 2)

## Resolved Question

Show me another »

# Creating a triangle pattern in C++?

Im trying to create a pattern that looks like this:

_____*
____***
___*****
__*******

Its the 1,3,5,7 triangle pattern, can someone correct my code to do this:

#include <iostream>
using namespace std;

// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
int main ()
{
printStars(f, g, h);
return 0;
}

int printStars (int f,int g,int h)
{
int f, g, h;

for (f=1; f<=7; f++)
{
for (h= 5; h >=0; h--)
{
cout<<" ";
while (g=0)
{
for (g=1; g<=lines; g++)
}

{
cout<<"* ";
}

}
cout<<endl;
}}

// --------------------------------
// --------- END USER CODE --------
// --------------------------------

I tried you method Sandeep K, but i the stars format to be 1,3,5,7

5 years ago

Member since:
January 15, 2007
Total points:
1,592 (Level 3)

## Best Answer - Chosen by Voters

/*
* Changed the 2*i+1 with 2*i-1 as the ith row
* will be having this much stars only. Should work now.
*
*/
include <iostream>
using namespace std;

// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
int main ()
{
void printStars(int,int);//prototype
printStars(4,2); //printing 4 lines, and the last line is having 2 leading spaces
return 0;
}

int printStars (int lines, int offset)
{
int i, j;

for(i=1;i<=lines;i++)
{
//print the ith line which has offset+lines-i spaces and 2*i-1 stars
for(j=0; j<offset+lines-i;j++)
cout << " ";
for(j=0;j<2*i-1;j++)
cout << "*";
cout <<endl;
}
}

// --------------------------------
// --------- END USER CODE --------
// --------------------------------
100% 1 Vote

There are currently no comments for this question.

### Other Answers (1)

• by uttaresh
Member since:
April 18, 2008
Total points:
1,185 (Level 3)
You're going about it the wrong way. There's no need for functions. All you have to do is first ask the user for the height of the triangle, then find the total length of one line (i.e. the number of stars in the last line), and then for each line, find the number of stars and spaces.This is the simple code it requires:

cout<<"Enter number of lines \\ height of triangle: ";
int height; ----- //Number of lines in triangle
cin>>height;
int length;
length = (((height-1)*2)+1); //Calculates length/stars of last line
int stars, i, j;

for (i=1;i<=height;i++)
{
--------stars = (((i-1)*2)+1);

--------for (j=1;j<=((length-stars)/2);j++)
---------------cout<<" ";

--------for (j=1;j<=stars;j++)
----------------cout<<"*";

--------cout<<endl;
}