Question

Excuse me if this tread has already been published before, I have few time for getting this code right because I need to send it tomorrow to my programming teacher but I'm not able to see what's wrong. It's simply a summa code with a limit number...but it keeps wrong. I tried to write the same instructions in C++ and it somehow works. Why!?

#include <stdio.h> 
int main()
{
    int a, n, suma;

    suma = 0;

    printf("Introduce un numero límite \n");

    scanf("%d", n);        

    for(a=0; a <= n; a++)
    {
        suma=suma+a;
    }

    printf("La suma de todos los numeros es: %d", suma);
}

Ignore the prints...they are just interacting with the user: "where should I stop adding numbers? The sum is...". Things alike.

I would be very thankful to you if you could help me. I'm at first year and a I am a newbie in C...

Oh! All the compiling warnings: http://puu.sh/54Rnh.png

Was it helpful?

Solution

Pass the address of n in scanf

scanf("%d", &n);

Just as a side note, you don't need to start your loop from 0 to calculate the sum

for(a=1; a <= n; ++a) //start from 1

Doesn't do much but saves one iteration.

Also, use preincrement when you do not intend to use the result of the expression as it has a slightly lesser overhead than postincrement.

OTHER TIPS

The scanf() function requires the address of the respective variables (n) declared in the string format "%d". Change your code to:

scanf("%d", &n); 

and everything will be OK and your teacher will give you a good note

scanf() reads in from the standard input stream. To store what has been read, you need to provide a proper address. Pointers hold the address.

& is unary operator helps you get the address of the operand.

&n is a valid pointer expression, provides you the address of n, wherein you will want to store the value for n

So, turn your scanf() to

scanf("%d",&n);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top