Bird
0
0
DSA Cprogramming

String Traversal and Character Access in DSA C

Choose your learning style9 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.