Write a C program that uses a pointer to an array to find the sum of all elements. Explain the steps you took to achieve this.

12 Sep 2023 Balmiki Mandal 0 C Programming

C program that uses a pointer to an array to find the sum of all elements:

C- Programming
#include 

int main() {
  int arr[5] = {1, 2, 3, 4, 5};
  int *ptr = arr;
  int sum = 0;

  // Find the sum of all elements in the array using the pointer
  for (int i = 0; i < 5; i++) {
    sum += *ptr++;
  }

  printf("The sum of all elements is %d\n", sum);

  return 0;
}

This program first declares an array of 5 integers called arr. Then, it declares a pointer to an integer called ptr and initializes it to the address of the first element of the array (arr).

Next, it declares an integer variable called sum to store the sum of all elements in the array.

The next loop iterates through the array and adds the value of each element to the variable sum using the pointer. The pointer is incremented after each iteration to point to the next element of the array.

Finally, the program prints the value of the variable sum.

The steps involved in achieving this are:

  1. Declare an array of integers.
  2. Declare a pointer to an integer and initialize it to the address of the first element of the array.
  3. Declare an integer variable to store the sum of all elements in the array.
  4. Iterate through the array and add the value of each element to the variable sum using the pointer.
  5. Print the value of the variable sum.

Further Reading:


What is Pointer to an array? Give one example.

Print The array element using Pointer to an array

Implications of Passing an Array and a Pointer to an Array as Function Arguments in C

Write a C program that uses a pointer to an array to find the sum of all elements.

Assingment of pointer to an array in c

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.