The question is as follow :
Write a program that prompts the user to enter a positive integer m that represents the sum of all page numbers in a book. The program prints whether the number is a valid sum or not. For example, the integer 21 is a valid sum of page numbers because 1 + 2 + 3 + 4 + 5 + 6 = 21. The integer 25 is not a valid sum because the sum of the first 6 page numbers is 21 and the next page number is 7, so the sum of the first 7 page numbers should be 28. If m is a valid sum of all page numbers, then there must be an integer n such that 1+2+3+ … + n = n(n+1)/2 = m
Here's my code:
#include <iostream>
using namespace std;
int main() {
int num,n=0,sum=0;
cout<<"Enter a positive integer"<<endl;
cin>>num;
for (int i=1;i<num;i++){
sum+=i;
n++;
if (sum==num)
break;
}
if (((n*(n+1))/2)==num){
cout<<"This number is valid";
}
else{
cout<<"This number is invalid";
}
}
The code is working but I need another way to implement this program without using loops but only selection statements.Is it possible to do that??