w3resource

C++ Exercises: Print all factors of the number

C++ For Loop: Exercise-63 with Solution

Write a program in C++ to enter any number and print all factors of the number.

Visual Presentation:

C++ Exercises: Print all factors of the number

Sample Solution:-

C++ Code :

#include <iostream> // Including the input/output stream library

using namespace std; // Using the standard namespace

int main() // Main function where the execution of the program starts
{
    int num, i; // Declare integer variables 'num' and 'i'

    // Display messages asking for input
    cout << "\n\n Print all factors of a number:\n";
    cout << "-----------------------------------\n";
    cout << " Input a number: ";
    cin >> num; // Read a number from the user

    cout << "The factors are: "; // Display a message before listing factors

    // Loop to find factors of the entered number
    for (i = 1; i <= num; i++) 
    {
        if (num % i == 0) // Check if 'i' divides 'num' completely (i.e., remainder is zero)
        {
            cout << i << " "; // If 'i' is a factor, display it
        }
    }

    cout << endl; // Move to the next line after displaying all factors
}

Sample Output:

 Print all factors of a number:                                        
-----------------------------------                                    
 Input a number: 63                                                    
The factors are: 1 3 7 9 21 63

Flowchart:

Flowchart: Print all factors of the number

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find power of any number using for loop.
Next: Write a program in C++ to find one's complement of a binary number.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-63.php