Programming Example
C Program to print the prime factors using recursion
Program to print the prime factors using recursion
If you don't know what is prime number please read form this tutorial. Prime Number & Prime Factors
#include<stdio.h>
void PFactors( int num);
void IPFactors( int n);
main( )
{
int num;
printf("Enter a number : ");
scanf("%d", &num);
PFactors(num); printf("\n");
IPFactors(num); printf("\n");
}/*End of main()*/
void PFactors( int num)
{
int i = 2;
if( num == 1 )
return;
while( num%i != 0 )
i++;
printf("%d ", i);
PFactors(num/i);
}/*End of PFactors()*/
/*Iterative*/
void IPFactors( int num)
{
int i;
for( i = 2; num!=1; i++)
while( num%i == 0 )
{
printf("%d ", i);
num = num/i;
}
}/*End of IPFactors()*/
Enter a number : 145
5 29
5 29
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.