C++ Program Help: Get Sum of N Numbers w/ Pointers

  • Context: C/C++ 
  • Thread starter Thread starter k_phanichandra
  • Start date Start date
  • Tags Tags
    C++ Program
Click For Summary
SUMMARY

The discussion focuses on a C++ program to calculate the sum of N numbers using pointers. The provided function, sum(type* p, int n), initializes a sum variable to zero and iterates through the array pointed to by p, adding each element to the sum. This method efficiently utilizes pointer arithmetic to access array elements. The solution is confirmed as effective for summing a list of numbers in C++.

PREREQUISITES
  • C++ programming fundamentals
  • Understanding of pointers and memory management
  • Basic knowledge of arrays in C++
  • Familiarity with function syntax in C++
NEXT STEPS
  • Explore C++ pointer arithmetic in-depth
  • Learn about dynamic memory allocation in C++
  • Investigate C++ standard library functions for array manipulation
  • Study performance implications of using pointers versus references in C++
USEFUL FOR

C++ developers, computer science students, and anyone looking to enhance their understanding of pointers and array manipulation in C++ programming.

k_phanichandra
Messages
3
Reaction score
0
What is the program code in c++ to get the sum of given n numbers using pointers?
 
Technology news on Phys.org
"using pointers" is vague, also there is a separate programming forum...

if you have a list of length n and some pointer p to the start of that list, of the correct type then:

Code:
type sum(type* p, int n)
{
  type sum = 0;
  for(int i = 0; i < n; i++) sum += p[i];
  return sum;
}

is a function that sums the numbers
 
Last edited:
Thanks for giving an answer to my question.
 

Similar threads

  • · Replies 17 ·
Replies
17
Views
3K
Replies
86
Views
2K
Replies
5
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
4K
Replies
14
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 118 ·
4
Replies
118
Views
10K
Replies
12
Views
2K
  • · Replies 19 ·
Replies
19
Views
6K
  • · Replies 25 ·
Replies
25
Views
3K