Adding variables in repetition

De_Meerleer_Gilles

New member
Joined
Dec 8, 2021
Messages
2
Programming Experience
Beginner
I am programming a calculator to calculate the expenditure of a group per person. I was wondering if it is possible to add variables in a iteration depending on the number of times the iteration is executed.
 
You can store the value the cumulative sum (or product) into variables with in a loop as long as the variable is declared outside of the scope of the loop.

You cannot declare more variables inside a loop each time the loop iterates because the code that declares the variables are fixed at compile time, but looping happens at run time. One way to simulate additional variables for each loop iteration is to declare an array or instantiate a list outside of the loop, and then use the array entries or add entries into the list each time the loop iterates.

Right now it sounds like all you need is the cumulative sum to get the total group cost. So something like this in pseudo code:
C#:
decimal sum = 0;
foreach(person in group)
{
    sum = sum + person.Expenses;
}
 
You can store the value the cumulative sum (or product) into variables with in a loop as long as the variable is declared outside of the scope of the loop.

You cannot declare more variables inside a loop each time the loop iterates because the code that declares the variables are fixed at compile time, but looping happens at run time. One way to simulate additional variables for each loop iteration is to declare an array or instantiate a list outside of the loop, and then use the array entries or add entries into the list each time the loop iterates.

Right now it sounds like all you need is the cumulative sum to get the total group cost. So something like this in pseudo code:
C#:
decimal sum = 0;
foreach(person in group)
{
    sum = sum + person.Expenses;
}
Thanks for your answer! I will defenetly try it.
 
Back
Top Bottom