Check if a Number is Divisible by 5 and 3 Simultaneously 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 number is divisible by both 5 and 3.

This exercise helps you understand how to use conditional statements and the modulus operator to check for divisibility. It's a simple yet important concept in programming that is commonly used in various mathematical and algorithmic problems.

Group

Flow Control in C++

Objective

1. Ask the user to input a number.
2. Use the modulus operator to check if the number is divisible by both 5 and 3.
3. Display a message indicating whether the number is divisible by both 5 and 3 or not.
4. Handle both positive and negative inputs.

Write a program that checks if a number is divisible by both 5 and 3 simultaneously.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Main function - the entry point of the program
int main() {
    int number; // Variable to store the user's input

    // Ask the user for input
    cout << "Enter a number: ";
    cin >> number; // Read the input number

    // Check if the number is divisible by both 5 and 3
    if (number % 5 == 0 && number % 3 == 0) { // If the number is divisible by both
        cout << "The number is divisible by both 5 and 3." << endl;
    }
    else { // If the number is not divisible by both
        cout << "The number is NOT divisible by both 5 and 3." << endl;
    }

    return 0; // Return 0 to indicate that the program executed successfully
}

 Output

Enter a number: 15
The number is divisible by both 5 and 3.

//Or for a number that is not divisible by both:
Enter a number: 7
The number is NOT divisible by both 5 and 3.

Share this C++ Exercise


More C++ Programming Exercises of Flow Control in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.