- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Environmental Science
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a ‘C’ Program to compute the sum of all elements stored in an array using pointers
C Program to compute sum of the array elements using pointers
Program :
#include <stdio.h>
#include <conio.h>
void main() {
int numArray[10];
int i, sum = 0;
int *ptr;
printf("\nEnter 10 elements : ");
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < 10; i++) {
sum = sum + *ptr;
ptr++;
}
printf("The sum of array elements : %d", sum);
}
Output :
Enter 10 elements : 11 12 13 14 15 16 17 18 19 20
The sum of array elements is 155
Explanation of Program :
Accept the 10 elements from the user in the array.
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
We are storing the address of the array into the pointer.
ptr = numArray; /* a=&a[0] */
Now in the for loop we are fetching the value from the location pointer by pointer variable. Using De-referencing pointer we are able to get the value at address.
for (i = 0; i < 10; i++) {
sum = sum + *ptr;
ptr++;
}
Suppose we have 2000 as starting address of the array. Then in the first loop we are fetching the value at 2000. i.e
sum = sum + (value at 2000)
= 0 + 11
= 11
In the Second iteration we will have following calculation –
sum = sum + (value at 2002)
= 11 + 12
= 23
- Related Questions & Answers
- How to Implement Stack Operations Using Array using C
- Write C Program to Delete duplicate elements from an array
- How to calculate gross salary of a person using C Program
- Write C Program to Find Largest Element in Array in C Programming
- How can we create recursive functions in Python?
- How to redirect HTTP to HTTPS Using htaccess
- How To Reduce the Array to 0 by decreasing elements by 1 or replacing at most K elements by 0
- How to find area and circumference of circle using C Programming
- How to print hello world using C Language
- How to Check Whether Number is Perfect Or Not using C
- Write C Program to Find Smallest Element in Array in C Programming
- How to Calculate Area of Rectangle using C Program
- How to reads customer number and power consumed and prints amount to be paid using C
- Write C program to find Exponent Power Series
- How to find gretest in 3 number using C Programming
- How to Solve Second Order Quadratic Equation Using C Program
Advertisements
ads