﻿ C# Sharp Exercises: Insert New value in the array (sorted list ) - w3resource

# C# Sharp Exercises: Insert New value in the array (sorted list )

## C# Sharp Array: Exercise-13 with Solution

Write a program in C# Sharp to insert New value in the array (sorted list ).

Sample Solution:-

C# Sharp Code:

``````using System;
public class Exercise13
{
public static void Main()
{
int[] arr1 = new int[10];
int i,n,p=0,inval;
Console.Write("\n\nInsert New value in the sorted array :\n");
Console.Write("-----------------------------------------\n");

Console.Write("Input the size of array : ");
/* Stored values into the array*/
Console.Write("Input {0} elements in the array in ascending order:\n",n);
for(i=0;i<n;i++)
{
Console.Write("element - {0} : ",i);
}
Console.Write("Input the value to be inserted : ");
Console.Write("The exist array list is :\n ");
for(i=0;i<n;i++)
Console.Write("{0} ",arr1[i]);
/* Determine the position where the new value will be insert.*/
for(i=0;i<n;i++)
if(inval<arr1[i])
{
p = i;
break;
}
/* move all data at right side of the array */
for(i=n;i>=p;i--)
arr1[i]= arr1[i-1];
/* insert value at the proper position */
arr1[p]=inval;

Console.Write("\n\nAfter Insert the list is :\n ");
for(i=0;i<=n;i++)
Console.Write("{0} ",arr1[i]);
Console.Write("\n");
}
}
```
```

Sample Output:

```Insert New value in the sorted array:
-----------------------------------------
Input the size of array : 2
Input 2 elements in the array in ascending order:
element - 0 : 2
element - 1 : 4
Input the value to be inserted : 3
The exist array list is :
2 4
After Insert the list is :
2 3 4
```

Flowchart:

C# Sharp Code Editor: