so I am trying to print out arr[n] in reverse order with a simple for loop, I tried with the code below, but after it prints it out in reverse it continues to print infinite zeros, I tried to edit the code with if else and do while but it still didn't help. Any hint or solution would be appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
int n=10;
int i;
int arr[n]={1,2,3,4,5,6,7,8,9,10};
for(int i=n-1; i<n; i--){
cout<<arr[i];
}
return 0;
}
Your termination condition says i<n, which is i<10. Since you're decrementing i, i will always be less than 10.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Basically it is printing out infinite zero because your for loop cannot run
since you are start from n - 1 ....when do you want your for loop to end
so you wrote i < n; which mean that it will never end since i will always be lower than 10 because you did i--
so think of it this way you start out with 9 .......... then you check if your going to end if 9 < 10 that is true meaning it won't end just yet and then you decrease the 9 with the i-- to become an 8 you check it again 8 < 10 still not great than 10 meaning you keep going on and on and on which is a never ending cycle.