In this article, we will write a C program to check if a number is divisible by 3 and 5 both.
The program takes a number from the user as input and checks if it is divisible by 3 and 5 both.
Sample Input:
Enter a number: 15
Output:
Number is divisible by 3 and 5
A number is said to be perfectly divisible by another number if it can be divided by that number without leaving a remainder i.e. the remainder is 0.
In C programming language, we use the modulo operator(%
) to get the remainder of a division operation. The modulo operator(%
) takes two operands and returns the remainder by dividing the first number by the second eg. a%b.
For example, 9%3 will give us 0 as 9 is perfectly divisible by 3. We will use this concept to write our program.
The following C program shows how you can check if a number is divisible by 3 and 5 both:
// C program to check if a number is divisible by 3 and 5 #include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); // Check if number is divisible by 3 and 5 both if ((num % 3 == 0) && (num % 5 == 0)) { printf("Number is divisible by 3 and 5"); } else { printf("Number is not divisible by 3 and 5"); } return 0; }
Output:
Enter a number: 15 Number is divisible by 3 and 5
Code Explanation:
- The program takes a number from the user and stores it in the
num
variable. - Inside the
if
condition, the statementnum % 3 == 0
evaluates to true only if the number is perfectly divisible by 3. - Similarly,
num % 5 == 0
evaluates to true only if the number is perfectly divisible by 5. - If both statements evaluate to true, the code inside the
if block
runs and prints that the number is divisible by 3 and 5 both. - If any of the two statements evaluate to false, the code inside the
else
block runs.
Thanks for reading.