Challenge - 5 Problems
String Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of character traversal with index
What is the output of the following C# code snippet that traverses a string and prints characters with their indices?
DSA C#
string s = "hello"; for (int i = 0; i < s.Length; i++) { Console.Write(i + ":" + s[i] + " "); }
Attempts:
2 left
💡 Hint
Remember that string indices start at 0 and s[i] accesses the character at index i.
✗ Incorrect
The loop runs from 0 to 4 (length 5). Each iteration prints the index, a colon, the character at that index, and a space. So output is '0:h 1:e 2:l 3:l 4:o '.
❓ Predict Output
intermediateOutput of foreach character traversal
What is the output of this C# code that uses foreach to traverse a string and print characters separated by commas?
DSA C#
string s = "world"; foreach (char c in s) { Console.Write(c + ","); }
Attempts:
2 left
💡 Hint
Each character is printed followed by a comma, including the last character.
✗ Incorrect
The foreach loop prints each character followed by a comma. Since it does not skip the last comma, output ends with a comma.
🔧 Debug
advancedIdentify the error in string character access
What error does the following C# code produce when accessing characters in a string?
DSA C#
string s = "test"; for (int i = 0; i <= s.Length; i++) { Console.Write(s[i]); }
Attempts:
2 left
💡 Hint
Check the loop condition and valid indices for string characters.
✗ Incorrect
The loop runs from 0 to s.Length inclusive, but valid indices are 0 to s.Length - 1. Accessing s[s.Length] causes IndexOutOfRangeException.
❓ Predict Output
advancedOutput of reversed string traversal
What is the output of this C# code that prints characters of a string in reverse order?
DSA C#
string s = "abcde"; for (int i = s.Length - 1; i >= 0; i--) { Console.Write(s[i]); }
Attempts:
2 left
💡 Hint
Loop starts from last index and moves backward to 0.
✗ Incorrect
The loop prints characters from index 4 to 0, resulting in 'edcba'.
🧠 Conceptual
expertNumber of characters accessed in nested loops
Consider this C# code snippet. How many characters are printed in total?
DSA C#
string s = "xyz"; for (int i = 0; i < s.Length; i++) { for (int j = 0; j <= i; j++) { Console.Write(s[j]); } }
Attempts:
2 left
💡 Hint
Count characters printed in each inner loop iteration and sum them.
✗ Incorrect
Outer loop i=0 prints 1 char, i=1 prints 2 chars, i=2 prints 3 chars. Total = 1+2+3=6.
