I am trying to input an array and then print it in reverse order using for loop. Firstly, I tried to print out the array elements in original order as follows:
#include <stdio.h>
int main()
{
int a[100];
int n,i;
int *p=a;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i ){
printf("Enter array element [%d]:",i);
scanf("%d",p i);
}
printf("Array elements in reverse order: ");
for (i=0;i<n;i ){
printf("%d\n",*(p i));
}
The above code worked and desired output was achieved. And then I tried to output array elements in reverse order using following changes in the last for loop:
for (i=n;i>0;i--){
printf("%d\n",*(p i));
But doing this the output appears as below:
while the desired output is:
3
2
1
What am I missing?
CodePudding user response:
In your first attempt, the indices range from 0 to n-1 which is correct. In your second attempt the indices range from n to 1, so you read and write one element past the end of the array.
The proper initialization and condition is:
for (i=n-1;i>=0;i--){
CodePudding user response:
You iterate from p 3 (array[3]), while max index is 2 -> undefined behavior, garbage printed
You iterate until p 0, excluded, you exclude array[0].
for (i = n - 1; i >= 0; i--) {
//...
}