To start with, the problem is not directly with the algorithm (at least I think I got it); the problem shows whenever I use the function that finds the average.
The code compiles but when I get to the line in which said function executes, the program stops working, maybe because of how I'm playing with arrays, or maybe because of how long it takes to execute (although I highly doubt it's the last one).
If someone could please tell me where the problem is:
So, for the program: Try to get the average of an array using divide and conquer. I divide the array by two, then proceed until I only have 1 element of the array and return that value, else, return (avg(lefmost part of the array) + avg(rightmost part of the array))/2.
#include <stdio.h>
#include <stdlib.h>
int avg(int in, int end, int* a){
if ((end - in) == 0){
return a[end];
}
return (avg(in, ((end - in)/2)-1, a) + avg((end - in)/2, end, a));
}
int main(){
int a,*b,i;
printf("Please say how long the array is going to be: ");
scanf("%d",&a);
b = (int*)malloc(sizeof(int) * a);
if (b){
for(i=0; i<a; ++i){
printf("Please enter the element number %d of the array: ", i+1);
scanf("%d",&b[i]);
}
printf("The array is:\n\n{\n");
for(i=0; i<a; ++i){
printf(" %d\n", b[i]);
}
printf("}\n\n");
printf("The array's average is : %d", avg(0, a-1,b));
}
else{
printf("Sorry, but an array of that size can't be created!\n");
}
return 0;
}
if ((end - in) == 0){is a funny (funny peculiar, that is) way of writingif (end == in) {. - Jonathan Leffler