Read, Print and Sum Array Using Pointers in C
On this page (5sections)
About this page
This program reads array elements from the user with scanf(pt + i), then prints and sums them using pointer traversal (pt++). It extends the basic sum program with interactive input.
For summing a fixed (pre-filled) array only, see Sum of Integer array using pointers.
Syntax
pointer_variable = &var[position];
pointer_variable++ is increasing Address value based on Data Type
pt++; --> Its location next position of Array
Print and Sum of Integer in an array using pointers in C
/* Simple Program for Reading, Print and Sum of Integer in an array using pointers in C*/
/* Pointer and Array Program, C Pointer Examples */
#include <stdio.h>
#define MAX_SIZE 5
int main() {
int var[] = {10, 20, 30, 40, 50};
int i = 0, sum = 0;
//Pointer Variable Declaration for Integer Data Type
int *pt;
//& takes the address of var , Here now pt == &var, so *pt == var
pt = &var[0];
printf("Enter %d Elements : \n", MAX_SIZE);
while (i < MAX_SIZE) {
// pt + i is increasing Address value based on Data Type
scanf("%d", pt + i);
i++;
}
i = 0;
printf("\nPrint Elements:\n");
while (i < MAX_SIZE) {
i++;
// Calculate sum using pointer
printf(" %d\t", *pt);
sum = sum + *pt;
// pt++ is increasing Address value based on Data Type
pt++;
}
printf("\nSum of Array : %d", sum);
return 0;
}
Sample Output
Enter 5 Elements :
2
4
6
8
1
Print Elements:
2 4 6 8 1
Sum of Array : 21
Related Pages
Learn the concept first, then study the code:
- C Programs — Browse all C Programs.
- C Pointers — Concept — pointers, addresses and dereferencing.
- Simple Pointer Example Program — More in c pointer example programs.
- Simple Program for Print address of Variable Using Pointer in C — More in c pointer example programs.