Solution for q1.cpp

  

Here is a code to make a triangle with a “char”  or one string.  The program itself, is able to print one character by just asking the user for the number of rows.
For this program you need:

  • 4 variables:
  • 1-> string T= “T”;
  • 2-> int rows, cols, norows;

where norows are the number of rows you will ask for, to the user. 
Now that we have our variables, it is also important to use the correct libraries. In this case we used:

  • <iostream>
  • <sstream>

In order to make the program, we will use nested “for” loops, where the first loop, will have our variable “rows”,  and “norows”, and the nested one (second one) will have our variables “cols” and “rows”. The first loop should work by asigning the value “1” to cols, then, our conditional will be that “rows” has to be smaller than ” therefore, rows++. The second loop will look like this: for (cols=1; cols<=rows; cols++).

inside the second loop, we will print out our variable T, and then, inside the first loop we will print <<endl; <– to separate each string.

After this step, the program should print a triangle like this:

T
TT
TTT
TTTT
TTTTT

 In order to complete the final triangle, we will have to do 2 “for” nested loops again, but this time, make it backwards.
These loops should look like: 

for(rows=norows-1; rows>0; rows–){

  for(cols=1; cols<rows; cols++){

  cout<<T;
               }

   cout<<endl;

}

Here is a picture of the code and how it should run:

CC BY 4.0 Solution for q1.cpp by carlos green is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.