# C++ Program to Display Factors of a Number

C++ProgrammingServer Side Programming

Factors are those numbers that are multiplied to get a number.

For example: 5 and 3 are factors of 15 as 5*3=15. Similarly other factors of 15 are 1 and 15 as 15*1=15.

The program to display the factors of a number are given as follows.

## Example

Live Demo

#include<iostream>
using namespace std;
int main() {
int num = 20, i;
cout << "The factors of " << num << " are : ";
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
return 0;
}

## Output

The factors of 20 are : 1 2 4 5 10 20

In the above program, the for loop runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of num and is printed.

for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}

The same program given above can be created using a function that calculates all the factors of the number. This is given as follows −

## Example

Live Demo

#include<iostream>
using namespace std;
void factors(int num) {
int i;
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
}
int main() {
int num = 25;
cout << "The factors of " << num << " are : ";
factors(num);
return 0;
}

## Output

The factors of 25 are : 1 5 25

In the above program, the function factors() finds all the factors of “num”. It is called from the main() function with one parameter i.e. “num”.

factors(num);

The for loop in the function factors() runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of “num” and is printed.

for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}