Write a program that prompts the user to enter an integer number between 1 and 999. The program displays the sum of all digits in the integer if the input is valid; otherwise, it displays a message indicating that the integer is not between 1 and 999 and hence, is invalid.
Name the program file Q1.cpp
Example: if the user enters 12, sum of digits is 3.
If the user enters 122, sum of digits is 5.
#include <iostream> using namespace std; int main() { int n; cout << "Enter a number: "; cin >> n; if (n < 1 || n > 999) { cout << "Input is invalid!" << endl; } else { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } cout << "sum of digits is " << sum << "." << endl; } return 0; }
Get Answers For Free
Most questions answered within 1 hours.