Decisions statements in C
The if statement So far we have only learnt how to make programs that do one thing after the other without being able to make decisions. Th...
https://things-for-students.blogspot.com/2012/01/decisions-statements-in-c.html
The if statement
So far we have only learnt how to make programs that do one thing after the other without being able to make decisions. The if statement can be used to test conditions so that we can alter the flow of a program. The following example has the basic structure of an if statement:
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
return 0;
}
Now we must also test if the user has failed. We could do it by adding another if statement but there is a better way which is to use the else statement that goes with the if statement.
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
else
pass = 'n';
return 0;
}
If you want to execute more than 1 instruction in an if statement then you have to put them between curly brackets. The curly brackets are used to group commands together.
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
{
pass = 'y';
printf("You passed");
}
else
{
pass = 'n';
printf("You failed");
}
return 0;
}
#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&a);
scanf("%d",&b);
if (a > 0 && b > 0)
printf("Both numbers are positive\n");
if (a == 0 || b == 0)
printf("At least one of the numbers = 0\n");
if (!(a > 0) && !(b > 0))
printf("Both numbers are negative\n");
return 0;
}
Boolean operators
In the above examples we used > and < which are called boolean operators. They are called boolean operators because they give you either true or false when you use them to test a condition. The following is table of all the boolean operators in c:== | Equal |
!= | Not equal |
> | Greater than |
>= | Greater than or equal |
< | Less than |
<= | Less than or equal |
&& | And |
|| | Or |
! | Not |
The switch statement
The switch statement is just like an if statement but it has many conditions and the commands for those conditions in only 1 statement. It is runs faster than an if statement. In a switch statement you first choose the variable to be tested and then you give each of the conditions and the commands for the conditions. You can also put in a default if none of the conditions are equal to the value of the variable. If you use more than one command then you need to remember to group them between curly brackets.
#include<stdio.h>
int main()
{
char fruit;
printf("Which one is your favourite fruit:\n");
printf("a) Apples\n");
printf("b) Bananas\n");
printf("c) Cherries\n");
scanf("%c",&fruit);
switch (fruit)
{
case 'a':
printf("You like apples\n");
break;
case 'b':
printf("You like bananas\n");
break;
case 'c':
printf("You like cherries\n");
break;
default:
printf("You entered an invalid choice\n");
}
return 0;
}