Answer the question
In order to leave comments, you need to log in
How to overwrite a dynamic array?
Good time of day friends. The task is:
Write a C++ program to create a dynamic array A[N],
fill the array using a random number generator (getting a random number in the interval [a, b])
and format it as a function (a = -30, b = 30 )) Overwrite the resulting array by removing all even numbers from it.
Overwrite to issue as a function.
Stuck on rewriting an array, specifically I don't know how to remove even numbers from an array?
#include <iostream>
#include <math.h>
using namespace std;
//генератора случайных чисел в интервале[a, b]
int generateInt(int a, int b) {
return rand() % (b - a + 1) + a;
}
//перезапись массива
int rewriteArray(int *A, int i) {
if (A[i] % 2 != 0) {
// Удаление четных чисел ??????
}
return A[i];
}
int main() {
setlocale(LC_ALL, "RUSSIAN");
int const N = 10; //размер массива
int *A = new int[N]; //выделяю память для динамического массива
int a = -30, b = 30; //интервал[a, b] для генератора случайных чисел
srand(time(0));
for (int i = 0; i < N; i++) {
A[i] = generateInt(a,b);
cout << rewriteArray(A,i) << endl;
}
delete [] A; //очищаю память
return 0;
}
Answer the question
In order to leave comments, you need to log in
1. Count the number of even numbers in the original array. Create a count variable to count even numbers.
int count = 0;
for(int i = 0; i<N; i++)
{
if(A[i]%2==0)
{
count++;
}
}
int *A_new = new int [N-count];
for (int i = 0,j=0; i < N; i++)
{
if(A[i]%2!=0)
{
A_new[j]=A[i]
j++; //переход к следующему элементу массива
}
}
for(int i = 0, i < (N-count);i++)
{
cout<<A_new[i]<<" ";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question