Factors of a Natural Number
Program to find all factors of a number
BeginnerTopic: Loop Programs
C++ Factors of a Natural Number Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Factors of " << num << " are: ";
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
cout << i << " ";
}
}
cout << endl;
return 0;
}Output
Enter a number: 24 Factors of 24 are: 1 2 3 4 6 8 12 24
Understanding Factors of a Natural Number
Factors of a number are all integers that divide it evenly. We iterate from 1 to the number itself and check if the number is divisible (num % i == 0). All divisors are printed as factors.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.