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 : ");
n = Convert.ToInt32(Console.ReadLine());
/* 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);
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Input the value to be inserted : ");
inval = Convert.ToInt32(Console.ReadLine());
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:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to sort elements of the array in descending order.
Next: Write a program in C# Sharp to insert New value in the array (unsorted list ).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework