Below is C program which allows a user to enter a maximum of 10 numbers, then reverses the array using a temporary variable and finally prints the elements of the reversed array.
/*Program to reverse an array using a temporary variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10],n,i,j,temp;
printf("Enter the number of elements:");
scanf("%d",&n);
if(n>10 || n<1)
{
printf("Invalid size.Try again...!");
}
else
{
/*Reading the array elements*/
printf("Enter the elements into the array:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
/*Reversing the elements in the array*/
for(i=0,j=n-1;i<n/2;i++,j--)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*Prinitng the array elements after reversing it*/
printf("After reversing, the array elements are:\n");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}
getch();
}
Sample input and output:
Enter the number of elements:6
Enter the elements into the array:
1 2 3 4 5 6
After reversing, the array elements are:
6 5 4 3 2 1
No comments:
Post a Comment