C query

Joined
Jun 8, 2022
Messages
4
Reaction score
0
Suppose i have predefine array of elements. I want to calculate the sum of first five elements, then display it & then calculate the sum of next elements & so on till last.
 
Joined
Mar 28, 2022
Messages
82
Reaction score
11
Untitled.png

C:
// given an array and an index, return sum of next five elements
double sumNextFiveElements(double[] array, int index)
 
Last edited:
Joined
Mar 28, 2022
Messages
82
Reaction score
11
I write in Java not C, so I cannot give you the code, only an algorithm.
Java:
// loop through segments of the array (assumes array length divisible by 5)
for(int offset = 0; offset < array.size(); offset += 5){
    // gather elements of segment
    for(int index = offset; index < offset + 5; index++){
        total += array[index]
    }
    // could print total here, and then reset total if desired
}
 
Last edited:
Joined
Jun 8, 2022
Messages
4
Reaction score
0
I write in Java not C, so I cannot give you the code, only an algorithm.
Java:
// loop through segments of the array (assumes array length divisible by 5)
for(int offset = 0; offset < array.size(); offset += 5){
    // gather elements of segment
    for(int index = offset; index < offset + 5; index++){
        total += array[index]
    }
    // could print total here, and then reset total if desired
}
Thank you so much
 
Joined
Jun 28, 2022
Messages
2
Reaction score
0
C++:
for(int i= 0; i < arr.size(); i += 5)
{
    for(int j = i; j < i+ 5; j++){
        sum += arr[j];
    }
    cout<<sum<<endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top