String ready in memory
The string has four visible characters and the terminator in cell 4.
C programming · Lesson
Follow index i as it visits one character at a time and stops exactly when it reaches the terminator.
A C string does not carry its length. A loop can compute it by advancing while parola[i] differs from '\0'. When the test fails, i is the number of visible characters.
i=0 → parola[i] != '\0'? → i++ → repeat → at the end i = length
The flowchart shows the logical string value; the String Memory Explorer below shows the individual char cells and the \0 terminator actually required in C.
Each cell contains one char. The \0 terminator occupies a real cell and tells C functions where the string ends.
The string has four visible characters and the terminator in cell 4.
The loop starts by checking parola[0].
parola[0] is C: the condition is true and i becomes 1.
parola[1] is I: the loop continues and i becomes 2.
parola[2] is A: the loop continues and i becomes 3.
parola[3] is O: the loop continues and i becomes 4.
parola[4] is the terminator: the while condition becomes false and the loop stops.
When the loop stops, i equals the number of characters before \0.
Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.
1#include <stdio.h>
2
3int main(void)
4{
5 char parola[] = "CIAO";
6 int i = 0;
7 while (parola[i] != '\0')
8 {
9 i = i + 1;
10 }
11 printf("%d\n", i);
12 return 0;
13}
Read one word up to 50 characters and print its length without strlen.
This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.
With parola = "CIAO", what value does i have when the while ends?
Challenge 1 / 5 · Understanding
Progress: 0 / 5 · correct: 0
ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.
Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.