Reputation: 23
int main()
{
int arrFactors[50] , i , number ;
printf("please enter a number : ");
scanf("%d",&number); // take the value from the user
for (i = 0 ; i <= number ; i++) // loop for storing the factors
{
if(number%(i+1)==0) // condition to check if number have factors from 1 to number
arrFactors[i]=(i+1); // if the condition true then save the value to the arr
}
printf("the Factors of %d = " ,number);
for(i=0 ; arrFactors[i]=='\0' ; i++) // printing the arr
{
printf("%d\t",arrFactors[i]);
}
return 0;
}
I am trying to get factors of a number using array what is the wrong ?
Upvotes: 2
Views: 73
Reputation: 780724
Don't use i
as the index to store the factors, because you're not filling in the array elements that aren't factors. Use a different variable to hold the array index. Since you didn't initialize the array, you get indeterminate values when you print the values of these elements. And if you were to initialize it to 0
, the loop would stop when it gets to the first non-factor, since you're looping until you get to 0
.
Use a different variable for the array index and the factors that you're testing. Then you don't need to keep adding 1 to the factor, and you can use the final value of the index as the limit of the printing loop.
#include <stdio.h>
int main()
{
int arrFactors[50] , i , number, j = 0 ;
printf("please enter a number : ");
scanf("%d",&number); // take the value from the user
for (i = 1 ; i <= number ; i++) // loop for storing the factors
{
if(number % i == 0) // condition to check if number have factors from 1 to number
arrFactors[j++]=i; // if the condition true then save the value to the arr
}
printf("the Factors of %d = " ,number);
for(i=0 ; i < j ; i++) // printing the arr
{
printf("%d\t",arrFactors[i]);
}
printf("\n");
return 0;
}
Upvotes: 4