Write a C program to insert an element at a given position in an array.
int main() {
int data[100], n, i, pos, newdata;
/* get the number of entries from the user */
printf("Enter ur value for n(1-99):");
scanf("%d", &n);
if (n < 0 || n > 99) {
printf("U have entered wrong input!!");
return 0;
}
/* get the input data */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++)
scanf("%d", &data[i]);
/* get the position and new data to insert */
printf("Enter your new data to insert and its pos:");
scanf("%d%d", &newdata, &pos);
if (pos < 0 || pos > 99) {
printf("Wrong position!!\n");
return 0;
}
/* relocate the existing data at pos to n */
for (i = n; i > pos - 1; i--) {
data[i] = data[i - 1];
}
/* insert the new data into the array */
data[i] = newdata;
/* print the result */
for (i = 0; i <= n; i++)
printf("%d\n", data[i]);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter ur value for n(1-99):5
Enter your inputs:
100
200
300
400
500
Enter your new data to insert and its pos:250 3
100
200
250
300
400
500
Enter ur value for n(1-99):5
Enter your inputs:
100
200
300
400
500
Enter your new data to insert and its pos:250 3
100
200
250
300
400
500
No comments:
Post a Comment