#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
int myarray[4] = {5,5,5,5};
int count=0;
int sum=0;
do
{
sum += myarray[count];
++count;
}
while(count<=4);
cout << sum;
cin.get();
cin.get();
return 0;
};
when i run the above code it prints out a random HUGE positive or negative integer and idk why or how it's doing this am i just missing something stupid in my short code?
also int myarray[4] = {5,5,5,5}; i'm declaring an array of 4 which should have 5 element so when i try to initialize a 5th element it says
1>testprograms.cpp(8): error C2078: too many initializers
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
is this a standard in c++ that was changed?
and if you're wondering what i'm trying to do i'm trying to add all the elements of the array together and get the sum of the array and print it out on the screen
The [4] on line 8 indicates how large your array is, not what the last index is. Your array is 4 elements long, (meaning it goes from 0 to 3), not 5. It's confusing, I know, and it takes a while to get used to. But I trust you will! :)
That said, you're going out of the bounds of your array on line 18. Using a < operator might be a good idea.
also int myarray[4] = {5,5,5,5}; i'm declaring an array of 4 which should have 5 element so when i try to initialize a 5th element it says...
you declare and initialize an array with 4 elements, each one with the value 5. since the program starts counting at 0, myarray[4] is out-of-bounds, hence the hissy fit from the compiler.
The solution would be to change the while(count<=4) statement to while(count<4)
Thank you so much for the reply and help i got it to work with a for loop and i'm going to do the while loop and i realized that declaring an array of... 5 it has 5 elements starting from 0,1,2,3,4 = 5 in total i was under the assumption it worked by 0,1,2,3,4,5=6 total elements
and i see it was just poor use of operators on my part
do you have any insight on why overloading an array assigns a huge random integer instead of saying, "overload of array or something"?
Well, because C++ doesn't do any bounds checking on normal C-style arrays. It's a performance thing. When you go out of the bounds of an array, depending on where that array is in the memory, two things might happen: you'll access memory you don't have rights to access and your program will crash, or you'll access an integer that contains garbage, as if you used a normal uninitialized int.