C++ program that makes an equilateral triangle using stars??????

Follow
  • Follow publicly
  • Follow privately
  • Unfollow
i tried my best bu ti could not find the right answer fo r that question.. i want to write a c++ programm that will print the following on the console: * *** ***** it should ...show more
Update : i tried your progrm <jman> well,it didn't have the equilateral ...show more
Best Answer
  • cja answered 6 years ago
See my code below for a C++ solution to the problem. Only one 'for' loop is needed, if you take advantage of what iomanip can do for you. If you consider the spaces between the lines as contributing a unit of length, then it's an equilateral triangle. Otherwise, it's isosceles.

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
int n;
const char star('*');
const char space(' ');

if ((argc < 2) || (sscanf(argv[1],"%d",&n) != 1)) {
cout << "usage : " << argv[0] << " <n>" << endl;
cout << " where n is an integer" << endl;
return -1;
}
n = abs(n);
for (int i = 0; i < n; i++) {
cout << setfill(space) << setw(n-i) << space;
cout << setfill(star) << setw(i*2+1) << star << endl;
}
return 0;
}
  • 1
  • Comment

Other Answers (2)

Rated Highest
  • Rated Highest
  • Oldest
  • Newest
  • Badlass answered 6 years ago
    It looks like you want to print an extra 2 stars every line. Based on that, the following works, where lines is the number of lines you want to print.

    #include <iostream>
    int main() {
    int lines = 3;

    for(int i = 0; i < lines; i++) {
    for(int j = 0; j < (2*i+1); j++) {
    std::cout << '*';
    }
    std::cout << std::endl;
    }
    }
    • Rate
    • Comment
  • jman answered 6 years ago
    You are right, the previous code didnt work....didnt test it before i wrote it. Here is some revised code

    for (i=0; i<6; i++)
    {
    if (i mod 2 = 0)
    {
    for (n = 0; n < i +1; i++)
    {print ("*");}
    }
    print line method
    }

    I tested this in vb.net and it gave me the exact printout you have above. I just took out the not equals and updated the second loop to have a different index variable.....the two i's wont work well. Update the code you tried and it will work.

    Source(s):

    your momma
    • 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