K
K
Kirill Sinyavsky2016-01-16 21:39:03
C++ / C#
Kirill Sinyavsky, 2016-01-16 21:39:03

How to perform array operations?

Good day. Tell me how to add an element with a value of 0 after each even element of the array? I have a one-dimensional array generated using a random number counter. Please answer with examples.
My code:

#include<iostream>
#include<time.h>
#include<cstdlib>
#include<clocale>

using namespace std;

int main()

{
    setlocale(LC_CTYPE , "rus");
    const int N = 5;
    int Array[N];

    cout<<"Формируем одномерный массив случайных чисел,используя датчик случайных чисел:\n" << endl;

    srand(time(NULL));// функция для использования генератора случайных чисел,его т.н. база//
    for(int i = 0; i < N; i++)
    {
       Array[i] = rand()%6;// генератор случайных чисел//
    cout<<"Massive ["<<i<<"] = "<< Array[i] << endl;
    }
    cout << endl;

    cout<<"Удаляем элемент массива под номером K:\n" << endl;
    int Array1[N];
    for(int i = 0; i< N; i++)
    {
       Array1[i] = Array[i+1];// производим операцию сдвига,удаляя элемент массива//
       cout<<"Massive 1 ["<<i<<"] = " << Array1[i] << endl;
    }
    cout<< endl;

   cout<<"Добавляем после каждого четного элемента массива элемент со значением 0:\n"<<endl;
   int Array2[2*N];
   int Fix = 0, k = 0;
   for(int i = 0; i < 2*N; i++)
   {
       if(Array2[k]%2 == 0)
       {
           Fix = Array1[i+1] = 0;
       }
         cout<< "Massive 3 ["<<k<<"] = " << Fix << endl;

       if(Array2[k]%2 != 0)
        Array2[k] = Array[i];
        cout<< Array2[k] << endl;

   }
   k++;
    return 0;
}

The fact is that the last paragraph is written incorrectly (this is obvious). So I ask for help. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2016-01-16
@gbg

Obviously, you need to start the deletion cycle not from element 0, but from this one.
In terms of style, it's time to switch to ranged for.
All removal can be done without an additional array.

M
Makaleks, 2016-01-17
@Makaleks

Enter
we get

for(int i = 0; i < N; i++)
{
       Array2[i+offset] = Array1[i];
       if(Array1[i]&1 == 0)
       {
           offset++;
           Array2[i+offset] = 0;
       }
}

it remains to remember the new size of the array (N + offset), add your output to the console

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question