Hello. I continue to study #. There is a task:

The input to the method is an array of integers. The method must calculate the sum of all even elements.

If it is solved without breaking into methods, there are no problems, a trifling matter. But I decided to do it right and break into methods. And immediately there was a problem. I decided to add two methods: The first method will find even numbers in the array. The second method will add these even numbers. And the main will display the result. Here is my code:

static int EvenNumber(int[] array) { //тут получение четных чисел из массива int evenNum = 0; for (int i = 0; i < array.Length; i++) { if (array[i] % 2 == 0) { evenNum = array[i]; } } return evenNum; //это неправильно(( } static int SummValue(int[] summ) { //получение суммы массива return summ.Sum(); } static void Main(string[] args) { int[] arrays = { 2, 4, 3, 10, 1 }; Console.ReadKey(); } 

How to return even numbers from an EvenNumber method and use them in SummValue method? Then to display the result in main. Already what day I fight ... Thank you in advance. Everyone for the help!

  • вернуть четные числа , and you return a single number (int). Make an array of these numbers on the output ( static int[] EvenNumber... ), well, form an array with the results, which is on the line evenNum = array[i]; fill, and return through return . - EvgeniyZ February
  • one
    static IEnumerable<int> EvenFilter(IEnumerable<int> source) => source.Where((item, index)=>index%2==0); - tym32167
  • one
    static int Sum(IEnumerable<int> source)=>source.Sum(); - tym32167
  • I do not answer for compilability, I write from the phone, but the idea should be clear - tym32167

1 answer 1

The answer will be as a beginner (with the appropriate code) and with some recommendations.

Here you have created a project and wrote the first line

 static void Main(string[] args) { int[] inputArray = new[] { 1, 2, 5, 7, 4, 7, 8, 6, 4, 0 }; } 

what to do next? Reflect in writing, i.e. write comments like this

 static void Main(string[] args) { int[] inputArray = new[] { 1, 2, 5, 7, 4, 7, 8, 6, 4, 0 }; //получить массив четных чисел из входного массива //получить сумму четных чисел из массива //вывести результат на экран Console.ReadKey(); } 

Thought over? Start writing code.

first stage

Wrote lines with nonexistent methods. How to be? Let them write for us studio. So bring the mouse to the underlined red name of the method and get such a hint, press Enter and the desired method is created. studio function

Repeat the same operation with the second method. And we get the second method. And the program is almost ready!

 static void Main(string[] args) { int[] inputArray = new[] { 1, 2, 5, 7, 4, 7, 8, 6, 4, 0 }; //получить массив четных чисел из входного массива int[] evenNumbers = GetEvenNumbersArray(inputArray); //получить сумму четных чисел из массива int sum = GetSum(evenNumbers); //вывести результат на экран Console.WriteLine(sum); Console.ReadKey(); } private static int GetSum(int[] evenNumbers) { throw new NotImplementedException(); } private static int[] GetEvenNumbersArray(int[] inputArray) { throw new NotImplementedException(); } 

It even compiles! But not satisfied ...

Now we reflect on the first method.

 private static int[] GetEvenNumbersArray(int[] inputArray) { //создать массив-аккумулятор для сбора четн.чисел //пройти по аккумулятору и назначить всем элементам -1 //выбрать в цикле четные и занести их в аккумулятор //подсчитать кол-во чисел не равных -1 в аккумуляторе //cоздать результирующий массив //внести в результирующий массив все числа не равные -1 из аккумулятора //вернуть результат throw new NotImplementedException(); } 

Writing code ...

 private static int[] GetEvenNumbersArray(int[] inputArray) { //создать массив-аккумулятор для сбора четн.чисел int[] accum = new int[inputArray.Length]; //пройти по аккумулятору и назначить всем элементам -1 for (int i = 0; i < accum.Length; i++) { accum[i] = -1; } //выбрать в цикле четные и занести их в аккумулятор for (int i = 0; i < inputArray.Length; i++) { if (inputArray[i] % 2 == 0) { accum[i] = inputArray[i]; } } //подсчитать кол-во чисел не равных -1 в аккумуляторе int count = 0; for (int i = 0; i < accum.Length; i++) { if (accum[i] != -1) { count++; } } //cоздать результирующий массив int[] result = new int[count]; //внести в результирующий массив все числа не равные -1 из аккумулятора int j = 0; for (int i = 0; i < accum.Length; i++) { if (accum[i] != -1) { result[j] = accum[i]; j++; } } //вернуть результат return result; } 

Now you can test the work of the first method. Return to the Main() method and on the second method call, place the cursor and press the F9 key, or click on the left gray frame opposite the required line. setting breakpoint So we set a breakpoint. In debug mode, the program will stop at this line and will be able to check the result of the method execution, like this display of the result of the method execution hover the mouse over the desired variable and a tooltip pops up where you can check the result of the method execution.

In the same spirit, we continue with the second method.

 private static int GetSum(int[] evenNumbers) { //создать результирующую переменную int result = 0; //пройти в цикле по evenNumbers и просуммировать в результат for (int i = 0; i < evenNumbers.Length; i++) { result += evenNumbers[i]; } //вернуть результат return result; } 

Everything. You can check the program. The breakpoint can be disabled by clicking on it again or re-setting the cursor on this line and pressing F9 .

You say that you are too lazy to write comments, but you just want the code. When you are just learning it is better to first sketch the outline of the decision in the comments, and then write the code. This mode of operation helps to keep the thread of thinking, and this approach helps even experienced programmers in complex and confusing situations.

I wish you success!

  • one
    Something is not enough details ( - Igor
  • @Igor yes, I wanted more in detail, but did not master it :) - Bulson February
  • But the question is: is it worth it to add another method, such as DataBase, to store the data obtained from the methods: even numbers and the sum of even numbers. And in the main already make a display. Or nonsense?)) - mygedz
  • You have made the intermediate value evenNumbers array. Is this not a superfluous complication? why not make it through IEnumerable<int> ? Linq magic will do everything with pleasure and will not spend extra resources - calculations in one pass - dgzargo
  • @dgzargo I specifically started the answer like this: "The answer will be like a beginner (with the appropriate code) ...". - Bulson pm