Introduction
In this tutorial, you will learn how to write a C program to check if a number is divisible by 3 or not using if-else Statement in C. From mathematics, We know that if the sum of a given number is divisible by 3 then the number will be divisible by 3. We can check the divisibility by 3 using the % operator. In this article, we will see using the % operator. Also In this article, we have covered the algorithms, explanations, and examples to solve this problem.
Problem Statement
Write a C program that reads a number from the user. And checks whether it is divisible by 3 or not using the “if-else” statement. The program should give the output whether the number is divisible by 3 or not.
Example
Enter a number: 15
The number 15 is divisible by 3.
In the above example, we can see that the given input is 15. If we add 1 and 5 it will become 6. As 6 is divisible by 3, 15 will be also divisible by 6.
We can directly check the input number by applying % Operator. We need not to perform the summation of the input number digits.
Algorithm
- Start the program.
- Read a number from the user and store it in a variable, let’s say
num
. - Use the modulo operator (
%
) to calculate the remainder whennum
is divided by 3. - If the remainder is equal to 0, display a message indicating that the number is divisible by 3.
- Otherwise, display a message indicating that the number is not divisible by 3.
- End the program.
Program to Check a GivenNumber is Divisible by 3 or not
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 3 == 0) {
printf("The number %d is divisible by 3.\n", num);
} else {
printf("The number %d is not divisible by 3.\n", num);
}
return 0;
}
Output 1
Enter a number: 15
The number 15 is divisible by 3
Output 2
Enter a number: 14
The number 14 is not divisible by 3
I hope this program is clear to you all.