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();
}

>p<p+n
That's a moving target. Perhaps you meant p < a + n .

Logically speaking, p < p + n is always true when n is greater or equal to zero.

Thank You both of you . I understood where I went wrong. The program is working now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.