Chapter 3
Chapter 3
Types -
1. if-else
if(Condition) {
//do something if true
}
else{
//do something if false
}
For ex.-
#include<stdio.h>
int main() {
int age;
printf("enter age : ");
scanf("%d", &age);
printf("thank you");
return 0;
}
Note : Curly brackets are compulsory when there are multiple statements, not on
single statement. But it is recommended to use in both types so that chances of
error are low.
if(Condition) {
//do soemthing if true
}
else if (Condition 2) {
//do something if 1st is false and 2nd is true
}
For ex-
#include<stdio.h>
int main() {
int age;
printf("enter age : ");
scanf("%d", &age);
if(age >= 18) {
printf("adult \n");
}
else if(age > 13 && age <18) {
printf("teenager \n");
}
else {
printf("child");
}
return 0;
}
If - If mutiple statements are there and all are independnet irrespective to other
and we have to check all statements seperately, then we can use 'If' in every line.
Ternary Operator
Syntax -
Condition? do Something if True : do Something if false
for ex-
age >= 18 ? printf("adult \n") : printf("not adult \n")
2. Switch
switch(number) {
case C1: //do something
break;
case C2: //do somthing
break;
default: //do something
}
used in same syntax. and writing break; after a case is compulsory otherwise it
will print all results below the actual result instead of only printing actual
result.
Properties of Switch:
a. Cases can be in any order.
b. Nested switch (switch inside switch) are allowed.
Example of nested if :
int main() {
printf("enter number : ");
scanf("%d", &number);
if(number >= 0) {
printf("positive \n");
if(number % 2==0) {
printf("even \n");
}
else {
printf("odd \n");
}
}
else {
printf("negative \n");
}
}
Q. Write a program to check if a student passed or failed.
marks > 30 is pass
marks <= 30 is fail
int x = 2;
if(x = 1) {
printf("x is equal to 1");
} else {
printf("x is not equal to 1");
}
a. give error
b. print "x is equal to 1"
c. print "x is not equal to 1"