Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why output is 0 here. i am a newbie (20 days experience)

*i want to copy inputed array in sum_of_elements function as argument and then sum all the elements of array, but i am getting output 0.

#include <stdio.h>

int i, num, sum;
int sum_of_elements(int arr[]) {
  for (i = 0; i < num; i++) {
    for (i = 0; sum = 0, i < num; i++) {
      sum += arr[i];
    }
    return sum;
  }
}
int main() {
  printf("enter number of digits you want to add\n");
  scanf("%d", & num);

  int arr[num];

  for (i = 0; i < num; i++) {
    printf("enter number %d\n", i + 1);
    scanf("%d", & arr[i]);
  }
  int total = sum_of_elements(arr);
  printf("%d", total);

  return 0;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue was with the double for loop in your sum_of_elements function.

Removing the extra for loop, resolves the error.

#include <stdio.h>

int i, num, sum;
int sum_of_elements(int arr[]) {
    for (i = 0; i < num; i++) {
        sum += arr[i];
    }
    return sum;
}
int main() {
    
    
      printf("enter number of digits you want to add\n");
      scanf("%d", & num);
    
      int arr[num];
    
      for (i = 0; i < num; i++) {
        printf("enter number %d\n", i + 1);
        scanf("%d", &arr[i]);
      }
      int total = sum_of_elements(arr);
      printf("%d", total);
    
      return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading