29.4k views
3 votes
Write a C++ program that loops forever and asks the user to enter 2 positive numbers n1 and n2 that are less than 1000 each. Ignore out-of-range numbers and start all over. Calculate the sum of the sequence from n1 to n2, inclusive. Ask the user if they want to repeat. Write the function int seqsum (int n1, int n2) and use it in the question

1 Answer

4 votes

Final answer:

To write a C++ program that loops forever and asks the user to enter 2 positive numbers n1 and n2, use a while loop with a condition that is always true. Prompt the user for numbers within the specified range, calculate the sum using the seqsum() function, and repeat if desired.

Step-by-step explanation:

To write a C++ program that loops forever and asks the user to enter 2 positive numbers n1 and n2, we can use a while loop with a condition that is always true. Inside the loop, we prompt the user to enter the numbers, and if they are within the specified range, we calculate the sum using the seqsum() function. If the user wants to repeat, we continue the loop. Here is an example:

#include <iostream>

int seqsum(int n1, int n2) {
int sum = 0;
for(int i = n1; i <= n2; i++) {
sum += i;
}
return sum;
}

int main() {
while(true) {
int n1, n2;
std::cout << "Enter two positive numbers (less than 1000): ";
std::cin >> n1 >> n2;
if(n1 >= 1 && n1 <= 1000 && n2 >= 1 && n2 <= 1000) {
int sum = seqsum(n1, n2);
std::cout << "Sum of the sequence: " << sum << std::endl;
}
else {
std::cout << "Invalid range!" << std::endl;
}
std::cout << "Do you want to repeat? (y/n): ";
std::string repeat;
std::cin >> repeat;
if(repeat != "y") {
break;
}
}
return 0;
}
User Jatha
by
8.7k points