-1

I am a beginner in C++. I am wondering how can I compute a new list by adding 8 consecutive elements and then divide them by the number of elements added in a list with C++. For example, the new list is re[], and the list we'll be using is a[], it has 200 elements. so re[i] = (a[i-1]+a[i-2]+a[i-3]+a[i-4]+a[i]+a[i+1]+a[i+2]+a[i+3]+a[i+4])/9

for(int i=4;i<196;i++){
    re[i] = (a[i-1]+a[i-2]+a[i-3]+a[i-4]+a[i]+a[i+1]+a[i+2]+a[i+3]+a[i+4])/9
}

However the above code is not applicable to the first 4 elements and the last 4 elements in re[], because a[i] in these cases has no 4 consecutive elements either preceding or following a[i]. So I am wondering how can I do the same using for loop for these elements? Thanks for any help.

yam
  • 35
  • 4
  • start your loop from i = 0 and continue to i<192. In each iteration, calculate the average of a[i]+a[i+1]....+a[i+7]. You have to calculate re[192], re[193].... and re[199] after finishing this loop. – Forhad Hossain Dec 01 '19 at 09:29

1 Answers1

0

I don't really know what you are doing but you might need to use Modulo Symbol so you wont get out of range For example: I want to stick with number 7 not get more and not getting less than 0 I will say for example 1 mod 7 and I will get 1 how? because it takes the reminder of the division To understand more about it go here To calculate and try go here

in your example

for(int i=0;i<200;i++){
    re[i] = (a[(i-1)%200]+a[(i-2)%200]+a[(i-3)%200]+a[(i-4)%200]+a[(i)%200]+a[(i+1)%200]+a[(i+2)%200]+a[(i+3)%200]+a[(i+4)%200])/9
}
Essam Adel
  • 95
  • 10