Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

C Programming – Decision Making – Branching

By Exforsys | on April 4, 2006 |
C Language

“Decision making” is one of the most important concepts of computer programming. Programs should be able to make logical (true/false) decisions based on the condition they are in; every program has one or few problem/s to solve; depending on the nature of the problems, important decisions have to be made in order to solve those particular problems.

In C programming “selection construct” or “conditional statement” is used for decision making. Diagram 1 illustrates “selection construct”.

Diagram 1 simple selection construct

Conditional statement is the term used by many programming languages. The importance of conditional statements should not be ignored because every program has an example of these statements. “IF statement” and “switch statement” are the most popular conditional statements used in C.

Branching

Branch is the term given to the code executed in sequence as a result of change in the program’s flow; the program’s flow can be changed by conditional statements in that program. Diagram 2 shows the link between selection (decision making) and branching (acting).

Diagram 2 "branch" depends on the condition of the selection code

Branching is the process of choosing the right branch for execution, depending on the result of “conditional statement”.

If Statement

“If statement” is the selection statement used to select course of action depending on the conditions given. Therefore programmers can use this statement to control the flow of their program. If the program’s condition matches “if statement” condition then the code will be executed otherwise it will be ignored and the rest of the program will be executed.

Definition:

  1.   if (condition) {   code here if “true”}

Tips :

{ } can be removed if only one line of code is to be executed. For example:

  1. If(a==1)
  2. 	Printf(“1”);
  3.  
  4. Instead of:
  5.  
  6. If(a==1)
  7. 	{ printf(“1”); }

Example:

consider the case when we are asked to write a program for exforsys.com where users are asked to give ratings on each article; we want to output different messages depending on the ratings given. Messages are as follow: 1 is bad, 2 is average and 3 is good.

Code :

  1. int rate;
  2.  
  3. printf("Please Enter Rating? 1 for bad , 2 for average and 3 for goodn");
  4. scanf("%d",&rate);
  5.       if(rate==1)
  6. 	{
  7. 	printf("nit is poor");
  8. 	}
  9.       if(rate==2)
  10. 	{
  11. 		printf("nit is average");
  12. 	}
  13.  
  14. 	if(rate==3)
  15. 	{
  16. 		printf("nit is good");
  17. 	}
Figure 1 code 1 screen shot

Description of “code 1”: this code asks user to input in first 3 lines, once the user inputs an integer the program will then checks all the “if statements”. If any of them match the input “rate” then the output for that statement will be printed out. Diagram 3 shows the function of the code 1.

}

The If – Else Construct

“if else construct” is the upgraded version of “if statement”. Unlike “if statement” where you could only specify code for when condition is true; for “if else statement” you can also specify code for when the condition is not True (false). So the definition for the “if else statement” is:

Definition:

if(condition){ code when true } else { code when not true }

Tips :

{ } can be removed if only one line of code is to be executed. For example:

  1. If(a==1)
  2. 	Printf(“1”);
  3. Else
  4. 	Printf(“none”);
  5.  
  6. Instead of:
  7.  
  8. If(a==1)
  9. 	{ printf(“1”); } 
  10. else
  11. 	{ Printf(“none”);}

Example:

imagine the case where we need an input “greater than or equal to 5” and we want to warn the user if they use invalid input (less than 5). We can use the code below:

Code:

  1. int number;
  2.  
  3. 	printf("Please Enter a number greater than or equal to 5?n");
  4. 	scanf("%d",&number);
  5. 	if(number>=5)
  6. 	{
  7. 		printf("nit is valid");
  8. 	}
  9. 	else
  10. 	{
  11. 	    printf("nit is invalid");
  12. 	}

Figure 2 code 2 screenshots

Compound Relational Tests

In order to check the conditions within the programs, C has number of relational operators. The table 1 summarises these operators using variables a=10 and b=5.

==

Is Equal to –
a==a returns 1, a==b returns 0

!=

Not equal to
a!=b returns 1 , a!=a returns 0

> 

Greater than
a>breturns 1 , b>a returns 0
a>10 returns 0, b>5 returns 0

< 

Less than
a<b returns 0 , b<a returns 1
a<10 returns 0, b<5 returns 0

>=

Greater than or equal to
a>=10 returns 1 , b>=5 return 1

<=

Less than or equal to
a<=10 returns 1 , b<=5 return 1

Table 1 relational operators

Tips:

Relational operators can only compare two variables, for example: ‘a==a’ is correct, ‘a==a==b’ is incorrect syntax.

‘Logical operators’ are used in conditional statements such as ‘if statement’ to create a single testing condition. However some conditional statements require more than one testing conditions. For example: if we are asked to write program which output the word “yes” if the user’s input value is between 4 and 8 including number 8, we obviously can’t program this condition using only one testing condition; therefore we require logical operators to link those conditions. There are three logical operators: ‘!’,‘&&’ and ‘||’.

‘&&’ denotes to an operation of logical AND gate. ‘||’ denotes to an operation of logical OR gate. Table 2 and 3 describe the behaviour of && and || respectively.

Condition A

Condition B

Result

0

0

0

0

1

0

1

0

0

1

1

1

Table 2 && operation

Condition A

Condition B

Result

0

0

0

0

1

1

1

0

1

1

1

1

Table 3 || operation

Example #1: using && operator

Here we will refer back to the example we had before. We want to write a program which outputs “yes” if the user’s input is between 4 and 8 (including number 8). In order to write this we have to program the following condition in our ‘if statement’.

Input is greater than 4 AND less than or equal to 8.

Condition A                Condition B

As you can see above, we have two conditions for our ‘if statement’; so we need to separate these two conditions in order to program the conditions in C.

Condition A is ‘greater than 4’; we program this in C assuming that the variable ‘A’ is the user input, now we have:

Condition A: A>4

We do the same for the second condition and we get:

Condition B: A<=8

Our two conditions are ready. We need to link them together using logical operators. For this example we need to use && operator. Therefore our final condition becomes (A>4 && A<=8).

Code:

  1. int A;
  2.  
  3. printf("Please Enter a number greater than  4 and less than or equal to 8?n");
  4. scanf("%d",&A);
  5. if(A>4 && A<=8)
  6. {
  7. 	printf("nyes");
  8. }
Figure 3 code 3

Description:

We have evaluated the written description of the problem and we produced the C code from that. As you can see above, the testing condition “A>4 && A<=8” is the same as mathematical expression “4

Hints:

Be extra careful with the way you format your conditions together. Using brackets to separate each condition from another is the best practice to avoid confusions for complex testing conditions. For example: we can write “A>4 && A<=8” as “(A>4) && (A<=8)”.

{mospagebreak}

Nested if Statement

Using “if…else statement” within another “if…else statement” is called ‘nested if statement’. “Nested if statements” is mainly used to test multiple conditions. They can be structured using following syntax:

  1. If(conditionA)
  2. 	{
  3. 	Statements
  4. 	}
  5. Else if (conditionB)
  6. 	{
  7. 	statementB
  8. 	}
  9. Else 
  10. 	{
  11. 	statement
  12. 	}

Example #1:

Consider the case that you are asked to program a university marking system which identifies student’s grade on response to user input. Here is how grades should be grouped: 40+ E, 50-59 D , 60-69 C , 70-79 B , 80+ A

Code:

  1. int Mark;
  2. 	printf("Please Enter the grade between 0-100?n");
  3. 	scanf("%d",&Mark);
  4. 	if(Mark >= 40 && Mark <50)
  5. 	{
  6. 		printf("your grade is E n");
  7. 	}
  8. 	else if(Mark>=50 && Mark<60)
  9. 	{
  10. 		printf("Your grade is D n");
  11. 	}
  12. 	else if(Mark>=60 && Mark<70)
  13. 	{
  14. 		printf("Your grade is C n");
  15. 	}
  16. 	else if(Mark>=70 && Mark<80)
  17. 	{
  18. 		printf("Your grade is B n");
  19. 	}
  20. 	else if(Mark>=80 && Mark<90)
  21. 	{
  22. 		printf("Your grade is A n");
  23. 	}else
  24. 		printf("you have failed");

Figure 4 code 4 screenshot

Description:

This code checks from lowest boundary and checks for every grade, once one of conditions matches the mark the remaining conditions will be ignored. If none of the conditions match, it will then print out the message “you have failed”.

The Switch Statement

“Switch statement” is another type of “conditional statement” used by programmers. Switch is widely used for menus.

  1. Switch (variable)
  2. 	{
  3. 	Case 1: statement1 break;
  4. 	Case 2: statement 2 break;
  5. 	Case 3:statement 3 break;
  6. 	.
  7. 	.	
  8. 	.
  9. 	Default: default statement break;
  10. 	}

Tips:

“break” statement is very important. If it is not used properly all the code after the matched condition will be executed incorrectly. For example: looking at syntax 4; if the break for case 2 was missing, all the codes after and including case 2 would be executed until the next break statement was reached.

Example #1:

This example will cover a very basic character based menu that responds to a , b, c and d; it also warns the user if any other characters are used.

Code:

  1. char response;
  2. 	printf("Please Enter a,b,c or d?n");
  3. 	scanf("%c",&response);
  4.  
  5. 	1:switch(response)
  6. 	{
  7. 	2:case 'a': printf("you have inputed 'a'"); break;
  8. 	3:case 'b': printf("you have inputed 'b'"); break;
  9. 	4:case 'c': printf("you have inputed 'c'"); break;
  10. 	5:case 'd': printf("you have inputed 'd'"); break;
  11. 	6:default: printf("unrecognised character"); break;
  12.  
  13. 	}

Figure: 5 simple menu

Description:

“statement 1” indicates that “switch” will be applied on ‘response’. “Statement 2” defines the action needed in case ‘response’ is holding the value of ‘a’. “statement 3,4,5” define action in case ‘response’ is holding value of ‘b’, ’c’ or ‘d’ respectively. “Statement 6” is defining the action needed if none of the cases meet the conditions.

About this tutorial

All codes presented in this tutorial are snippets therefore they will not work unless they are put into acceptable structure. Acceptable structure includes stdio.h library( or any other relevant library) and main() function in the program. All the snippets in this tutorial are tested by Microsoft Visual C++ Express 2010.

« « Working with CSS Units, Colors and References
C Programming – Decision Making – Looping » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • C Programming – Constants and Identifiers

    March 2, 2006 - 0 Comment
  • C Programming – Structures and Unions

    May 25, 2006 - 0 Comment
  • C Programming – Data Types : Part 1

    March 7, 2006 - 0 Comment
  • C Programming – Pointers

    May 25, 2006 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Programming – Dynamic Memory allocation

    May 29, 2006 - 0 Comment
  • C Programming – Operators

    March 30, 2006 - 0 Comment
  • C Programming – Linked Lists

    May 29, 2006 - 0 Comment
  • C Programming – Expressions

    March 30, 2006 - 0 Comment
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • Call by Value and Call by Reference

    July 6, 2006 - 0 Comment
  • C Language – The Preprocessor

    May 31, 2006 - 0 Comment
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Linked Lists

    May 29, 2006 - 0 Comment
  • C Programming – Dynamic Memory allocation

    May 29, 2006 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • C Programming – Data Types : Part 2
  • C Circular Linked Lists
  • C Doubly Linked Lists
  • TSR in C – An Introduction
  • Concept of Pixel in C Graphics

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT