simple array

Hello, i am very new to C++ programing. I started learning about three days ago.
From what i have learned so far i tried to create a simple array program. It doest work! What is wrong with it?








#include <iostream>
#include <string>

using namespace std;

int main()
{

int array1[4];

for ( int n = 4 ; n>0; n=n + 1)
{
cout << "Type in a number." << endl << endl;
int zzz;
cin >> zzz;

array1[n] = zzz;

}
cout << "this is what you typed" << endl << endl;

cout << array1[0] << endl;

cout << array1[1]<< endl;

cout << array1[2] << endl;

cout << array1[3] << endl;

cout << array1[4] << endl;

system("pause");

return(0);

}
Last edited on
Well, your program is fine, except for your for loop, which is incorrect...What you currently have says to do this:

 
for (int n = 4; n > 0; n = n+1) //While n (4) is greater then zero, run the loop and add 1 every time 


You will also get out of array errors...since you are starting a 4 (the end of the array) and going up, which is out of bounds of the array you defined.

I think you wanted this as your for loop:

for(int n = 0; n < 4; ++n) //while n (0) is less then 4, run the loop and add 1 every time
closed account (z05DSL3A)


Edit: beaten to it.
Last edited on
It seems you try to output 5 integers in a 4-element array.

1
2
3
4
5
cout << array1[0] << endl;
cout << array1[1] << endl;
cout << array1[2] << endl;
cout << array1[3] << endl;
cout << array1[4] << endl; // <--- this is one too many 
Last edited on
Thank you for the help.

NiCk!
Topic archived. No new replies allowed.