String Length Without strlen() in C: 3 Placement-Ready Methods
Three C programs that find string length without strlen(): loop scan, pointer arithmetic, and recursion, with traced outputs for TCS NQT and AMCAT rounds.
C placement rounds at TCS NQT, Infosys, and AMCAT routinely ask you to trace or write a string-length function that doesn’t call strlen().
The reason is not arbitrary. C has no built-in string type; a string is an array of characters with a null terminator at the end. Understanding how length is derived from that terminator reveals whether a candidate has an accurate mental model of memory, not just library knowledge. The three methods below cover loop scan, pointer arithmetic, and recursion in the order they most often appear in test questions.
Why Placement Tests Include String Internals
The cppreference strlen documentation describes the function’s contract succinctly: it returns the number of characters preceding the null terminator. That sentence contains the entire algorithm. No magic, no buffered length field, no hash. Just a count of how many non-null bytes exist before the sentinel value.
Service-tier companies ask candidates to re-implement this because the question tests several things at once. It checks whether the candidate knows that strings are null-terminated, not length-prefixed. It tests whether they can write a correct loop termination condition. And it shows whether they understand why str[length] and *(str + length) are equivalent expressions.
CSE and ECE students at Tier-2 and Tier-3 colleges often encounter this in their second-year programming labs before they see it in placement preparation. The placement version tends to be framed as a multiple-choice or fill-in-the-blank question rather than a full coding round, so the focus is on tracing output correctly rather than on edge-case handling.
The three methods below progress from most readable to most compact to most elegant. All three produce identical output for the same input. The differences matter mostly when a placement MCQ asks you to predict what a specific version returns.
For additional C MCQ patterns covering pointers, double pointers, and memory allocation, the C placement MCQs practice set has 10 traced questions at the same difficulty level.
Method 1: Loop with an Index Counter
This is the direct translation of the algorithm description into code. An integer length starts at zero and increments each time a non-null character is found. The loop exits when str[length] equals the null terminator.
Code
#include <stdio.h>
int findLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main(void) {
char s[] = "hello";
printf("Length: %d\n", findLength(s));
return 0;
}
Traced execution for “hello”
str[0]is'h', not null.lengthbecomes 1.str[1]is'e', not null.lengthbecomes 2.str[2]is'l', not null.lengthbecomes 3.str[3]is'l', not null.lengthbecomes 4.str[4]is'o', not null.lengthbecomes 5.str[5]is the null terminator. Loop exits.- Returns 5. Output:
Length: 5
In an MCQ, the trap version of this function sometimes initialises length to 1 or uses str[length+1] in the condition. Both produce an off-by-one result. Always check the initial value and the condition carefully before committing to an answer.
The array-index notation str[length] is syntactic sugar for *(str + length). The compiler generates identical machine code for both forms. Some placement questions show the pointer form and ask whether it produces the same result; the answer is yes.
Method 2: Pointer Arithmetic
Instead of advancing an integer index, this method advances the pointer itself. When the pointer exits the loop, the distance between its final position and the starting address equals the string length.
The key insight from C null-terminated byte string semantics: pointer subtraction on two pointers into the same array gives the number of array elements between them. Since char elements are one byte each, pointer subtraction here gives the character count directly.
Code
#include <stdio.h>
int findLengthPointer(const char *str) {
const char *ptr = str;
while (*ptr != '\0') {
ptr++;
}
return (int)(ptr - str);
}
int main(void) {
char s[] = "hello";
printf("Length: %d\n", findLengthPointer(s));
return 0;
}
Traced execution for “hello”
ptrstarts atstr, pointing to'h'.*ptris'h', advance.*ptris'e', advance.*ptris'l', advance.*ptris'l', advance.*ptris'o', advance.*ptris the null terminator. Loop exits.ptr - str= 5. Returns 5. Output:Length: 5
Pointer arithmetic in MCQs
Placement test MCQs sometimes present the return statement as return ptr - str; and ask what type the expression has. In C, pointer subtraction yields a ptrdiff_t, which is implementation-defined but is at least a signed integer type wide enough to hold the result. Casting to int is safe for strings that fit in memory.
Other MCQ variants ask what happens if str is NULL. The loop immediately dereferences the pointer, causing undefined behaviour. Real production code adds a null check before the loop. In a placement MCQ, the expected answer is “undefined behaviour” unless the question specifies a non-null guarantee.
Method 3: Recursive Function
The recursive approach reduces the problem: the length of a string equals one plus the length of the string starting at the next character, bottoming out when the current character is null.
Code
#include <stdio.h>
int findLengthRecursive(const char *str) {
if (*str == '\0') {
return 0;
}
return 1 + findLengthRecursive(str + 1);
}
int main(void) {
char s[] = "hello";
printf("Length: %d\n", findLengthRecursive(s));
return 0;
}
Traced call stack for “hello”
findLengthRecursive("hello")callsfindLengthRecursive("ello"), adds 1.findLengthRecursive("ello")callsfindLengthRecursive("llo"), adds 1.findLengthRecursive("llo")callsfindLengthRecursive("lo"), adds 1.findLengthRecursive("lo")callsfindLengthRecursive("o"), adds 1.findLengthRecursive("o")callsfindLengthRecursive(""), adds 1.findLengthRecursive("")hits the base case. Returns 0.- Unwinding returns: 0 + 1 + 1 + 1 + 1 + 1 = 5. Output:
Length: 5
Stack depth consideration
Each recursive call adds one frame to the call stack. For placement test inputs this is never a practical concern, since questions use short strings. The memory tradeoff, framed for MCQ reasoning:
- Loop method: O(1) extra memory. One integer variable regardless of string length.
- Pointer method: O(1) extra memory. One pointer variable regardless of string length.
- Recursive method: O(n) extra stack memory. One new frame per character.
Placement tests that include a recursive version usually ask you to trace the call sequence rather than assess performance. The key tracing facts: str + 1 advances the pointer by one character, and the recursion bottoms out at the null byte, not after a fixed number of calls.
Comparing the Three Methods
| Method | Mechanism | Extra memory | Most common MCQ form |
|---|---|---|---|
| Loop with index | Integer counter, array notation | O(1) | Fill-in-the-blank loop condition |
| Pointer arithmetic | Pointer advance, subtraction | O(1) | Output prediction, type of return expression |
| Recursion | Call stack unwinding | O(n) stack frames | Trace the call sequence |
All three return the same value for the same input. The loop is the most commonly taught form and accounts for the majority of placement MCQ appearances. The pointer form is favoured in questions that test pointer arithmetic concepts. The recursive form appears when the question topic is recursion specifically.
For other loop-based C program patterns, the article on Pascal’s Triangle in C covers nested loop construction with a worked trace at the same difficulty level.
Choosing the Right Version for Your Situation
In a coding round where you write working code, use Method 1. It is the most readable, the least likely to have a subtle bug, and the easiest to verify by hand. Method 2 is equally valid and more idiomatic C, but the pointer subtraction return puzzles interviewers who are not C-fluent.
Use Method 3 only when the problem statement says “recursive solution” or when the larger coding question uses recursion and a helper fits the structure. Adding recursion where it is not required does not earn extra points in automated assessment platforms.
For MCQ tracing questions, focus on the loop termination condition and the initial counter value. The most common wrong answers come from off-by-one errors, not from misunderstanding the null terminator itself.
The pointer walk you traced through “hello” is structurally the same operation a tokenizer performs on input text: advance element by element, stop at a sentinel value, return the count. TinkerLLM lets you apply that instinct at the LLM layer, starting at ₹299, without a full ML environment setup.
Primary sources
Frequently asked questions
What does strlen() actually do internally in C?
strlen() walks the character array one byte at a time from the starting address until it finds the null terminator, then returns the distance travelled. The loop scan in Method 1 does exactly the same thing, just without the library wrapper.
Why doesn't the pointer method count the null terminator?
The while loop exits when the pointer is sitting on the null terminator, not after moving past it. At that point, subtracting the start address gives the distance from the first character to the null byte, which is the string length.
Which of the three methods is most memory-efficient?
The loop and pointer methods use a constant amount of extra memory regardless of string length. The recursive method allocates a new stack frame for every character, so it uses O(n) stack space. For long strings in resource-constrained environments, avoid recursion.
Can I find string length in C without any loop at all?
Not practically for a general-purpose function. Every manual approach requires traversal proportional to the string length. Some interview questions use pointer arithmetic tricks that look loop-free but still perform the same sequential scan internally.
Do placement tests ask students to write the full function or just trace it?
AMCAT and TCS NQT mostly test output prediction and fill-in-the-blank. Infosys Hackerday and coding-round platforms like HackerRank ask for the complete working function. Practising both forms covers all eventualities.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)