Our website is made possible by displaying online advertisements to our visitors.Please consider supporting us by disabling your ad blocker.
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Translate it in your own Language

Print this Job Post

Print Friendly and PDF

Thursday, May 22, 2014

C program to insert an element in an array

This code will insert an element into an array, For example consider an array a[10] having three elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45 at location 1 i.e. a[0] = 45, so we have to move elements one step below so after insertion a[1] = 1 which was a[0] initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean increasing its size i.e array will not be containing 11 elements.

C programming code

#include <stdio.h>
#include<conio.h> 
void main()
{
   int array[100], position, c, n, value;
   clrscr();
   printf("Enter number of elements in array\n");
   scanf("%d", &n);
   printf("Enter %d elements\n", n);
   for (c = 0; c < n; c++)
   scanf("%d", &array[c]);
   printf("Enter the location where you wish to insert an element\n");
   scanf("%d", &position);
   printf("Enter the value to insert\n");
   scanf("%d", &value);
   for (c = n - 1; c >= position - 1; c--)
   array[c+1] = array[c];
   array[position-1] = value;
   printf("Resultant array is\n");
   for (c = 0; c <= n; c++)
   printf("%d\n", array[c]);
   getch();
}

Output of program:


No comments:

Post a Comment

Copyright @ CrackMNC 2014-2024
Divas Nikhra Theme by Crack MNC