Why the result of this code in C of 55?

1

I wanted to know why the result of this code is 55, I'm reading the book and I did not understand it, I compiled it in codeblocks.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, soma = 0;
    for(i=1;i<=10;i++) {

    soma = soma + i;
}
printf("Soma %d\n", soma);
system("pause");
return 0;
}
    
asked by anonymous 13.05.2015 / 05:06

2 answers

4

I suggest adding the following line inside the for:

printf("i vale %d Soma vale%d\n",i, soma);

Getting:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int i, soma = 0;
    for(i=1;i<=10;i++) {
        soma = soma + i;
        printf("i vale %d Soma vale %d\n",i, soma);
    }
    printf("Soma %d\n", soma);
    system("pause");
    return 0;
}

Then you will know that ...

i vale 1 Soma vale 1  //1ª Iteração
i vale 2 Soma vale 3  //2ª Iteração
i vale 3 Soma vale 6  //3ª Iteração
i vale 4 Soma vale 10  //4ª Iteração
i vale 5 Soma vale 15  //5ª Iteração
i vale 6 Soma vale 21  //6ª Iteração
i vale 7 Soma vale 28  //7ª Iteração
i vale 8 Soma vale 36  //8ª Iteração
i vale 9 Soma vale 45  //9ª Iteração
i vale 10 Soma vale 55  //10ª Iteração

When you do soma = soma + i; you increment the sum value by adding what you previously had.

For example, when i = 3 and soma = 3 , then sum will become valid 6 because soma recebe soma (que vale 3) + i (que vale 3)

I recommend that you start by taking a piece of paper and pencil and writing down the value of each iteration within the for loop. This way you will understand what happens in each iteration.

    
13.05.2015 / 05:20
0

Well come on, you're looping with the variable int i which in the first iteration of for has the value of 1. You also assumed that int soma has a value of 0. Your loop will run until int i reaches the value of 10, remembering that you started it as 1 for (i = 1; your loop will run while int i is less than or equal to 10 i <= 10;

Let's now simulate your loop step by step.

First Iteration

sum = sum + i; Soma = 0 | int i = 1 | Resultado = 1

Second Iteration

sum = sum + i; Soma = 1 | int i = 2 | Resultado = 3

Third Iteration

sum = sum + i; Soma = 3 | int i = 3 | Resultado = 6

Fourth Iteration

sum = sum + i; Soma = 6 | int i = 4 | Resultado = 10

Fifth Iteration

sum = sum + i; Soma = 10 | int i = 5 | Resultado = 15

Sixth Iteration

sum = sum + i; Soma = 15 | int i = 6 | Resultado = 21

Seventh Iteration

sum = sum + i; Soma = 21 | int i = 7 | Resultado = 28

Eighth Iteration

sum = sum + i; Soma = 28 | int i = 8 | Resultado = 36

Ninth Iteration

sum = sum + i; Soma = 36 | int i = 9 | Resultado = 45

Tenth Iteration

sum = sum + i; Soma = 45 | int i = 10 | Resultado = 55

#include <stdio.h>
#include <stdlib.h>

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

    for (i = 1; i <= 10; i++) 
    {  
        soma = soma + i;
    }

    printf("Soma %d\n", soma);
    getchar();
    return 0;
}
    
13.05.2015 / 05:45