+ 1

About array in loops

When I write this code : int apple[5]; for(int x=0; x<5; x++){ apple[x] = 42; cout<<apple<<endl; } I get this : 0x28fed4 0x28fed4 0x28fed4 0x28fed4 0x28fed4

16th Nov 2018, 5:33 AM
Mohanad Methkal
2 Respuestas
+ 1
I assume you want to print each element of list apple, for that you need to change your cout statement to cout<<apple[x]<<endl; What your program is currently doing is printing the memory location of list apple.
16th Nov 2018, 6:15 AM
Jayesh Bhushan
Jayesh Bhushan - avatar
+ 6
And don't get confuse with char array because << operator treats it differently like this #include <iostream> int main() { char apple[5]; for (int x = 0; x<5; x++) { apple[x] = 42; std::cout << apple << std::endl; } } Output: * ** *** **** *****
16th Nov 2018, 6:40 AM
Babak
Babak - avatar