In this article, we will be writing a C Program to find all factors of a number. We will first understand the concept behind it and then we will continue writing the C program. The concept of C program is very clear, we need to find the factors of a given number.
To begin with lets understand what do we mean by Factors of a number. Factors of a number is a number that divides the original number exactly or evenly. A Prime number will have only two factors i.e. 1 and number itself. whereas a composite number will have more than two factors.
Examples-
Factors of 5 – 1 and 5
Factors of 10 – 1, 2, 5 and 10
To know more about Factors, read your Mathematics notebook.
1. Program Outline
In this C tutorial we will learn how we can find all factors of a number. I’ll help you to understand the concept behind it and we’ll move forward to write it’s C program.
First we’ll take input from the user and store it in a variable which we created in the beginning. Further after doing some calculations we’ll print factors of given numbers .I’ll guide you through its concept and the logic required to solve this problem. At the end, I will provide a output and the resources so, you can try this program on your device or computer. So, Let’s begin with this program.
2. Concept
The basic requirement you should have before writing this program is and which we also gonna use further in the program are :-
1. C basics such as Printf( ) , scanf( ).
2. If else
3. for loop
Now lets head towards the main part of the program.
Logic behind this Program.
- Take input number from the user , and store it in variable num.
- Start loop from 1 to num by incrementing 1 in each iteration.
- something like this ( i=1, i<=num, i++);
- Then use if statement inside for loop to print factors of a number if ( num % i ==0 ) then i is a factor of num.
- If i is the factor of num then print it.
Its good if you understood and if not you’ll understand while writing its code . Lets head towards writing its C program.
3. Program
C Program to find all factors of a number:
#include <stdio.h>
int main() {
int num, i;
//taking input from the user
//store it in variable num.
printf("Enter any positive number: ");
scanf("%d", &num);
printf("Factors of %d are: ", num);
//using for loop and iterating to each number till our actual value
//then using if inside for loop to print our factors
for (i = 1; i <= num; ++i) {
if (num % i == 0)
{
printf("%d ", i);
}
}
return 0;
}
4. Output
At last we finally reached our conclusion after writing C program , let’s check what output it gives .
