C++ Program to check whether a number is divisible by another number


January 31, 2023, Learn eTutorial
1502

this is a program in C++ for checking whether a number is divisible by another number or not.

How can we check if a Number is Divisible by Another?

A number is divisible by another number if it can be divided equally by that number, or the remainder will be zero after the division.

How to write a C++ program to check number is divisible by another?

Here we are going to check whether the first number is completely divisible by the second number by checking the remainder is zero or not. If the answer is 0 then the number is divisible by another number. Else it is not divisible by that number.

Ask the user to enter two numbers. The first entered number is the numerator and the second entered number is considered as the denominator. Get the numbers into the variables nume and denom. Use the mod operator with if condition to check the remainder is zero after division and if it is zero, print the numerator is completely divisible by the denominator, else not.

The above program code checks whether the denom divides the nume without leaving any remainder, or leaving 0 as remainder or not. The mod operator gives the remainder therefore if nume mod denom gives means the numerator is divisible by the denominator.

Algorithm

Step 1: Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the main function; int main().

Step 4: Declare two integer type variables nume and denom;

Step 5: Ask the user to enter a number;

Step 6: Get the number into the variable nume;

Step 7: Ask the user to enter the second number;

Step 8: Get the number into the variable denom;

Step 9: Check if nume mod denom is 0;

Step 10: If yes then print the first number is divisible by the second number;

Step 11: else print the first number is not divisible by the second number

Step 12: Exit

C++ Source Code

                                          #include<iostream>
using namespace std;
int main()
{
   int nume, denom;
   cout<<"Enter a Number (Numerator): ";
   cin>>nume;
   cout<<"Enter another Number (Denominator): ";
   cin>>denom;
   if(nume mod denom==0)
      cout<<endl<<nume<<" is divisible by "<<denom;
   else
      cout<<endl<<nume<<" is not divisible by "<<denom;
   cout<<endl;
   return 0;
}
                                      

OUTPUT

Run 1
Enter a Number (Numerator): 85
Enter another Number (Denominator): 5
85 is divisible by 5
Run 2
Enter a Number (Numerator): 6
Enter another Number (Denominator): 5
6 is not divisible by 5