Check if a Number is Divisible by 5 and 3 Simultaneously

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.

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 if statement using &&.
  • 4. Display whether the condition is met or not.

Example C++ Exercise

divisibility_check.cpp Modulus Logic
#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.
Flow Control & Logic
Divisibility Check in C++ Simultaneous Divisibility Logic If-Else Statements and Remainder Operator Basic Algorithmic Math in C++

Share this C++ Exercise

Help others learn modulus logic and conditions in C++.

© C++ Programming Exercises. Master the art of performance coding.