As I am taking my first steps in C, I study K&R (I guess most of you did the same, right?)
In the introductory chapter about functions (1.7) there is an example showing how to create a function that is then called to calculate powers (b**n). I simplified it to calculate only one given power, 2**5:
Code:
#include <stdio.h>
int power(int m, int n);
main()
{
printf("%d", power(2,5));
}
int power(int base, int n)
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}
which works fine, resulting 32.
Now, trying to go deeper, I want to create a similar* program to make calculations with words and characters, but oh! characters look to me tougher than numbers all the time (*with "similar", I mean create a function and call it to do the job, instead of doing it in the body of the code).
Lets say I want to make a program to scan a string of words and calculate the mean number of characters per word.
The string will be "This is an extremely complicated code I would call it rocket science". It has 12 words, 57 chars (blanks don't belong to any word so they don't count) and 4.75 chars per word.
My function, mean_num_chars, will have to
(a) count chars without blanks
(b) count words
(c) calculate mean number of chars per word
It will then be called to make the calculation in the above string.
First things first: we already know how to use while(getchar!=EOF) to count characters (K&R chapter 1.5.2) but what if -instead- the input is a specific string? How to "read" it and how to tell my program that the string is finished? And most important: "reading" will be done in the function or in the rest of the body?
Any hint on this before I proceed?