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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { int n, i; cout << "Enter a positive integer: "; cin >> n; cout << "Factors of " << n << " are: " << endl; for(i = 1; i <= n; ++i) { if(n % i == 0) cout << i << endl; } return 0; } |

Another Example
#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 −
Another Example
#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 << " ";
}
Post a Comment