Arrays

Now both of these codes are logically correct and should give the same answers and in arrays if I did not put the index but I assigned values to the array I do not need to put the size because by default it become the amount of numbers I added, so I need to know since both of the codes are logically the same why do I get different answers

#include <iostream>
using namespace std;

// code(1)
// output 123
int main(){
int num[]= {1,2,3};

for(int i = 0 ; i<3 ; i++){
cout << num[i];
}
return 0;
}

and

// code(2)
// output 233
int main(){
int num[]={1,2,3};

for(int i=1 ; i<4 ; i++){
cout << num[i];
}
return 0;
}

Thank you
Last edited on
Now both of these codes are logically correct


'Fraid not.
Your first loop:
1
2
3
4
for(int i = 0; i < 3; i++)
{
     cout << num[i];
}

Your second loop:
1
2
3
4
for(int i = 1; i < 4; i++)
{
     cout << num[i];
}


The size of the num array is 3 in both examples, yet in the second loop you go up to index 3, which you don't have access to.

num is of size 3, meaning you can access elements from index 0, 1, and 2. Your first loop does that.

Your second loop goes through indexes 1, 2, and 3. Trying to access num[3] is undefined - could crash your program, and the value you receive from num[3] could be anything.
In your second loop, during the process you are trying to display the fourth element in your array. So you got an error. Starting i at 1, at first you write the second value 2, then the third and when your code tries to write the forth, it crashes because it does not exist.
Don't forget that your first value in your array is i[0] and I guess that you thought that it could be i[1].

First loop displays : 1, 2, 3
Second loop displays : 2, 3, <- and it crashes
Last edited on
Topic archived. No new replies allowed.