Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Sample Run: Write a C++ program to print a variable number of rows of characters

ID: 3787365 • Letter: S

Question


Sample Run: Write a C++ program to print a variable number of rows of characters arranged in the form of one to four side-by-side triangles. The user chooses the number of triangles and the triangle size Here is a sample run in which the user asks for 4 triangles of size 5 -bash-4.3$ /triangles enter number and size of triangles 4 5 k -bash-4.3$ o The source code file must be named triangles .cpp and we suggest you create a directory named -/cs 16/p3 to store it In o Your program must make certain the user enters a number of triangles between 1 and 4, and a size greater than 0 in response to the prompt. If a faulty value is entered, the program does not print triangles and does not exit, but instead it calmly informs the user about the mistake(s) and prompts for the number of triangles and size again. (See "sample runs" link below.)

Explanation / Answer

#include<iostream>

using namespace std;

void first_triangle(int size)

{

int i,j;

for(i = 1; i <= size; i++)

{

   for(j = 1; j <= i; j++)

{

cout << "*" <<" ";

}

cout << endl;

}

}

void second_triangle(int size)

{

int i,j;

for(i = size; i > 0; i--)

{

   for(j = 1; j <= i; j++)

{

cout << "*" <<" ";

}

cout << endl;

}

}

void third_triangle(int size)

{

int i,j,k;

for (i = 1; i <= size; i++)

{

for(j = size-i; j>0; j--)

cout << " "; //two spaces

   for(k = 1; k <= i; k++)

{

cout << "*" <<" ";

}

cout << endl;

}

}

void fourth_triangle(int size)

{

int i,j,k;

for(i = size; i > 0; i--)

{

for(j = 0; j<size-i; j++)

cout << " "; //two spaces

   for(k = 1; k <= i; k++)

{

cout << "*" <<" ";

}

cout << endl;

}

}

int main()

{

int n,s;

cout<<"Enter the number of trianlge want to print -> ";

cin>>n;

cout<<"Enter the size of triangle -> ";

cin>>s;

if ((n < 1) || (n > 4) || (s <= 0))

{

cout<<"Please enter the number of trianlge between 1 and 4 and the size of triangle greater than zero -> ";

cin>>n;

cin>>s;

}

switch(n){

case 1:

first_triangle(s);

break;

case 2:

first_triangle(s);

cout<<endl;

cout<<endl;

second_triangle(s);

break;

case 3:

first_triangle(s);

cout<<endl;

cout<<endl;

second_triangle(s);

cout<<endl;

cout<<endl;

third_triangle(s);

cout<<endl;

cout<<endl;

break;

case 4:

first_triangle(s);

cout<<endl;

cout<<endl;

second_triangle(s);

cout<<endl;

cout<<endl;

third_triangle(s);

cout<<endl;

cout<<endl;

fourth_triangle(s);

break;

default:

cout<<"some issue"<<endl;

break;

}

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote