C
C#2y ago
krixsick

❔ C# Error with a while loop (course work)

Hello! This i my code currently. The main issue that arises is that the code will still print out -9 for some reason. I'm not too sure on why it does that because I have a module function that checks whether a number is divisible by 3 or not. I was told not to change the "if (i == 11). { Console.WriteLine(" FINAL BREAK REACHED! This should not happen!"); break; } Console.WriteLine(i++);" part but to instead add code inside the while function to do that. My goal is for the loop should skip all divisible by 3 values and stop running when i = 10. So far it achieves this result for the other numbers expect for -9 namespace Challenge_LoopsOneAverage { internal class Program { static void Main(string[] args) { int i = -10; while (true) { if (i % 3 == 0) { i++; continue; } else if (i == 10) { break; } Console.WriteLine(i++); if (i == 11) { Console.WriteLine(" FINAL BREAK REACHED! This should not happen!"); break; } Console.WriteLine(i++); } } } }
6 Replies
krixsick
krixsickOP2y ago
namespace Challenge_LoopsOneAverage
{
internal class Program
{
static void Main(string[] args)
{
int i = -10;

while (true)
{

if (i % 3 == 0)
{
i++;
continue;
}
else if (i == 10)
{
break;
}
Console.WriteLine(i++);
if (i == 11)
{
Console.WriteLine(" FINAL BREAK REACHED! This should not happen!");
break;
}
Console.WriteLine(i++);
}
}
}
}
namespace Challenge_LoopsOneAverage
{
internal class Program
{
static void Main(string[] args)
{
int i = -10;

while (true)
{

if (i % 3 == 0)
{
i++;
continue;
}
else if (i == 10)
{
break;
}
Console.WriteLine(i++);
if (i == 11)
{
Console.WriteLine(" FINAL BREAK REACHED! This should not happen!");
break;
}
Console.WriteLine(i++);
}
}
}
}
TravestyOfCode
So we can step through this to try and determine where the problem is comming from. Starting with -10, the first if is not true (-10 % 3) is not zero. Next, -10 is not 10, so we skip the else if. Next we write to the console the value of i and then increment it. So console shows -10, and i now equals -9. We then continue on with the next if, -9 is not 11, so we skip the if and go to the Console.WriteLine
Teddy
Teddy2y ago
while (true)
{
if (i % 3 == 0)
{
i++;
continue;
}
else if (i == 10)
{
break;
}
Console.WriteLine(i++); <---
if (i == 11)
{
...
}
Console.WriteLine(i++); <---
}
while (true)
{
if (i % 3 == 0)
{
i++;
continue;
}
else if (i == 10)
{
break;
}
Console.WriteLine(i++); <---
if (i == 11)
{
...
}
Console.WriteLine(i++); <---
}
The incrementing of i twice in a given loop
TravestyOfCode
Yep
krixsick
krixsickOP2y ago
OH Okok Ims tupid lol Tysm I forgot htat was outside the loop I appreciate the help Tof and Zane!
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server