Saturday, 12 March 2011

Write a program using pointers to read an array of integers and print its elements in reverse order

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,i,n;
clrscr();
printf("Enter the no of elements:");
scanf("%d",&n);
ptr=(int *)malloc(sizeof(int)*n);
if(ptr==NULL)
{
printf("Not enough memory");
exit(1);
}
for(i=0; i<n; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&ptr[i]);
}
printf("Array in original order\n");
for(i=0; i<n; i++)
{
printf("%d\n",ptr[i]);
}
printf("Array in reverse order\n");
for(i=n-1; i>=0; i--)
{
printf("%d\n",ptr[i]);
}
getch();
return 0;
}
Output:
Enter the no of elements:5
Enter 1 element : 12
Enter 2 element : 56
Enter 3 element : 89
Enter 4 element : 45
Enter 5 element : 23
Array in original order
12
56
89
45
23
Array in reverse order
23
45
89
56
12

No comments:

Post a Comment