C
C#3w ago
Kenji!!!

✅ For loops, while loops, and TryParses

I still don't understand them, nor do I know how to apply em.
133 Replies
canton7
canton73w ago
That's a very vague question, which makes it hard to answer. Loops are completely different to TryParse What specifically are you having trouble with?
MODiX
MODiX3w ago
Angius
REPL Result: Success
for (int i = 0; i <= 5; i++)
{
Console.WriteLine($"Number is {i}");
}

string[] arr = { "foo", "bar", "baz" };
foreach (string s in arr)
{
Console.WriteLine($"The word is'{s}'");
}

string str = "69";
bool parsed = int.TryParse(str, out int num);
Console.WriteLine($"Parsed: {parsed} and number is {num}");
for (int i = 0; i <= 5; i++)
{
Console.WriteLine($"Number is {i}");
}

string[] arr = { "foo", "bar", "baz" };
foreach (string s in arr)
{
Console.WriteLine($"The word is'{s}'");
}

string str = "69";
bool parsed = int.TryParse(str, out int num);
Console.WriteLine($"Parsed: {parsed} and number is {num}");
Console Output
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
The word is'foo'
The word is'bar'
The word is'baz'
Parsed: True and number is 69
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
The word is'foo'
The word is'bar'
The word is'baz'
Parsed: True and number is 69
Compile: 516.128ms | Execution: 55.582ms | React with ❌ to remove this embed.
Kenji!!!
Kenji!!!OP3w ago
Sorry, so here's what I don't really get; I know the format it's in, but not the specifics for example, "for (int i = 1; i <= num; i++)", or "while(true)", I really don't get it thus I can't really apply it... Since I also mentioned TryParses I just don't get em at all, I only mentioned it since I learned with both loops in a course I'm going through Wth
canton7
canton73w ago
Have a run through https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/branches-and-loops?tutorial-step=1, then if you don't understand something specific, ask here
Branches and loops - Introductory interactive tutorial
In this tutorial about branches and loops, you'll use your browser to learn C# interactively. You'll write C# code and see the results of compiling and running your code directly in the browser.
Mąż Zuzanny Harmider Szczęście
int i=0 //start from 0
i<=5//end when i reaches 5
i++ //after each iterration increase i by 1
int i=0 //start from 0
i<=5//end when i reaches 5
i++ //after each iterration increase i by 1
thats what u mean by dont understand @Kenji!!!
Kenji!!!
Kenji!!!OP3w ago
Then what is I, like why do we have it
Angius
Angius3w ago
In other words,
for(start state; run condition; state modifier)
for(start state; run condition; state modifier)
Mąż Zuzanny Harmider Szczęście
i is just a number to keep track of iterrations a for loop could as well just be for(;;)
Angius
Angius3w ago
Think of it this way:
for (int i = 0; i <= 5; i++)
{
Console.WriteLine($"Number is {i}");
}
for (int i = 0; i <= 5; i++)
{
Console.WriteLine($"Number is {i}");
}
can be written as
int i = 0;
while(i <= 5)
{
Console.WriteLine($"Number is {i}");
i = i + 1;
}
int i = 0;
while(i <= 5)
{
Console.WriteLine($"Number is {i}");
i = i + 1;
}
MODiX
MODiX3w ago
Angius
REPL Executing
Compiling and Executing your code...
Mąż Zuzanny Harmider Szczęście
int number = 0; //initialize number at 0
while(number<5){ //run until number is lower than 5
Console.WriteLine(number);
number++; //increase number by one
}
int number = 0; //initialize number at 0
while(number<5){ //run until number is lower than 5
Console.WriteLine(number);
number++; //increase number by one
}
Kenji!!!
Kenji!!!OP3w ago
What if I wanted to make something like the following, " * ** "?
Mąż Zuzanny Harmider Szczęście
what? u mean like a slope of * characters?
Kenji!!!
Kenji!!!OP3w ago
Yeah
Mąż Zuzanny Harmider Szczęście
for(int i=0;i<5;i++){ // run for 5 loops
for(int j=0;j<i;j++){ //run for i loops
Console.Write("*");
}
Console.Write("\n");
}
for(int i=0;i<5;i++){ // run for 5 loops
for(int j=0;j<i;j++){ //run for i loops
Console.Write("*");
}
Console.Write("\n");
}
canton7
canton73w ago
Then you want 2 loops. The first one prints each line every time it loops, and then there's a second one inside which prints the right number of '*'s
Angius
Angius3w ago
Or
No description
canton7
canton73w ago
They're obviously trying to learn basic loops. That's unhelpful
Mąż Zuzanny Harmider Szczęście
wtf, didnt know u could do that in c#
Angius
Angius3w ago
Fair
canton7
canton73w ago
Also your terminal is broken ><
No description
Mąż Zuzanny Harmider Szczęście
is is basically:
Kenji!!!
Kenji!!!OP3w ago
wait what's /n
Angius
Angius3w ago
Ligatures \n is newline
MODiX
MODiX3w ago
Angius
REPL Result: Success
Console.WriteLine("hello\n\nworld");
Console.WriteLine("hello\n\nworld");
Console Output
hello

world
hello

world
Compile: 342.738ms | Execution: 18.458ms | React with ❌ to remove this embed.
canton7
canton73w ago
.WriteLine() does (roughly) the same as .Write("\n")
Kenji!!!
Kenji!!!OP3w ago
Oh wait so new string would be the same?
Angius
Angius3w ago
Wait until you see \t :when:
Mąż Zuzanny Harmider Szczęście
\n is a way to say newline what did it do? it that a tab?
Kenji!!!
Kenji!!!OP3w ago
Since in your code you've written newstring
Angius
Angius3w ago
.WriteLine("foo") is the same as .Write("foo" + "\n") Yeah, \t is a tab
Kenji!!!
Kenji!!!OP3w ago
I get that, but what's new string then
No description
canton7
canton73w ago
Ignore that code They went too advanced too quickly
Angius
Angius3w ago
It repeats the given character a number of times
Kenji!!!
Kenji!!!OP3w ago
I understand that one way more
Mąż Zuzanny Harmider Szczęście
it creates a new string of length i all filled with *
MODiX
MODiX3w ago
Angius
REPL Result: Success
new string('x', 5)
new string('x', 5)
Result: string
xxxxx
xxxxx
Compile: 190.682ms | Execution: 14.982ms | React with ❌ to remove this embed.
canton7
canton73w ago
The point of this exercise is to understand loops
Kenji!!!
Kenji!!!OP3w ago
I get that, but when I see advanced applications of concepts I get to understand stuff easier dk why
canton7
canton73w ago
This is unrelated to loops, though
Mąż Zuzanny Harmider Szczęście
btw tryparse tries to parse something and if it parses successfully it returns true otherwise it returns false
Kenji!!!
Kenji!!!OP3w ago
Yeah, but it's part of that code and since it's shorter and clearer I just end up asking one thing Ik that, I just don't get the entire format
Angius
Angius3w ago
int num;
bool wasParsingSuccessful = int.TryParse("45", out num);
int num;
bool wasParsingSuccessful = int.TryParse("45", out num);
Which part of this, in particular, is unclear?
Kenji!!!
Kenji!!!OP3w ago
int.TryParse("45", out num) | |
Angius
Angius3w ago
int.TryParse(string to parse, where to put the number)
Kenji!!!
Kenji!!!OP3w ago
ohhhhhhhhh Thank you!
canton7
canton73w ago
out is a mechanism for returning multiple values from a method.
int Test(out int first, out int second)
{
first = 1;
second = 2;
return 3;
}

int first;
int second;
int test = Test(out first, out second);
int Test(out int first, out int second)
{
first = 1;
second = 2;
return 3;
}

int first;
int second;
int test = Test(out first, out second);
When we declare a method parameter as out, it means we use it to pass a value out of the method, rather than passing a value into the method
Mąż Zuzanny Harmider Szczęście
to explain this code:
int num; //initialize a variable to store number
bool wasParsingSuccessful = int.TryParse("45", out num); // return wherether parse was successfull
// out num is basically if parse was success then write result to num
int num; //initialize a variable to store number
bool wasParsingSuccessful = int.TryParse("45", out num); // return wherether parse was successfull
// out num is basically if parse was success then write result to num
canton7
canton73w ago
TryParse uses that to output 2 values: it returns a bool saying whether parsing was successful, and also uses an out parameter to return the parsed value
Mąż Zuzanny Harmider Szczęście
to explain this code:
int Test(out int first, out int second)
{
first = 1;
second = 2;
return 3;
}

int first; //this is overwriten with 1
int second; //this is overwriten with 2
int test = Test(out first, out second); //test is equal to 3
int Test(out int first, out int second)
{
first = 1;
second = 2;
return 3;
}

int first; //this is overwriten with 1
int second; //this is overwriten with 2
int test = Test(out first, out second); //test is equal to 3
its basically a way to mutate passed values
Kenji!!!
Kenji!!!OP3w ago
Wdym by mutate?
Mąż Zuzanny Harmider Szczęście
change so instead of doing:
int addOne(int num){
return num+1;
}
int a=1;
a=addOne(a);
int addOne(int num){
return num+1;
}
int a=1;
a=addOne(a);
you can just do:
void addOne(out int num){
num+=1;
}
int a=1;
addOne(out a);
void addOne(out int num){
num+=1;
}
int a=1;
addOne(out a);
FusedQyou
FusedQyou3w ago
Argument 1 must be passed with the 'out' keyword
-addOne(a);
+addOne(out a);
-addOne(a);
+addOne(out a);
Kenji!!!
Kenji!!!OP3w ago
So I made this Console.WriteLine("enter number"); Console.ReadLine(); int num; while (!int.TryParse(Console.ReadLine(), out num)) { Console.WriteLine("Invalid input! Please enter a positive integer greater than 0."); } for (int i = 1; i <= num; i++) { Console.WriteLine("*"); } Console.Write("\n"); It has 2 issues most important one is that it doesn't make a slope it just repeats the charcther
Mąż Zuzanny Harmider Szczęście
two forloops because: one forloop is for rows second is for columns
Kenji!!!
Kenji!!!OP3w ago
ah I'll try to apply it
Mąż Zuzanny Harmider Szczęście
and change WriteLine to Write in this code you could enter a -1, there's no check for that
Kenji!!!
Kenji!!!OP3w ago
What would that do What's the difference
Mąż Zuzanny Harmider Szczęście
it just wouldnt run the loops
for(int i=0;i<5;i++){
Console.Write("*");
}
//*****
for(int i=0;i<5;i++){
Console.WriteLine("*");
}
//*
//*
//*
//*
//*
for(int i=0;i<5;i++){
Console.Write("*");
}
//*****
for(int i=0;i<5;i++){
Console.WriteLine("*");
}
//*
//*
//*
//*
//*
FusedQyou
FusedQyou3w ago
WriteLine applies an enter at the end of the line basically Write does not Or in other words, it adds a line end
Kenji!!!
Kenji!!!OP3w ago
Console.Write("enter number"); Console.ReadLine(); int num; while (!int.TryParse(Console.ReadLine(), out num)) { Console.WriteLine("Invalid input! Please enter a positive integer greater than 0."); } for (int i = 0; i < num; i++) { for (int j = 0; j < i; j++) { Console.Write("*"); } Console.Write("\n"); } alright thanks But it still worked without a-1 or whatever that is
Mąż Zuzanny Harmider Szczęście
if you want to check for negative just inside while add &&num>0
Kenji!!!
Kenji!!!OP3w ago
wha
Mąż Zuzanny Harmider Szczęście
//if parsed successfully and num is higher than 0
while (!int.TryParse(Console.ReadLine(), out num)&&num>0)
//if parsed successfully and num is higher than 0
while (!int.TryParse(Console.ReadLine(), out num)&&num>0)
i hate drawing * inside console so much, the teacher made me do christmass trees inside the console for like 3 months straight
Kenji!!!
Kenji!!!OP3w ago
Still dk what that does
Mąż Zuzanny Harmider Szczęście
!int.TryParse(Console.ReadLine() // if parse was successful
&& // and operator
num>0 // num is higher than 0
!int.TryParse(Console.ReadLine() // if parse was successful
&& // and operator
num>0 // num is higher than 0
Kenji!!!
Kenji!!!OP3w ago
so mutate, and make sure it's higher than 0?
canton7
canton73w ago
Isn't your logic inverted there? If the parse is not successful, and num > 0...
Mąż Zuzanny Harmider Szczęście
not sure if u have to do a null check tho its while
Anton
Anton3w ago
people please don't try to put multiple steps in a single line
Anton
Anton3w ago
use an infinite loop
FusedQyou
FusedQyou3w ago
Code makes no sense
Mąż Zuzanny Harmider Szczęście
it should be num<0
Anton
Anton3w ago
and break out manually
canton7
canton73w ago
No it shouldn't
Mąż Zuzanny Harmider Szczęście
thats also a way
FusedQyou
FusedQyou3w ago
You have to remove the !
canton7
canton73w ago
If int.TryParse returns false, num is always 0
FusedQyou
FusedQyou3w ago
The reason it's confusing is because you should not make a conditional like this Just put it on separate lines
Mąż Zuzanny Harmider Szczęście
but he wants the user to repeat until passed a valid number
FusedQyou
FusedQyou3w ago
Because I don't think it helps the case Yes use a while loop that just has true in it and break; manually
canton7
canton73w ago
You probably want || rather than && then. But splitting it out a bit rather than cramming everything onto one line will help
Kenji!!!
Kenji!!!OP3w ago
huh
FusedQyou
FusedQyou3w ago
It's going to be confusing for them, definitely, but in the end it willbe a lot easier to manage
Kenji!!!
Kenji!!!OP3w ago
while (true) { string input = Console.ReadLine();
if (int.TryParse(input, out num) && num > 0) { Console.WriteLine(new string('*', num)); break; } else { Console.WriteLine("Invalid input. Please enter a positive number."); } ?
FusedQyou
FusedQyou3w ago
Yes, this is exactly what I mean
Kenji!!!
Kenji!!!OP3w ago
🔥
FusedQyou
FusedQyou3w ago
Infinite while loop until they pass the correct number, in which case it ends by breaking the loop with break; Nice
Kenji!!!
Kenji!!!OP3w ago
also
FusedQyou
FusedQyou3w ago
Now I can't comment on if it ends up working as a whole, but this correcty gets a number
Kenji!!!
Kenji!!!OP3w ago
Console.Write("enter number"); Console.ReadLine(); int num; while (!int.TryParse(Console.ReadLine(), out num)) { Console.Write("Invalid input! Please enter a positive integer greater than 0."); } for (int i = 0; i < num; i++) { for (int j = 0; j < i; j++) { Console.Write(""); } Console.Write("\n"); } for (int i = 0; i < - num; i++) { for(int j = 0; j < - i; j++) { Console.Write(""); } } Console.Write("*"); I'll do a while version later So i'm trying to reverse it now * * * ** * ** * Like this Wait uh
Mąż Zuzanny Harmider Szczęście
a reversed slope?
Kenji!!!
Kenji!!!OP3w ago
yeah
Mąż Zuzanny Harmider Szczęście
inside j start from i and substract one
Kenji!!!
Kenji!!!OP3w ago
for(int j = i; j < - i; j--)?
Mąż Zuzanny Harmider Szczęście
for(int i=0;i<5;i++){
for(int j=i;j>0;j--){
//print
}
//newline
}
for(int i=0;i<5;i++){
for(int j=i;j>0;j--){
//print
}
//newline
}
Kenji!!!
Kenji!!!OP3w ago
oh j greater than 0
Mąż Zuzanny Harmider Szczęście
just the -i wrong btw if u want to do codeblocks: \
Kenji!!!
Kenji!!!OP3w ago
didn't work
No description
Kenji!!!
Kenji!!!OP3w ago
just the output
Mąż Zuzanny Harmider Szczęście
```<language>(for example cs (c#)) ``` hmm, idk then, i really hate doing this stuff, i get flashbacks
Kenji!!!
Kenji!!!OP3w ago
\like this\ damn \damn\
Mąż Zuzanny Harmider Szczęście
use `x3 then newline and `x3 again




Kenji!!!
Kenji!!!OP3w ago
wdym by that
SG97
SG973w ago
$code
MODiX
MODiX3w ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Mąż Zuzanny Harmider Szczęście
Console.WriteLine("HelloWorld")
Console.WriteLine("HelloWorld")
No description
Kenji!!!
Kenji!!!OP3w ago
Console.Write("enter number");
Console.ReadLine();
int num;

while (!int.TryParse(Console.ReadLine(), out num))
{
Console.Write("Invalid input! Please enter a positive integer greater than 0.");
}

for (int i = 0; i < num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (int i = 0; i < - num; i++)
{
for(int j = i; j > 0; j++) {
Console.Write("*");
}
}
Console.Write("*");
Console.Write("enter number");
Console.ReadLine();
int num;

while (!int.TryParse(Console.ReadLine(), out num))
{
Console.Write("Invalid input! Please enter a positive integer greater than 0.");
}

for (int i = 0; i < num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (int i = 0; i < - num; i++)
{
for(int j = i; j > 0; j++) {
Console.Write("*");
}
}
Console.Write("*");
ah
Mąż Zuzanny Harmider Szczęście
yeah and u can add language after the ``` for example c# is cs
Kenji!!!
Kenji!!!OP3w ago
oh shi
Mąż Zuzanny Harmider Szczęście
at the top one
Kenji!!!
Kenji!!!OP3w ago
Console.Write("enter number");
Console.ReadLine();
int num;

while (!int.TryParse(Console.ReadLine(), out num))
{
Console.Write("Invalid input! Please enter a positive integer greater than 0.");
}

for (int i = 0; i < num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (int i = 0; i < - num; i++)
{
for(int j = i; j > 0; j++) {
Console.Write("*");
}
}
Console.Write("*");
Console.Write("enter number");
Console.ReadLine();
int num;

while (!int.TryParse(Console.ReadLine(), out num))
{
Console.Write("Invalid input! Please enter a positive integer greater than 0.");
}

for (int i = 0; i < num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (int i = 0; i < - num; i++)
{
for(int j = i; j > 0; j++) {
Console.Write("*");
}
}
Console.Write("*");
Mąż Zuzanny Harmider Szczęście
yeah it adds highlights which helps when reading code
Kenji!!!
Kenji!!!OP3w ago
using System;

class Program
{
static void Main()
{
int num;
Console.Write("Enter a positive integer greater than 0: ");

while (!int.TryParse(Console.ReadLine(), out num) || num <= 0)
{
Console.Write("Invalid input! Please enter a positive integer greater than 0: ");
}

for (int i = 1; i <= num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}

for (int i = num - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
using System;

class Program
{
static void Main()
{
int num;
Console.Write("Enter a positive integer greater than 0: ");

while (!int.TryParse(Console.ReadLine(), out num) || num <= 0)
{
Console.Write("Invalid input! Please enter a positive integer greater than 0: ");
}

for (int i = 1; i <= num; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}

for (int i = num - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
canton7
canton73w ago
The mix of up-counting loops, down-counting loops, loops starting at 1 and at 0, is really jarring ><
Mąż Zuzanny Harmider Szczęście
yeah it makes my brain go into error mode
Kenji!!!
Kenji!!!OP3w ago
It be painful Well it's weird to me ask here, but what're concepts I should learn for game dev
Mąż Zuzanny Harmider Szczęście
dont understand the question Models, Views and ViewModels are a good start mvvm for short
Kenji!!!
Kenji!!!OP3w ago
are those to display graphics or for scripting
Mąż Zuzanny Harmider Szczęście
bost both nvm, scripting mvvm is a very clean way to code
FusedQyou
FusedQyou3w ago
MVVM is great
Kenji!!!
Kenji!!!OP3w ago
Alright after I finish my course I'll learn those Do they give any headstarts for c++ since I want learn that too sorry to ask this here
Angius
Angius3w ago
I mean, sure, knowing C# will give you a headstart in C++ With all that said, I don't think MVVM is used all that often in gamedev Unreal Engine uses it for UI binding... but that's about it
FusedQyou
FusedQyou3w ago
Not a native thing in Unity at least, though I can see the benefit of implementing a system for it Oh, look, it does actually exist in a way https://docs.unity3d.com/Packages/[email protected]/manual/mvvm-intro.html
canton7
canton73w ago
Yeah, that's certainly nowhere near where I'd start for game dev!
MODiX
MODiX3w ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?