Bird
Raised Fist0
DSA Cprogramming

String Traversal and Character Access in DSA C

Choose your learning style10 modes available
Mental Model
A string is a sequence of characters stored one after another. Traversing means visiting each character one by one to read or process it.
Analogy: Imagine reading a sentence letter by letter from left to right, like reading a book page from start to end.
S -> t -> r -> i -> n -> g -> \0
↑
(start)
Dry Run Walkthrough
Input: string: "cat"
Goal: Print each character of the string one by one in order
Step 1: Access first character 'c'
c -> a -> t -> \0
↑
Why: Start reading from the first character
Step 2: Access second character 'a'
c -> a -> t -> \0
  ↑
Why: Move to next character to continue reading
Step 3: Access third character 't'
c -> a -> t -> \0
    ↑
Why: Move to next character to continue reading
Step 4: Detect null character '\0' to stop
c -> a -> t -> \0
      ↑
Why: Null character marks end of string, stop traversal
Result:
c\na\nt\n
Annotated Code
DSA C
#include <stdio.h>

void traverseString(const char *str) {
    int i = 0;
    while (str[i] != '\0') { // check for end of string
        printf("%c\n", str[i]); // print current character
        i++; // move to next character
    }
}

int main() {
    const char *myString = "cat";
    traverseString(myString);
    return 0;
}
while (str[i] != '\0') {
check if current character is not end marker to continue traversal
printf("%c\n", str[i]);
print the current character
i++;
advance index to next character
OutputSuccess
c a t
Complexity Analysis
Time: O(n) because we visit each character once until the null terminator
Space: O(1) because we use a fixed number of variables regardless of string size
vs Alternative: Compared to recursive traversal, this iterative approach uses less memory and is simpler
Edge Cases
empty string ""
The loop does not run and nothing is printed
DSA C
while (str[i] != '\0') {
string with one character "a"
Prints the single character then stops
DSA C
while (str[i] != '\0') {
When to Use This Pattern
When you need to process or examine each character in a string one by one, use string traversal with a loop until the null character.
Common Mistakes
Mistake: Forgetting to check for the null character '\0' and causing out-of-bounds access
Fix: Always check str[i] != '\0' before accessing str[i]
Mistake: Using incorrect loop condition like i < length without knowing string length
Fix: Use null character check to safely traverse strings of unknown length
Summary
It visits each character in a string one by one until the end.
Use it when you want to read or process every character in a string.
The null character '\0' marks the end and stops traversal.

Practice

(1/5)
1. What does the expression str[0] represent when str is a string in C?
easy
A. The first character of the string
B. The length of the string
C. The last character of the string
D. A pointer to the string

Solution

  1. Step 1: Understand string indexing in C

    In C, strings are arrays of characters. Indexing starts at 0, so str[0] accesses the first character.
  2. Step 2: Identify what str[0] returns

    It returns the character stored at the first position of the string, not the length or pointer.
  3. Final Answer:

    The first character of the string -> Option A
  4. Quick Check:

    str[0] = first character [OK]
Hint: Remember: string indexing starts at zero in C [OK]
Common Mistakes:
  • Confusing character access with string length
  • Thinking indexing starts at 1
  • Mixing pointer and character access
2. Which of the following is the correct way to traverse a string str of length n in C using a for loop?
easy
A. for (int i = 1; i < n; i++)
B. for (int i = 0; i <= n; i++)
C. for (int i = 0; i < n; i++)
D. for (int i = 1; i <= n; i++)

Solution

  1. Step 1: Understand string indexing and loop bounds

    String indices in C start at 0 and go up to n-1 for length n.
  2. Step 2: Choose loop condition to cover all characters

    The loop should run from 0 to n-1, so i < n is correct.
  3. Final Answer:

    for (int i = 0; i < n; i++) -> Option C
  4. Quick Check:

    Loop from 0 to n-1 = for (i=0; i<n; i++) [OK]
Hint: Loop from 0 to less than length for strings [OK]
Common Mistakes:
  • Using <= n causes out-of-bounds access
  • Starting loop at 1 misses first character
  • Confusing string length with last index
3. What is the output of the following C code?
char str[] = "hello";
for (int i = 0; i < 5; i++) {
    printf("%c-", str[i]);
}
medium
A. hello-
B. h-e-l-l-o-
C. h e l l o
D. h-e-l-l-o

Solution

  1. Step 1: Analyze the loop and print statement

    The loop runs from i=0 to 4, printing each character followed by a dash.
  2. Step 2: Trace each iteration output

    Characters printed: 'h-', 'e-', 'l-', 'l-', 'o-'. Combined output is "h-e-l-l-o-".
  3. Final Answer:

    h-e-l-l-o- -> Option B
  4. Quick Check:

    Each char + '-' printed = h-e-l-l-o- [OK]
Hint: Look at printf format and loop range carefully [OK]
Common Mistakes:
  • Ignoring the dash after each character
  • Printing the whole string once instead of chars
  • Confusing spaces with dashes
4. Identify the error in the following code snippet that tries to print each character of a string str.
char str[] = "world";
for (int i = 1; i <= 5; i++) {
    printf("%c", str[i]);
}
medium
A. Both A and B are errors
B. Loop condition should be i < 5 instead of <= 5
C. No error, code works fine
D. Loop starts at 1 and misses the first character

Solution

  1. Step 1: Check loop start index

    Loop starts at 1, so it skips str[0] which is the first character.
  2. Step 2: Check loop end condition

    Loop runs while i <= 5, but valid indices are 0 to 4. Accessing str[5] causes out-of-bounds error.
  3. Final Answer:

    Both A and B are errors -> Option A
  4. Quick Check:

    Start at 0 and use i < length to avoid errors [OK]
Hint: Loop from 0 to less than length to avoid errors [OK]
Common Mistakes:
  • Starting loop at 1 and missing first char
  • Using <= length causing out-of-bounds access
  • Ignoring array indexing rules
5. Given a string str of unknown length, which of the following code snippets correctly prints all characters until the null terminator in C?
hard
A. for (int i = 0; str[i] != '\0'; i++) { printf("%c", str[i]); }
B. for (int i = 0; i < strlen(str); i++) { printf("%c", str[i]); }
C. while (*str != '\0') { printf("%c", *str); str++; }
D. All of the above

Solution

  1. Step 1: Analyze for (int i = 0; str[i] != '\0'; i++) { printf("%c", str[i]); }

    Loops until character is not null terminator, printing each character. Correct method.
  2. Step 2: Analyze for (int i = 0; i < strlen(str); i++) { printf("%c", str[i]); } and C

    for (int i = 0; i < strlen(str); i++) { printf("%c", str[i]); } uses strlen to get length, then loops printing characters. while (*str != '\0') { printf("%c", *str); str++; } uses pointer traversal until null terminator. Both are correct.
  3. Step 3: Combine results

    All three methods correctly print the string characters until the null terminator.
  4. Final Answer:

    All of the above -> Option D
  5. Quick Check:

    All methods stop at '\0' and print chars [OK]
Hint: Any loop stopping at '\0' prints full string safely [OK]
Common Mistakes:
  • Not checking for null terminator causing overflow
  • Using wrong loop conditions
  • Modifying string pointer incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard