Function that is not running in C

Asked

Viewed 97 times

1

This is a code whose goal is to add all the integers between a and b. Being "a" less than "b". The expected output was a number representing this sum, however, after reading a and b, nothing happens.

#include <stdio.h>
int soma(int n1,int n2) 
{
    int i,s; 
    for(i;n2-1;i++) 
        s=s+i; 
    }
    return s; 
}
int main()
{
    int a,b,s; 
    printf("Digite dois numeros:");
    scanf("%d %d",&a,&b);
    s=soma(a,b);
    printf("Soma=%d",s);
    return 0;
}
  • 4

    What is the initial value of variable i in your command for? Wouldn’t it be: for (i=n1; i<=N2; i++)? Also the variable s should be initialized with zero.

1 answer

1


You haven’t given a specific criteria clear where it starts and where it ends, but the error may be at most one. This code of yours makes no sense. It does not have the correct boot block and should start the variable by some value, preferably where the sequence will start and should have a loop termination condition, so there should be a comparison if the variable has already arrived where it needs to, that is, until the number of the end of the sequence.

In addition to this it failed to initialize the sum so it can start with a random value whatever is in memory which will give a wrong result.

#include <stdio.h>

int soma(int n1, int n2) {
    int soma = 0;
    for (int i = n1; i < n2; i++) soma += i; 
    return soma; 
}
int main() {
    int a, b; 
    printf("Digite dois numeros:");
    scanf("%d %d",&a,&b);
    printf("\nSoma = %d", soma(a, b));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.