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

  • Thread starter Thread starter k_phanichandra
  • Start date Start date
  • Tags Tags
    C++ Program
AI Thread Summary
The discussion centers on creating a C++ program to calculate the sum of a given number of elements using pointers. A provided code snippet demonstrates a function that takes a pointer to the start of a list and the number of elements, iterating through the list to accumulate the sum. The function is defined with a generic type, allowing it to handle different data types. The response emphasizes the importance of correctly defining the pointer type to ensure proper functionality. Overall, the conversation highlights the utility of pointers in C++ for accessing and manipulating array data efficiently.
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.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top