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

Time:11-28

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

CodePudding user response:

Look at this line of code:

for (i = 0; sum = 0, i < num; i  ) {

This resets sum to 0 every loop.

It should be

for (i = 0, sum = 0; i < num; i  ) {

But it's probably better to do this:

sum = 0;
for (i = 0; i < num; i  ) {

CodePudding user response:

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