Now that we can create our random numbers we can think about how we are going to store and display the messages.
We know that we can store a string of text as an array of characters. We can mark the end of the array with a terminator which is the value 0. One way to to store lots of messages would be to have lots of arrays, but this would make it difficult to select particular ones. Instead I would rather have one enormous array and then look down it to find the message which I want.
I am going to use a cunning trick where I use a special, magic character (in my case '*
') to mean "the end of the message". Each message in the long array will have a '*
' at the end.
In the code on the right I have an array called messages which contains two messages which are terminated by the *
character and then a zero value to mark the end of the array itself..
I want to make the program flexible so that I can add new messages without changing the code too much, so I need a way of findout out how many messages are present. I can do this by counting the number of '*
'.
The function count_messages
works out how many '*
' characters there are in the string and returns that value. Note how I am using a for loop. Normally you check to make sure that the control variable (in this case i) is below a certain limit. In this case we are making the loop keep going until the element at location i is a 0, at which point our loop stops. There is nothing to stop you using conditions in for loops like this.
const unsigned char messages [] =
{
'n','o','*'
'y','e','s','*',
0x00
}
unsigned char count_messages (void)
{
int i, count = 0 ;
for ( i=0;messages[i]!=0;i=i+1 )
{
if ( messages [i]=='*' )
{
count = count + 1 ;
}
}
return count ;
}