简体   繁体   中英

Finding the max value in an array

As part of school, one of my assignments is to write 10 pieces of code about 10 different search patterns, etc.

For this one, i need to use a linear search to find the highest and lowest value in a defined array, and then display the number of times that value was found.

Heres the code i came up with:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Maxvaluefinder
{
    class Program
    {
        static void Main(string[] args)
        {
            var array = [1, 31, 10, 9, 420, -5, 77, 420, 300, 99]; //Sets up the array
            var maxvalue = 0; //Establishes variables for maximum value and the counter of maximum value.
            var maxvaluecount = 0;

            for (i = 1; i < array.Length; i++)
            {
                if (array[i] > maxvalue)
                {
                    maxvalue = array[i];
                    maxvaluecount = 1;
                }
                if (array[i] == maxvalue)
                {
                     maxvaluecount = maxvaluecount + 1;
                }
            }

            Console.WriteLine("The highest number in this array was" + maxvalue + "which appeared a total of" + maxvaluecount + "times."); // Prints the final outcome.
        }
    }
}

As of now, i am not 100% sure how the "for (i = 1; i < intArray.Length; i++)" part works, and the 'i' bits 'do not exist in current context'

Please help?

Also, somewhat unrelated: how do i test run the code in microsoft visual studio?

Thanks :)

1st question: You need to declare your i inside for loop if you only want to use i inside it. Otherwise you need to declare i before the for loop.

for (var i = 1; i < array.Length; i++)

And this is how you create new int array

var array = new int[] { 1, 31, 10, 9, 420, -5, 77, 420, 300, 99}; 

2nd question: Go to VS, create new console project, paste your code under main function and press F5

You need to declare a variable before you can use it. Try:

for (int i = 1; i < array.Length; i++){...}

A for loop works as follows:

  1. You declare a control variable, in this case i , you assign it the starting value 1.
  2. The for loop checks at the start of each loop if its end condition is satisfied, in the given case i < array.Length
  3. At the end of every loop, the control variable gets updated according to the last part of your syntax i++ , which is equivalent to i = i+1

Also, I am not sure if you knew that, but in C# arrays are zero-based indexed, which means, that the first element in an array has actually the index zero. So you probably want to initialize: int i = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM