How to make the last element of an array null?(c++)So for my data structures class, we are working in c++. We are supposed to create a function that takes in an array, shifts everything to the left and leaves the original final element as null. Now I haven't found any simple way to convert them to null so I was just converting them to "0".I was seeking help on how to modify my code such to make the final element a null value.
We are also testing our code with catch 2,so I will include my test case that isn't running. Any help would be greatly appreciated. I was also seeking help on how to get the function to be called and properly function
Thank you! :)
edit:Sorry if the question was ambiguous
here is the code I have so far.
```
int * left_shift(int arr[],int n)
{
for(int i = 0 ; i {
if(i==n-1){ arr[i] = 0; } // make
last element null
arr[i] = arr[i+1]; //shift element
to the right
}
return arr; //function then returns modifed
array
}
```
and here are the failing tests,that are saying I am converting the file incorrectly. I don't quite understand the error message to be honest
```
TEST_CASE("left_shift","[Lab1]"){
SECTION("ex1")//test one
{
int arr[] =
{1,2,3,4};//initial array
int n =
sizeof(arr)/sizeof(int);
int r[]=
{left_shift(&arr,n)};
CHECK(r[n-1] ==
0);
}
}
```
Thanks again !
Hi,
Please find the solution below:
------------------------------
There is a small bug in the code. After checking for the final last
element and assigning it to zero,
We need to break the code.
Note: On assumption that the last element is set to zero.
if(i==n-1){
arr[i]
= 0;
break;
} // make last element
null
Otherwise, the code shifts some junk content to the last element in
the next line.
arr[i] = arr[i+1]; //shift element to the right
The above would execute and overrides the assignment of zero in the
last element.
-----
The function returns the base address of the array. Use of pointers
would be helpful in the test case.
Sample code:
// Example program
#include <iostream>
int* left_shift(int arr[],int n)
{
for(int i = 0 ; i<n;i++) {
if(i==n-1){
arr[i]
= 0;
break;
} // make last element
null
arr[i] = arr[i+1]; //shift
element to the right
}
return arr; //function then returns modifed
array
}
int main()
{
int arr[] = {1,2,3,4};//initial array
int n = sizeof(arr)/sizeof(int);
int* p;
p=left_shift(arr,n);
for ( int i = 0; i < n; i++ ) {
std::cout << *(p + i) <<
"\n" ;
}
}
------------------------------
Hope this helps.
Get Answers For Free
Most questions answered within 1 hours.