S
S
Shadow20202020-12-12 13:06:23
C++ / C#
Shadow2020, 2020-12-12 13:06:23

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;
}

I hope for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PUTINVODKAGTA, 2020-12-12
@PUTINVODKAGTA

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++;
  }
}

2. Create a new N-count array. 3. Copy odd numbers from the original array.
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++; //переход к следующему элементу массива
 }
}

4. Output the result to the console
for(int i = 0, i < (N-count);i++)
{
   cout<<A_new[i]<<" ";
}

As a result, you will get an array of only odd numbers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question