Home > Enterprise >  Someone help me explain part of this for loop please
Someone help me explain part of this for loop please

Time:09-05

I have this code which lets you enter 4 values and it prints the highest value you entered. I understand everything up until the second for loop, how does it print the highest value? I'm rather new to c# and this is part of a school assignment. The part of code which is within "**" is what i dont really understand

        int[] inputNum = new int[4];
        for(int i = 0; i < 4; i  )
        {
            Console.Write("Enter number: ");
            inputNum[i] = int.Parse(Console.ReadLine());
        }
        **int inputMax = 0;
        for(int i2 = 0; i2 < inputNum.Length; i2  )
        {
        
            if(inputNum[i2] > inputMax)
            {
            
                inputMax = inputNum[i2];
            }**
        }
        Console.WriteLine($"Highest value number: {inputMax}");

CodePudding user response:

The second loop goes over the numbers that were inputted in the first loop and for each iteration checks if the current number is larger than the previous maximum, and if it is, saves it in inputMax. Once the loop is done, you'll be left with the largest number in that variable.

To be honest, though, this problem doesn't really need both loops. If the only requirement is to input four numbers and print out the largest one, there's no need to save them to an array, and you could just perform this check on each number that's inputted.

  •  Tags:  
  • c#
  • Related