Complementary task for topic: 6
M Nemeth · 2023-08-29 15:21:04.626219'
Pointers: Pointer Arithmetic (array)
Pointers: Pointer Arithmetic (array)
Create a C program that demonstrates pointer arithmetic by printing the elements of an integer array using pointers. Also the sum and average of the elements.
Output:
Array Elements: 10 20 30 40 50
Sum of Elements: 150
Average of Elements: 30
Hint: The name of the arrays refers to a memory address, the first element's adress. If you add one to the pointer, you got the 2nd element. The indexing operatore really does:
Arr[i]=*(Arr+i);
Here is the answer why the indexing starts with 0.
Define an integer array with some elements and initialize it.
Define a pointer to point to the first element of the array.
Use pointer arithmetic to traverse the array and print its elements.
Calculate the sum of the elements using pointers.
Calculate the average of the elements using pointers.
Solution
#include
int main() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr;
int size = 5;
int sum = 0;
printf("Array Elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", *(ptr + i));
sum += *(ptr + i);
}
double average = (double)sum / size;//type conversion!
printf("\nSum of Elements: %d\n", sum);
printf("Average of Elements: %.2lf\n", average);
return 0;
}
Explanation
In this task, we have an integer array arr with elements {10, 20, 30, 40, 50}. We define a pointer ptr and initialize it to point to the first element of the array. The size variable is used to keep track of the number of elements in the array. We use pointer arithmetic to traverse the array and print its elements using a for loop. The expression *(ptr + i) is equivalent to arr[i]. Inside the loop, we also calculate the sum of the elements by adding each element's value to the sum variable. To calculate the average, we convert the sum to a double and divide it by the number of elements in the array. Finally, we print the sum and average of the elements using printf(). The average is displayed with two decimal places using the format specifier %.2lf.