Decision Making in C

Decision Making in Statements in C

As in the real world, we need to make a decision according to the situation. In the same sense, we need to make decision while creating programs.

For decision-making C provides various construct as follows:

  1. if statement
  2. if-else statement
  3. nested if-else statement
  4. else if Ladder
  5. conditional operator
  6. switch/case construct

By using the above-given decision-making statement we can implement the sense in a program that program can create decisions automatically.

if-else statement Syntax

if(condition) {
      statement1;
      statement2;
      statement3;
      ........
      ........
} else {
      statement1;
      statement2;
      statement3;
      ........
      ........
}
if(condition)
       statement;
else
       statement;
Syntax Explained

The block which is specified with if is called if-block and the block with else is called else block. If there is a single statement in if block or else block then no need to enclose in {} (curly braces). But in the case of more than one statement and if a block is not maintained then the only first statement is considered is a part of "if" or "else" block and the rest of the statements are considered outside the if or else block.

In the above syntax, the first condition is evaluated. If the condition is true then "if" block is executed otherwise else block is executed. After the execution of if block or else blocks the control continue executing the program written after the if-else construct.

Program to find the max of 2 numbers

#include<stdio.h>
int main() {
	int a,b,max;
	
	printf("Enter any two numbers: ");
	scanf("%d%d",&a,&b);
	
	if(a > b) {
		max = a;
	} else {
		max = b;
	}
	
	printf("Max = %d",max);
}

Output

Enter two numbers: 4 9
Maximum=9

Program Explained

  1. The first few lines declare the required variable and get the input from the user.
  2. Then statement if(a>b) is evaluated, if a condition is true then if block will be run and by using max=a statement a is stored otherwise else block executes and b is stored in max.
  3. After that the result gets printed through the statement printf("Maximum=%d",max);
Note: In the above discussed if-else statement the else part is optional. If you don’t want to perform anything when condition is false then skip the else part and then it becomes only if construct.

if statement

Syntax

if(condition)
{ 
        statement1;
        statement2;
        statement3;
}
if(condition)
       statement;
Syntax Explained

In the above syntax if condition evaluated true then if block is executed otherwise skipped. After executing the if block the rest program continues executing.

Program to calculate bonus salary

Program to calculate the bonus salary, if the salary is less than 5000 then the bonus will be 500 otherwise 0 and print the total salary received.
#include<stdio.h>
int main() {
	int sal, bonus;
	
	printf("Enter the salary: ");
	scanf("%d",&sal);
	
	bonus = 0;
	if(sal <= 5000) {
		bonus = 500;
	}
	
	printf("Total Salary = %d",sal+bonus);
	return 0;
}

Output:

Enter the salary: 4900
Total Salary = 5400

Program Explained

  1. Program logic starts with the statement bonus=0. We consider that the bonus is 0.
  2. Then statement if(sal<5000) check the salary against 5000 if the condition evaluates true the bonus=500 will be executed otherwise not.
  3. Finally the total salary gets print by using the statement printf("Total Salary: %.2f",sal+bonus);. This statement %.2f is used, By using this only 2 digits gets printed after the decimal point.

Program to find the max of 4 numbers

#include<stdio.h>
int main() {
	int a,b,c,d,max;
	printf("Enter any 4 numbers: ");
	scanf("%d%d%d%d",&a,&b,&c,&d);
	
	max = a;
	
	if(b > max) {
		max = b;
	}
	
	if(c > max) {
		max = c;
	}
	
	if(d > max) {
		max = d;
	}
	
	printf("Max = %d",max);
	return 0;
}

Output

Enter any 4 numbers: 4 8 2 5
Maximum=8

Program Explained

  1. The concept in the program is that, consider the first number is largest among the given numbers and store it into max.
  2. Then check to remain with against the max, if any number is greater than max, then change the max otherwise not.
  3. This is an important logic if there are many numbers in a program is given.

Nested if else statement

Nested if-else statement

If or if-else statement can be nested in another if statement or an if-else statement. The rest of the rules is the same as previously discussed. Some possible patterns are shown below. Some possible Syntax of nested if else

Syntax-1
if(condition) { 
    if(condition) {   
                statement1;
                statement2;
                statement3;
          }
}
Syntax-2
if(condition) {
          if(condition) {   
                statement1;
                statement2;
                statement3;
          }
}
else {
          statement1;
          statement2;
          statement3;
}
Syntax-3
if(condition) {
          if(condition) {   
                statement1;
                statement2;
                statement3;
          }
          else {
                statement1;
                statement2;
                statement3;

           }
}
else {
          statement1;
          statement2;
          statement3;
}
Syntax-4
if(condition) {
          if(condition) {   
                statement1;
                statement2;
                statement3;
          }
          else {
                statement1;
                statement2;
                statement3;

           }
}
else {
          if(condition) {   
                statement1;
                statement2;
                statement3;
          }
          else {
                statement1;
                statement2;
                statement3;

           }
}

Program to find the largest of 3 numbers

#include<stdio.h>
int main() {
	int a,b,c,max;
	
	printf("Enter any 3 numbers: ");
	scanf("%d%d%d",&a,&b,&c);
	
	if(a > b) {
		if(a > c) {
			max = a;
		} else {
			max = c;
		}
	}else {
		if(b > c) {
			max = b;
		}else {
			max = c;
		}
	}
	printf("Max = %d",max);
}

Program Explained

  1. Trace out the program itself and find out the logic behind it.
  2. OK! I make it clear. The first if(a>b) check whether a is greater than b, if it is true then the comparison if(a>c)within the if is tested if this test is true the a is max otherwise c is max.
  3. If the first if of the logic becomes false then the else part associated with it is executed. To enter in the else block means a is not greater so b is tested with c. if(b>c) test evaluates true the max is b otherwise max is c.

else-if ladder

If you Observe the above-given example carefully, you see that statement within the "if" block is right indented. This is a good way to write the program.

Even compiler will never affect the result if you don't follow the specific writing style. But for better understanding and readability, it is a good idea.

But this idea becomes a problem when there are many more nesting levels of if.

The next style of if-else makes it easy to maintain and understand the program. This style is called the else-if ladder.

Syntax of the else-if ladder

if(conditon) {
    statement1;
    statement2;
    ..........;
    ..........;
    }
    else if(condition) {
    statement1;
    statement2;
    ..........;
    ..........;
    }
    else if(condition) {
    statement1;
    statement2;
    ..........;
    ..........;
    }
    else {
    statement1;
    statement2;
    ..........;
    ..........;
    } 

Syntax Explained

In the above syntax first, if-condition is tested and if evaluated as true then associated if block is executed otherwise next if block will be tested and so on. If any condition doesn’t evaluate true then the else block is executed.

Program to calculate Grade

Program to find the grade of a student as per the following rules...
  • Input 3 subject marks
  • Calculate Percentage.
  • Find grade as per the following rules
PercentageGrade
>= 85S
75 - 85A
65 - 75B
55 - 65C
50 - 55D
< 50F
#include<stdio.h>
int main() {
	int m1,m2,m3;
	float per;
	char gd;
	
	printf("Enter 3 subject marks: ");
	scanf("%d%d%d",&m1,&m2,&m3);
	
	per = (m1 + m2 + m3) / 3.0f;
	
	if(per >= 85) gd = 'S';
	else if(per >= 75) gd = 'A';
	else if(per >= 65) gd = 'B';
	else if(per >= 55) gd = 'C';
	else if(per >= 50) gd = 'D';
	else gd = 'F';
	
	printf("Per=%.2f\nGrade=%c",per,gd);
	
	return 0;
}

Output

Enter 3 subject marks: 55 75 84
Per=71.33
Grade=B

ASCII

  1. Ascii stands for American standard code for information interchange.
  2. In computer memory, everything is saved in the form of 1's and 0's means bit pattern.
  3. We can find the binary(bit pattern) of any numeric number. But, how a character is stored in computer memory?
  4. Actually every character has a numeric code representing it known as ASCII code.
  5. The characters and their ascii table is given below:
Total Character Character Range Ascii Range
26 A-Z(Uppercase Alphabets) 65-90
26 a-z(Lowercase Alphabets) 97-122
10 0-9(Digits) 48-57
34 Non-printable character(alt,shift,enter,ctrl etc.) 0-33
128 Graphics Character 128-255
32 Special Symbol Rest
256 Total Character 0-255

Program to check whether a character is in uppercase or not.

#include<stdio.h>
int main() {
	char ch;
	
	printf("Enter any alphabet: ");
	scanf("%c",&ch);
	
	if(ch >= 65 && ch<= 90) {
		printf("%c is in uppercase",ch);
	} else {
		printf("%c is not in uppercase",ch);
	}
	return 0;
}

Output

Enter any alphabet: E
E is in uppercase.

Enter any alphabet: e
e is not in uppercase.

Enter any alphabet: AbCde
A is in uppercase.

Program Explained

  1. To check whether a character is in uppercase or not. We have to check that the character falls between the uppercase character range or not.
  2. Statement if(ch>=65 && ch<=90) check the range of input character between 65 to 90. If the condition is evaluated true the character is in uppercase otherwise not.
  3. The output section of the program shows the output of 3-run. In the last run, you can see that we input multiple characters, but how it can be saved in a character variable.
  4. Because the character variables can save only one character. The output also prints the character saved in the variable ch.you can see the first character is saved.
  5. This happens because the scanf() doesn't terminate until the enter is pressed. So it is clear that scanf() can read the character until enter is pressed.
  6. The first character is saved into the variable and rest will remain in the buffer of standard input(stdin).

Character input

For the character input multiple options are available in C.

  1. scanf()
  2. getchar()
  3. getche()
  4. getch()

Funcation Explained

  1. scanf() and getchar() both wait for the enter and receive input until the enter is pressed. The difference between scanf() and getchar() is that scanf() is a formatted input whereas getchar() belongs to the unformatted category.
  2. As against scanf() and getchar(), getche() and getch() don't wait for the enter and input character as soon as you press a character and move to the next statement.
  3. The difference between getche() and getch() is that getche() display the inputted character whereas getch() doesn't display.Actually in getche() "e" stands for echo means display.
  4. One more thing is that in the turbo C++ compiler at the end of the program people used getch(). It is because as soon as the output is finished the output window will disappear. so if we put getch() at the end of the program then the program needs to receive input from the user and the window will be held until you press a key.
  5. But remember that getch() is a function used to input a character not to hold the output screen.

Syntax of getch(),getche(),getchar()

getchar(),getch(),getche() returns the ascii of the input character.

printf("Enter any character: ");
ch=getchar();
printf("Enter any character: ");
ch=getche();
printf("Enter any character: ");
ch=getch(); 

Leap year program

Check the year is leap year or not.
#include<stdio.h>
int main() {
	int year;
	printf("Enter any year: ");
	scanf("%d",&year);
	
	if(year % 100 == 0) {
		if (year % 400 == 0) {
			printf("%d is a leap year",year);
		} else {
			printf("%d is not a leap year",year);
		}
	}else {
		if(year % 4 == 0) {
			printf("%d is a leap year",year);
		} else {
			printf("%d is not a leap year",year);
		}
	}
	return 0;
}
Output
Enter any year: 1996
1996 is leap year

Enter any year: 2001
2001 is no a leap year

Enter any year: 1800
1800 is not a leap year
Program Explained
  1. You know the year which is divisible by 4 is called leap year, but what about the century? Each century is divisible by 4. but to check whether the century is a leap year or not we have to check its divisibility by 400. So the logic to check the year is a leap or not:
  2. The first check the year is a century if the year is century then check its divisibility by 400. if it is fully divisible by 400 then the century is leap year otherwise not.
  3. If the year is not the century then check its divisibility with 4. if it is divided by 4 then the year is a leap or not.

Check Leap year using Logical operator

if(year%100==0 && year%400==0 || year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);
Program Snippet Explained

Observe the above program section, first check the year is divisible by 100 then check it is divisible by 400 then the year is a leap year.

But if the year is not a century then its divisibility is checked by 4. it is OK.

But what happens when the year is century but not a leap year, then in the above program snippet its divisibility is checked by 4. That is not ok according to leap year logic. So the above program logic is wrong.

The improvement in the above logic is to ensure that the divisibility by 4 should be checked only in the case when the year is not a century. The improved logic is given below:

if(year%100==0 && year%400==0 || year%100!=0 && year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);

The above-given logic is perfectly OK. But one more improvement can be added that is if the year is divisible by 400 then it is also divisible by 100. so no need to check the divisibility by 100.

if(year%400==0 || year%100!=0 && year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);

Conditional operator

?: are known as the conditional operator. This is a shorthand way to deal with a conditional statement. These operators are also known as a ternary operator because they receive 3 arguments to work.

Syntax of Conditional operator

condition ? statement if true : statement if false;

Syntax explained

In the above-given syntax, the first condition is evaluated and if condition is true then the "statement if true" part is executed otherwise "statement if false" part is executed.

Example of Conditional operator

max = a > b ? a : b;

In the above example first, a>b condition is tested if the condition becomes true then a is stored in max otherwise b is stored in max.

a > b ? printf("%d",a) : printf("%d",b);

The above-given program snippet shows another way to find the max of two numbers, but the statement print the max.

a > b ? max = a : max = b;

One more way to find the max of two numbers as given in the above statement. When you compile this program the compile shows and syntax error.

The reason for the error is that: enjoy the higher priority than =. The solution of the given error is given below.

a > b ? max = a : (max = b);
So this is a good way to enclose the statement in brackets to avoid the error while using the conditional statement.
max = a > b ? (a > c ? a : c) : (b > c ? b : c);

The conditional operator can be nested this is shown in the above example. The above example is finding the max of 3 numbers a,b,c and the result is stored in max. Trace out the above statement yourself.

Decision making in C | Video Tutorial in Hindi

Decision making in C part-2 | Video Tutorial in Hindi

Decision making in C part-3| Video Tutorial in Hindi

Decision making in C | Examples | Video Tutorial

Decision making in C | Example-2 | Video Tutorial in Hindi