The first thing is that I see that you have declared variables for each person, when using the for loop, you only need a variable of type float in this case. In my case, I'm going to call the variable: money . float dinero;
This variable will store the money that each person has. Next, we will create another variable of type float called sum : float suma = 0.0f;
. Here it is important to equal it to 0 because otherwise, the variable sum will be initialized with the value that is stored in the memory address in which our variable has been saved. With this variable, we will be carrying the sum of all the money.
Before continuing with the code, I give you another tip when it comes to naming variables: EVITA start the first letter of a variable in capital , that is, it is better this int numero;
than this int Numero;
. The first uppercase letter is usually used when creating classes or methods .
Now yes, we start with the code:
#include <iostream>
using namespace std;
int main(){
float dinero, suma = 0;
for (int i = 1; i <= 5; i++){
cout << "Introduce el dinero que tienes: ";
cin >> dinero;
suma += dinero;
}
cout << "Teneis " << suma << " euros." << endl;
return 0;
}
I created the for loop as you can see in the code. In that loop, we start by creating a variable that is responsible for keeping track of the cycle of the loop: int i = 1;
. I initialize it to 1 so that the loop repeats 5 times.
Next, we set the condition to exit the loop. In this case it is: i <= 5;
. This means that as long as the value of the variable i is less than or equal to 5, the loop will continue to run.
The last thing is to increase the value of the variable i to 1 ( i++
), otherwise the variable i will always be the initial value and the loop will be Infinite .
Inside the loop, you will ask us to enter the money we have. In the following line of code, the variable sum will store the sum of the value entered in each cycle of the loop: suma += dinero;
(is the same as putting suma = suma + dinero;
.) But in this case, we repeat suma
twice and it's not good to repeat code in programming).
When i is 6, we will exit the loop and the content of the sum variable will be displayed on the screen.
Another thing to mention is that you have to put return 0;
at the end of the program, if not, the program will close automatically. You have used system("PAUSE");
. I do not know if you have run the program, but seeing your code, it will not let you compile the program. If you want to use that line I think you have to add another library.
This is all. I have seen that in other answers they have done the example with vectors. I think without vectors, it's simpler and faster to do. Since each one choose how to do this exercise. Greetings and I hope I have helped you!