Converting a while loop to a for loop
Hey guys, super new to these forums but I was having some issues converting a while loop/if statem to a for loop so it has the same functionality. I'm not even sure it's possible :s: My attempt is at the bottom. (I'm sure i'm doing it completely wrong but i'm a noob so please help me out) :(nod):
Code:
int k = 0;
int sum = 0;
while (sum < n){
k = k + 1;
sum = sum + k;
}
if (sum > n){
k = 0;
}
This is my attempt:
Code:
for (int sum=0; sum<n; sum = sum+k)
{
k = k + 1;
if (sum > n){
k = 0;
}
}
Thanks for your time!
Re: Converting a while loop to a for loop
You need to get your indenting sorted out first off.
What are you seeing with the bottom code that you aren't seeing in the original while loop code?
Re: Converting a while loop to a for loop
There is code missing, I'm not sure whether you've just snipped it out or you've forgotten it.
The integers k & sum can be declared and defined once in the top of your code, and after that your for-loop only has to be about one line of code. Study how you build a for-loop, and as Tolls said, sort out the indenting so the code is manageable and easy to read.
Re: Converting a while loop to a for loop
Thanks for the advice so far. As for the indenting, that was just a copying mistake from my code to the forum, I think all my code is correctly indented. I've now managed to get to this point now and it seems to be working. Am i able to include the if statement into the for loop to simplify this code any further?
Code:
int k = 0;
int sum = 0;
for (sum=0; sum<n; sum=sum+k)
{
k = k + 1;
}
if (sum > n)
{
k = 0;
}
Re: Converting a while loop to a for loop
Why would that simplify it?
It would be the same amount of code.
Re: Converting a while loop to a for loop
I'm wondering if there is a better way to write that segment of code that would be simplified. Sorry if i'm not coming across clear like I said, first post and very new.
I appreciate your help but your answers are only really questions back at me and they make me feel dumb. I'm asking these questions because I don't know myself and needed a little assistance.
Re: Converting a while loop to a for loop
I'm only asking because I don't really understand what you are getting at.
You've achieved what you set out to do, which is turn the while loop into a for loop.
If you put the 'if' statement into the loop it will do the check everytime it goes round the loop and, since the loop exits when sum >= n, the 'if' statement will never be true.
Re: Converting a while loop to a for loop
Converting a while loop to a for loop is easy (always):
Code:
while: while (<boolean_expression>) <statement>;
for: for (; <boolean_expression>; ) <statement>;
The other way around is a bit trickier if you want to pay notice to the scope of variables and abnormal termination/continuation of the loops.
kind regards,
Jos