Greetings,
When you get more into it, you'll learn about vectors, and this won't be an issue, but learning arrays is important!
I just wanted to make some notes about your code though:
This line:
for (int i = 0; i < (myArray[i]); i++)
Will yield some results that you don't want. You're checking to see if the variable i is less than whats at the array at position i. What I assume you're looking to do is run through the array. In that case you want to iterate through the length of the array. What you would want to use is the size function of arrays.
for (int i = 0; i < myArray.size(); i++)
The second thing is here:
1 2 3 4 5 6
|
if (myArray[i] == 2)
{
myArray[4] = myArray[i - 1];
cout << myArray[i];
}
| |
The if statement is good, you're looking for the value '2'. However, you're accessing the array at a hard coded position, which can be dangerous if you don't know what you're doing. You're array's size and number of elements are actually different numbers (off by one). For example, you have an array of size 4 but it starts counting at 0 so element 0 is 1, element 1 is 2, element 2 is 3, and element 3 is 4. So what is at element 4 (the position you're trying to access)?
For simple programs you should try and trace out whats going on, line by line. You'll find out whats wrong.
So, to trace this out:
i is 0 so it outputs 1
it fails the if statement and goes back to the top of the loop
i is 1 so it outputs 2
it passes the if statement
it then assigns 1 to position 4 in the array (but you don't have access to it)
then it outputs 2 (i is still 1!)
then it goes back to the top of the loop
i is 2 so it outputs 3
it fails the if statement and goes back to the top of the loop
i is 3 so it outputs 4
it fails the if statement and goes back to the top of the loop
then i is 4 but you don't have access to myArray[4] (its usually garbage)
However, if you were allowed, you assigned 1 to myArray[4] so it fails the while condition of the for loop, and drops out completely.
the program for me segfaulted at this point (Which it should have)