What does the fowlloing program do show the result for some
What does the fowlloing program do? show the result for some sample input
#include <stdio.h>
void mystery1 (char*, const char*);
int main() {
char string1[80], string2[80];
printf(\"Enter two strings:\");
scanf(\"%s %s\", string1, string2);
mystery1(string1,string2);
printf(\"%s\ \", string1);
}
void mystery1(char*s1, const char *s2){
while(*s1 != \'\\0\')
++s1;
for(; *s1 = *s2; s1++; s2++); /*empty statement*/
}
Solution
Here is the code explained in comments:
#include <stdio.h>
void mystery1 (char*, const char*); //Declares a function mystery1, which takes 2 character pointers as input, and returns nothing.
int main() {
char string1[80], string2[80]; //Declares 2 strings, string1, and string2.
printf(\"Enter two strings:\"); //Prompts the user to enter 2 strings.
scanf(\"%s %s\", string1, string2); //Reads 2 strings into variables string1, and string2.
mystery1(string1,string2); //Calls the function mystery1, with the parameters string1, and string2.
printf(\"%s\ \", string1); //Prints the string string1.
}
void mystery1(char*s1, const char *s2){
while(*s1 != \'\\0\') //Till you reach the end of first string.
++s1; //Move forward.
//There is an error with this code.
//Multiple increments should be separated by commas, and not semicolons.
//After modification, this is how it looks like.
for(; *s1 = *s2; s1++, s2++); /*empty statement*/
//This loop will copy the string s2 (appends s2 to s1), to the end of string s1.
}
And the code in main() reads 2 strings, and passes to the function mystery1(), which appends the second string to the first string.
