C++ Exercises: Create a new array taking the first and last elements of a given array of integers and length 1 or more
C++ Basic Algorithm: Exercise-88 with Solution
Write a C++ program to create a new array taking the first and last elements of a given array of integers and length 1 or more.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
int *test(int nums[], int arr_length) {
static int r_array[]
= {nums[0], nums[arr_length - 1] };
return r_array;
}
int main () {
// a pointer to an int.
int *p;
int nums[] = { 10, 20, -30, -40, 30 };
int arr_length = sizeof(nums) / sizeof(nums[0]);
cout << "Original array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << nums[i] << " ";
}
p = test(nums, arr_length);
arr_length = sizeof(p) / sizeof(p[0]);
cout << "\nNew array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << *(p + i) << " ";
}
return 0;
}
Sample Output:
Original array: 10 20 -30 -40 30 New array: 10 30
Pictorial Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to create a new array containing the middle elements from the two given arrays of integers, each length 5.
Next: Write a C++ program to check if a given array of integers and length 2, contains 15 or 20.
What is the difficulty level of this exercise?