![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Display Factors of a Number
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
#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
#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 << " "; }