//lesson 6 exercise 2
#include <iostream>
usingnamespace std;
int main()
{
int MyInts1[3] = {1, 2, 3};
int MyInts2[2] = {4, 5};
cout << "Going to add elements of arrays in reverse order" << endl;
for(int index = 3; index > 0; index--)
{
for(int index2 = 2; index2 > 0; index2--)
{
cout << MyInts1[index]<< " + " << MyInts2[index2]
<< " = " << MyInts1[index] + MyInts2[index2] << endl;
}
}
system("pause");
return 0;
}
ok guys once again this is not homework in anyway this is life enrichment for the hurt fat guy. Basically what I am trying to do is get each element of the 1st array to add itself to each element of the 2nd array. I have achieved this but I am getting more output than I need. This is what I am getting and it is driving me nuts I have been working on it all day even going back and examining the fundamentals of for loops with my father...although his expertise is basic.
that is the output I am getting in codeblocks. It is starting correctly with the last element of 3 then going to 2 and finally 1, but the 3+1 shouldn't be there, the 2nd set of the 3's shouldn't be there and the 2+1 and 1+1 shouldn't be there. Any input good bad or nasty is appreciated.
You're out of range in index and index2. Remember, arrays start at 0, so MyInts[0] = 1, MyInts[1] = 2 and MyInts[2] = 3, yet you are trying to access MyInts[3] with index = 3. Pretty much the same problem with MyInts2[2] and index2 = 2. MyInts2[0] = 4 and MyInts2[1] = 5. There is no MyInts[2].
//lesson 6 exercise 2
#include <iostream>
usingnamespace std;
int main()
{
int MyInts1[2];
MyInts1[0] = 1;
MyInts1[1] = 2;
MyInts1[2] = 3;
int MyInts2[1];
MyInts2[0] = 4;
MyInts2[1] = 5;
cout << "Going to add elements of arrays in reverse order" << endl;
for(int index = 2; index >= 0; --index)
{
for(int index2 = 1; index2 >= 0; --index2)
cout << MyInts1[index]<< " + " << MyInts2[index2]
<< " = " << MyInts1[index] + MyInts2[index2] << endl;
}
return 0;
}
cleaned up the arrays like they should be now I need to work on the loops a little bit...thanks for the responses also fellas...I have been down 2 days and still not right...I took a header into a treadmill and had to have my lip sewed back together with a few stitches but I will try to figure out the loops here today or tomorrow and may need some help but thanks again.
You still have to increase your array indices. Remember, an array that is created, as you did with, int MyInts1[2];, has two place holders only, MyInts1[0] and MyInts1[1]. There is no MyInts1[2]. Increase it to int MyInts1[3]; and int MyInts2[2]; to accommodate MyInts2[0] and MyInts2[1].