In this C++ tutorial, you will learn how to write a program to find the factors of a given number.
Display all Factors of a Number Program in C++
To print all the factors of a number n, iterate from 1 to n in a loop, and during each iteration check if this number divides n with zero reminder. All those numbers that leave zero reminder are the factors of the given number.
Program
In the following program, we read a number to n from user via console input, and print all the factors of this number. We use C++ For Loop for iteration.
C++ Program
</>
Copy
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number : ";
cin >> n;
for (int i = 1; i <= n; ++i) {
if (n % i == 0) {
cout << i << " ";
}
}
cout << endl;
}
Output
Enter a number : 10
1 2 5 10
Program ended with exit code: 0
Enter a number : 24
1 2 3 4 6 8 12 24
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to display all the factors of a given number in C++, with example program.