¤ Home » Programming » C Tutorial » Logical constructs in C - if..else & switch..case statements

Logical constructs in C - if..else & switch..case statements

if-else statement

The syntax of if statement, or if-else statement which requires evaluation of a condition and branching according to the outcome of the decision test is written as follows:

if(<expression>)
{
    <statement block>
}

OR

if(<expression>)
{
    <statement block 1>
}
else
{
    <statement block 2>
}

C treats logical values as integer data type with value 0 for false and non-zero for true. Thus, the <statement block> in the first syntax and <statement block 1> in the second syntax is executed if <expression> evaluates to true, i.e. evaluates to a non-zero value. Even a negative value is treated as true. Note that enclosing the block within curly braces becomes mandatory if the statement block consists of multiple statements. The <statement block 2> is executed when the <expression> in the if statement evaluates to false, i.e evaluates to a zero value.


Example:
#include <stdio.h>
main()
{
    int min, x, y;
    printf("\nProvide two numbers:");
    scanf("%d %d", &x, &y);
    fflush(stdin);

    /* Computes minimum of x and y */
    if(x < y)
        min = x;
    else
        min = y;
    printf("%d is the minimum of %d and %d\n", min, x, y);
}

The if statements can be nested. See some examples below.

if(<expression1>)
{
    <statement block1>
}
else if(<expression2>)
{
    <statement block2>
}
else
{
    <statement block3>
}
if(<expression1>)
{
    if(<expression2>)
    {
        <statement block1>
    }
    else
    {
        <statement block2>
    }
}
else
{
    <statement block3>
}

Note that these two examples are not the same.


Example of nested if-else:
#include <stdio.h>
#define  TRUE  1
#define  FALSE 0

main()
{
	int EQUAL, min, max, x, y;
	printf("\nProvide two numbers:");
	scanf("%d %d", &x, &y);
	fflush(stdin);

	/* Compare the two numbers x and y */
	if(x == y)
	{
		EQUAL = TRUE;
		min = max = x;
	}
	else
	{
		EQUAL = FALSE;
		if(x > y)
		{
			min = y; 
			max = x; 
		}
		else
		{
			min = x; 
			max = y; 
		}
	}

	if(EQUAL)
		printf("Both x and y are equal\n");
	else
		printf("Minimum: %d, Maximum: %d \n", min, max);
}

Exercises:
1. Identify the mistake in the following C program.

	#include <stdio.h>
	main()
	{
		float basic;
		printf("Enter basic: ");
		scanf("%f", &basic);
		fflush(stdin);
		if(basic = 0)
			printf("Invalid Input\n");
		else
			printf("Basic is %.2f", basic);
	}


2. Predict the output of the following C program.

	#include <stdio.h>
	main()
	{
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		if(a > b)
		{
			a += b;
			a ++;
		}
		if(a > c)
			a *= c;
		else
			c -= (a + b);
	
		printf("%d %d %d\n", a, b, c);
	}



switch statement

The switch statement is usefull when there are multiple if-else conditions to be checked. The syntax is:

switch <expression> 
{
	case <expression 1>
		<statement block 1>
		break;

	case <expression 2>
		<statement block 2>
		break;

	case <expression 3>
		<statement block 3>
		break;
	...

	case <expression n>
		<statement block n>
		break;

	default:
		//When none of the above expressions evaluate to true
		<statement block n+1>
		break;
}

The switch statement is a compound statement which specifies alternate course of actions. Each alternative is expressed as a group of one or more statements which are identified by one or more labels called case labels. The following two different programs, intended to perform the same task, illustrate how nested if..else can be replaced by a switch..case construct.

/* Program having nested if statements */
#include <stdio.h>
main()
{
	char category;
	printf("Enter Category: ");
	category = getchar();
	fflush(stdin);

	if(category == 'B')
	{
		printf("B.TECH students\n");
		/* Statements for B.TECH Processing will go here */
	}
	else if(category == 'M')
	{
		printf("M.Sc. Student \n");
		/* Statements for M.Sc Processing will go here */
	}
	else if(category == 'T')
	{
		printf("M.TECH Student \n");
		/* Statements for M.TECH Processing will go here */
	}
	else if(category == 'P')
	{
		printf("Ph. D. Student \n");
		/* Statements for Ph.D Processing will go here */
	}
	else
	{
		printf("ERROR\n");
		/* Statements for Error Processing will go here */
	}
}


/*
  Such programs with multiple condition checks can be better implemented with
  switch-case construct. The advantage is better readability of the code.
*/
#include <stdio.h>
main()
{
	char category;
	printf("Enter Category: ");
	category = getchar();
	fflush(stdin);

	switch(category)
	{
		case 'B' :
			printf("B.TECH students\n");
			/* B.TECH Processing */
			break;
		
		case 'M' :
			printf("M.Sc. Student \n");
			/* M.Sc Processing */
			break;
	
		case 'T' :
			printf("M.TECH Student \n");
			/* M.TECH Processing */
			break;

		case 'P' :
			printf("Ph. D. Student \n");
			/* Ph. D. Processing */
			break;
		
		default :
			printf("ERROR\n");
			/* Error Processing */
	}
}


Share:




comments powered by Disqus


Buy Domain & Hosting from the most reliable and trusted company - WebServicesWorldWide.com.

Looking to build a website?
Launch a 20 page website in 1 day at only Rs.200/month or US$ 3.19/month. Hosting & Email included.





About the Author

Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of XLRI, industry professionals, and govt. officials.

Rajeev has founded Computer Solutions & WebServicesWorldwide.com, and has hands-on experience of building variety of web applications and portals, that include - SAAS based ERP & e-commerce systems, independent B2B, B2C, Matrimonial & Job portals, and many more.



Copyright © How2Lab.com. All rights reserved.

Refer a friend | Sitemap | Disclaimer | Privacy Policy