C++ Whole Number Program
Definition
What Is a Whole Number?
On this page a whole number is a nonnegative integer: 0, 1, 2, 3, …. The matching test is n >= 0.
The natural number page on this site uses the school rule n > 0, so 0 is whole and not natural here. Some courses swap those words. Say which rule you are using.
Remember
n is whole ⇔ n is an integer and n >= 0
n is natural ⇔ n is an integer and n > 0 (this site)
0 → whole, not natural
5 → whole and natural
-3 → neither Approach
How to Check a Whole Number
- Read the value as an integer so fractions are not accepted as whole numbers.
- Reject the input if extraction fails.
- Accept the value when
n >= 0.
Program
C++ Program
Read one integer and print whether it is a whole number under the rule above.
C++
#include <iostream>
int main() {
int n;
std::cout << "Enter an integer: ";
if (!(std::cin >> n)) {
std::cout << "That is not an integer.\n";
return 0;
}
if (n >= 0)
std::cout << n << " is a whole number\n";
else
std::cout << n << " is not a whole number\n";
return 0;
} Frequently Asked Questions
A nonnegative integer: 0, 1, 2, 3, and so on.
Yes, on this page. The natural-number page treats zero as not natural.
No. Whole numbers here do not include negatives.
No. A whole number is an integer. The program reads an int, so 2.5 is not accepted as 2.5; the stream would read 2 and leave the rest.
Some authors start natural numbers at 0 and use whole number for the same set. State the definition before you write the check.
Next: Even Number
Once a value is a whole number, check whether it is even.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
7 people found this page helpful
