Simple Program for Read, Print and Sum of Integer in an array...
On this page (6sections)
About this program
This is an example program in c pointer example programs. Read the concept first: Pointer Example Program in C++, then study the code and output below.
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 Read, Print and Sum of Integer in an array using pointers in C++*/
/* Pointer and Array C++ Program,C++ Pointer Examples */
// Header Files
#include <iostream>
#include<conio.h>
using namespace std;
#define MAX_SIZE 5
int main() {
// Declare Variables
int var[5];
int i = 0, sum = 0;
//Pointer Variable Declaration for Integer Data Type
int *pt;
cout << "Pointer Example C++ Program : Read, Print and Sum of Integer Pointer and Array \n";
//& takes the address of var , Here now pt == &var, so *pt == var
pt = &var[0];
cout << "Enter " << MAX_SIZE << " Elements : \n";
while (i < MAX_SIZE) {
// pt + i is increasing Address value based on Data Type
cin>>*pt;
i++;
pt++;
}
i = 0;
pt = &var[0];
cout << "\nPrint Elements:\n";
while (i < MAX_SIZE) {
i++;
// Calculate sum using pointer
cout << *pt << "\t";
sum = sum + *pt;
// pt++ is increasing Address value based on Data Type
pt++;
}
cout << "\nSum of Array : " << sum;
getch();
return 0;
}
Sample Output
Pointer Example C++ Program : Read, Print and Sum of Integer Pointer and Array
Enter 5 Elements :
6
7
1
2
3
Print Elements:
6 7 1 2 3
Sum of Array : 19
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
- Pointer Example Program in C++ — Concept — pointers, addresses and dereferencing in C++.
- Simple Program for Print address of Variable Using Pointer in C++ — More in c pointer example programs.
- Pointer Simple Example Program with Reference operator (&) and Dereference operator (*) — More in c pointer example programs.
Frequently Asked Questions
What does this C++ program do?
It is a C++ example program that demonstrates Simple Program for Read, Print and Sum of Integer in an array..., including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and reading user input, illustrating a common pattern in C++ programming.