Answer:
The cpp program for the scenario is given below.
#include <iostream>
using namespace std;
int main() {
// number of odd numbers to be printed
int n;
// variable to keep count of odd numbers
int odd=1;
// variable to print odd numbers
int j=1;
// user is prompted to enter number of odd numbers to be displayed
cout<<"Enter the number of odd numbers to be printed ";
cin>>n;
do
{
// odd number is displayed
cout<<j<<" ";
// variable incremented after odd number is displayed
odd++;
// variable incremented to consecutive odd number
j = j+2;
// loop continues until required number of odd numbers are reached
}while(odd<=n);
}
OUTPUT
Enter the number of odd numbers to be printed 10
1 3 5 7 9 11 13 15 17 19
Explanation:
The program works as described below.
1. The variable, odd, is declared and initialized to 1 to keep count of number of odd numbers to be displayed and other variable, j, declared and initialized to 1 to display odd numbers in addition to variable n.
2. User is prompted to enter value of n.
3. Inside do-while loop, initially, first odd number is displayed through variable j.
4. Next, variable odd is incremented by 1 to indicate number of odd numbers displayed.
5. Next, variable j is incremented by 2 to initialize itself to the next consecutive odd number.
6. In the while() clause, variable odd is compared against variable n.
7. The do-while loop executes till the value of variable odd becomes equal to the value of variable n.
8. The main() method has return type int and thus, ends with return statement.
9. The iostream is required to enable the use of basic keywords like cin and cout and other keywords.
10. This program can calculate and print any count of odd numbers as per the user.