With the logical operators and expressions we can extend the program of the last lecture.
/* L-7 MCS 260 Fri 31 Aug 2001 : rolling a die, extended version */
#include <stdio.>
#include <stdlib.h> /* for the rand() function */
#include <time.h> /* time is used as random seed */
int main(void)
{
int n; /* number of times to roll the die */
int t = 0; /* target value for the die */
int i = 0; /* index counter to control while loop */
int die = 0; /* value of the die */
srand(time(NULL)); /* random seed for random number generator */
printf("Give number of times to roll the die : ");
scanf("%d", &n);
printf("Give target value for the die (between 1 and 6) : ");
scanf("%d", &t);
while ((die != t) && (i < n)) /* untill die == t, no more than n rolls */
{
die = rand(); /* rand() returns random integer */
die = die % 6 + 1; /* die must be in the range 1..6 */
printf(" %d", die); /* print space and the die on screen */
i++; /* increment counter */
}
printf("\n"); /* finish off with new line */
printf("Got %d after %d times.\n", die, i);
return 0;
}
In the second program we explore logical operators :
/* L-7 MCS 260 Wed 5 Sep 2001 : test on logical operators and expressions */
#include<stdio.h>
int main(void)
{
int n; /* some integer number */
int test; /* outcome of test */
printf("Give integer : "); scanf("%d", &n);
printf("Executing one test : \n");
test = (n > 0);
printf(" Is n positive? (1=yes,0=no) : %d\n", test);
printf(" Negation of last statement : %d\n", !test);
printf("Combining tests : \n");
test = (n > 0) && (n % 2 == 1);
printf(" Is n odd and positive? (1=yes,0=no) : %d\n", test);
printf(" Negate this is n even or n <= 0 : %d\n", !test);
test = (n % 2 == 0);
printf(" Is n even? (1=yes,0=no) : %d\n", test);
test = (n <= 0);
printf(" Is n negative? (1=yes,0=no) : %d\n", test);
test = (n <= 0) || (n % 2 == 0);
printf(" Negation of \"n even or n <= 0\" : %d\n", !test);
return 0;
}