0

Arrays and Indices

For my next to last for loop, I'm trying to get the odd indices to print 1 and even indices to print 0. I'm having trouble trying to print the even indices. #include<iostream> #include <cstdlib> #include<ctime> using namespace std; int main() { int myArray[10]; //print 0 for ea. element for (int a = 0; a < 10; a++) { myArray[a] = 0; cout << "Element" << a << "= " << myArray[a] << endl; } //print random # for ea. element srand(time(0)); for (int a = 0; a < 10; a++) { myArray[a] = rand() % 10 + 1; cout << "Random" << a << "= " << myArray[a] << endl; } //print odd # for ea. element for (int a = 0; a < 10; a++) { myArray[a] = 2 * a + 1; cout << "Term" << a << "= " << myArray[a] << endl; } //print odd elements=1 and even elements=0 for (int a = 0; a < 10; a++) { int evenArr = 0; int oddArr = 1; myArray[a] = a++; if (myArray[a] % 2 == 0) cout << "Even" << a << "= " << evenArr << endl; else cout << "Odd" << a << "= " << oddArr << endl; } //print elements to multiples of 10 then print backwards for (int a = 0; a < 10; a++) { myArray[a] = 10 + 10 * a; } for (int a = 9; a >= 0; a--) { cout << "Multiple" << a << "= " << myArray[a] << endl; } system("pause"); return(0); }

29th Sep 2018, 7:16 PM
Krista Clark
Krista Clark - avatar
5 Antworten
+ 3
The problem is this line: myArr[a] = a++; Doings this results in a being incremented twice per iteration, so you effectively leave out half of the elements. You shouldn't increment/decrement the running variable inside a for-loops body to prevent especially this. You can use a + 1 instead of a++ since a + 1 won't effect the original value of a. But I don't see why you would want to do it this way, because this way odd indices will print even and the other way round.
29th Sep 2018, 8:05 PM
Shadow
Shadow - avatar
+ 8
Can you elaborate more what's the problem?
29th Sep 2018, 7:57 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 4
Is this what you mean? you can ask again if I misunderstood your intention ... for (int a = 0; a < 10; a++) { int evenArr = 0; int oddArr = 1; myArray[a] = a+1; if (myArray[a] % 2) cout << "Even" << a << "= " << evenArr << endl; else cout << "Odd" << a << "= " << oddArr << endl; }
29th Sep 2018, 8:04 PM
Ipang
+ 4
Krista, actually I agree with Shadow, the snippet I passed there gives output that was *not* supposed to be, (read Shadow's explanation for reason why). Another way to do that, without the twisted 'if' branch, would be to evaluate the element index in the 'if' branch, instead of the element value. myArray[a] = a + 1; if (a % 2 == 0) // <= evaluate index Either way still, the value assignment to elements here should do with; myArray[a] = a + 1; instead of; myArray[a] = a++;
29th Sep 2018, 8:55 PM
Ipang
+ 2
Thanks guys. Shadow thank you for explaining. Ipang's code output what I wanted.
29th Sep 2018, 8:27 PM
Krista Clark
Krista Clark - avatar