Resolved How to store Variable A's *value*, before Variable A is changed in a while loop

vanilliqs

New member
Joined
Jan 3, 2022
Messages
3
Programming Experience
Beginner
Hi, beginner here.

I have this program where I use rnd.next to generate a random number from 1-14, however this happens inside a while loop, and in this while loop, the same variable is responsible for many calculations and it has to be equal to 0 at a point in order for the while loop to continue (To make this happen, I manually set the variable to = 0). I want to know if I can take the variable's previously randomly generated value and STORE it onto another variable Before it reaches the variable = 0 line :
C#:
result = (randomlygeneratednumber);
//find a way to store result's value before it is changed
result = 0;
I tried using if statements like this, but it didn't seem to work, and I tried using else but i kept getting build errors. I'd really appreciate any help as to why what I did doesn't work or if there's any alternative solution, Thanks!

My failed solution below :
C#:
bool Storecheck;
Storecheck = true;
if (Storecheck == true)
{
result = (randomlygeneratednumber);
}
Storecheck = false;
result = 0;
 
Last edited by a moderator:
I want to know if I can take the variable's previously randomly generated value and STORE it onto another variable Before it reaches the variable = 0 line
Yes you can. You should try it out.
 
No it won't. Try the following:
C#:
var rnd = new Random();
int a;
int b;
for(int i = 0; i < 10; i++)
{
    a = rnd.Next();
    b = a;
    a = 0;
    Console.WriteLine($"{a} {b}");
}

I think you maybe mixing up the concept of value types and reference types. With value types, the value is in the variable itself, not in the object being referenced by the variable.
 
I never responded to this, thanks, I found out what it was a while back;

Was previously doing
a = b ;
a = 0;

when it was supposed to be
b = a
a = 0;
like you showed me, Thanks again, will try not to mix these things up in the future!
 

Latest posts

Back
Top Bottom