#include <iostream>
#include<string>
using namespace std;
int main()
{
//for left shift geeksforgeeks should become eksforgeeksge
//for right shift geeksforgeeks should become ksgeeksforgeeks
char* original = new char[100];
cout << "enter the array\n";
cin >> original;
cout << "the array entered is " << original << endl;
int temp = 0;
for (int i = 0; original[i] != '\0'; i ) { temp ; }
cout << "the size of array is " << temp << endl;
int num;
//left shift
cout << "enter the number of digits to be left shifted\n";
cin >> num;
char* temp1 = new char[temp - num];
char* temp2 = new char[num];
int tempn= temp-num;
//storing the characters in the short std::array
for (int i = temp - num; i < temp; i ) {
temp2[i] = original[i temp-num];
cout << temp2[i];
}
//storing the characters in the larger std::array<T, N> ;
for (int i = 0; i < temp - num; i ) {
temp1[i] = original[i];
cout << temp1[i];
}
cout << endl;
cout <<"the left shifted array is\n ";
for (int i=0; i<num;i ){
original[i]=temp2[i];
cout << original[i];
}
for (int i=0; i < temp; i ){
original[num i]=temp1[i];
cout <<original[num i];
}
I have tried to implement a left shift on the dynamic array. But, this does not give the correct answer. It does not display the initial characters after left shifting. The issue is in storing the new array temp2 in the original array. But I cannot figure out how to fix this. Please help.
CodePudding user response:
Given an array of 4 characters:
--- --- --- ---
ltrs = | a | b | c | d |
--- --- --- ---
Step 1: copy the first character to a temp variable:
const char temp = ltrs[0];
Step 2 copy slot 1 to slot 0:
--- --- --- ---
ltrs = | b | b | c | d |
--- --- --- ---
^ |
---
Step 3: keep copying until end of array:
--- --- --- ---
ltrs = | b | c | d | d |
--- --- --- ---
Step 4: Copy the temporary variable to the last position in the array:
--- --- --- ---
ltrs = | b | c | d | a | <--- temp
--- --- --- ---
Changing to a larger array size is left as an exercise for the OP.