Showing posts with label insert any element in array. Show all posts
Showing posts with label insert any element in array. Show all posts

Monday, September 12, 2011

Insert any element into an array and then sort the array

Insert any element into an array  and then sort the array
#include<stdio.h>
#include<conio.h>
main()
{
    int a[15],n,m,i,j,temp;
    clrscr();
    printf("\n How many elements: ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
      {
          printf("\n Enter element no. %d : ",i+1);
          scanf("%d",&a[i]);
      }
    printf("\n Original unsorted elements are:");
    for(i=0;i<n;i++)
         printf(" %d ",a[i]);
    printf("\n enter the element to be inserted : ");
    scanf("%d",&a[n]);

    m=n+1;  // n is increased b'coz of entry of new element
    for(i=0;i<m;i++)  // Bubble Sort
        for(j=0;j<m-1;j++)
            if(a[j]<=a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
    printf("\n Sorted elements of the array are:");
    printf("\n");
    for(i=0;i<m;i++)
         printf(" %d ",a[i]);
    getch();
}

Insert any element into an array at a desired position

Insert any element into an array at a desired position
#include<stdio.h>
#include<conio.h>
main()
{
    int a[15],n,i,item,pos;
    clrscr();
    printf("\n How many elements: ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
      {
          printf("\n Enter element no. %d : ",i+1);
          scanf("%d",&a[i]);
      }
    printf("\n Array elements are:");
    for(i=0;i<n;i++)
         printf(" %d ",a[i]);
    printf("\n enter the element to be inserted : ");
    scanf("%d",&item);
    printf("\n enter the position of insertion : ");
    scanf("%d",&pos);
    for(i=n;i>=pos;i--)  // shifting the elements
         a[i]=a[i-1];

    a[--pos]=item;
      /* pos=pos-1; // pos. is decremented b'coz of Array storage process
    a[pos]=item; */

    printf("\n New array elements are:");
    printf("\n");
    for(i=0;i<=n;i++)
         printf(" %d ",a[i]);
    getch();
}

Popular 5 Posts Last 7 days