Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The printArray() function call in main() function is not printing the left rotated array. Here is the code that I wrote: -

What I have tried:

C++
#include<bits/stdc++.h>
using namespace std;

void leftRotate(int [], int);
void printArray(int [], int);

int main()
{
    int n, ar[50];
    cout << "Enter the size of the array: ";
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        cout << "ar[" << i << "] = ";
        cin >>ar[i];
    }
    leftRotate(ar, n);
    printArray(ar, n);
}

void leftRotate(int arr[], int size)
{
    int temp = arr[0];
    for(int i = 1; i<size; i--)
    {
        arr[i-1] = arr[i];
    }
    arr[size-1] = temp;
}

void printArray(int arr1[], int size1)
{
    for(int i = 0; i<size1; i++)
    {
        cout << arr1[i] << " ";
    }
}
Posted
Updated 14-Jul-22 20:07pm

Um ... what does this do?
C++
for(int i = 1; i<size; i--)
You start from one and reduce it each time round the loop ...

To be honest, 30 seconds with the debugger would have shown you exactly what was going on - you really should get used to using it as it's your best friend when your code doesn't do what you expected!
 
Share this answer
 
Comments
CPallini 15-Jul-22 2:11am    
5.
Quote:
Why is this code not printing the rotated array?

Time to learn the debugger.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
Comments
CPallini 15-Jul-22 2:12am    
5.
Patrice T 15-Jul-22 2:17am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900