What is wrong with the logic of this code that sums bands of numbers?

Asked

Viewed 76 times

1

My algorithm needs to sum all the values between a and b, for example if I type a=3 e b=6 the program needs to speak 3 7 12 18 (3+4= 7/ 7+5=12 / 12+6=18) only he only makes the first two then starts to miss.

#include <stdio.h>  

int main ()  
{  

int a,b,i,n,x,c;  

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

  c=0;  
  for(i=1;i<=b;i++)  
  {  
    c=a;  
    a=c+(a+1);  

    printf("%d\n ",c);  

  }


    return 0;  
}

2 answers

4


The code is a bit confusing and tries to do too many things. Just start the loop with the first data entered and end on the second. The end is correct, but you need to start with a.

#include <stdio.h>  

int main() {
    int a, b;
    printf("Digite a: ");
    scanf("%d", &a);
    printf("Digite b: ");
    scanf("%d", &b);
    int soma = 0;
    for (int i = a; i <= b; i++) {
        soma += i;
        printf("%d ", soma);
    }
}

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

  • Got it, bridagao bro

0

#include <stdio.h>

int main()
{
    int a, b, soma=0, i;

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

    for(i=0; i<=b; i++)
    {
        if(i >= a)
        {
            soma = soma + i;
        }
    }
    printf("%i\n", soma);
}
  • As brief as it may be try to include a note in your code to aid understanding.

Browser other questions tagged

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