Number is divisible by second number or not
C program to determine whether the second number is a factor of first when both the numbers are entered by user.
C Program to Check if a Number is Divisible By Second Number or not.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
printf("Enter first number\t:");
scanf("%d",&num1);
printf("Enter second number\t:");
scanf("%d",&num2);
if(num2>num1)
{
printf("\nSecond number can not be greater by first number");
}
else
{
if((num1%num2)==0)
{
printf("\nSecond number is a factor of first number");
}
else
{
printf("\nSecond number is not a factor of first number");
}
}
getch();
}
Output
********** Run1 **********
Enter first number :20
Enter second number :5
Second number is a factor of first number
********** Run2 **********
Enter first number :20
Enter second number :6
Second number is not a factor of first number
Explanation
we will first check whether the second number is smaller then first, because if second number is greater than first number then it can never be a factor of first number.
Now, if on dividing first number from second number, remainder is 0, then second number is the factor of first number.
This is done using the modulus operator.
if
Now, if on dividing first number from second number, remainder is 0, then second number is the factor of first number.
This is done using the modulus operator.
if
(num1 % num2 == 0)
then num2 is the factor of num1, else it is not the factor of num2.