1) Write a function in C that takes in a single integer parameter and returns an array of factors.
The function signature should be :
int* get_factors(int number)
To make things a little easier, assume that the input (number) will never have more than 100 factors. The returned array should be null-terminated.
2) Write a main() function that asks a user for a number, calls the function above, then prints the results.
#include <stdio.h> #include <stdlib.h> int* get_factors(int number){ int* arr = (int*)malloc(sizeof(int)*100); int k = 0, i; for(i = 1;i<=number;i++){ if(number%i==0){ arr[k++] = i; } } arr[k] = -1; return arr; } int main() { int n, i; int* res; printf("Enter number: "); scanf("%d",&n); res = get_factors(n); printf("Factors of %d are:\n",n); for(i = 0;res[i]!=-1;i++){ printf("%d\n",res[i]); } return 0; }
Get Answers For Free
Most questions answered within 1 hours.