C++ Program to Display Factors of a Number

In this post, we will learn how to display factors of a number using the C++ Programming language.

A factor is a number that divides into another number exactly and without leaving a remainder. For example, the factors of 20 are 1, 2, 4, 5, 10, and 20.

We will calculate the factors of a number entered by the user using a simple for loop statement.

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

C++ Program to Display Factors of a Number

// C++ Program to Display Factors of a Number
#include <iostream>
using namespace std;

int main(){
    int n, i;
    
    // Asking for input
    cout << "Enter a positive integer: ";
    cin >> n;
    
    // Finding factor 
    cout << "Factor of " << n << " are: " << endl;
    for (i = 1; i <= n; i++){
        if (n % i == 0){
            cout << i << endl;
        }
    }
    return 0;
}

Output

Enter a positive integer: 48
Factor of 48 are: 
1
2
3
4
6
8
12
16
24
48

How Does This Program Work?

    int n, i;

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

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

Then, the user is asked to enter a positive integer. This number gets stored in the n named variable.

    // Finding factor 
    cout << "Factor of " << n << " are: " << endl;
    for (i = 1; i <= n; i++){
        if (n % i == 0){
            cout << i << endl;
        }
    }

For each iteration, we check whether that iteration of i is divisible by n or not. If it is exactly divisible by n, then that iteration of i is a factor of n and we print it on the screen using the cout statement.

Conclusion

I hope after going through this post, you understand how to display factors of a number using the C++ Programming language.

If you have any doubt regarding the program, then feel free to 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 *