Answer:
I am writing the code in C++. Let me know if you want the program in some other programming language.
#include <iostream> // includes header file for input output functions
using namespace std;
//to identify objects like cin cout
string CopyStrings(string string1, string string2)
{
string newString = "";
for (int loop = 0; loop < string1.length() ||
loop < string2.length(); loop++) {
if (loop < string1.length())
newString += string1[loop];
if (loop < string2.length())
newString += string2[loop]; }
return newString;
}
int main()
{
string stringA = "ace";
string stringB = "bdf";
cout << CopyStrings(stringA, stringB); }
Output:
abcdef
Explanation:
The function CopyStrings() function takes two strings i.e. string1 and string2 as parameters to copy characters from both the string one character from each.
The newString variable stores the new string after copying characters from both strings string1 and string2.
Then the for loop starts which has a variable loop which is an index variable that traverses through both the strings stored in string1 and string2. The loop continues to execute until it moves through entire length of string1 and string2 which means it copies all the characters from both string1 and string2. length() is used here which returns length of the string1 and string2.
If statement in the for loop checks the character that loop (index) variable is pointing to is less than the string1 length which means it checks each character stored in string1. For example if string1 contains "ace" and loop variable is moving through the string and is currently at "a" then this condition is true. If the condition evaluates to true then the body of if statement is executed. The next statement stores that character a into the newString variable.
Next If statement checks character that loop variable is pointing to is less than the string2 length which means it checks each character stored in string2. For example if string2 contains "bdf" and loop variable is moving through the string and is currently at "b" then this condition is true. If the condition evaluates to true then the body of if statement is executed. The next statement stores that character b into the newString variable.
Then the second iteration starts which again first stores the next character i.e. c from string1 into newString and then stores next character i.e d from string2 into newString.
Then the third iteration starts which again first stores the next character i.e. e from string1 into newString and then stores next character i.e f from string2 into newString.
Then the loop breaks as the loop variable reaches end of both the string1 and string2.
return newString will return the copied string into the output screen which is abcdef.
The screenshot of code along with output is attached.