1

I was trying to write a code that would display pascals triangle. Instead of displaying the result as : enter image description here

my result is displayed as
1
1 1
1 2 1
1 3 3 1

Please help me figure out how to modify it to be able to get the actual triangle. I cant use arrays and pointers since those aren't covered in my class yet. Here's my code:

#include "stdafx.h"
#include <iostream> 
using namespace std; 
void PascalsTriangle(int);

int main() 
{   
    int n;
    cout << "Enter the number of rows you would like to print for Pascal's Triangle: "; 
    cin >> n;
    PascalsTriangle(n);
    return 0; 
}

void PascalsTriangle (int n){
    int i,j,x;  
    for(i=0;i<n;i++) 
    { 
        x=1; 
        for(j=0;j<=i;j++) 
        { 
            cout << x << " "; 
            x = x * (i - j) / (j + 1); 
        } 
        cout << endl; 
    } 
}
Noctis
  • 11,507
  • 3
  • 43
  • 82
user2977810
  • 35
  • 1
  • 1
  • 4

5 Answers5

1

Try this :

#include <iostream>
using namespace std;
int main()
{
    int n,k,i,x;
    cout << "Enter a row number for Pascal's Triangle: ";
    cin >> n;
    for(i=0;i<=n;i++)
    {
        x=1;
        for(k=0;k<=i;k++)
        {        
            cout << x << " ";
            x = x * (i - k) / (k + 1);
        }
        cout << endl;
    }
    return 0;
}

EDITED:

#include <iostream>
using namespace std;
int main()
{
    int n,coef=1,space,i,j;
    cout<<"Enter number of rows: ";
    cin>>n;
    for(i=0;i<n;i++)
    {
        for(space=1;space<=n-i;space++)
        cout<<"  ";
        for(j=0;j<=i;j++)
        {
            if (j==0||i==0)
                coef=1;
            else
               coef=coef*(i-j+1)/j;
            cout<<"    "<<coef;
        }
        cout<<endl;
    }
}
Surabhil Sergy
  • 1,946
  • 1
  • 23
  • 40
  • this gives the exact same output as my code. i am trying to get a symmetric isosceles triangle instead of a right triangle. – user2977810 Nov 11 '13 at 05:27
1

Here is the updated version. Works for any n. I've added a function to return the number of digits in a number since that computation is needed each iteration of the inner loop.

#include <iostream>
#include <string>
using namespace std;
void PascalsTriangle(int);

int main()
{
    int n;
    cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
    cin >> n;
    cout << endl;
    PascalsTriangle(n);
    return 0;
}

int numdigits(int x)
{
    int count = 0;
    while(x != 0) {
        x = x / 10;
        ++count;
    }
    return count;
}

void PascalsTriangle (int n)
{
    int i, j, x, y, maxlen;
    string len;
    for(i = 0; i < n; i++) {
        x = 1;
        len = string((n-i-1)*(n/2), ' ');
        cout << len;
        for(j = 0; j <= i; j++) {
            y = x;
            x = x * (i - j) / (j + 1);
            maxlen = numdigits(x) - 1;
            if(n % 2 == 0)
                cout << y << string(n - 1 - maxlen, ' ');
            else {
                cout << y << string(n - 2 - maxlen, ' ');
            }
        }
        cout << endl;
    } 
}

OUTPUTS:

Enter the number of rows you would like to print for Pascal's Triangle: 3

  1  
 1 1  
1 2 1  

Enter the number of rows you would like to print for Pascal's Triangle: 6

               1      
            1     1      
         1     2     1      
      1     3     3     1      
   1     4     6     4     1      
1     5    10    10     5     1  

Enter the number of rows you would like to print for Pascal's Triangle: 9

                                1        
                            1       1        
                        1       2       1        
                    1       3       3       1        
                1       4       6       4       1        
            1       5      10      10       5       1        
        1       6      15      20      15       6       1        
    1       7      21      35      35      21       7       1        
1       8      28      56      70      56      28       8       1        

Enter the number of rows you would like to print for Pascal's Triangle: 12

                                                                  1            
                                                            1           1            
                                                      1           2           1            
                                                1           3           3           1            
                                          1           4           6           4           1            
                                    1           5          10          10           5           1            
                              1           6          15          20          15           6           1            
                        1           7          21          35          35          21           7           1            
                  1           8          28          56          70          56          28           8           1            
            1           9          36          84         126         126          84          36           9           1            
      1          10          45         120         210         252         210         120          45          10           1            
1          11          55         165         330         462         462         330         165          55          11           1      

UPDATE for a more tighter triangle:

void PascalsTriangle(int n)
{
    int i, j, x, y, maxlen;
    string len;
    for(i = 0; i < n; i++) {
        x = 1;
        if(n % 2 != 0)
            len = string((n-i-1)*(n/2), ' ');
        else
            len = string((n-i-1)*((n/2)-1), ' ');
        cout << len;
        for(j = 0; j <= i; j++) {
            y = x;
            x = x * (i - j) / (j + 1);
            maxlen = numdigits(x);
            if(n % 2 == 0)
                cout << y << string(n - 2 - maxlen, ' ');
            else {
                cout << y << string(n - 1 - maxlen, ' ');
            }
        }
        cout << endl;
    } 
}

OUTPUT

Enter the number of rows you would like to print for Pascal's Triangle: 3
  1  
 1 1  
1 2 1  

Enter the number of rows you would like to print for Pascal's Triangle: 6
          1    
        1   1    
      1   2   1    
    1   3   3   1    
  1   4   6   4   1    
1   5  10  10   5   1    

Enter the number of rows you would like to print for Pascal's Triangle: 9
                                1        
                            1       1        
                        1       2       1        
                    1       3       3       1        
                1       4       6       4       1        
            1       5      10      10       5       1        
        1       6      15      20      15       6       1        
    1       7      21      35      35      21       7       1        
1       8      28      56      70      56      28       8       1  

Enter the number of rows you would like to print for Pascal's Triangle: 12
                                                       1          
                                                  1         1          
                                             1         2         1          
                                        1         3         3         1          
                                   1         4         6         4         1          
                              1         5        10        10         5         1          
                         1         6        15        20        15         6         1          
                    1         7        21        35        35        21         7         1          
               1         8        28        56        70        56        28         8         1          
          1         9        36        84       126       126        84        36         9         1          
     1        10        45       120       210       252       210       120        45        10         1          
1        11        55       165       330       462       462       330       165        55        11         1          
Mars
  • 4,677
  • 8
  • 43
  • 65
  • THANKS a lot! but for some reason when i use your code in my compiler it looks like a perfect triangle till the 9th row. It gets distorted if i input more 10 or 12 rows – user2977810 Nov 11 '13 at 07:58
  • @user2977810. That's probably because some of the rows are spilling over to the next line. Expanding the browser will fix the problem. What do you use to compile and print your output? – Mars Nov 11 '13 at 08:01
  • I figured it was my window size. if i increase the width of my window it looks perfectly fine! THANKS A LOT!!! – user2977810 Nov 11 '13 at 08:02
  • @user2977810. I made one more update. This will make the triangle closer together and not as wide as the previous. – Mars Nov 11 '13 at 09:15
  • @Dochevsky thanks for the other update. I was just wondering if this code can be written without using strings? – user2977810 Nov 12 '13 at 09:32
0

Do you expect this result?

1111

123

13

1

You need to add endl or constant string equivalent to "\r\n" to the end of the output string, or use commas in output, then, for example:

"1111,123,13,1"

"1,11,121,1331"

Alan Turing
  • 2,482
  • 17
  • 20
0

If you want it to look like a 'triangle', that is, a symmetric looking isosceles triangle, try this code for your PascalTriangle function. The only problem with this is that when you get larger digits, it will break some of the symmetry but up to 5 rows it'll work fine.

void PascalsTriangle(int n)
{
    int i, j, x;
    string len;
    for(i = 0; i < n; i++)
    {
        x = 1;
        len = string(n - i - 1, ' ');
        cout << len;
        for(j = 0; j <= i; j++)
        {
            cout << x << " ";
            x = x * (i - j) / (j + 1);
        }
        cout << endl;
    } 
}

OUTPUT

Enter the number of rows you would like to print for Pascal's Triangle: 5
    1 
   1 1 
  1 2 1 
 1 3 3 1 
1 4 6 4 1 

As opposed to:

Enter the number of rows you would like to print for Pascal's Triangle: 5
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
Mars
  • 4,677
  • 8
  • 43
  • 65
  • I've edited the OP question since the output wasn't clear. seems you got the idea for what he wanted. – Noctis Nov 11 '13 at 04:54
  • the line cout << len; seems to have errors. the code won't build. the compiler says that no operator "<<" matches these operands. do you know why is it so? Also, i need to print ateast 12 lines of the triangle. any help would be much appreciated. Thank you – user2977810 Nov 11 '13 at 05:26
  • @user2977810. Yes you need to include the header `#include ` at the top of your program along with your other headers. – Mars Nov 11 '13 at 05:31
  • @user2977810. I'll take a look and see if I can update the code for the case of more than 5 lines. – Mars Nov 11 '13 at 05:32
  • @Dochevsky Thanks. I'd be really grateful if you can update your code for it to print 12 lines. Thanks again – user2977810 Nov 11 '13 at 05:43
0
#include <iostream>

using namespace std;


const int MAXC = 13; //-- Max column constant
const int MAXF = 7; //-- Max row constant

int m, n, k, x, y; //-- Counters and accumulators for loops
int arrayTriangulo[MAXF][MAXC]; // Array that stores the values of the Pascal Triangle

int main() {

    m = (MAXC/2); // Middle Column
    k = (MAXC/2); // Middle row

    //-- 1.- Fill in the Array from Left to Right and from Top to Bottom
    //-- 2.- Fill in the Array starting from row 0 through 13 (MAXF)

    for ( x = 0; x < MAXF; x++ ) {

        n = 1;

        //-- 3.- Fill in the Array starting from Column 0 through 7 (MAXC)

        for ( y = 0; y < MAXC; y++ ) {

            //-- Assign 0 to the Array element that is not part of the triangle.

            arrayTriangulo[x][y] = 0;

            //-- 4.- If it is on the edges of the triangle assigns the value of "n". Which we initialize in 1.

            if (( y == m ) || ( y == k )) {
                arrayTriangulo[x][y] = n;           
            } 

            //-- 5.- For the rest of the internal values of the triangle other than the edges.
            //-- The sum of the value is assigned (upper left row -1) + (upper right row + 1)

            if ( ( x > 1 ) && ( x < MAXF ) && ( y < MAXC-1 ) ) {
                arrayTriangulo[x][y] = arrayTriangulo[x-1][y-1] + arrayTriangulo[x-1][y+1];             
            }

            //-- 6.- Finally Draw the Triangle by omitting the values at zero.

            if ( arrayTriangulo[x][y] > 0 )
                cout << arrayTriangulo[x][y] << "  ";
            else
                cout << "   ";

        } 

        cout << endl;
        m--;
        k++;
    }
    return 0;
}
  • 1
    Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include [clarification, context and try to mention any limitations, assumptions or simplifications in your answer.](https://stackoverflow.com/help/how-to-answer) – Sᴀᴍ Onᴇᴌᴀ Jun 19 '17 at 19:21