Write a C++ program that asks the user for two positive integer values, M and N.
ID: 3680601 • Letter: W
Question
Write a C++ program that asks the user for two positive integer values, M and N. The program should use a loop to get the sum of all integers from M up to N (inclusive). Input validation is necessary to guarantee that M is less than or equal to N.
Modify the above looping construct to also calculate sum of all odd integers and even integers from M up to N (inclusive). e.g. If user enters M = 4 and N = 10 The loop will find the sum of 4,5,6,….,9,10 & the sum of Odd Numbers: 5,7,9 & the sum of Even Numbers: 4,6,8,10
Display the following:
M = ____ N = ____
Sum of numbers between M and N = _____
Sum of even numbers = ______
Sum of odd numbers = ______
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main() {
int m,n, sum = 0,sumeven=0,sumodd=0;
cout << "Enter a positive integer M value: ";
cin >> m;
cout << "Enter a positive integer N value: ";
cin >> n;
for (int i = m; i <= n; ++i) {
sum += i;
if(i%2==0)
sumeven+=i;
else
sumodd+=i;
}
cout<<"M= "<<m<<" "<<"N= "<<n<<endl;
cout << "Sum of numbers between M and N = " << sum<<endl;
cout<<"Sum of even numbers ="<<sumeven<<endl;
cout<<"Sum of odd numbers = "<<sumodd<<endl;
return 0;
}
Enter a positive integer M value: 3
Enter a positive integer N value: 12
M= 3 N= 12
Sum of numbers between M and N = 75
Sum of even numbers =40
Sum of odd numbers = 35
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.