Combine or merge 2 array with loop or function - c

I'm new to the C world. I'm using Visual 2010. I need to create an array from 2 other arrays, or a function to merge them; I come from PHP so I'm sorry if this is stupid. I tested some loop without success..
a real example could be helpful:
int arrayA[5] = {3,2,1,4,5}
int arrayB[5] = {6,3,1,2,9}
And the printed expected output of the third arrayC should be :
arrayC {
[3][6]
[2][3]
[2][1]
[4][2]
[5][9]
}

A straightforward approach can look the following way
#include <stdio.h>
#define N 5
int main( void )
{
int a[N] = { 3, 2, 2, 4, 5 };
int b[N] = { 6, 3, 1, 2, 9 };
int c[N][2];
for ( size_t i = 0; i < N; i++ )
{
c[i][0] = a[i]; c[i][1] = b[i];
}
for ( size_t i = 0; i < N; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] );
return 0;
}
The program output is
3, 6
2, 3
2, 1
4, 2
5, 9
If you want to write a function that will merge arrays of any size then it can look like
#include <stdio.h>
#include <stdlib.h>
#define N 5
int ** merge( int *a, int *b, size_t n )
{
int **c = malloc( n * sizeof( int * ) );
if ( c != NULL )
{
size_t i = 0;
for ( ; i < n && ( c[i] = malloc( 2 * sizeof( int ) ) ); i++ )
{
c[i][0] = a[i]; c[i][1] = b[i];
}
if ( i != n )
{
while ( i-- ) free( c[i] );
free( c );
c = NULL;
}
}
return c;
}
int main( void )
{
int a[N] = { 3, 2, 2, 4, 5 };
int b[N] = { 6, 3, 1, 2, 9 };
int **c;
c = merge( a, b, N );
if ( c != NULL )
{
for ( size_t i = 0; i < N; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] );
for ( size_t i = 0; i < N; i++ ) free( c[i] );
free( c );
}
return 0;
}
The program output will be the same as shown above.

Really It's unclear to all. I had understood like this.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int arrayA[5] = {3,2,2,4,5};
int arrayB[5] = {6,3,1,2,9};
int arrayC[5][5];
int i,j;
for(i=0; i<5; i++)
{
int a = arrayA[i]*10 + arrayB[i];
arrayC[i][0] = a;
}
for(i=0; i<5; i++)
{
printf("%d ", arrayC[i][0]);
printf("\n");
}
return 0;
}
After your comment:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int arrayA[5] = {3,2,2,4,5};
int arrayB[5] = {6,3,1,2,9};
int arrayC[5];
int i,j;
for(i=0; i<5; i++)
{
arrayC[arrayA[i]] = arrayB[i];
}
for(i=0; i<5; i++)
{
printf("[%d %d]",arrayA[i], arrayC[arrayA[i]]);
printf("\n");
}
return 0;
}

Please edit your question and specify it (you can read https://stackoverflow.com/help/how-to-ask ).
If you know size of the array, you can create 2D array in that way:
int array[2][5] = { {2, 3, 4, 5}, {6, 3, 1, 2, 9} };
Also take a look to malloc function. This is how to create dynamic 2D array
# create array of two pointers
int **tab = (int**) malloc(sizeof(int*) * 2);
# create pointer to array
tab[0] = (int*) malloc(sizeof(int) * 5);
tab[1] = (int*) malloc(sizeof(int) * 5);
tab[0][0] = 3;
tab[0][1] = 2;
// ...
tab[1][0] = 6;
tab[1][1] = 3;
tab[1][2] = 1;
// ...
// remember to call free
free(tab[0]);
free(tab[1]);
free(tab);
Of course you should use for loop. I show you only how to create array. Please also take a look at this thread Using malloc for allocation of multi-dimensional arrays with different row lengths

you can do this in c++ if i get what you mean
#include <iostream>
using namespace std;
int main()
{
int arrayA[5] = {3,2,2,4,5};
int arrayB[5] = {6,3,1,2,9};
int arrayC[10];
int a=0;
int b=0;
bool use_a= true;
bool use_b = false;
for ( int i =0 ; i <10 ; i++ )
{
if(use_a){
arrayC[i]=arrayA[a];
use_a=false;
use_b= true;
a++;
}else if(use_b){
arrayC[i]= arrayB[b];
use_b=false;
use_a= true;
b++;
}
}
for(int i =0 ; i <10 ; i++)
cout<<arrayC[i];
return 0;
}

Related

Two sum leetcode clang

I practice in c language, here is the exercise:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example :
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Here my attempt:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
static int r[2];
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if(i!=j&&(nums[i]+nums[j])==target){
r[0]=i;
r[1]=j;
}
}
}
return r;
}
But Irecieve a wrong answer:
enter image description here
The function definition does not satisfies the requirement specified in the comment
Note: The returned array must be malloced, assume caller calls free()
Moreover the parameter
int* returnSize
is not used within your function definition.
It seems the function should be defined the following way as it is shown in the demonstration program below. I assume that any element in the source array can be present in the result array only one time.
#include <stdio.h>
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *twoSum( int *nums, int numsSize, int target, int *returnSize )
{
int *result = NULL;
*returnSize = 0;
for (int i = 0; i < numsSize; i++)
{
for (int j = i + 1; j < numsSize; j++)
{
if (nums[i] + nums[j] == target)
{
int unique = result == NULL;
if (!unique)
{
unique = 1;
for (int k = 1; unique && k < *returnSize; k += 2)
{
unique = nums[k] != nums[j];
}
}
if (unique)
{
int *tmp = realloc( result, ( *returnSize + 2 ) * sizeof( int ) );
if (tmp != NULL)
{
result = tmp;
result[*returnSize] = i;
result[*returnSize + 1] = j;
*returnSize += 2;
}
}
}
}
}
return result;
}
int main( void )
{
int a[] = { 2, 7, 11, 15 };
int target = 9;
int resultSize;
int *result = twoSum( a, sizeof( a ) / sizeof( *a ), target, &resultSize );
if (result)
{
for (int i = 0; i < resultSize; i += 2 )
{
printf( "%d, %d ", result[i], result[i + 1] );
}
putchar( '\n' );
}
free( result );
}
The program output is
0, 1
Though as for me then I would declare the function like
int *twoSum( const int *nums, size_t numsSize, int target, size_t *returnSize );
The brute force approach is very simple to this problem.
int* twoSum(int* arr, int n, int t, int* returnSize){
int *res=malloc(2*sizeof(int));
*returnSize=2;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if((arr[i]+arr[j])==t)
{
res[0]=i;
res[1]=j;
goto exit;
}
}
}
exit:
return res;
}

main.c:36:9: error: array size missing in ‘num’ int num[]; Why am I getting error for array size although i have given array size in code?

#include <stdio.h>
int removeduplicates(int arr[],int n){
int j=0;
int temp[15];
if(n==0 || n==1){
return n;
}
for(int i=0;i<n-1;i++){
if(arr[i]!=arr[i+1]){
temp[j++]=arr[i];
}
temp[j++]=arr[n-1];
}
for(int i=0;i<j;i++){
arr[i]=temp[i];
}
return j;
}
int main(){
int n;
int num[];
num[]= {1,2,3,3,4,4,5,5,5};
n= sizeof(num)/sizeof(num[0]);
n=removeduplicates(num,n);
printf("%d",n);
return 0;
}
Here in this question I was writing a code to remove duplicates from a sorted array. But I am getting the following error although I defined the array size and although I provided the array size.
main.c:36:9: error: array size missing in ‘num’
int num[];
^~~
main.c:37:9: error: expected expression before ‘]’ token
num[]= {1,2,3,3,4,4,5,5,5};
This code snippet
int num[];
num[]= {1,2,3,3,4,4,5,5,5};
is syntactically incorrect.
Instead write
int num[] = {1,2,3,3,4,4,5,5,5};
Also within the function this declaration with the magic number 15
int temp[15];
and this statement
temp[j++]=arr[n-1];
in the substatement of this for loop
for(int i=0;i<n-1;i++){
if(arr[i]!=arr[i+1]){
temp[j++]=arr[i];
}
temp[j++]=arr[n-1];
}
do not make a sense.
To remove duplicates there is no need to define an auxiliary array.
The function can be written for example the following way as shwon in the demonstrative program below.
#include <stdio.h>
size_t removeduplicates( int arr[], size_t n )
{
size_t m = 0;
for ( size_t i = 0; i != n; )
{
if ( m != i )
{
arr[m] = arr[i];
}
++m;
while ( ( ++i != n && arr[i] == arr[i-1] ) );
}
return m;
}
int main(void)
{
int num[]= { 1, 2, 3, 3, 4, 4, 5, 5, 5 };
const size_t N = sizeof( num ) / sizeof( *num );
for ( size_t i = 0; i != N; i++ )
{
printf( "%d ", num[i] );
}
putchar( '\n' );
size_t m = removeduplicates( num, N );
for ( size_t i = 0; i != m; i++ )
{
printf( "%d ", num[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3 3 4 4 5 5 5
1 2 3 4 5

To perform insert operation in a sorted array

What is wrong with this code and where is the problem?
I ran this code many times but it's showing that the code is running but I am not getting any output.
Can you tell me where is the mistake?
#include <stdio.h>
int print_arr(int *arr, int n)
{ for(int i=0; i<=n; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
int insert_ele(int *arr_a, int *arr_b, int n, int Key)
{
int i,j;
for(i=0, j=0; i<n; i++, j++)
{
if(arr_a[i]>Key)
{
arr_b[j] = Key;
arr_b[j+1] = arr_a[i];
j++;
}
else
{
arr_b[j] = arr_a[i];
}
}
return 0;
}
int main()
{
//code
int arr_a[] = {12, 16, 20, 40, 50, 70};
int arr_b[10];
int Key = 26;
int n = sizeof(arr_a)/sizeof(arr_a[0]);
int indx = insert_ele(arr_a, arr_b, n, Key);
print_arr(arr, n);
return 0;
}
For starters there is a typo in this statement
print_arr(arr, n);
It seems you mean
print_arr( arr_b, n + 1 );
The return type int of the function print_arr does not make a sense and is useless.
The first parameter of the function should have the qualifier const because the passed array is not being changed within the function.
The second parameter should have the type size_t.
This for loop
for(int i=0; i<=n; i++)
can invoke undefined behavior if the user of the function will pass the number of elements in the array in the second parameter n because in this case there will be an attempt to access memory beyond the array.
Again the return type int of the function insert_ele does not make a sense and is useless.
The first parameter should have the qualifier const because the source array is not being changed within the function. The parameter n should have the type size_t.
The function has a logical error.
Let's assume that the value of the variable Key is less than values of all elements of the array arr_a.
In this case the index j will be incremented twice and as a result you will have
b[0] = Key; b[2] = Key; b[4] = Key; and so on.
The logic of the function will be much clear if to split the for loop in two for loops.
The program can look the following way.
#include <stdio.h>
size_t insert_ele( const int *a, size_t n, int *b, int key )
{
size_t i = 0;
for ( ; i < n && !( key < a[i] ); i++ )
{
b[i] = a[i];
}
b[i] = key;
for ( ; i < n; i++ )
{
b[i+1] = a[i];
}
return i;
}
FILE * print_arr( const int *a, size_t n, FILE *fp )
{
for ( size_t i = 0; i < n; i++)
{
fprintf( fp, "%d ", a[i] );
}
return fp;
}
int main(void)
{
int a[] = { 12, 16, 20, 40, 50, 70 };
const size_t N = sizeof( a ) / sizeof( *a );
int b[10];
int key = 26;
size_t m = insert_ele( a, N, b, key );
fputc( '\n', print_arr( b, m, stdout ) );
return 0;
}
The program output is
12 16 20 26 40 50

Select certain elements in array to create new array

How could I select a certain number of elements from an array by giving a start and ending index number to create a new array?
For example, if my original array was {1,2,3,4,5,6}, and I say x=0 and y=2 for their index values, I would have a new array that is {1,2,3}.
Thank you.
If your compiler supports variable length arrays then you can do this the following way
#include <stdio.h>
#include <string.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 6 };
size_t n1 = 0, n2 = 2;
int b[n2 - n1 + 1];
memcpy( b, a + n1, ( n2 - n1 + 1 ) * sizeof( int ) );
size_t n = sizeof( b ) / sizeof( *b );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", b[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3
Otherwise the new array should be allocated dynamically as for example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 6 };
size_t n1 = 0, n2 = 2;
size_t n = n2 - n1 + 1;
int *b = malloc( n * sizeof( *b ) );
memcpy( b, a + n1, n * sizeof( int ) );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", b[i] );
}
putchar( '\n' );
free( b );
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_arr(int* arr, int len) {
for (int i = 0; i < len; i ++) {
printf("%d", arr[i]);
if (i != len - 1) {
printf(" ");
} else {
printf("\n");
}
}
}
int main() {
int arr1[] = {1, 2, 3, 4, 5, 6};
int start, end;
printf("input the beginning and the end: ");
scanf("%d %d", &start, &end);
int len = end - start + 1;
// we use malloc to dynamically allocate an array of the correct size
int* arr2 = (int*)malloc(len * sizeof(int));
// we use memcpy to copy the values
memcpy(arr2, arr1 + start, len * sizeof(int));
print_arr(arr1, 6);
print_arr(arr2, len);
// we have to free the memory
free(arr2);
return 0;
}

Most long series of element in array

I've prepared a code that should found the longer series of elements in growing order .for example ,in arrays exists following elements : 1 2 3 4 5 2 7 6 7 9,output will 5 (the series from 1 to 5) ,function will return integer tempcount that include numbers of element and print it.but get an error ,the function
isn't working:
#include "stdafx.h"
#include <stdio.h>
int find_maximum(int[], int);
int main() {
int c, array[100], size, location, maximum,found;
scanf_s("%d", &size);
for (c = 0; c < size; c++)
scanf_s("%d", &array[c]);
location = find_maximum(array, size);
maximum = found;
printf("Maximum elements = %d ", maximum);
return 0;
}
int find_maximum(int a[], int n) {
int c, index = 0,count =1,tempCount=1;
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
else
{
if (count > tempCount)
{
tempCount=count;
}
}
return tempCount;
}
The variables maximum and found are not initialized and are used nowhere except this statement that does not make sense
maximum = found;
You are storing the length of the maximum subsequence in the variable location
location = find_maximum(array, size);
It is the variable value which you need to output.
The function find_maximum also does not make sense. For example you are comparing elements of the array with the same element at position 0.
int c, index = 0,count =1,tempCount=1;
^^^^^^^^^
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
//…
The function can be declared and implemented as it is shown in the demonstrative program below.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && a[i-1] < a[i] ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
A more generic function can be written the following way.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n, int predicate( int, int ) )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && predicate( a[i-1], a[i] ) ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int less_than( int x, int y )
{
return x < y;
}
int greater_than( int x, int y )
{
return y < x;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N, less_than );
printf( "%zu\n", max_n );
max_n = max_ascending_seq( a, N, greater_than );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
2

Resources