Creating a triangle pattern in C++?

Follow
  • Follow publicly
  • Follow privately
  • Unfollow
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 ...show more
Update : I tried you method Sandeep K, but i the stars format to be 1,3,5,7
Best Answer
/*
* 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 --------
// --------------------------------
  • Rate
  • Comment

Other Answers (1)

  • uttaresh answered 5 years ago
    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;
    }
    • Rate
    • Comment
  • Sign In 

    to add your answer

Who is following this question?

    %
    BEST ANSWERS
    Member Since:
    Points: Points: Level
    Total Answers:
    Points this week:
    Follow
     
    Unfollow
     
    Block
     
    Unblock