right side pattern triangle c++
C++ code for right side pattern triangle:
#include <iostream>
using namespace std;
int main() {
int rows, i, j;
cout << "Enter number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= rows; j++) {
if (j <= rows - i) {
cout << " ";
} else {
cout << "*";
}
}
cout << endl;
}
return 0;
}
Explanation:
Include necessary libraries:
#include <iostream>
is used to include the input/output stream library in the program.Declare the namespace:
using namespace std;
is used to avoid writingstd::
before standard library objects likecin
,cout
, etc.Main function: The
main()
function is the entry point of the program.Declare variables:
int rows, i, j;
declares the variables for the number of rows and the loop iterators.Input:
cout << "Enter number of rows: ";
prompts the user to enter the number of rows, andcin >> rows;
stores the input in the variablerows
.Nested loops: The outer loop runs from
i = 1
torows
, and the inner loop runs fromj = 1
torows
.Print spaces and stars: Based on the condition
if (j <= rows - i)
, spaces or stars are printed to create the right-side pattern triangle.Newline:
cout << endl;
is used to move to the next line after each row is printed.Return statement:
return 0;
indicates successful termination of the program.