#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.
char* temp1 = new char[temp - num];-- Why are you allocating additional memory to do a left shift? -- we are not allowed to use vectors or built-in functions -- but nothing stops you from looking at the possible implementation. Note that the possible implementation allocates no memory.