Reputation: 25
So I'm practicing coding before classes begin again and I wanted to create a random array of 10 integers and wanted to find which two numbers, when added together, equal greater than 100.
When I run the code below
int arr[9];
for(int i = 0; i<=9; i++){
arr[i]=(rand()%100)+1;
cout<<arr[i]<<endl;
}
cout<<endl;
for(int k = 0; k<=9; k++){
for (int j = k+1; j<=9; j++){
if((arr[k]+arr[j])>100){
cout<<arr[k]<<" + "<<arr[j]<<" "<<"over 100"<<endl;
}
else{
cout<<arr[k]<<" + "<<arr[j]<<" "<<"under 100"<<endl;
}
}
}
return 0;
I notice that the value of arr[9] is equal to one number but the program has another number for it. For example: the array that's created is [42 68 35 1 70 25 79 59 63 65]
but my output shows a 9 as arr[9]
42 + 68 over 100
42 + 35 under 100
42 + 1 under 100
42 + 70 over 100
42 + 25 under 100
42 + 79 over 100
42 + 59 over 100
42 + 63 over 100
42 + 9 under 100
(I'll just include the first loop to not make this any longer)
Where did my 65 go??
Where did the 9 come from??
Did I write something wrong??
Thanks
Upvotes: 2
Views: 53
Reputation: 9366
I notice that the value of arr[9] is equal to one number but the program has another number for it.
Counting in computers starts from 0
and ends at one number less than the total size. For int arr[9]
arr[8]
arr[0]
arr[1]
When you do arr[9]
, you are crossing the boundary (accessing an element that's not in the range) which leads to undefined behaviour.
As a result, your loop should stop at i < 9
:
for(int i = 0; i < 9; i++) // i < 9 now vs i <=9
The same changes need o be made to the loops below the first one.
Upvotes: 1