The following snippet finds the least, greatest and sum of the elements of an array.
It works when I give the test condition with variable "i" in the for loop (as in the first snippet).
But when I replace it with a pointer(as in second snippet), it gives a wrong output.
I couldn't find any logical error in my program. Please help.
Snippet 1
p=a; /* The array is a,of size n */
/* l,s,m stands for least, sum and maximum respectively */
l=*p;
s=*p;
m=*p;
for(p=p+1,i=0;i<n-1;i++,p++) /* The for loop */
{
s=s+*p;
if(l>*p)
l=*p;
if(m<*p)
m=*p;
}
printf("The sum is %d.\nThe least no. is %d.\nThe maximum no. is %d.\n",s,l,m);
getch();
}
Snippet 2
p=a; /* The array is a,of size n */
/* l,s,m stands for least, sum and maximum respectively */
l=*p;
s=*p;
m=*p;
for(p=p+1;p<p+n;p++) /* The for loop */
{
s=s+*p;
if(l>*p)
l=*p;
if(m<*p)
m=*p;
}
printf("The sum is %d.\nThe least no. is %d.\nThe maximum no. is %d.\n",s,l,m);
getch();
}