w3resource

C Exercises: Concatenate two arrays

C Array: Exercise-107 with Solution

Write a program in C to concatenate two given arrays of integers.
If this is as simple as array1 + array2, so be it.

Sample Data:
({ 10, 20, 30, 40, 50, 60 }, { 70, 80, 90, 100, 110, 120 }) -> "10 20 30 40 50 60 70 80 90 100 110 120"

Sample Solution:

C Code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define CONCAT_ARRAY(TYPE, A, An, B, Bn) \
  (TYPE *)test((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *test(const void *a, size_t an,
                   const void *b, size_t bn, size_t s)
{
  char *p = malloc(s * (an + bn));
  memcpy(p, a, an*s);
  memcpy(p + an*s, b, bn*s);
  return p;
}

const int x[] = { 10, 20, 30, 40, 50, 60 };
const int y[] = { 70, 80, 90, 100, 110, 120 };
   
int main(void)
{
  unsigned int i;

  int *z = CONCAT_ARRAY(int, x, 6, y, 6);
  printf("Original arrays:\n");
  printf("Array-1:\n");
  for(int i = 0; i < 6; i++)
    printf("%d ", x[i]);
  printf("\nArray-2:\n");
  for(i = 0; i < 6; i++)
    printf("%d ", y[i]); 
  printf("\nConcatenate above arrays:\n");
  for(i = 0; i < 12; i++)
    printf("%d ", z[i]);
  free(z);
  return 0;
}

Sample Output:

Original arrays:
Array-1:
10 20 30 40 50 60 
Array-2:
70 80 90 100 110 120 
Concatenate above arrays:
10 20 30 40 50 60 70 80 90 100 110 120 

Flowchart:

Flowchart: Double its value and replace the next number with 0 if current and next value are same and shift all 0's to the end.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous C Programming Exercise: Array, shift all 0 to the end, double the value of next.
Next C Programming Exercise: C Pointer Exercises Home

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M