In: Computer Science
In C create an array of 4 integers. Assign a pointer to the array. Use the pointer to find the average value of the elements in the array and display the results on the screen.
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments(read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation
please refer code Images
Typed Code:
//Header Files
#include <stdio.h>
int main()
{
//creating an array of 4 integers
int arr[4] = { 1, 2, 3, 4 };
//declaring pointer
int *ptr;
//Assigning a pointer to the array
ptr = arr;
//initializing sum as 0
int sum = 0;
//for loop will iterate 4 times
for (int i = 0; i < 4; ++i)
//adding array values to sum
//*ptr is a pointer assigned to arr[0] --> *(ptr+0)
//to access other elements --> arr[1] --> *(ptr+1),
// arr[2] --> *(ptr+2),
// arr[3] --> *(ptr+3)
sum = sum + *(ptr + i);
//printing Average
printf("Average: %.2f",sum/4.0);
return 0;
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!