Jump to content

While Loops C#

RockyRZ
Go to solution Solved by minibois,
8 hours ago, Sakuriru said:

This code has two bugs.

  1. The greater than or equal to symbol is ">=" and not "=>".
  2. When input is less than zero it will include it in the total calculation.

If I told you I included those errors on purpose, so OP still had to debug some code, would that be believable?
No? Okay.. 😔

/s

 

Thanks for the corrections, I just kinda typed that code on the spot and it's clear I rely a bit on Visual Studio showing me a red line when doing stuff like "=>", lol.

How do I break a While loop in C# when I enter a negative integer?

 

MacBook Air M1 / Steam Deck

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, RockyRZ said:

How do I break a While loop in C# when I enter a negative integer?

if(number < 0)
{
	break;
}

 

Of course without having any more information, there could be a million other ways of handling this, but this is the simplest way to directly answer your question,

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

9 minutes ago, minibois said:

if(number < 0)
{
	break;
}

 

Of course without having any more information, there could be a million other ways of handling this, but this is the simplest way to directly answer your question,

So I’m supposed to break the loop when a negative number is inputted then give out the result of all inputted numbers.

 

<int value = 0;
        int total = 0;
        
        int x = 1;
        while ( x <= 1){
        Console.Write("Input a number: ");
        value = Int32.Parse(Console.ReadLine());
        total = value + total;
        }
        
        Console.WriteLine($"{total}");>

MacBook Air M1 / Steam Deck

Link to comment
Share on other sites

Link to post
Share on other sites

So at every iteration a while loop evaluates some condition. So in the the parenthesis of your while loop you have to put the logic for that condition. So if you did

// Here is where you set your conditions for the loop to be executed. 
while(number >= 0)
{
	// Run some code
    foo();
}

// you can also check if multiple conditions using boolean logic.
// so if you wanted to run the loop while say 2 (or more you can do as many conditions as you like) variables are between 2 values you could do this

// always initialize something to a variable but this is just pseudo code so...
int number;
bool keepGoing = true;

while(number >= 0 && keepGoing)
{
	// run some code
    foo();
    if(bar)
    {
    	keepGoing false;
    }
}

// you can also check if either condition is true and run the while loop as well with || and many others

 

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, RockyRZ said:

So I’m supposed to break the loop when a negative number is inputted then give out the result of all inputted numbers.

 

<int value = 0;
        int total = 0;
        
        int x = 1;
        while ( x <= 1){
        Console.Write("Input a number: ");
        value = Int32.Parse(Console.ReadLine());
        total = value + total;
        }
        
        Console.WriteLine($"{total}");>

You can make the condition in the while trigger what you want to do.

int input = 0;        
int total = 0;

while(input => 0)
{
        Console.Write("Input a number: ");
        input = Int32.Parse(Console.ReadLine());
        total += input;
}

Console.WriteLine("Total is: " + total);

The while 'tests' if the 'input' variable is 0 or higher. If it's lower than 0 (a negative number), the while will stop and the "total is" line will be written.

If the inputted number is 0 or above (a positive number) it will count up.

 

This code is missing some sanitization on the input, as if you input anything that is not a number (i.e. a letter, or symbol), the code will not break under the Int32.Parse.

For a proper program, you want to test the input using Int32.TryParse (which tells you if the input is a number or not) and only then once confirmed a number, you want to actually convert the input to an int.

But if you want/need to implement that depends on if that is needed in the homework assignment.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, minibois said:

You can make the condition in the while trigger what you want to do.


int input = 0;        
int total = 0;

while(input => 0)
{
        Console.Write("Input a number: ");
        input = Int32.Parse(Console.ReadLine());
        total += input;
}

Console.WriteLine("Total is: " + total);

The while 'tests' if the 'input' variable is 0 or higher. If it's lower than 0 (a negative number), the while will stop and the "total is" line will be written.

If the inputted number is 0 or above (a positive number) it will count up.

 

This code is missing some sanitization on the input, as if you input anything that is not a number (i.e. a letter, or symbol), the code will not break under the Int32.Parse.

For a proper program, you want to test the input using Int32.TryParse (which tells you if the input is a number or not) and only then once confirmed a number, you want to actually convert the input to an int.

But if you want/need to implement that depends on if that is needed in the homework assignment.


 

“A local variable named `input' cannot be declared in this scope because it would give a different meaning to `input', which is already used in a `parent or current' scope to denote something else
Compilation failed: 1 error(s), 0 warnings”

 

It seems this method didn’t work.
 

MacBook Air M1 / Steam Deck

Link to comment
Share on other sites

Link to post
Share on other sites

56 minutes ago, Sakuriru said:

This code has two bugs.

  1. The greater than or equal to symbol is ">=" and not "=>".
  2. When input is less than zero it will include it in the total calculation.

Yeah I was able to find a way around that with:

 

      

        int input = 0;
        int total = 0;
        
        int x = 1;
        while (x > 0) {
        Console.Write("Input a number: ");
        input = Int32.Parse(Console.ReadLine());
        if (input < -1)
        break;
        total += input;
        }
        
        Console.WriteLine("\nSum total is" + total); 

 

MacBook Air M1 / Steam Deck

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, Sakuriru said:

This code has two bugs.

  1. The greater than or equal to symbol is ">=" and not "=>".
  2. When input is less than zero it will include it in the total calculation.

If I told you I included those errors on purpose, so OP still had to debug some code, would that be believable?
No? Okay.. 😔

/s

 

Thanks for the corrections, I just kinda typed that code on the spot and it's clear I rely a bit on Visual Studio showing me a red line when doing stuff like "=>", lol.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

On 11/12/2020 at 7:05 PM, Sakuriru said:

"int x = 1" and "while (x > 0)" can be reduced to simply "while (true)", since x will never be set to another value.

This is the only advise I would change, while it's true it overlooks the bigger improvement of using a do while loop.  (and just testing for input < 0)

 

3735928559 - Beware of the dead beef

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×