Thursday, September 26, 2013

Insert into Array

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

namespace InsertArray
{
    class Program
    {
        static void Main(string[] args)
        {

            int n, pos;

            Console.WriteLine("Enter the array total number of elements:\t");
            n = Convert.ToInt32(Console.ReadLine());

            int[] num = new int[100];

            Console.WriteLine("Enter the Array Element one by one");
            for (int i = 0; i < n; i++)
            {
                num[i] = Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("------------------------------");
            Console.WriteLine("         Array Elements       ");
            Console.WriteLine("------------------------------");
            Console.WriteLine();
            for (int i = 0; i < n; i++)
            {
                Console.Write(num[i] + "\t");
            }

            Console.WriteLine("\n\n");
            Console.WriteLine("***************************");
            Console.WriteLine("   Sorted Array Elements   ");
            Console.WriteLine("***************************");
            Console.WriteLine();
            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (num[i] > num[j])
                    {
                        int temp = num[i];
                        num[i] = num[j];
                        num[j] = temp;
                    }
                }
            }

            for (int i = 0; i < n; i++)
            {
                Console.Write(num[i] + "\t");
            }

            Console.WriteLine("\n");
            Console.Write("Enter the position to insert in array:\t");
            pos = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\n");
            Console.Write("Enter the value to insert:\t");
            int val = Convert.ToInt32(Console.ReadLine());

            for (int c = n - 1; c >= pos - 1; c--)
            {
                num[c + 1] = num[c];
            }
            num[pos - 1] = val;

            Console.WriteLine("\n");
            for (int i = 0; i <= n; i++)
            {
                Console.Write(num[i] + "\t");
            }
            Console.ReadLine();
           
                     
        }
    }
}


Output

Insert element into Array using console Application

No comments:

Post a Comment