C Program to Find Factors of a Number | Using for loop, while loop & function
The numbers which are completely divisible by the given value(remainder is 0) called as factors of a given number in C.
Example: Factors of 20 = 1,2,4,5,10,20.
Factors of 36 = 1,2,3,4,6,9,12,18,36.
In this example, you will learn to find all the factors of an number entered by the user using for loop, while loop, function & if statement in C programming.
Program to Find Factors of a Number
Using for loop:
#include <stdio.h>
int main()
{
int i, Num;
printf("Enter a number to Find Factors ");
scanf("%d", &Num);
printf("Factors of the Given Number are: ");
for (i = 1; i <= Num; i++) //for loop for iteration
{
if(Num%i == 0) //condition check for factor
{
printf(" %d ", i);
}
}
return 0;
}
Using while loop:
#include <stdio.h>
int main()
{
int Number, i = 1;
printf("Enter a number to Find Factors ");
scanf("%d", &Number);
printf("Factors of the Given Number are: ");
while (i <= Number) //while loop for iteration
{
if(Number%i == 0) //condition check for factor
{
printf("%d ", i);
}
i++;
}
return 0;
}
Using function:
#include <stdio.h>
void Find_Factors(int Number) //function for checking the factor
{
int i;
for (i = 1; i <= Number; i++)
{
if(Number%i == 0) //condition check for factor
{
printf("%d ", i);
}
}
}
int main()
{
int Number;
printf("Enter a number to Find Factors ");
scanf("%d", &Number);
printf("Factors of the Given Number are: ");
Find_Factors(Number); //function call
return 0;
}
Output:
Enter a number to Find Factors 36
Factors of the Given Number are: 1 2 3 4 6 9 12 18 36
Enter a number to Find Factors 20
Factors of the Given Number are: 1 2 4 5 10 20
Enter a number to Find Factors 49
Factors of the Given Number are: 1 7 49
No comments: