Write a program that reads two strings CH1 and CH2 and copies the first half of CH1 and the first half of CH2 into a third CH3. Show the result.
Use only the gets and puts functions.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
void main()
{
/* Declarations */
char CH1[100], CH2[100]; /* given strings */
char CH3[100]=""; /* resulting string */
int L1,L2; /* length of CH1 and CH2 */
int I; /* counter for CH1 and CH2 */
int J; /* counter for CH3 */
/* Reading */
puts("Enter the first string : ");
gets(CH1);
puts("Enter the second string : ");
gets(CH2);
/* Determine the lengths of CH1 and CH2 */
for (L1=0; CH1[L1]; L1++) ;
for (L2=0; CH2[L2]; L2++) ;
/* Copy the first half of CH1 to CH3 */
for (I=0 ; I<(L1/2) ; I++)
CH3[I]=CH1[I];
/* Copy the first half of CH2 to CH3 */
J=I;
for (I=0 ; I<(L2/2) ; I++)
{
CH3[J]=CH2[I];
J++;
}
/* Terminate the string CH3 */
CH3[J]='\0';
/* Display */
puts("Resulting string : ");
puts(CH3);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Find the missing element in n consecutive elements