Write a program that reads an integer value n from the user
Solution
Please follow the code and comments for description :
CODE :
a) for-loop :
#include <iostream>// required header files
using namespace std;
int main() // driver method
{
int n; // required initialisations
cout << \"Please Enter the Value : \" << endl; // prompt for the user to enter the data
cin >> n;
for(int i = 0; i <= n; i++){ // first loop that iterates till the size of the data
for(int j = 0; j <= i; j++){ // iterating over the loop till the number of the first loop
cout << j << \" \"; // printing the data with a space
}
cout << \"\ \"; // new line character
}
return 0;
}
OUTPUT :
Please Enter the Value :
6
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
b) while-loop :
#include <iostream> // required header files
using namespace std;
int main() // driver method
{
int n, a = 0, b; // required initialisations
cout << \"Please Enter the Value : \" << endl; // prompt for the user to enter the data
cin >> n; // getting the data
while(a <= n){ // first loop that iterates till the size of the data
b = 0; // initializing the local variable
while(b <= a){ // iterating over the loop till the number of the first loop
cout << b << \" \"; // printing the data with a space
b++; // incrementing the value of second variable
}
a++; // incrementing the value of first variable
cout << \"\ \"; // new line character
}
return 0;
}
OUTPUT :
Please Enter the Value :
6
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
Hope this is helpful.
