#include <iostream>
#include <random>
#include <iomanip>
using namespace std;
unsigned set_size(const char* msg) {
cout << msg;
unsigned value;
cin >> value;
cin.ignore(cin.rdbuf()->in_avail());
return value;
}
int* create_array(const size_t n) {
return new(nothrow) int[n];
}
int* destroy(int* box) {
if (box != nullptr) {
delete[] box;
box = nullptr;
}
return box;
}
void random_fill(int* box, const size_t n, int a, int b) {
if (a > b) swap(a, b);
uniform_int_distribution<> uid(a, b);
mt19937_64 gen{ random_device()() };
for (auto i = 0U; i < n; ++i) box[i] = uid(gen);
}
void show(int* box, const size_t n, const streamsize w) {
for (auto i = 0U; i < n; ++i) cout << setw(w) << box[i];
puts("");
}
int* erase_even(int* box, size_t& n) {
auto m = 0U;
auto tmp = create_array(n);
for (auto i = 0U, j = 0U; i < n; ++i) {
if (box[i] & 1) {
tmp[j] = box[i];
++j;
++m;
}
}
box = destroy(box);
n = m;
box = create_array(n);
for (auto i = 0U; i < n; ++i) box[i] = tmp[i];
tmp = destroy(tmp);
return box;
}
int* between_insert(int* box, size_t& n, int value = 0) {
if (n < 2) return box;
size_t m = (n << 1) - 1;
auto tmp = create_array(m);
for (auto i = 0U, j = 1U, k = 0U; i < m; i += 2, j += 2, ++k) {
tmp[i] = box[k];
if (j < m) tmp[j] = value;
}
box = destroy(box);
n = m;
box = create_array(n);
for (auto i = 0U; i < n; ++i) box[i] = tmp[i];
tmp = destroy(tmp);
return box;
}
int main() {
auto n = set_size(" Size: ");
auto box = create_array(n);
if (box) {
const auto w = 3U;
random_fill(box, n, 1, 9);
show(box, n, w);
box = erase_even(box, n);
show(box, n, w);
box = between_insert(box, n);
show(box, n, w);
box = destroy(box);
} else {
puts("Not enough memory!");
}
system("pause > nul");
}
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define MAX 100
int main()
{
int n, *array;
printf("Enter size of array n = ");
scanf("%d", &n);
array=(int*)malloc(n*sizeof(int));
if(array)
{//if array
srand(time(NULL));
printf("\nStart array[%d]:\n",n);
for(int i = 0; i < n; i++)
{//for i
array[i] = rand()%MAX;
printf("%3d",array[i]);
}//for i
printf("\n\nResult array[%d]:\n",n);
for(int i = 0; i < n; i++)
{//for i
if(array[i]%2==0) array[i]=0;
printf("%3d",array[i]);
}//for i
free(array);
}//if array
else
printf("\nError. Array not created.");
fflush(stdout);
sleep(10);
return 0;
}