¤ 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


Download Mobile App for Android


Web Service Offers

.CLUB Registration
1,199 199 (83.4% off)
per Year

Ecommerce on the Cloud

An online store hosted on the Cloud. Sell unlimited products. Integrated business functions. Well-suited for high traffic website.

39,999 29,999 (25% off)

Ecommerce Premium

An e-commerce website well-suited for companies having a large portfolio of products. Sell unlimited products. Manage both offline and online sales from one system.

40,000 25,000 (37.5% off)

Ecommerce Business

Launch your online business. Sell up to 5000 products. Collect payment via multiple online and offline payment methods.

35,000 25,000 (28.57% off)

Ecommerce Pro

Get a Mobile friendly online store front. Sell up to 1000 products.

35,000 25,000 (28.57% off)

Ecommerce Starter

Start selling your products online. Scale up as your business grows.

35,000 25,000 (28.57% off)

Website on the Cloud

Custom built, responsive corporate website hosted on the cloud. Mirrored on 3 servers. Includes visitor signup with CRM functions/

19,999 9,999 (50% off)

Website Corporate

Custom built, responsive corporate website with CRM. Our most popular website plan.

19,000 9,000 (52.63% off)

Website Business - 1000 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

18,000 8,000 (55.56% off)

Website Business - 500 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,500 7,500 (57.14% off)

Website Business - 100 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,000 7,000 (58.82% off)

Website Business - 50 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,500 6,500 (60.61% off)

Website Business - 25 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,000 6,000 (62.5% off)

Website Starter - 5 Pages

Get started with your own website at most affordable cost.

15,000 5,000 (66.67% off)


Looking to build a website?
Launch a 5 page website in 1 day at only Rs.499/year. Hosting 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