Question

In: Computer Science

In this question using c++, you have to design the Pascal triangle where you can create...

In this question using c++, you have to design the Pascal triangle where you can create a list of coefficients of a binomial of any size that is passed to the constructor. Data members and member functions of this class are of your design choice. You need to use only pointers and pointers to pointers (do not use regular array notations). Create a two-dimensional array in the heap memory (which creates a dynamic memory). Use an application program to print out coefficients of a binomial in a triangle shape.

Output be like:

Enter the size of the Pascal triangle (to quit: -1): 5

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

Enter the size of the Pascal triangle (to quit: -1): -1

Thank you for using my program. See you soon!

Solutions

Expert Solution

The solution code has been tried to keep as simple as possible to help you understand the code in a better way, Also the explanation of the code has been added with upper case letters as comment lines. Still if you couldn't understand anything or want to ask anything you can just mention in the comment section I will try to reach you as soon as possible. To allocate space dynamically here new keyword of c++ has been used, it could have been done by using malloc as well.

CODE:

#include<iostream>
using namespace std;

class PascalTriangle{                // CLASS DEFINED
    public:
        PascalTriangle(int _size){   // CONSTRUCTOR OF THE CLASS WHICH TAKES THE SIZE OF THE PASCAL TRAINGLE
            n = _size;               // INITIALIZED THE DATA MEMBER N WITH SIZE OF THE PASCAL TRAINGLE FROM CONSTRUCTOR

            arr = new int*[n];       // ALLOCATED THE ARR POINTER TO N POINTERS DYNAMICALLY USING NEW KEYWORDS
            for (int i=0;i<n;i++)
                *(arr+i) = new int[n]; // SIMILARLY N INTEGERS ALLOCATED TO EACH THOSE POINTERS TO STORE THE COEFFICIENT OF PASCAL TRAINGLE, ALSO ARR[i] IS SAME AS *(ARR + i)
        }

        void calculateCoefficients();  // MEMBER FUNCTION DECLARATION WHICH WILL CALCULATE THE COEFFICIENTS AND STORE IN THE 2D ARRAY GENERATED
        void printTriangle();          // MEMBER FUNCTION DECLARATION WHICH WILL PRINT THE PASCAL COEFFICIENTS IN THE SPECIFIED MANNER

    private:
        int n;                       // DATA MEMBERS OF THE CLASS, N WHICH DENOTES SIZE, AND A POINTER TO A POINTERS WHICH DENOTES 2D ARRAY
        int **arr;

};

void PascalTriangle::calculateCoefficients(){  // MEMBER FUNCTION DEFINITION WHICH CALCULATES THE COEFFICIENTS
    for (int l = 0; l < n; l++) {              // L DENOTES ROWS, I.E, LINES
        for (int i = 0; i <= l; i++) {         // I DENOTES COLUMNS
            if (l == i || i == 0)              // IN A LINE LAST VALUE AND FIRST VALUE ARE 1
                *(*(arr+l)+i) = 1;
            else                               // AND OTHER VALUES ARE JUST ADDITION OF 2 VALUES FROM JUST UPPER ROWS(LINES) HAVING COLUMN VALUES COL-1 AND COL SO ADDED
               *(*(arr+l)+i) = *(*(arr+l-1)+i-1) +  *(*(arr+l-1)+i);   // *(arr+l) denotes arr[l] and *(*(arr+l)+i) denotes arr[l][i]
        }
    }
}

void PascalTriangle::printTriangle(){         // MEMBER FUNCTION DEFINITION WHICH PRINTS THE COEFFICIENTS IN TRIANGE FORM
    for (int l = 0; l < n; l++) {             // FOR EVERY LINE
        for (int i = 0; i <= l; i++) {        // PRINT EACH VALUE OF THE ROW(LINE) SEPARATED BY SPACE
            cout << *(*(arr+l)+i) << " ";

        }
        cout << "\n";                         // CHANGE THE LINE AFTER EVERY ROW

    }

}

int main()                                   // MAIN FUNCTION
{
    int n;
    while (1){                              // INFINITE LOOP TO KEEP ASKING THE USER SIZE OF THE PASCAL TRIANGLE UNTIL -1 IS ENTERED

        cout<<"Enter the size of the Pascal triangle (to quit: -1): ";    // ASK THE USER FOR SIZE
        cin>>n;
        if (n!=-1){                         // IF SIZE ENTERED IS NOT -1 THEN
            PascalTriangle p1(n);           // MADE THE OBJECT OF PASCAL  TRIANGLE CLASS PASSING THE SIZE IN ITS CONSTRUCTOR
            p1.calculateCoefficients();     // CALLED THE CALCULATE FUNCTION FUNCTION
            p1.printTriangle();              // AND THEN CALLED THE PRINT TRIANGLE FUNCTION
        }
        else                                // IF SIZE EQUALS -1 JUST BREAK THE INFINITE LOOP TO END THE PROGRAM
            break;

    }

    return 0;
}

SCREENSHOT(SAMPLE INPUT + OUTPUT):

NOTE: If you have any doubt regarding the solution please ask in the comment section. if you want any modification or better code you can mention that there as well, HAPPY LEARNING


Related Solutions

Using C++, you will create a program, where you will create two doubly linked lists. These...
Using C++, you will create a program, where you will create two doubly linked lists. These doubly linked lists will contain integers within them. Using the numbers in both of these linked lists, you add the numbers together, and insert the addition of the two numbers into a singly linked list. the input can be from the user or you just write the input. for example, if one number in the doubly linked list is 817 and in the other...
I have to create a program in C++ where a user can enter as many numbers...
I have to create a program in C++ where a user can enter as many numbers as they want (they predetermine the number of values to be inputted) and then the program can echo that input back to the user and then determine if the numbers were even, odd, or a zero and it outputs how many of each were found. This is to be down with four void functions and no arrays. The program initializes the variables zero, odds,...
Using C# Create the “TestQuestion” class. It will have two class variables: 1) a question and...
Using C# Create the “TestQuestion” class. It will have two class variables: 1) a question and 2) the answer to that question. Please create an accessor and mutator method for both of those variables, without which we would not be able to see or change the question or the answer. There should be a constructor method. We will also have a “ToString” or “__str__” method, which will print the question followed by its answer. The constructor method has two parameters...
In C++, Design and implement an ADT that represents a triangle. The data for the ADT...
In C++, Design and implement an ADT that represents a triangle. The data for the ADT should include the three sides of the triangle but could also include the triangle’s three angles. This data should be in the private section of the class that implements the ADT. Include at least two initialization operations: one that provides default values for the ADT’s data, and another that sets this data to client-supplied values. These operations are the class’s constructors. The ADT also...
Using key terms, create a scenario where you can find a population, a sample, the parameter,...
Using key terms, create a scenario where you can find a population, a sample, the parameter, the statistic, a variable, and data. Post your scenario and provide a detailed description using the key terms. After reviewing the information, what did you learn about your target population?
Consider the integralHC F·dr where F = yi−xj + z3k where C is the triangle with...
Consider the integralHC F·dr where F = yi−xj + z3k where C is the triangle with vertices (0,0,3), (1,1,4), (2,0,0), oriented counterclockwise if viewed from above. a. [2] Represent the equation of the plane containing the triangle in the form z = ax + by + c and find a, b and c. b. [2] Compute curl F. c. [4] Compute the original line integral using Stokes’ theorem.
where can you create a new payroll schedule?
where can you create a new payroll schedule?
create a C++ program where you have 2 functions with two parameters. Limit the first function...
create a C++ program where you have 2 functions with two parameters. Limit the first function allowed input to values of numbers from 1-10 and from 5 to 20 for the second function. have each function add their two-parameter together then add the functions final values together. Show error message if wrong input is entered   Ask the user if they wish to continue the program (use loop or decision for this question).
1.Using key terms, create a scenario where you can find a population, a sample, the parameter,...
1.Using key terms, create a scenario where you can find a population, a sample, the parameter, the statistic, a variable, and data. Post your scenario and provide a detailed description using the key terms. After reviewing the information, what did you learn about your target population? 2.define confidence interval and degree of confidence. provide one example of confidence interval and interpret the result?
This is c++ Create a program where you create, display, search, delete elements within a linked...
This is c++ Create a program where you create, display, search, delete elements within a linked list. Watch your function arguments. Pointer parameters are passed by reference to some functions and by value to others. Functions to make: copy : copies element in linked list destroy all: destroys all elements in linked list wherethisgoes:user  enters element and returns where the element is located insert sorted: inserts element create using linked lists with a head pointer and so forth
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT