C++ Program to Check Whether a Number is Integer or Not using While | For loop
ADVERTISEMENTS
C++ program to check whether a number is integer or not.
In this article, you will learn how to check whether a number is an integer or not using the for loop and while loop in the c++ programming language.
Example-1
Input: 16
16 is an integer number.
Example-2
Input: 16.5
16.5 is a floating-point number.
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++ Strings
- C++
main()
function - C++
for
loop statement - C++
while
loop statement - C++
if-else
condition statement - C++
break
keyword - C++
cin
object - C++
cout
object
C++ Program to Check Whether a Number is Integer or Not using While loop
// C++ Program to Check Whether a Number is Integer or Not using While loop
#include <iostream>
using namespace std;
int main() {
char random_number[100];
int f = 0, i = 0;
cout << "Enter the number to check itself: ";
cin >> random_number;
while (random_number[i++] != '\0') {
if (random_number[i] == '.') {
f = 1;
break;
}
}
if (f)
cout << endl << random_number << " is a floating-point number.\n";
else
cout << endl << random_number << " is an integer number.\n";
return 0;
}
Output
Enter the number to check itself: 16
16 is an integer number.
C++ Program to Check Whether a Number is Integer or Not using For loop
// C++ Program to Check Whether a Number is Integer or Not using For loop
#include <iostream>
using namespace std;
int main() {
char random_number[100];
int f = 0;
cout << "Enter the number to check itself: ";
cin >> random_number;
for (int i = 0; random_number[i] != 0; i++) {
if (random_number[i] == '.') {
f = 1;
break;
}
}
if (f)
cout << endl << random_number << " is a floating-point number.\n";
else
cout << endl << random_number << " is an integer number.\n";
return 0;
}
Output
Enter the number to check itself: 16.5
16.5 is a floating-point number.
Explanation
In this program, we have taken input 16
from the user and parsed this input as a string.
Meanwhile using for
loop or while
loop on this string we find the .
symbol to verify It's an integer or floating-point number.