I've been trying to do something simple like reversing an array using 2 nested for loops, but I've been having trouble doing so.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1,2,3};
int index = 0;
int length = sizeof(arr)/sizeof(arr[0]);
int temp;
// Before reverse
cout<<endl;
for (int j = 0; j < length; j++)
{
cout<<arr[j]<<" ";
}
for(int l = 0; l < length-index; l++)
{
// swap elements
for(int i = 0; i < length-1; i++)
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
index++;
}
// After Reverse
cout<<endl;
for (int k = 0; k < length; k++)
{
cout<<arr[k]<<" ";
}
}
Using this for loop alone, I can get the first index to the end. However, when I use another for loop, I try decrementing the length so that the first index, that was moved to the end, does not get moved, but I it doesn't work. The first index at the end continues to move and I do not want that to happen
for(int i = 0; i < length-1; i++)
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
Please help.