This task is typically accomplished using recursive function calls.
Moreover, you are getting always the same result because the random generator starts always with the same sequence: You do need to call
srand
in order to provide a different starting point (see
srand(3): pseudo-random number generator - Linux man page[
^]).
Try the program listed below.
(Note, such a code gives more chances to the
empty
production, in rule
B
in order to give the program itself chances, pardon the pun, to terminate).
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void produce_E();
void produce_Y();
void produce_A();
void produce_B();
int main()
{
time_t t;
srand((unsigned) time(&t));
produce_E();
return 0;
}
void produce_E()
{
putchar('(');
produce_Y();
putchar(')');
}
void produce_Y()
{
produce_A();
produce_B();
}
void produce_A()
{
switch( rand() % 2) {
case 0:
putchar('v');
break;
case 1:
produce_E();
break;
}
}
void produce_B()
{
switch ( rand() % 5) {
case 0:
putchar('-');
produce_Y();
break;
case 1:
putchar('+');
produce_Y();
break;
default: break;
}
}