Decision Making Statements

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

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. condional 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 decision automatically.

if-else statement

Syntax-1

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

Syntax-2

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 only first statement is consider is a part of "if" or "else" block and rest of the statements are considered outside the if or else block.

In the above syntax 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 block the control continue executing the program written after the if-else construct.

Program: Find the max of two 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 are declare the required variable and get the input from the user.
  2. Then statement if(a>b) is evaluated, if condition is true the 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.

Syntax of if

Syntax-1

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

Syntax-2

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 continue executing.

Program to give the bonus if the salary is less than 5000 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 staement if(sal<5000) check the salary against 5000, if condition evaluates true the bonus=500 will be executes otherwise not.
  3. Finally the total salary gets print by using the statement printf("Total Salary: %.2f",sal+bonus);. In This statement %.2f is used, By using this only 2 digits gets printed after the decimal point.

Program: 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 any number is max among the given numbers and store it into max.
  2. Then check reamining with against the max, if any number is greater than max, then change the max ohterwise not.
  3. This is important logic if there are many numbers in a program is given.

Nested if else statement

If or if-else statement can be nested in another if statement or an if-else statement. 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 max 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 if is executed. To enter in the else block means a is not greater so b is tested with c. if(b>c) test is evaluates true the max is b otherwise max is c.

Else if ladder

If you Observe 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 the 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 make it easy to maintain and understand the program.This style is called else-if ladder.

Syntax of 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 condition is tested and so on. If any condition doesn’t evaluated true then the else block is executed.

Program: Find the grade of a student

#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 charater is stored in computers 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: Check 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 is fall 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 condition is evaluated true the character is in uppercase otherwise not.
  3. The output section of program shows the output of 3-run. In the last run you can see that we input multiple character, but how it can be saved in a character variable.
  4. Because character variable can save only one character. The output also print the character saved in the variable ch.you can see first character is saved.
  5. This happens because 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 remains 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 of 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 output is finish the output window will be disappear. so if we put getch() at the end of the program then program need to receive input from the user and the window will be hold 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(); 

Try these and feel the difference.

Previous Back to C Programming index Next

Comments

Popular posts from this blog

Overview of Go lang

Arrays in C Language

Data Types in Go language

Creating your first html page

Say Hello world in Go lang

Arrays in Go lang

Installing go lang

String in golang

Decision Making in Go lang

Floating point Data types in Go lang