Write a program that reads an integer value n from the user

Write a program that reads an integer value n from the user and prints a pattern of numbers that is shown below for n = 5 and n = Generate the pattern separately using each loop given below for loop while loop for loop Sample input/output (using for loop): Test Case I: Enter the number: 5 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 Test case 2 Enter the number: 3 0 0 1 0 1 2 0 1 2 3

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.

 Write a program that reads an integer value n from the user and prints a pattern of numbers that is shown below for n = 5 and n = Generate the pattern separate

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site