Monday 26 September 2016

Insertion Operation on array- after the index of array

Insert the element after the given index of array


#include <stdio.h>
#include <conio.h>
#define MAX 5
void main()
{
   int array[MAX] = {1, 2, 4, 5};
   
   int N = 4;        // Used for number of elements in array
   int i = 0;        // Used for loop variable
   int index = 1;    // Used for indexing location after which value will be inserted
   int value = 3;    // new data element to be inserted
   // Used for printing array before insertion
    printf("Printing array before insertion −\n");
    for(i = 0; i < N; i++)
   {
      printf("array[%d] = %d \n", i, array[i]);
   }
   // now shift rest of the elements downwards using it  
    for(i = N; i >= index + 1; i--)
  {
      array[i + 1] = array[i];
   }
   // add new element at first position
  array[index + 1] = value;
   // increase N to reflect number of elements
    N++;
   // print to confirm
    printf("Printing array after insertion −\n");
    for(i = 0; i < N; i++) {
      printf("array[%d] = %d\n", i, array[i]);
   }
}

When we compile and run the this program, it will produce the following result −

Printing array before insertion −
array[0] = 1
array[1] = 2
array[2] = 4
array[3] = 5

Printing array after insertion −
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

Insertion Operation on Array- on specific Index

C Program to Insert the element onto the specific location of the array.
#include <stdio.h>
#include <conio.h>
#define MAX 5
void main()
{
   int array[MAX] = {1, 2, 4, 5};
 
   int N = 4;        // Number of total elements in array
   int i = 0;        // Use as loop variable
   int index = 2;    // Use as index location to insert new value
   int value = 3;    // Use as new data element to be inserted
 
   printf("Printing array before insertion −\n");  // print array before insertion
    for(i = 0; i < N; i++) {
      printf("array[%d] = %d \n", i, array[i]);
   }
 
// now shift rest of the elements downwards  
    for(i = N; i >= index; i--)
 {
      array[i+1] = array[i];
   }
   // Now, add new element at first position
   array[index] = value;
   // used to increase N to reflect number of elements
   N++;
   // print to confirm
   printf("Printing array after insertion −\n");
   for(i = 0; i < N; i++) {
      printf("array[%d] = %d\n", i, array[i]);
   }
}

If we compile and run the above program, it will produce the following result −

Printing array before insertion −
array[0] = 1
array[1] = 2
array[2] = 4
array[3] = 5

Printing array after insertion −
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

Wednesday 21 September 2016

Welcome!

Welcome to the world of programming.