Find Factors of a Number C++ using While loop | For loop
Find factors of a number C++ using while loop and for loop.
In this article, you will learn how to find factors of a number c++ using while loop and for loop.
Example-1
The factors of the 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
Example-2
The factors of the 70 are: 1 2 5 7 10 14 35 70
What are the factors of a number?
The factors of a number are defined as numbers that divided the original number without leaving any remainder (left reminder = 0).
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
for
loop statement - C++
while
loop statement - C++
cin
object - C++
cout
object
In this article, we solve this problem in two methods:
Find Factors of a Number C++ using While loop
// Find Factors of a Number C++ using While loop
#include <iostream>
using namespace std;
int main() {
int x, i = 1;
cout << "-----Enter the positive integer number-----\n";
cin >> x;
cout << "\nThe factors of the " << x << " are: ";
while (i <= x) {
if (x % i == 0) {
cout << i << " ";
}
++i;
}
cout << "\n";
return 0;
}
Output
-----Enter the positive integer number-----
86
The factors of the 86 are: 1 2 43 86
Find Factors of a Number C++ using For loop
// Find Factors of a Number C++ using For loop
#include <iostream>
using namespace std;
int main() {
int x, i;
cout << "-----Enter the positive integer number-----\n";
cin >> x;
cout << "\nThe factors of the " << x << " are: ";
for (i = 1; i <= x; ++i) {
if (x % i == 0) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
Output
-----Enter the positive integer number-----
86
The factors of the 86 are: 1 2 43 86
Explanation
In these given programs, we have taken input 86
a random number then applied the for
loop and makes a calculation on this random number.
With Itself reminder zero to find the possible factors of this random number.
The same calculation applied to the second program with while
loop.
Also, visit these links
C Program to Find Factors of a Number