Hi Everyone,
I'm trying to write a program where I can:
1.) Select the number of elements to place inside an array of size 10, and
2.) Select an element and insert that element into the proper location
resulting in an array where all of the elements are sorted in ascending order,
from 0 to n - 1.
So far, I've been able to place all of the elements I desire into that array and select an element to insert. However, when I insert new element into the array, I keep overwriting the next element in the array and then there is some garbage value for the last value in the array. I'm getting a bit confused and was wondering if someone could point out the error in my code and suggest a better alternative so that I end up with a nice sorted array in ascending order after inserting the new element.
Here is my code:
Code:
#include <stdio.h>
int main()
{
int arr[10];
int i, j, n, num;
printf("\nEnter the number of elements in the array: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\narr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted: ");
scanf("%d", &num);
for (i = 0; i < n; i++)
{
if (arr[i] > num)
{
for (j = n; j <= i; j--)
{
arr[j+1] = arr[j];
}
arr[i] = num;
break;
}
}
printf("\nThe array after insertion of %d is: ", num);
for (i = 0; i < n + 1; i++)
{
printf("\narr[%d] = %d", i, arr[i]);
}
return 0;
}
Thanks