C: Logical Operators - Logical AND (Page 2 of 4 )
Logical AND is used to test whether two conditions are true. For example, if I wanted to make a joke about your mother, I could check to see if she is both fat and ugly. If so, I could make my program say something extra insulting. If not, it would say something only slightly insulting. Let's look at a program that asks you to try to guess what two numbers the computer is thinking of:
#include <stdio.h>
int main()
{
char c,d;
char numone='1';
char numtwo='3';
printf("I am thinking of a number between 1-10.n");
printf("Please enter a number: ");
c=getchar();
fflush(stdin);
printf("nnI am thinking of another number between 1-10.n");
printf("Please enter a second number: ");
d=getchar();
if(c==numone && d==numtwo)
{
printf("nnYou guessed both numbers in the proper sequence!n");
printf("nYou're a genius! An ugly genius, but a genius nonetheless!");
}
else
{
printf("nnYou have failed to guess the numbers in the proper
sequencenn");
printf("Dumb and ugly...what a shame!n");
}
return(0);
}
The program begins by creating four variables: "c" and "d", which will hold the users two guesses, and numone and numtwo. both of which hold the numbers the computer is thinking of. Next the computer asks the user to enter a number between 1-10 and stores the value in "c". Then it asks for a second number, and stores that value in "b".
We then enter an If statement, that says if the value in "c" is equal to numone AND the value in "d" is equal to numtwo then print some text. Note that, in this example, the numbers much match up exactly. For instance, if the user enters in '1' and then '3', they have guessed the right numbers. However, if they enter in '3' and then '1', they have not. If the user enters the wrong number and sequence, then some other text is printed. Here are the results:
If the user enters the correct data:
I am thinking of a number between 1-10.
Please enter a number: 1
I am thinking of another number between 1-10.
Please enter a second number: 3
You guessed both numbers in the proper sequence!
You're a genius! An ugly genius, but a genius nonetheless!
If the user enters the wrong data or enters it out of sequence:
I am thinking of a number between 1-10.
Please enter a number: 3
I am thinking of another number between 1-10.
Please enter a second number: 1
You have failed to guess the numbers in the proper sequence
Dumb and ugly...what a shame!
Next: You Are Cool....Not(!) >>
More BrainDump Articles
More By James Payne