C++ Program to Print Numbers Divisible by 3 and 5

In this post, we will learn how to print numbers divisible by 3 and 5 using the C++ Programming language.

The below program asks the user to enter a number. Then, this program will print all the numbers divisible by 3 and 5 lying in that  particular range.

So, without further ado, let’s begin this tutorial.

C++ Program to Print Numbers Divisible by 3 and 5

// C++ Program to Print Numbers Divisible by 3 and 5
#include <iostream>
using namespace std;

int main(){
    int i, n;
    
    // Asking for input
    cout << "Enter a number: ";
    cin >> n;
    
    // Displaying numbers divisible by 3 and 5
    cout << "Numbers divisible by 3 and 5 are: " << endl;
    for (i = 1; i <= n; i++){
        if (i % 3 == 0 && i % 5 == 0){
            cout << i << endl;
        }
    }
    return 0;
}

Output

Enter a number: 75
Numbers divisible by 3 and 5 are: 
15
30
45
60
75

How Does This Program Work?

    int i, n;

In this program, we have declared two integer data type variables named i and n.

    // Asking for input
    cout << "Enter a number: ";
    cin >> n;

Then, the user is asked to enter a number. The entered value gets stored in the n named variable.

    // Displaying numbers divisible by 3 and 5
    cout << "Numbers divisible by 3 and 5 are: " << endl;
    for (i = 1; i <= n; i++){
        if (i % 3 == 0 && i % 5 == 0){
            cout << i << endl;
        }
    }

Now, we use a for loop to check whether the iterations of i are divisible by both 3 and 5

If any iteration of i is divisible by both 3 and 5, then we print the value of that particular iteration. This loop keeps on executing until i <= n.

This gives us all the numbers divisible by 3 and 5 lying between 0 to the entered number.

Conclusion

I hope after reading this post, you understand how to print numbers divisible by 3 and 5 using the C++ Programming language.

If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *