C program to chek divisibility of number
C program to chek divisibility of a given number
Write a C program to input a number from user and check it's divisibility by some other number as divisor using if...else. Let's see the below step by step logic check divisibility of a number.
Exmaple:
- INPUT
- Enter any number to check it's divisibility: 30
- Enter another number as divisior: 6
- Enter any number to check it's divisibility: 45
- Enter another number as divisior: 8
OUTPUT
30 is divisible by 6.
45 is not divisible by 8.
Required knowledge for this exercise
Logic to check divisibility of a number using if...else:
A number is exactly divisible by some other number if it gives 0 as remainder after dividing otherwise not. Example: 18 is exactly divisible by 9 i.e18 / 9 = 2
with a remainder 0.
in C, modulo%
division operator returns remainder after integer division. If it returns zero it means number is exactly divisible otherwise not. For Example: if(18 % 4 == 0)
it's not true since it returns 2 as remainder, therefore 18 is not divisible by 4.
Now let's see the below step by step logic to check divisibility of a number.
1) Input any number from user and store it in variable num
using scanf()
2) Check the given number is exactly divisible by some other number or not using modulo %
operator. Likeif (num % divisor == 0)
if it's remainder is equal to0
then number is exactly divisible otherwise not. Since we know that, modulo %
operator always returns remainder.
Program to check divisibility of a number using if...else:
#
include <stdio.h>
int main()
{
int num, divisor;
printf("Enter any number to check it's divisivility: ");
scanf("%d", &num);
/* Input another number as divisor from user */
printf("Enter another number as divisor: ");
scanf("%d", &divisior);
if(num % dvisor == 0)
{
printf("Yes! %d is divisible by %d", num, divisior);
}
else
{
printf("NO! %d is not divisible %d", num, divisor);
}
return 0;
}
Output:
Enter any number to check it's divisibility: 30Enter another number as divisor: 6Yes! 30 is divisible by 6
Enter any number to check it's divisibility: 45 Enter another number as divisor: 8No! 45 is not divisible by 8
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
Thursday, July 23, 2020
C
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.