Start · i=0 · vowels=0 · position=-1
The string is ready. We search for A and use the same traversal to count vowels.
C programming · Lesson
Scan a string once and observe how the same traversal can update multiple results: vowel count and the position of the first searched character.
During one traversal you can evaluate conditions on the current character and update accumulators or search results. In this example vocali counts A/E/I/O/U and posizione stores the first index of A.
i=0 → while parola[i] != '\0' → vowel? update count → first A? save i → i++
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 is ready. We search for A and use the same traversal to count vowels.
C is not a vowel and is not A: vowels stays 0, position stays -1.
I satisfies the vowel condition, so the counter becomes 1. It is not the searched character.
A is a vowel and matches the target. Because position is still -1, we store the first index: 2.
O increments the vowel count again. position does not change because the first result has already been found.
The terminator makes the while condition false. No character past \0 is processed.
One traversal produced two results: three vowels and the first A at index 2.
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 char cercato = 'A';
7 int vocali = 0;
8 int posizione = -1;
9 int i = 0;
10
11 while (parola[i] != '\0')
12 {
13 int e_vocale =
14 parola[i] == 'A' || parola[i] == 'E' ||
15 parola[i] == 'I' || parola[i] == 'O' ||
16 parola[i] == 'U';
17
18 if (e_vocale)
19 vocali = vocali + 1;
20
21 if (posizione == -1 && parola[i] == cercato)
22 posizione = i;
23
24 i = i + 1;
25 }
26
27 printf("%d\n", vocali);
28 printf("%d\n", posizione);
29 return 0;
30}
Read an uppercase word and count vowels A E I O U.
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" and searched character = 'A', what results do you get?
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.