0

I was thinking of a code to find the sum of numbers.

So i wrote bellow code :

#include <stdio.h>
#include <math.h>
int main()
{
    int n,i,s=0,a[100];
    printf("enter number of numbers");
    scanf("%d",n);
    for(i=1;i<=n;i++)
    scanf("%d",&a[i]);
    s=0;
    for (i=1;i<=n;i++)
     {s=s+a[i];}
    printf("sum is%d\n",s);
}

But in the output it shows segmentation error . I.e.enter image description here

So whats the mistake?

user187604
  • 148
  • 8

2 Answers2

2

So this line:

scanf("%d",n);

should be replaced by

scanf("%d",&n);

Explanation:

scanf() reads data from stdin according to format and store data in the location pointed by next additional argument. this case, format is %d means we want to read an integer number and this integer number will be stored in the location of n. The & operator is to get the location of a variable in C.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
Loc Tran
  • 1,170
  • 7
  • 15
2

Use this :

scanf("%d",&n);

The reason :

You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.

Examples :

scanf("%d %d", &a, &b);
printf("%d %d", a, b);

As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value. But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.