int main()
{
float dizi[10], *ptr, ort, toplam = 0.0;
int i;
ptr = dizi;
for (i = 1; i <= 3; i )
{
printf("input %d. value : ", i);
scanf("%f", &*ptr);
toplam = *ptr;
}
for (i = 4; i <= 10; i )
{
*(ptr i) = toplam / 3;
printf("%d. value is : %f\n", i, *(ptr i));
}
}
The procedure is as follows: For example, the first three values I entered are 2,3,4 and the average of them, '3', is shown as the 4th element of the array. After that, it should take the average of the 2nd, 3rd and 4th values of the array, '3','4','4', and save the number 3.66 as the 5th value of the array. This process should continue until the last element of the array, the 10th value. In short, each element must be calculated as the average of the previous three element values and added to the array sequentially. I need to solve this using pointer.
CodePudding user response:
There are multiple problems in your code:
- you do not read the second and third numbers into the second and third entries in the array.
- you do not update the sum as you move and compute the next entries.
Here is a modified version:
#include <stdio.h>
int main() {
float dizi[10], *ptr = dizi, sum = 0.0;
int i;
for (i = 1; i <= 3; i ) {
printf("input %d. value: ", i);
if (scanf("%f", ptr) != 1)
return 1;
sum = *ptr;
ptr ;
}
for (i = 4; i <= 10; i ) {
*ptr = sum / 3; // store the average
printf("%d. value is: %g\n", i, *ptr);
sum -= ptr[-3]; // subtract the first value
sum = *ptr; // add the next value
ptr ;
}
return 0;
}
Sample run:
input 1. value: 2
input 2. value: 3
input 3. value: 4
4. value is: 3
5. value is: 3.33333
6. value is: 3.44444
7. value is: 3.25926
8. value is: 3.34568
9. value is: 3.34979
10. value is: 3.31824
