Function getInterlacedString: The function/method getInterlacedString accepts four arguments – X, Y, ch1 and ch2. X and Y represent two integer values. ch1 and ch2 represent two characters.
The function/method getInterlacedString must form a string of length X+Y based on the following conditions.
– The character ch1 must occur X times in the string.
– The character ch2 must occur Y times in the string.
– The characters ch1 and ch2 must be interlaced alternatively in the string.
Finally, the function must return the string value.
Your task is to implement the function getInterlacedString so that it passes all the test cases.
IMPORTANT: Do not write the main() function as it is already defined.
Example Input/Output 1:
Input:
5 5
a b
Output:
Length: 10
String: ababababab
Explanation:
Here X = 5 and Y = 5.
So the character a occurs 5 times and the character b occurs 5 times alternatively in the string.
Example Input/Output 2:
Input:
14 11
# *
Output:
Length: 25
String: #*#*#*#*#*#*#*#*#*#*#*###
Example Input/Output 3:
Input:
6 12
S K
Output:
Length: 18
String: SKSKSKSKSKSKKKKKKK
#include <stdio.h>
#include <stdlib.h>
char* getInterlacedString(int X, int Y, char ch1, char ch2)
{
char *str=malloc((X+Y)*sizeof(char));
int i=0;
while(X!=0 || Y!=0)
{
if(X!=0)
{
str[i]=ch1;
X--;
i++;
}
if(Y!=0)
{
str[i]=ch2;
Y--;
i++;
}
}
return str;
}
int main()
{
int X, Y;
char ch1, ch2;
scanf("%d %dn%c %c", &X, &Y, &ch1, &ch2);
char *str = getInterlacedString(X, Y, ch1, ch2);
printf("Length: %dn", strlen(str));
printf("String: %s", str);
return 0;
}
Leave a Reply