In this post, you will learn ** how to Display Factors of a Number **using

**.**

*C++ programming language*This lesson will teach you how to Display Factors of a Number, with a for loop, mathematical operations and decision making statement using the C++ Language. Let’s look at the below source code.

## How to Display Factors of a Number?

RUN CODE SNIPPET## Source Code

#include <iostream> using namespace std; int main() { int n, i; cin >> n; cout << "Enter a positive integer: "<<n<<endl; cout << "\nFactors of " << n << " are: "; for(i = 1; i <= n; ++i) { if(n % i == 0) cout << i << " "; } return 0; }

## Input

10

## Output

Enter a positive integer: 10 Factors of 10 are: 1 2 5 10

The statements **#include<iostream>, using namespace std, int main** are the main factors that **support** the function of the source code. Now we can look into the working and layout of the code’s function.

- Factors of a number are the integers that can divide the original number exactly. For example, 8 is the factor of 24, since it can divide into three equal parts. 24/8 = 3. Here we are building a code to find the factors of a number.
- First, declare the variables
*n, i*an**integers**collect the number from the user and store it in*n*using function`cin>>`

and display the value using`cout<<`

and the**Insertion Operators'<<‘ , ‘>>’.** - Use an output statement to display the answer.
- Using a
**for loop**with the condition`(i = 1; i <= n; ++i)`

and the loop statement consisting of an if statement with a condition which verifies if the reminder of**n**and**i**is equal to**0**and an output statement to be displayed when the condition is true. - The
**if statement**checks if the number is a factor of the number as a factor leaves the reminder as 0, and the**for loop**according to the condition increments the value ofand repeats the loop statement until the condition is not satisfied.*i* - The output statement is displayed and execution is terminated.

**Note:** The **‘ << endl ‘ **in the code is used to **end the current line **and move to the next line and **‘\n’ **is also a **new line function,** to understand how both the functions work exclude it from the code, move it around and work with it.

## Leave a Review