开发者

Write a function int caluculate_sum(int *a, int size) that calculates the sum of all the elements in an array

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;
}


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.


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.


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;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜