Programming language novice help with C#-For loops

Updated 2 days ago in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 3 days ago

In https://www.youtube.com/watch?v=eIsGXwisKPE&list=PLPV2KyIb3jR6ZkG8gZwJYSjnXxmfPAl51&index=6

there’s a part I need help with such as printing out numbers each on a separate line- (1-10). https://pastebin.com/Xvk4PANZ. I tried my own code, but it didn’t work so I tried the latter, and it didn’t work either. https://pastebin.com/cg9YdMDm. Please help. 

  • Liked by
Reply
0 3 days ago

Your latter attempt is close, and could technically work, but it’s not following a standard for loop pattern.

You have:

for (int i = 0; i <= 9)
{
     console.WriteLine (I);
     I += 1;
}

 

Which while this could work, there are a few issues.

  1. You have 2 different  variable (i, and I) both of which are completely different variables.
  2. While you can change the index variable inside the loop, typically you just let the for loop handle that.

Try this:

for(int i = 0; i <= 9; i++)
{
     console.WrightLine(i);
}

 

The proper format for a for loop is:

for(index; while something; do this)

“Index” are you variables, yes you can have multiple in 1 for loop, that your going to use in your loop. (or not, you don’t have to use them, I guess)

“While something” is some condition that will cause the loop to keep going until it is false.

“Do this” is what the loop is gonna do every time it starts over. In most cases, you just increase the index.

 

Fun tip, you can do your line print thing with nothing inside the for loop. It might look something like this:

for(int i = 0; i <=9; console.WrightLine(i++)) {}

The only thing to note here, is where the ++ are relative to the i. If it’s ‘i++’ then i is printed to the screen before the ++ happens, while ‘++i’ will increase i before reading it.

  • Liked by
Reply
Cancel

Thanks.

  • Liked by
Reply
Cancel