Home > Enterprise >  Write a program that reads N and then continuously read integers and check if there are odd or even
Write a program that reads N and then continuously read integers and check if there are odd or even

Time:10-03

This is what I tried:

using System;

namespace OddAndEvenNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
            int oddNumbersCount = 0;
            int evenNumbersCount = 0;
            int n = Convert.ToInt32(Console.ReadLine());
            while (oddNumbersCount <= requiredOddAndEvenNumbers || evenNumbersCount <= requiredOddAndEvenNumbers)
            {
                if (n % 2 == 0)
                {
                    evenNumbersCount  ;
                }
                else if (n % 2 != 0)
                {
                    oddNumbersCount  ;
                }
            }
            Console.WriteLine(evenNumbersCount   " "   oddNumbersCount);
            Console.ReadLine();
        }
    }
}

I don't know why it doesn't work. The program should stop when odd numbers and even number equals N.

CodePudding user response:

You never update n so the loop will never exit
So evenNumbersCount and oddNumbersCount will never count up

using System;

namespace OddAndEvenNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
            int oddNumbersCount = 0;
            int evenNumbersCount = 0;
            int n = Convert.ToInt32(Console.ReadLine());
            while (oddNumbersCount <= requiredOddAndEvenNumbers || evenNumbersCount <= requiredOddAndEvenNumbers)
            {
                if (n % 2 == 0)
                {
                    evenNumbersCount  ;
                }
                else if (n % 2 != 0)
                {
                    oddNumbersCount  ;
                }
                n  ;
            }
            Console.WriteLine(evenNumbersCount   " "   oddNumbersCount);
            Console.ReadLine();
        }
    }
}

CodePudding user response:

It seems you've forgotten to get new number inside the loop. It keeps checking the first number ItThe while loop works until the Odd Even numbers are equal to n.

int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
int oddNumbersCount = 0;
int evenNumbersCount = 0;
int n = 0;

while ((oddNumbersCount   evenNumbersCount) < requiredOddAndEvenNumbers)
{
    n = Convert.ToInt32(Console.ReadLine());
    if (n % 2 == 0)
    {
        evenNumbersCount  ;
    }
    else if (n % 2 != 0)
    {
        oddNumbersCount  ;
    }
}

Console.WriteLine("evenNumbersCount: {0}", evenNumbersCount);
Console.WriteLine("oddNumbersCount: {0}", oddNumbersCount);
  •  Tags:  
  • c#
  • Related