views:

74

answers:

4

This is what I was given to start with.

     int main(){
      int a[5] = {0,1,2,3,4};
      printf("Sum of elements of a: %d\n", calculate_sum(a,5));
      return 0;          
     }

Here's what I've got, I don't know why it doesn't work, please help me.

#include <stdio.h>

int main()
{
      int a[5] = {0,1,2,3,4};
      int b;
      int calculate_sum(int, int);
      b = *a;

      printf("Sum of elements of a: %d\n", calculate_sum(b,5));
      return 0;          

}

int caluculate_sum(int *a, int size) 
{
    int i;
    int sum = 0;
    for(i = 0; i < size; i = i + 1)
     sum = sum + a[i];
    return sum;
}
+2  A: 

Your function looks fine. Use the original main() that was given to you without any changes. Your function prototype

int calculate_sum(int*, int);

should be above your main and functions. If you're writing this all in one file, a good place for the prototypes is below your #include statements.

MahlerFive
+1  A: 

Your problem is that your function declaration,

int calculate_sum(int, int);

does not match your function definition,

int caluculate_sum(int *a, int size)

(note that the name is misspelled in the definition and type of the first parameter is different--it needs to be a pointer in the declaration).

Generally, as MahlerFive points out, it's good practice to declare all of your functions before you define them and not to place function declarations inside of other functions.

James McNellis
A: 

Havent tested it.. but i guess this would work

#include <stdio.h>

int calculate_sum(int, int);
int main(){ 
int a[5] = {0,1,2,3,4};      
//int b;         
//b = *a;      
//printf("Sum of elements of a: %d\n", calculate_sum(b,5));
printf("Sum of elements of a: %d\n", calculate_sum(a,5)); // you can directly pass an array     
return 0;          
}

//int caluculate_sum(int *a, int size) {
int caluculate_sum(int a, int size) {    
int i;    int sum = 0;    
for(i = 0; i < size; i = i + 1)        
sum = sum + a[i];    
return sum;}
Richie
if you want to pass pointer to array in the function then you might want to change the function body.The function you have written is for taking array as such.
Richie
A: 

thanks, the funtion prototype didnt match the cal, thNKS, I KNEW IT WAS SOMETHING MALL.

henry