0
0
Cprogramming~10 mins

String comparison - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String comparison
Start
Read two strings
Compare characters one by one
Characters equal?
NoReturn difference
Yes
End of strings?
NoMove to next char
Yes
Strings equal
Return 0
End
The program compares two strings character by character until a difference is found or both strings end.
Execution Sample
C
int result = strcmp("cat", "car");
if (result == 0) {
  printf("Equal\n");
} else {
  printf("Not equal\n");
}
This code compares two strings "cat" and "car" and prints if they are equal or not.
Execution Table
StepIndexChar in str1Char in str2ComparisonResultAction
10'c''c''c' == 'c'0Continue to next character
21'a''a''a' == 'a'0Continue to next character
32't''r''t' != 'r''t' - 'r' = 2Return 2 (strings differ)
💡 At index 2, characters differ ('t' vs 'r'), so strcmp returns positive value 2.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
index01222
char_str1'c''a''t''t''t'
char_str2'c''a''r''r''r'
resultundefined0022
Key Moments - 2 Insights
Why does strcmp return a positive number instead of just 1 or -1?
strcmp returns the difference between the first differing characters' ASCII codes, not just 1 or -1, as shown in step 3 of the execution_table where 't' - 'r' equals 2.
What happens if both strings are exactly the same?
If all characters match and both strings end at the same time, strcmp returns 0, indicating equality, as explained in the concept_flow and would be shown if no difference was found.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 2?
A1
B0
C2
D-1
💡 Hint
Check the 'result' column in execution_table row for step 2.
At which index do the two strings first differ according to the execution_table?
A2
B1
C0
D3
💡 Hint
Look at the 'Index' column where 'Comparison' shows characters are not equal.
If the first differing characters were 'r' in str1 and 't' in str2, what would strcmp return?
A0
B2
C-2
D1
💡 Hint
strcmp returns the difference: char_str1 - char_str2, so 'r' - 't' is negative.
Concept Snapshot
strcmp(str1, str2) compares two strings character by character.
Returns 0 if equal.
Returns positive if first differing char in str1 > str2.
Returns negative if first differing char in str1 < str2.
Stops at first difference or end of strings.
Full Transcript
This visual execution shows how the C function strcmp compares two strings. It checks each character from the start, comparing them one by one. If characters are equal, it moves to the next. When it finds a difference, it returns the difference of their ASCII codes. If no difference is found and both strings end, it returns zero meaning the strings are equal. The example compares "cat" and "car". At index 2, 't' and 'r' differ, so strcmp returns 2, a positive number. This means "cat" is greater than "car" in lexicographical order.