Printing All Factors of a Number in C++

Exercise:

Write a C++ program to print all factors of the number provided by the user.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num;
    cout << "Insert a positive number:\n";
    cin >> num;
    cout << "Factors of " << num << " are: " << endl;  
    for(int i = 1; i <= num; ++i)
    {
        if(num % i == 0)
        cout << i << " ";
    }
    return 0;
}
Click Here to View the Output:
Insert a positive number:
 24
 Factors of 24 are:
 1 2 3 4 6 8 12 24
Click Here to View the Explanation:
  • A number num is requested to be inserted by the user.
  • The for loop is iterated. The value of i = 1. It is incremented by 1 through every iteration.
  • Through every for loop, it is checked if i can perfectly divide num, or not. If yes, it is printed on the screen.
  • Iterations continue until i = num. The loop is terminated. This allows all the all the numbers from 1 to num to be checked and printed on the screen.