Write a program that uses while loops performing the following steps: A. Prompt
ID: 3877910 • Letter: W
Question
Write a program that uses while loops performing the following steps: A. Prompt the user to input two integers: firstNum and secondNum (firstNum must be less than secondNum). B. Output the numbers between (inclusive) firstNum and secondNum. C. Output the sum of the numbers between (inclusive) firstNum and secondNum. D. Output all odd numbers between (exclusive) firstNum and secondNum. Match the output of the examples below.
Example 1: Enter two space separated numbers:
5 13 5 6 7 8 9 10 11 12 13
Sum is: 81
7 9 11
Explanation / Answer
#include <iostream>
using namespace std;
int main() {
int firstNum,secondNum;
int sum = 0;
cout<<"Enter two space seperated numbers : ";
cin>>firstNum>>secondNum;
cout<<endl;
//use counters to store the value of firstnumber to use in while loops
int counter = firstNum;
int counter1 = firstNum;
while(counter<=secondNum)
{
cout<<counter<<" ";
sum = sum + counter; // sum of all numbers
counter++;
}
cout<<" Sum is:"<<sum<<endl;
counter1++;
while(counter1<secondNum)
{
if(counter1%2 != 0) // check if number is divisible by 2
{
cout<<counter1<<" ";
}
counter1++;
}
return 0;
}
Output:
Enter two space seperated numbers :5 13
5 6 7 8 9 10 11 12 13
Sum is:81
7 9 11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.