how to prevent display the"The sum of all the digits is " when i input the value 0 .

#include <iostream>
using namespace std;

int main()
{

int num, x, sum=0;


cout<<"Insert an integer between 0 and 1000: ";
cin>>num;

if(num<1 || num>999)
cout<<"Invalid input. Please insert an integer between 0 and 1000"<<endl;

while (num >0 && num<1000)
{
x = num % 10;
sum = sum + x;
num = num / 10;

}

cout<<"The sum of all the digits is "<<sum<<endl;



return 0;

}
If the input integer is out of range, you either prompt the user to retry using "do while" statement, or simply end the program.
All you needed to do, was add an else statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Sum of digits.cpp : Defines the entry point for the console application.

#include <iostream>
using namespace std;

int main()
{
	int num, x, sum=0;

	cout<<"Insert an integer between 0 and 1000: ";
	cin>>num;

	if(num<1 || num>999)
		cout<<"Invalid input. Please insert an integer between 0 and 1000"<<endl;
	else
	{
		while (num >0 && num<1000)
		{
			x = num % 10;
			sum = sum + x;
			num = num / 10;
		}
	cout<<"The sum of all the digits is "<<sum<<endl;
	}
	return 0;
}
thx very much whitenite1.
Last edited on
may i know between 0 and 1000 got included 1 and 10????
@B031110034

May I ask, to what part are you referring?
"Insert an integer between 0 and 1000"
Topic archived. No new replies allowed.