0

I just started learning C++ in college and my task is to do the following: I have to write some code that will use iteration (i.e. looping) to calculate the cumulative sum of the items in an array of integers; my code is:

int main() {
 int myArray[] = {1,2,3,4,5};
 int i;
 int j;
 j+= myArray[]; 
 for(i=0;i<5;i++){
 printf("%d\n",myArray[j]);
 }
} 

Although this code does not produce what I am looking for and I am confused as to what I should do next.

abhi312
3722 gold badges6 silver badges26 bronze badges
asked Apr 27, 2016 at 4:10
5
  • 1
    did this even compile for you? Commented Apr 27, 2016 at 4:15
  • No the error is as follows: Line 5: error: expected primary-expression before ']' token compilation terminated due to -Wfatal-errors. @PaulRooney Commented Apr 27, 2016 at 4:17
  • add the error to the question. Commented Apr 27, 2016 at 4:17
  • Do you want j become 15? Commented Apr 27, 2016 at 4:21
  • Regardless of your actual issue, you should get out of the habit of using short variable names other than for localised loop variables, and then scoped to the loop itself such as for (int i = ... ). There is no reason why an accumulator variable should be called j. Fix that bad habit and hordes of developers that have to maintain your code in the future will sing your praises rather than curse your mother for producing such vile issue :-) Commented Apr 27, 2016 at 7:28

5 Answers 5

2
int main() {
 int myArray[] = {1,2,3,4,5};
 int sum = 0;
 for(int i=0; i<5; i++)
 sum += myArray[i] ;
 std::cout << sum; 
}

Here sum is initialized to 0 and each element in the array is added to the sum in a loop.

you can use std::accumulate to do the same, hence you dont worry about the size of the array.

#include <iostream>
#include <algorithm>
int main() {
 int myArray[] = {1,2,3,4,5};
 std::cout << std::accumulate(std::begin(myArray), std::end(myArray), 0);
} 

Note that std::begin() and std::end() were introduced in C++11. For earlier versions, you will have to use pointers instead:

std::accumulate(myArray, myArray + 5, 0);
answered Apr 27, 2016 at 4:22
1
  • 1
    note that std::begin() and std::end() were introduced in C++11. For earlier versions, you will have to use pointers instead: std::accumulate(myArray, myArray + 5, 0); Commented Apr 27, 2016 at 4:39
1

I've edited your code with comments and a line of code. please review them.

#include <cstdio>
int main() {
 // Array and index into it.
 int myArray[] = {1,2,3,4,5};
 int i;
 // Initialise sum to zero for starting.
 int sum = 0;
 // Adding whole array will not work (though it would be nice).
 // Instead, go through array element by element.
 // j += yArray[];
 for (i = 0; i < 5; i++) { 
 // Add element to sum and output results.
 sum += myArray[i];
 printf ("Adding %d to get %d\n", myArray[i], sum);
 }
 // Output final result.
 printf ("Final sum is: %d\n", sum);
}

Also note that I've used printf as per your question but you really should be using the C++ streams facilities for input and output.

The output of that code is:

Adding 1 to get 1
Adding 2 to get 3
Adding 3 to get 6
Adding 4 to get 10
Adding 5 to get 15
Final sum is: 15
paxdiablo
887k241 gold badges1.6k silver badges2k bronze badges
answered Apr 27, 2016 at 4:16
3
  • 5 in the for loop would probably be better written as sizeof(myArray) / sizeof(*myArray),, should you ever want to change the length of said array at some point. Though, of course, that'a a problem with the original code rather than something specific to your answer. Commented Apr 27, 2016 at 7:32
  • Youre correct, yet Im unsure whether OP understands this kind of command and that it can only be used at the main function. Thus i've stuck with the basics and minimal change to original code. Commented Apr 27, 2016 at 12:21
  • thankyou @GiladMitrani, I needed to be able to understand how every line impacts the output and this is great explanation! CHEERS Commented Apr 27, 2016 at 12:52
1

Note that <algorithm> has a function for that:

const int myArray[] = {1,2,3,4,5};
const int sum = std::accumulate(std::begin(myArray), std::end(myArray), 0);

If you want to do the loop yourself, you may use the for-range (since c++11):

const int myArray[] = {1, 2, 3, 4, 5};
int sum = 0;
for (auto e : myArray) {
 sum += e;
}
answered Apr 27, 2016 at 8:04
0

You need to put j+= myArray[] inside the loop and put i inside [] of myArray in order to perform the summation operation. Thereby, your code could be modified as follows to be matched to what you want to do. After summation of all the elements in the array, it exits for-loop, and print the final summation as in the second printf. Note that j was replaced by sum in order to be readable.

int main() {
 int myArray[] = {1,2,3,4,5};
 int sum=0; // sum
 for(int i=0; i<5; i++){
 sum += myArray[i];
 printf("%d\n", myArray[i]);
 }
 printf ("Sum: %d \n", sum);
}

You can see a runnable code at this link. Hope this help.

answered Apr 27, 2016 at 4:36
0
int main() {
 int yourArray[] = {1,2,3,4,5};
 int sum = 0;
 for(int i=0; i<5; i++) {
 sum = sum + yourArray[i] ;
 std::cout << sum; 
 }
}

In the above code, the for loop will iterate 5 times, each time a value in the array will be added to the sum variable.

In the first iteration, the value of sum will be 0, and the value at yourArray[0] will be 1, so sum = 0 + 1;.

In the second iteration, the value of sum will be 1, and the value at yourArray[1] will be 2, so sum = 1 + 2;.

And so on...

After each iteration is complete, we output the sum, which will be 1, 3, 6, 10, 15.

So 15 is the complete sum of all the values of the array.

Remy Lebeau
607k36 gold badges515 silver badges870 bronze badges
answered Apr 27, 2016 at 4:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.