Friday, 27 April 2012

Reverse array


                                               $  Reverse array:-

#include<stdio.h>

void main()
{
   int n, c, d, a[50], b[50];

   printf("Enter the number of elements in array\n");
   scanf("%d",&n);

   printf("Enter the range elements\n");

   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&a[c]);

   for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )
      b[d] = a[c];

   for ( c = 0 ; c < n ; c++ )
      a[c] = b[c];

   printf("Reverse array is\n");

   for( c = 0 ; c < n ; c++ )
      printf("%d\n", a[c]);

   getch0;
}

output:-

                  $ Reverse array by swapping(without using additional memory):-



#include <stdio.h>

int main()
{
  int array[100], n, c, t, end;

  scanf("%d", &n);
  end = n - 1;

  for (c = 0; c < n; c++)
{
    scanf("%d", &array[c]);
  }

  for (c = 0; c < n/2; c++)
{
    t          = array[c];
    array[c]   = array[end];
    array[end] = t;

    end--;
  }

  printf("Reversed range components are:\n");

  for (c = 0; c < n; c++)
{
    printf("%d\n", array[c]);
  }

  getch0;
}


                             $ c program to reverse an array using pointers:-


#include<stdio.h>
#include<conio.h>

void reverse_array(int*, int);

main()
{
   int n, c, *pointer;

   scanf("%d",&n);

   suggestion = (int*)malloc(sizeof(int)*n);

   if( suggestion == NULL )
      exit(EXIT_FAILURE);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d",(pointer+c));

   reverse_array(pointer, n);

   printf("Original range on revers is\n");

   for ( c = 0 ; c < n ; c++ )
      printf("%d\n",*(pointer+c));

   free(pointer);

    getch0;
}

void reverse_array(int *pointer, int n)
{
   int *s, c, d;

   s = (int*)malloc(sizeof(int)*n);

   if( s == NULL )
      exit(EXIT_FAILURE);

   for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )
      *(s+d) = *(pointer+c);

   for ( c = 0 ; c < n ; c++ )
      *(pointer+c) = *(s+c);

   free(s);
}

                                $  c program to insert an element in an array:-



C development code:-

#include <stdio.h>

main()
{
   int array[100], position, c, n, value;

   printf("Enter variety of elements's 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 place 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 >= place - 1 ; c-- )
       array[c+1] = array[c];

   array[position-1] = value;

   printf("Resultant range is\n");

   for( c = 0 ; c <= n ; c++ )
        printf("%d\n", array[c]);

   getch0;
}

No comments:

Post a Comment