Answer to Question 36-4
It recomputes strlen(s) each time around the loop.
Suppose that s has n characters. Then the loop goes
around n times. Each time, it spends time proportional
to n to compute strlen(s). So the total amount of time
is proportial to n2. (If you buy x things
and each one costs y dollars then your total bill
is xy dollars.)
You could compute strlen(s) once and save it in a variable.
But it is not really necessary to compute strlen(s) even once.
A better approach is to end the loop when s[i] is a
null character.
int numNonblanks(const char* s)
{
int count = 0;
for(int i = 0; s[i] != '\0'; i++)
{
if(s[i] != ' ')
{
count++;
}
}
return count;
}