Kfkgy8392992
Kfkgy8392992

Reputation: 23

Building a Triangle with c++ loops

I am trying to build a triangle, with a user entered base and height. When these entered values are different (base!=height), the program goes haywire and gets stuck in the triangle draw loop.

I've tried altering the code a couple of times, but please treat me as a programming novice.

//BUILD TRIANGLE//
#include <string>
#include <iomanip>
#include <iostream>

int main()
{
    std::cout << "\nEnter base and height:\n";
    int height{0}; int base{0};
    std::cin >> base >> height;

    std::string bottom(base, '*');
    std::string top = "*";
    int middlerows = height - 1;
    int middlespacechars;
    std::cout << top << std::endl;

    for (middlespacechars = 0; 
         middlerows != 1 || middlespacechars != base - 2; 
         ++middlespacechars, --middlerows) {

        std::string middlespace(middlespacechars, ' ');
        std::cout << "*" << middlespace << "*\n";
    }

    std::cout << bottom << "\n" << std::endl;
    std::cout << "^TRIANGLE\n";
    std::cout << "BASE = " << base << std::endl;
    std::cout << "HEIGHT = " << height << std::endl;
    std::cout << "goodbye" << "\n" << std::endl;
}

The output is totally haywire, with asterisks across the screen in no discernible shape. When I put in values where base=height, though, a pretty little right angle triangle pops up.

Upvotes: 0

Views: 1801

Answers (2)

Osama Khalid
Osama Khalid

Reputation: 337

//C++ program to display hollow star pyramid

#include<iostream>
using namespace std;

int main()
{
   int rows, i, j, space;

   cout << "Enter number of rows: ";
   cin >> rows;

   for(i = 1; i <= rows; i++)
   {
      //for loop to put space in pyramid
      for (space = i; space < rows; space++)
         cout << " ";

      //for loop to print star
      for(j = 1; j <= (2 * rows - 1); j++)
      {
         if(i == rows || j == 1 || j == 2*i - 1)
            cout << "*";
         else
            cout << " ";
      }
      cout << "\n";
   }
   return 0;
}

OUTPUT:

Upvotes: 0

BartekPL
BartekPL

Reputation: 2420

With your code, you can only draw well triangles which have base equal to height.

If you change stop condition in your for loop, you can get what you probably want to get:

for (middlespacechars = 0; middlerows != 1 || middlespacechars != base - 2; ++middlespacechars, --middlerows) {

... into ...

for (middlespacechars = 0; middlerows > 1 || middlespacechars < base - 2; ++middlespacechars, --middlerows) {

It was huge probability that if base and height are different then stop condition will not be achieved. For loop in your code will stop if middlerows will be 1 and middlespacechars will be base - 2 at the same moment.

Test it here.

Upvotes: 2

Related Questions