+ 1

What is wrong with this code?

Can someone explain to me what am I doing wrong? I am trying to use "foreach" instead of a "for loop": using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int[] numbers = new int[5]; int count = 0; while (count <5) { numbers[count] = Convert.ToInt32(Console.ReadLine()); count++; } //your code goes here foreach (int even in numbers) { if (even % 2 == 0) { count += even; } } Console.WriteLine(count); } } }

4th Apr 2023, 9:30 PM
Gradi Maxime Kasita Mbatika
6 Antworten
+ 4
I don't know what your code is supposed to do but I noticed that you don't reset "count" after the 1st loop?
4th Apr 2023, 10:31 PM
Lisa
Lisa - avatar
+ 3
Issues.. "count" is used both to count the number of integers inputted and to store the sum of even numbers.. to avoid this.. create new variable "sum" ; or at least "count" assign to 0 again before foreach int sum = 0; foreach (int even in numbers) { if (even % 2 == 0) { sum += even; } } Console.WriteLine(sum);
5th Apr 2023, 1:16 AM
Kaminorsabir Kamin
Kaminorsabir Kamin - avatar
+ 1
Save the code as public in Code Playground and edit the question in order to add a link to the code in the question description - use "+" button. This way, we can run and debug your code easily, and without risk of copy errors. Also, if you saw something wrong in the results, you should tell us. To help you, we have to know what the problem is. When editting the question description, add explanations of your task and what you saw wrong.
5th Apr 2023, 12:40 AM
Emerson Prado
Emerson Prado - avatar
+ 1
Thank you Kaminorsabir! 😁👍
5th Apr 2023, 1:35 AM
Gradi Maxime Kasita Mbatika
0
The program I am given takes 5 numbers as input and stores them in an array. I have to complete the program so that it goes through the array and outputs the sum of even numbers. An integer is even if it is divisible by two, so it means that n number is even if n%2 equals 0. The thing is that I'm trying to use a "foreach" instead of a "for loop".
4th Apr 2023, 10:50 PM
Gradi Maxime Kasita Mbatika
0
Thank you Asim.
6th Apr 2023, 4:53 PM
Gradi Maxime Kasita Mbatika