Add results and display separately within the loop

1

I'd like to know how to add multiple results. I'm creating a simple application for a particular financial challenge. For example:

double salario = 1500;
double desafio;

for(double mes=1; mes<=12; mes++){
    desafio = (salario * mes)/100;
    System.out.println("Valor do Desafio:" + desafio);
}

This code generates as a result all the monthly values that need to be "deposited", perfect. I wanted to know how I can add all these generated results.

    
asked by anonymous 14.01.2018 / 12:53

2 answers

3

Would that be?

double salario = 1500;
double desafio = 0;

for(double mes=1; mes<=12; mes++){
    desafio += (salario * mes)/100;
    System.out.println("Valor do Desafio:" + desafio);
}

This will sum the previous values with the current one. See working at ideone: link

If you want to continue displaying the values for each month, simply create a temporary variable inside the loop:

double salario = 1500;
double desafio = 0;

for(double mes=1; mes<=12; mes++){
    double mesAtual = (salario * mes)/100;
    desafio += mesAtual;
    System.out.println("Valor do Mes Atual:" + mesAtual);
}

System.out.println("Valor do desafio:" + desafio);

The output will be:

Valor do Mes Atual:15.0
Valor do Mes Atual:30.0
Valor do Mes Atual:45.0
Valor do Mes Atual:60.0
Valor do Mes Atual:75.0
Valor do Mes Atual:90.0
Valor do Mes Atual:105.0
Valor do Mes Atual:120.0
Valor do Mes Atual:135.0
Valor do Mes Atual:150.0
Valor do Mes Atual:165.0
Valor do Mes Atual:180.0
Valor do desafio:1170.0

See working at ideone: link

    
14.01.2018 / 12:56
0

Declare and initialize a variable to receive the total:

double total = 0;

To sum the values use the following command (inside the loop):

total += desafio;

pretty much equals total = total + desafio;

    
14.01.2018 / 13:29