About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Read integers into an array and Reversing them using Pointers

#include<stdio.h>
#include<conio.h>
#define MAX 30

void main()
{
int size,i,arr[MAX];
int *ptr;
clrscr();

ptr=&arr[0];

printf("Enter the size of array : ");
scanf("%d",&size);

printf("\nEnter %d integers into array:n",size);
   for(i=0;i<size;i++)
   {
   scanf("%d",ptr);
   ptr++;
   }

ptr=&arr[size-1];

printf("\nElements of array in reverse order are:n");

 for(i=size-1;i>=0;i--)
   {
   printf("\nElement%d is %d :",i,*ptr);
   ptr--;
   }

getch();
}
Output :
Enter the size of array : 5
Enter 5 integers into array : 11 22 33 44 55
Elements of array in reverse order are :
Element 4 is : 55
Element 4 is : 44
Element 4 is : 33
Element 4 is : 22
Element 4 is : 11

Program to read integers into an array and reversing them using pointers Explanation :

  1. We have declared one pointer variable and one array.
int size,i,arr[MAX];
int *ptr;
  1. Address of first element of array is stored inside pointer variable.
ptr=&arr[0];
  1. Accept Size of an Array.
printf("Enter the size of array : ");
scanf("%d",&size);
  1. Now we have accepted element one by one using for loop and scanf statement .
printf("\nEnter %d integers into array:n",size);
   for(i=0;i<size;i++)
   {
   scanf("%d",ptr);
   ptr++;
   }
  1. Increment pointer variable so that it will then point to next element of array.
  2. After accepting all elements store address of last element inside pointer variable.
ptr=&arr[size-1];
  1. Again using reverse for loop and printf statement print an array.
for(i=size-1;i>=0;i--)
   {
   printf("\nElement%d is %d :",i,*ptr);
   ptr--;
   }

No comments: