The output of the below psuedocode(its psuedocode because it is not meant to be syntactically correct) produces "computers"
strcpy(s1, "computer");
strcpy(s2, "science");
if(strcmp(s1, s2) < 0)
{
strcat(s1, s2);
}
else
{
strcat(s2, s1);
}
s1[strlen(s1) - 6] = '\0';
I am unclear as to how the result is "computers". I cant wrap my head around the logic of how strcmp() is used in in the if() statements
Okay, first let's see a working example of the code and then I'll explain how it works:
#include <stdio.h>
#include <string.h>
void main() {
char s1[100], s2[100];
strcpy(s1, "computer");
strcpy(s2, "science");
if(strcmp(s1, s2) < 0)
{
strcat(s1, s2);
}
else
{
strcat(s2, s1);
}
s1[strlen(s1) - 6] = '\0';
printf("%s",s1);
}
Variable s1 gets set to "computer" and s2 gets set to "science". The first string comparison done with strcmp() evaluates whether s1 is less in value than that of s2. If so, then s1 gets concatenated with s2, so that the new value of s1 would be "computerscience". Otherwise whether the strings have the same value or s2 is greater than s1, s2 gets concatenated to s1 with s2 having the resulting value of "sciencecomputer".
The if-conditional that results in a true result is that "computer" is less than "science" so the value of s1 changes and becomes "computerscience". The value 6 is then subtracted from the length of s1 and at that index which happens to hold the character "c", a null character is set as that element's value. So, now the value of s1 is "computers\0ience". This means that when s1 is passed to printf() that function will print every character until it reaches the null character and then the function ceases to display the null as well as the characters following it.