Given an array of numbers, return array of products of all other numbers

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] numArray = { 1, 2, 3, 4, 5 };

            int[] tempArray1 = new int[numArray.Length];

            int[] tempArray2 = new int[numArray.Length];

            //Initializing tempArray1

            for (int i = 0; i < numArray.Length; i++)

            {

                if (i == 0)

                {

                    tempArray1[i] = 1;

                }

                else

                {

                    tempArray1[i] = tempArray1[i – 1] * numArray[i – 1];

                }

            }

            //Initializing tempArray2

            for (int i = numArray.Length – 1; i >= 0; i–)

            {

                if (i == numArray.Length – 1)

                {

                    tempArray2[i] = 1;

                }

                else

                {

                    tempArray2[i] = tempArray2[i + 1] * numArray[i + 1];

                }

            }

            //Printing the original array

            Console.WriteLine("Original array");

            Console.WriteLine("==============");

            for (int i = 0; i < numArray.Length; i++)

            {

                Console.Write(numArray[i] + " ");

            }

            Console.WriteLine();

            //Product of all other numbers

            Console.WriteLine("Product of all other numbers");

            Console.WriteLine("============================");

            for (int i = 0; i < numArray.Length; i++)

            {

                Console.Write((tempArray1[i] * tempArray2[i]) + " ");

            }

            Console.WriteLine();

        }

    }

}
 
Original array
==============
1 2 3 4 5
Product of all other numbers
============================
120 60 40 30 24
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s