Wednesday, 5 February 2014

sum all the elements of an array using pointer using printf

#include<stdio.h>
#include<conio.h>

int main()
{
 // Declaring array variable "a" of size 10 and initializing it
 int a[10]={21, -2, 4, 6, 9, 12, 43, 22, 4, 8}, sum=0;
 
 // Declaring pointer type variable pointing to the the base address i.e ( a[0] ) of array 'a'  
 int *ptr=a; // It is equivalent to : int *ptr; ptr=&a;
 
 // Declaring variable ptre = stores address of 11th element
 int *ptre;
 ptre = ptr+10;
 
 // Calculating sum
 while(ptr<ptre)
 {
  sum+=*ptr++; // sum=sum + *ptr++
 }
 
 // Displaying calculated sum
 printf("Sum of all elements : %d ",sum);
 
 getch();
 return 0;
}

No comments:

Post a Comment