Check if a Number is Divisible by 5 and 3 in C++
In this exercise, you will write a C++ program that checks if a given number is divisible by both 5 and 3 simultaneously. The program will take an integer input from the user and use the modulus operator % to determine if the division leaves a remainder of zero for both divisors.
Divisibility Logic
1. Modulus Operator
The % operator returns the remainder of a division. If number % n == 0, the number is perfectly divisible by n.
2. Logical AND (&&)
To check multiple conditions at once, we use &&. Both divisibility checks must be true for the whole condition to pass.
3. Integer Handling
The program uses the int type, which allows it to handle both positive and negative integers correctly.
Key Concepts Learned:
- Modulus Operator: Using
%for parity and divisibility logic. - Boolean Logic: Implementing "simultaneous" conditions using the logical AND operator.
- Conditional Branching: Directing program flow based on mathematical results.
Objective
- 1. Ask the user to input an integer.
- 2. Use the modulus operator to check divisibility by 5 and 3.
- 3. Combine both checks into a single
ifstatement using&&. - 4. Display whether the condition is met or not.
Example C++ Exercise
#include <iostream> // Include the iostream library
using namespace std; // Use the standard namespace
int main() {
int number; // Variable to store the user's input
// Ask the user for input
cout << "Enter a number: ";
cin >> number;
// Check if the number is divisible by both 5 and 3
if (number % 5 == 0 && number % 3 == 0) {
cout << "The number is divisible by both 5 and 3." << endl;
}
else {
cout << "The number is NOT divisible by both 5 and 3." << endl;
}
return 0; // Indicate successful execution
}
Console Output:
Enter a number: 15
The number is divisible by both 5 and 3.
Enter a number: 10
The number is NOT divisible by both 5 and 3.