1

How to do this:

array 1: 2 8 5 7 3 5
array 2: 2018 5 7 3 5

The problem said that if two even numbers are consecutive in the first array, put a 2018 in their place, like so. How can I do this?

for(a=n-1; a>=0; a--)
{
    if( b[a]%2==0 && b[a-1]%2==0)
    {
        for(c=a-1; c<n-1; c++)
        {
            b[c]=b[c+1];
        }
        b[a]= 2017;
    }

}
6
  • When a reaches 0 (i.e. a == 0) then what happens with b[a - 1]? May 15, 2019 at 19:08
  • And how to do what? It's really unclear what you're asking about and what you want to do. For some specified input, what should the output be? What is the output your minimal reproducible example creates? Also please read about how to ask good questions, as well as this question checklist. May 15, 2019 at 19:09
  • Well probably doesn't work, I have no idea how to do it May 15, 2019 at 19:09
  • I want to switch 2 numbers from any array with only 1 May 15, 2019 at 19:09
  • Here, 2 and 8 from the first array are even and consecutive so we put an 2018 in that place May 15, 2019 at 19:10

2 Answers 2

1

You can't really change the size of an array, but you can shift the elements and ignore elements at the end:

#include <stdio.h>

void shift_left(int* arr, size_t sz, size_t shift_cnt)
{
  for (size_t i = 0; i != sz - shift_cnt; ++i)
  {
    arr[i] = arr[i + shift_cnt];
  }
  for (size_t i = sz - shift_cnt; i != sz; ++i)
  {
    arr[i] = 0;
  }
}

int main()
{
  int arr[] = { 2, 8, 5, 7, 3, 5 };
  size_t sz = sizeof(arr) / sizeof(arr[0]);

  for (size_t i = 0; i < sz - 1;)
  {
    if (arr[i] % 2 == 0 && arr[i + 1] % 2 == 0)
    {
      shift_left(arr + i, sz-- - i, 1);
      arr[i] = 2018;
    }
    else
    {
      ++i;
    }
  }

  for (size_t i = 0; i != sz; ++i)
    printf("%d ", arr[i]);

  return 0;
}

// Output: 2018 5 7 3 5
1
  • 1
    @AndreiJarca Welcome! Also note that this will replace three consecutive even numbers with a single 2018, since 2018 itself is even and after replacing the first two, you still have 2018 and one other even next to each other. Hopefully this is the desired behavior. If it is not, fixing it should not be hard. I can help on that if needed May 15, 2019 at 20:00
0

March down the source array looking for even pairs

// return size used

size_t AJ_squish(int *dest, size_t dest_size, const int *src, size_t src_size) {
  size_t dest_len = 0;
  while (src_size > 1 && dest_len < dest_size) {
    // 2 evens in a row?
    if (src[0] % 2 == 0 && src[1] % 2 == 0) {
      dest[dest_len++] = 2018;
      src_size -= 2;
    } else {
      dest[dest_len++] = *src++;
      src_size--;
    }
  }
  if (src_size >  0 && dest_len < dest_size) {
    dest[dest_len++] = *src;
  }
  return dest_len;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.