×

C- DESCISION MAKING


In this chapter, we will understand how decision making is done in C programming. In C, 'if' statement is used to make decisions.

Basic Syntax of if
if(expression/condition)
{
	//statement
}

'if' statement takes an expression and evaluate the expression in the parenthesis. If the expression is evaluated to true then the statement inside the body of if statement is executed. If the expression is evaluated to be false the body of the if statement is skipped and not executed.

Lets write a simple C program to test if a number is negative or not.

Example #1. Simple if statement

File name - if_example_1.c
/* Program to display if a number is positive or negative */
#include<stdio.h>
void main()
{
	int number;
	printf("Enter a number");
	scanf("%d", &number);

	/* check if the number is less than 0 or negative */
	if(number < 0)
	{
		printf("You have entered negative number");
	}
}

In the above example we have seen how to use a simple if statement. Now lets see different examples of if statements in C.

Example #2. if...else statement

File name - if_example_2.c
/* Program to display positive if the number is positive, otherwise we will print negative */
#include<stdio.h>
void main()
{
	int number;
	printf("Enter a number : ");
	scanf("%d",&number);

	if(number < 0)
	{
		printf("Negative");
	}else{
		printf("Positive");
	}
}
                    

Example #3. if...else if...else or Nested if statement

File name - if_example_3.c
/* Program to check if a number is positive, negative or zero */
#include<stdio.h>
void main()
{
	int number;
	printf("Enter a number : ");
	scanf("%d",&number);

	if(number < 0)
	{
		printf("Number is Negative");
	}else if(number == 0){
		printf("Number is 0");
	}else{
		printf("Number is Positive");
	}
}

In this section we have learned how to make decision in c using if statement. We also learned if...else, Nested if statements.

In the next chapter we will learn about switch statement.