There is an exercise in this book that asks to make an array of 5 integers, then print all of them and then the sum of all the numbers. I thought i knew how to do this but I don't think I fully understand arrays yet to do this. any help is appreciated.
Here's my code so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main()
{
int jack[5] = {100,300,900,400,500};
int x = 0;
while(x < 5){
cout << jack[x] + jack[x++] << endl;
}
}
has undfined behavior. You may not use postfix increment operator of a variable with the variable itself in the same expression because the order of evaluation of subexpressions is undefined.
Your tasks are being done simply the following way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int jack[5] = {100,300,900,400,500};
for ( int x : jack ) std:;cout << x << ' ';
std::cout << std::endl;
int sum = 0;
for ( int x : jack ) sum += x;
std::cout << "The sum is equal to " << sum << std::endl;
}
ya also you dont have to use std:: because that's what using namespace std; does. also the way you put the for loops was a little confusing. but i think i got the jist of your program. thank you vlad
As I said use the ordinary for statement instead of the range-based for statement. You should understand what the for statemnet in my code does and substitute it for your for statement.
but i dont. all i know is you declared the variable x as an integer and assigned it no value then use ':' and then the name of my array... is it basically the same thing as jack[x]?
#include <iostream>
usingnamespace std;
int main()
{
int jack[5] = {100,300,900,400,500};
int sum = 0;
for (int x = 0; x < 5; x++){
cout << jack[x] << endl;
sum += jack[x];
}
cout << sum << endl;
}
Only it is a bad style of programming to use such identifiers as x as indexes of arrays in such simple loops. It is better to use identifiers i, j, k, l, m, n. This tradition came from FORTRAN.