Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array multiply pairs

Tags:

arrays

c#

c#-4.0

I must create code in C# to:

  • Ask the user to enter an arbitrary set of numbers into an array and display all the entered numbers. I done this part and the code is working properly

  • Then multiply pairs of numbers together and display the result. If you have an odd number of numbers then just display the last number.

    E.G. 2 3 8 4 become 6 32 2 3 8 4 7 become 6 32 7

My problem is with the odd arrays. if the arrays has even number of element it's no problem, but if the arrays has odd number of elements there are errors, never print the last element.

Here is my code:

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

namespace ArrayDisplay
{
    class Array
    {
        static void Main(string[] args)
        {
            int[] array = new int[9];
            int userInput = -1;
            int itt = 0;
            int count = 0;

            Console.WriteLine("Enter a integer number or -1 to exit:");
            userInput = Convert.ToInt32(Console.ReadLine());
            count++;
            while (userInput != -1 && itt<array.Length)
            {

                array[itt] = userInput;
                itt++;

                Console.WriteLine("Enter a integer number or -1 to exit:");
                userInput = Convert.ToInt32(Console.ReadLine());
                count++;
            }
              Console.WriteLine("The array contains: ");

            for (int i = 0; i < array.Length; i++) {
                Console.Write(" {0} , "  ,array[i]);

            }
            Console.WriteLine("");
            Console.WriteLine("count {0}",count-1);

            if (count % 2 == 0)
            {
                for (int i = 0; i < array.Length; i += 2)
                {
                    Console.Write(" {0} , ", array[i] * array[i + 1]);
                }
            }
            else {
                for (int i = 0; i < array.Length; i += 2)
                {
                    Console.Write(" {0} , ", array[i] * array[i + 1])
                }
            }
        }
    }
}
like image 213
Bogdanho Avatar asked Jul 02 '26 05:07

Bogdanho


1 Answers

Because 7*0=0, try below:

        if (count % 2 == 0)
        {
            for (int i = 0; i < array.Length - 1; i += 2)
            {
                Console.Write(" {0} , ", i == count - 2 ? array[i] : array[i] * array[i + 1]);
            }
        }
        else
        {
            for (int i = 0; i < array.Length - 1; i += 2)
            {
                Console.Write(" {0} , ", array[i] * array[i + 1]);
            }

        }
like image 67
ojlovecd Avatar answered Jul 04 '26 18:07

ojlovecd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!