Posts

Showing posts from June, 2012

Switch statement

Image
We have seen that when we have many alternatives and we have to select one of them, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when number of alternatives increases. To, come out from these situations C has a built-in multiway decision statement known as "switch" . It tests the value of a given variable or expression against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of a switch statement is:-  "switch(expression)    {      case value 1:          block 1          break;      case value 2:          block 2          break;      case value 3:          block 3          break;       ...................       ...................      default:        default statement         break;     }   statement x; " Here values are also called as "Case labels" . Each of the values should be unique within a switc

Decision making using if statement

Image
The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It's a basically two way decision statement and is used in conjuction with an expression. It's syntax is:- "if(test expression)" It allows the computer to evaluate the expression first and then, depending on condition, it transfers the control to a particular statement. This point of program has two paths to follow,one for the true and other for false condition.As shown in figure:-     Practical examples of if statement:- 1. if(bank balance is < 500)     deposit money 2. if(room is dark)     put on lights The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms of if statements are:- 1.Simple if statement 2.if....else statement 3.Nested if....else statement 4. else if ladder 1.Simple if statement.  The general form of simple if statement is

Decision making and branching

We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear. This happens when no options are available. During programming, we have a number of situations where we may have to change the execution of statements on certain conditions, or repeat a group of statements until certain  specified conditions are met. This involves a kind of decision making to see whether a particular condition has occured or not and then  direct the computer to execute certain statements accordingly.  C language supports the following statements to possesses such decision making capabilities.  i)   if statement  ii)  switch statement  iii) Conditional operator statement  iv)  goto statement These statements helps in decision making, so these are called as decision making statements. Also these statements controls the flow of execution ,so they are also known as control statements.