In: Computer Science
Do not use global variables.
Note : The interleave function should not accept input or display any output. The function should work with any size strings.
Caution : Inclusion of unnecessary or unrelated logic or code segment will result in loss of points.
Write C a program that has a main function and a utility function called merge. The main function should prompt the user to enter one short string (no longer than 20 characters) and hard code another string with value "123456" (this could be anything, not exceeding 20 characters). It should call the merge function that will interleave the first string and the second string to produce a third string. The merge stops with the shortest string. The main program should print out all the three strings after the function call.
Use as many variables and arrays as needed.
Expected input/output: ( do not worry about the exact number of blank lines in the output)
Scenario 1
Enter string 1 : ABCDE
Merged Result
String 1 : ABCDE
String 2 : 123456
Merged string : A1B2C3D4E5
Scenario 2
Enter string 1 : ABCDEFG
Merged Result
String 1 : ABCDEFG
String 2 : 123456
Merged string : A1B2C3D4E5F6
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//FUNCTION TO MERGE 2 STRINGS ALTERNATIVELY
char* merge(char a[], char b[]) {
int alen = strlen(a);
int blen = strlen(b);
int len=0;//len is length of merged string
if(alen==blen)
{
len = alen + blen;
}
else if(alen<blen)
{
len=2*alen;
}
else
{
len=2*blen;
}
char *arr;
int i = 0, j = 0, k = 0;
//Merging 2 strings
while(i < alen && j < blen)
{
arr[k++] = a[i++];
arr[k++] = b[j++];
}
arr[len]='\0';
return arr;//return merged string
}
int main() {
char string1[20];
char string2[]="123456";
char *res;
printf("Enter string1:");
scanf("%s",string1);
printf("Merged Result\n");
printf("String1 :%s\n",string1);
printf("String2 :%s\n",string2);
res =merge(string1,string2);
printf("Merged string :%s",res);
return 0;
}