C Exercises: Insert New value in the array (sorted list )
C Array: Exercise-13 with Solution
Write a program in C to insert the values in the array (sorted list).
Visual Presentation:

Sample Solution:
C Code:
#include <stdio.h>
int main()
{
int arr1[100], i, n, p, inval;
// Prompt user for input
printf("\n\nInsert New value in the sorted array:\n");
printf("-----------------------------------------\n");
printf("Input the size of array : ");
scanf("%d", &n);
// Input sorted elements for the array
printf("Input %d elements in the array in ascending order:\n", n);
for (i = 0; i < n; i++)
{
printf("element - %d : ", i);
scanf("%d", &arr1[i]);
}
// Input the value to be inserted
printf("Input the value to be inserted : ");
scanf("%d", &inval);
// Display the existing array
printf("The existing array list is :\n");
for (i = 0; i < n; i++)
printf("% 5d", arr1[i]);
// Determine the position where the new value will be inserted
for (i = 0; i < n; i++)
{
if (inval < arr1[i])
{
p = i;
break;
}
else
{
p = i + 1;
}
}
// Move all data at the right side of the array to make space
for (i = n + 1; i >= p; i--)
arr1[i] = arr1[i - 1];
// Insert the new value at the proper position
arr1[p] = inval;
// Display the array after insertion
printf("\n\nAfter Insert the list is :\n");
for (i = 0; i <= n; i++)
printf("% 5d", arr1[i]);
printf("\n");
return 0;
}
Sample Output:
Insert New value in the sorted array : ----------------------------------------- Input the size of array : 6 Input 6 elements in the array in ascending order: element - 0 : 2 element - 1 : 5 element - 2 : 7 element - 3 : 11 element - 4 : 9 element - 5 : 6 Input the value to be inserted : 8 The exist array list is : 2 5 7 11 9 6 After Insert the list is : 2 5 7 8 11 9 6 -------------------------------- Process exited after 33.18 seconds with return value 10 Press any key to continue . . .
Flowchart:

C Programming Code Editor:
Previous: Write a program in C to sort elements of an array in descending order.
Next: Write a program in C 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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join