A nested statement block

Similar documents
9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Sources: On the Web: Slides will be available on:

Two-way selection. Branching and Looping

arrays C Programming Language - Arrays

Informatica e Sistemi in Tempo Reale

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Selection Statements

1.6 The Order of Operations

Writing Control Structures

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Playing with Numbers

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Lecture 2 Notes: Flow of Control

13 Classes & Objects with Constructors/Destructors

Order of Operations More Essential Practice

Performing Simple Calculations Using the Status Bar

So far we have considered only numeric processing, i.e. processing of numeric data represented

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)

26 Integers: Multiplication, Division, and Order

6. Control Structures

Chapter 5 Names, Bindings, Type Checking, and Scopes

MULTIPLICATION AND DIVISION OF REAL NUMBERS In this section we will complete the study of the four basic operations with real numbers.

Tutorial on C Language Programming

Java Interview Questions and Answers

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Conditionals (with solutions)

SAT Math Facts & Formulas Review Quiz

2. Capitalize initial keyword In the example above, READ and WRITE are in caps. There are just a few keywords we will use:

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Binary Representation. Number Systems. Base 10, Base 2, Base 16. Positional Notation. Conversion of Any Base to Decimal.

Years after US Student to Teacher Ratio

Using Casio Graphics Calculators

Client Marketing: Sets

Chapter One Introduction to Programming

The C Programming Language course syllabus associate level

Binary Adders: Half Adders and Full Adders

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

Chapter 5. Selection 5-1

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

I PUC - Computer Science. Practical s Syllabus. Contents

Properties of Real Numbers

Introduction to Python

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Visual Logic Instructions and Assignments

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

PHP Debugging. Draft: March 19, Christopher Vickery

Organizing an essay the basics 2. Cause and effect essay (shorter version) 3. Compare/contrast essay (shorter version) 4

Chapter 8 Selection 8-1

Creating a table of contents quickly in Word

WRITING PROOFS. Christopher Heil Georgia Institute of Technology

How to Format a Bibliography or References List in the American University Thesis and Dissertation Template

Multiplying and Dividing Signed Numbers. Finding the Product of Two Signed Numbers. (a) (3)( 4) ( 4) ( 4) ( 4) 12 (b) (4)( 5) ( 5) ( 5) ( 5) ( 5) 20

Reading 13 : Finite State Automata and Regular Expressions

Conditions & Boolean Expressions

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Adding and Subtracting Positive and Negative Numbers

Tom wants to find two real numbers, a and b, that have a sum of 10 and have a product of 10. He makes this table.

03 - Lexical Analysis

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

Exercise 4 Learning Python language fundamentals

Object Oriented Software Design

JavaScript: Control Statements I

1(a). How many ways are there to rearrange the letters in the word COMPUTER?

Basics of I/O Streams and File I/O

Q&As: Microsoft Excel 2013: Chapter 2

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Moving from CS 61A Scheme to CS 61B Java

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

3.GETTING STARTED WITH ORACLE8i

ECE 122. Engineering Problem Solving with Java

6.080/6.089 GITCS Feb 12, Lecture 3

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.

Section 4.1 Rules of Exponents

Click on the links below to jump directly to the relevant section

23. RATIONAL EXPONENTS

Introduction to Python

Object Oriented Software Design

COMP 110 Prasun Dewan 1

Pseudo code Tutorial and Exercises Teacher s Version

Fundamentals of Programming

Exponents. Exponents tell us how many times to multiply a base number by itself.

2 SYSTEM DESCRIPTION TECHNIQUES

1 Description of The Simpletron

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Negative Integral Exponents. If x is nonzero, the reciprocal of x is written as 1 x. For example, the reciprocal of 23 is written as 2

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

Transcription:

M5.1: Code Block/ Statement Block/ Block : In computer programming, a statement block (or code block) is a section of code which is grouped together, much like a paragraph; such blocks consist of one, or more, statements. Statement blocks help make code more readable by breaking up programs into logical work units. In C, C++, Java and some other languages, statement blocks are enclosed by curly braces. In Algol, Pascal, Ada, and some other languages, they are denoted by "begin" and "end" statements. Unlike paragraphs, statement blocks can be nested; that is, with one block inside another. Blocks often define the scope of the identifiers used within. Blocks can be used anywhere a single statement is allowed. A typical statement block int main() return 0; A nested statement block int main() int x = 1; if (x == 1) x++; return 0; Page 1

M5.2: Control Statements : By default the instructions in a program are executed sequentially. Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction. C language possesses such decision-making capabilities by supporting the following statements: if Statement switch Statement Conditional operator statement goto Statement These statements are popularly known as decision-making statements. Since these statements control the flow of execution, they are also known as control statements. M5.3: Decision Making with if statement : The general form of if statement looks like this: Page 2 if ( this condition is true ) execute this statement ; The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if, is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. Now we will discuss some forms of if statement: M5.3.1: Simple if statement : The general form of a simple if statement is: if (test expression) statement-block ; statement-x ; The statement-block may be a single statement or a group of statements. If the test expression is true, the statement-block will be executed; otherwise the statementblock will be skipped and the execution will jump to the statement-x. Remember,

when the condition is true both the statement-block and the statement-x are executed in sequence. Also note that when there is only one statement in statement-block, then it is not necessary to put it in code block, you can directly put that statement after the test expression. Now the upper program would be as follows: if (test expression) statement-block ; statement-x ; Note that there is no difference between upper form and this form of if statement. The result will be same for both. Here is a simple program, which demonstrates the use of if and the relational operators. Example M5.1 /* Demonstration of if statement */ int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "\n The entered number is less than or equal to 10." ) ; On execution of this program, if you type a number less than or equal to 10, you get a message on the screen through printf( ). If you type some other number the program doesn t do anything. Truly speaking the general form is as follows: if ( expression ) statement ; Here the expression can be any valid expression including a relational expression. We can even use arithmetic expressions in the if statement. For example all the following if statements are valid: Page 3

if ( 3 + 2 % 5 ) printf ( "This works" ) ; if ( a = 10 ) printf ( "Even this works" ) ; if ( -5 ) printf ( "Surprisingly even this works" ) ; Note that in C a non-zero value is considered to be true, whereas a 0 is considered to be false. In the first if, the expression evaluates to 5 and since 5 is non-zero it is considered to be true. Hence the printf( ) gets executed. In the second if, 10 gets assigned to a so the if is now reduced to if(a) or if(10). Since 10 is non-zero, it is true hence again printf( ) goes to work. In the third if, -5 is a non-zero number, hence true. So again printf( ) goes to work. In place of -5 even if a float like 3.14 were used it would be considered to be true. So the issue is not whether the number is integer or float, or whether it is positive or negative. Issue is whether it is zero or non-zero. Example M5.2 Q. -> WAP to print whether a person is eligible for casting vote. #include <stdio.h> int age ; printf( Enter your age: ) ; scanf( %d, &age) ; if (age >= 18) printf( \n You are eligible to cast vote. ) ; getch( ) ; Output: Enter your age: 23 You are eligible to cast vote. Page 4

M5.3.2: if- statement : The if. statement is an extension of the simple if statement. The general form is: if (test expression) True-block statement(s) False-block statement(s) statement-x If the test expression is true, then the true-block statement(s), immediately following the if statement are executed; otherwise, the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both. In both cases, the control is transferred subsequently to the statement-x. Here is a simple program, which is very similar to the example M5.1. Example M5.3 /* Demonstration of if- statement */ int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "\n The entered number is less than or equal to 10." ) ; printf ( \n The entered number is something. ); On execution of this program, if you type a number less than or equal to 10, you get a message on the screen through printf( ), that is under if statement. If you type some other number, you get a message on the screen through printf( ), that is under statement. Page 5

Example M5.4 Q. -> WAP to check whether a given no. is even or odd. #include <stdio.h> #include <conio.h> int a ; clrscr( ) ; printf( Enter a number : ) ; scanf( %d, &a) ; if(a % 2 == 0) printf( Given number is even ) ; printf( Given number is odd ) ; getch( ) ; Output: Enter a number : 13 Given number is odd. In the above program condition given with if evaluated as false hence statements given under will be executed. Q. -> WAP to find the maximum value from two given values. #include <stdio.h> #include <conio.h> int a, b ; clrscr( ) ; printf( Enter two numbers: ) ; scanf( %d %d, &a, &b ) ; if( a > b ) Example M5.5 Page 6

printf( \n First number is bigger ) ; printf( \n Second number is bigger ) ; getch( ) ; Output: Enter two numbers: 20 10 First number is bigger. Example M5.6 Q. -> WAP to check whether a inputted character is vowel or consonant. #include <stdio.h> #include <conio.h> char ch ; clrscr( ) ; printf( Enter a character : ) ; scanf( %c, &ch) ; if( ch == a ch == e ch == i ch == o ch == u ) printf ( \n entered character is vowel. ) ; printf( \n entered character is consonant. ) ; getch( ) ; Output: Enter a character: i entered character is vowel. Example M5.7 Q. -> WAP to calculate the net bill amount on the basis of following: If bill > 500 discount = 25% of bill Otherwise discount = 5% of bill Page 7

#include <stdio.h> #include <conio.h> float bill, dis, net ; clrscr( ) ; printf( Enter bill amount : ) ; scanf( %d, &bill ) ; if(bill > 500) dis = bill *.25 ; dis = bill *.05 ; net = bill dis ; printf( \n discount is \t %f, dis ) ; printf( \n net amount is \t %f, net ) ; getch( ) ; Output: Enter bill amount : 1000 discount is 250 net amount is 750 Q. -> WAP to check whether inputted year is leap year or not. #include <stdio.h> #include <conio.h> Example M5.8 int year ; clrscr( ) ; printf( Enter year : ) ; scanf( %d, &year) ; if ( year % 4 == 0 ) printf( \n entered year is leap. ) ; printf( \n entered year is not leap. ) ; getch( ) ; Output: Enter year : 2000 entered year is leap. Page 8

M5.3.3: Nested if- statement : It is perfectly all right if we write an entire if- construct within either the body of the if statement or the body of an statement. This is called nesting of if s. This is shown in the following program. Q. -> WAP to find the largest value from given three values. #include <stdio.h> #include <conio.h> float a, b, c ; clrscr( ) ; printf( Enter three values \n ) ; scanf( %f %f %f, &a, &b, &c) ; printf ( \n Largest value is : ) ; if (a>b) if (a>c) printf( %f \n, a ) ; printf( %f \n, c) ; if (c>b) printf( %f \n, c ) ; printf( %f \n, b) ; Output: Example M5.9 Enter three values : 15.5 18.2 10.0 Largest value is : 18.2 In the above program an if- occurs within the block of the first if statement. Similarly, in some other program an if- may occur in the if block as well. There is no limit on how deeply the if s and the s can be nested. Page 9

M5.3.4: if- if ladder : There is another way of putting if s together when multipath decisions are involved. A multipath decision is a chain of if s in which the statement associated with each is an if. It takes the following form: if (condition 1) statement-1; if (Condition 2) statement-2; if (condition 3) statement-3; if (condition n) statement-n; default-statement; statement-x; This construct is known as the if ladder. The conditions are evaluated from the top (of the ladder) to downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of the ladder). When all the n condition become false, then the final containing the default statement will be executed. Here is a simple program, which demonstrates the use of if ladder: Example M5.10 #include <stdio.h> #include <conio.h> int m1, m2, m3, m4, m5, per ; printf( Enter five subject s marks \n ) ; scanf( %d %d %d %d %d, &m1, &m2, &m3, &m4, &m5) ; per = ( m1+ m2 + m3 + m4+ m5 ) / 500 ; if ( per >= 60 ) printf ( "\n First division" ) ; if ( per >= 50 ) printf ( "\n Second division" ) ; if ( per >= 40 ) printf ( "\n Third division" ) ; printf ( "fail" ) ; Page 10

Note that the if clause is nothing different. It is just a way of rearranging the with the if that follows it. This would be evident if you look at the following code: if ( i == 2 ) if ( i == 2 ) printf ( "With you " ) ; printf ( "With you " ) ; if ( j == 2 ) printf ( " All the time " ) ; if ( j == 2 ) printf ( " All the time" ) ; Now, Let s take a journey of a little summary of various forms of if s: Forms of if: The if statement can take any of the following forms: (a) if ( condition ) (b) if ( condition ) and this ; (c) if ( condition ) (d) if ( condition ) and this ; and this ; Page 11

(e) if ( condition ) if ( condition ) and this ; (f) if ( condition ) if ( condition ) and this ; (g) if (condition 1) statement-1; if (Condition 2) statement-2; if (condition 3) statement-3; if (condition n) statement-n; default-statement; Page 12

M5.4: Use of Logical Operators with if statement : C allows usage of three logical operators, namely, &&, and! These are to be read as AND OR and NOT respectively. The first two operators, && and, allow two or more conditions to be combined in an if statement. Let us see how they are used in a program. Consider the following example, which is much same as example M5.10, but it uses logical operators: Example M5.11 #include <stdio.h> #include <conio.h> int m1, m2, m3, m4, m5, per ; clrscr( ) ; printf( Enter five subject s marks \n ) ; scanf( %d %d %d %d %d, &m1, &m2, &m3, &m4, &m5) ; per = ( m1+ m2 + m3 + m4+ m5 ) / 500 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; As can be seen from the second if statement, the && operator is used to combine two conditions. Second division gets printed if both the conditions evaluate to true. If one of the conditions evaluate to false then the whole thing is treated as false. Example M5.12 Write a program to calculate the salary as per the following table: Page 13

#include <stdio.h> #include <conio.h> char g ; int yos, qual, sal ; clrscr( ) ; printf ( "Enter Gender, Years of Service and Qualifications ( 0 = G, 1 = PG ):" ) ; scanf ( "%c %d %d", &g, &yos, &qual ) ; if ( g == 'm' && yos >= 10 && qual == 1 ) sal = 15000 ; if (( g == 'm' && yos >= 10 && qual == 0 ) ( g == 'm' && yos < 10 && qual == 1 ) ) sal = 10000 ; if ( g == 'm' && yos < 10 && qual == 0 ) sal = 7000 ; if ( g == 'f' && yos >= 10 && qual == 1 ) sal = 12000 ; if ( g == 'f' && yos >= 10 && qual == 0 ) sal = 9000 ; if ( g == 'f' && yos < 10 && qual == 1 ) sal = 10000 ; if ( g == 'f' && yos < 10 && qual == 0 ) sal = 6000 ; printf ( "\n Salary of Employee = %d", sal ) ; Page 14

The! operator: The third logical operator is the NOT operator, written as! This operator reverses the result of the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying! operator to it makes it 1, a non-zero value. The final result (after applying!) 0 or 1 is considered to be false or true respectively. Here is an example of the NOT operator applied to a relational expression.! ( y < 10 ) This means not y less than 10. In other words, if y is less than 10, the expression will be false, since (y<10) is true. We can express the same condition as (y>= 10). The NOT operator is often used to reverse the logical value of a single variable, as in the expression if (! flag ) This is another way of saying if ( flag == 0 ) M5.5: A word of caution : Caution 1 #include <stdio.h> #include <conio.h> int i ; printf ( "Enter value of i " ) ; scanf ( "%d", &i ) ; if ( i = 5 ) printf ( "You entered 5" ) ; printf ( "You entered something other than 5" ) ; And here is the output of two runs of this program... Enter value of i 200 You entered 5 Enter value of i 9999 You entered 5 Page 15

Explanation: This is because we have written the condition wrongly. We have used the assignment operator = instead of the relational operator ==. As a result, the condition gets reduced to if(5), irrespective of what you supply as the value of i. And remember that in C truth is always non-zero, whereas falsity is always zero. Therefore, if(5) always evaluates to true and hence the result. Caution 2 #include <stdio.h> #include <conio.h> int i ; clrscr( ) ; printf ( "Enter value of i " ) ; scanf ( "%d", &i ); if ( i == 5 ) ; printf ( "You entered 5" ) ; And here is the output of two runs of this program... Enter value of i 200 You entered 5 Enter value of i 9999 You entered 5 Explanation: The ; makes the compiler to interpret the statement as if you have written it in following manner: if ( i == 5 ) ; printf ( "You entered 5" ) ; Here, if the condition evaluates to true the ; (null statement, which does nothing on execution) gets executed, following which the printf( ) gets executed. If the condition fails then straightaway the printf( ) gets executed. Thus, irrespective of whether the condition evaluates to true or false the printf( ) is bound to get executed. Remember that the compiler would not point out this as an error, since as far as the syntax is concerned nothing has gone wrong, but the logic has certainly gone awry. Page 16

M5.6: Indentation : When using control structures, a statement often controls many other statements that follow it. In such situations it is a good practice to use indentation to show that the indented statements are dependent on the preceding controlling statement. Some guidelines that could be followed while using indentation are listed below: Indent statements that are dependent on the previous statements; provide at least three spaces of indentation. Align vertically clause with their matching if clause. Use braces on separate lines to identify a block of statements. Indent the statements in the block by at least three spaces to the right of the braces. Align the opening and closing braces. Use appropriate comments to signify the beginning and end of blocks. Indent the nested statements as per the above rules. Code only one clause of statement on each line. M5.7: The Conditional Operator (?:) : The conditional operator?: is sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-. Their general form is: Conditional-Expression? expression1 : expression2 What this expression says is: if conditional-expression is true (that is, if its value is non-zero), then the value returned will be expression1, otherwise the value returned will be expression2. Let us understand this with the help of a few examples: (a) int x, y ; scanf ( "%d", &x ) ; y = ( x > 5? 3 : 4 ) ; This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y. The equivalent if statement will be, if ( x > 5 ) y = 3 ; y = 4 ; Page 17

(b) char a ; int y ; scanf ( "%c", &a ) ; y = ( a >= 65 && a <= 90? 1 : 0 ) ; Here 1 would be assigned to y if a >=65 && a <=90 evaluates to true, otherwise 0 would be assigned. The following points may be noted about the conditional operators: (a) It s not necessary that the conditional operators should be used only in arithmetic statements. This is illustrated in the following examples: Ex.: int i ; scanf ( "%d", &i ) ; ( i == 1? printf ( "Suraj Arora" ) : printf ( "All and sundry" ) ) ; Ex.: char a = 'z' ; printf ( "%c", ( a >= 'a'? a : '!' ) ) ; (b) The conditional operators can be nested as shown below. int big, a, b, c ; big = ( a > b? ( a > c? 3: 4 ) : ( b > c? 6: 8 ) ) ; The limitation of the conditional operators is that after the? or after the : only one C statement can occur. In practice rarely is this the requirement. Therefore, in serious C programming conditional operators aren t as frequently used as the if-. M5.8: The switch Statement : The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows: switch ( integer expression ) case constant1 : case constant2 : case constant3 : default : Page 18

The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The do this lines in the above form of switch represent any valid C statement(s). What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. A few examples will show how this control structure works. Consider the following program: #include <stdio.h> #include <conio.h> Example M5.13 int i = 2 ; switch ( i ) case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; Output: Page 19 I am in case 2 I am in case 3 I am in default

The break statement: There is a need of break statement after each case. The break statement at the end of each block signal the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch. Now take the upper example with break statement: Example M5.14 #include <stdio.h> #include <conio.h> int i = 2 ; switch ( i ) case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; Output: I am in case 2 The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x directly. Page 20

Tips for using Switch: (a) The earlier program that used switch may give you the wrong impression that you can use only cases arranged in ascending order, 1, 2, 3 and default. You can in fact put the cases in any order you please. Here is an example of scrambled case order: int i = 22 ; switch ( i ) case 121 : printf ( "I am in case 121 \n" ) ; case 7 : printf ( "I am in case 7 \n" ) ; case 22 : printf ( "I am in case 22 \n" ) ; default : printf ( "I am in default \n" ) ; The output of this program would be: I am in case 22 (b) You are also allowed to use char values in case and switch as shown in the following program: char c = 'x' ; switch ( c ) case 'v' : printf ( "I am in case v \n" ) ; case 'a' : printf ( "I am in case a \n" ) ; Page 21

case 'x' : printf ( "I am in case x \n" ) ; default : printf ( "I am in default \n" ) ; The output of this program would be: I am in case x In fact here when we use v, a, x they are actually replaced by the ASCII values (118, 97, 120) of these character constants. (c) At times we may want to execute a common set of statements for multiple cases. How this can be done is shown in the following example. char ch ; printf ( "Enter any of the alphabet a, b, or c " ) ; scanf ( "%c", &ch ) ; switch ( ch ) case 'a' : case 'A' : printf ( "a as in ashar" ) ; case 'b' : case 'B' : printf ( "b as in brain" ) ; case 'c' : case 'C' : printf ( "c as in cookie" ) ; default : printf ( "wish you knew what are alphabets" ) ; Page 22

Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it doesn t encounter a break statement. That is why if an alphabet a is entered the case a is satisfied and since there are no statements to be executed in this case the control automatically reaches the next case i.e. case A and executes all the statements in this case. (d) Even if there are multiple statements to be executed in each case there is no need to enclose them within a pair of braces (unlike if, and ). (e) Every statement in a switch must belong to some case or the other. If a statement doesn t belong to any case the compiler won t report an error. However, the statement would never get executed. For example, in the following program the printf( ) never goes to work. int i, j ; printf ( "Enter value of i" ) ; scanf ( "%d, &i ) ; switch ( i ) printf ( "Hello" ) ; case 1 : j = 10 ; case 2 : j = 20 ; (f) If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any,) that follows the closing brace of switch. (g) Is switch a replacement for if? Yes and no. Yes, because it offers a better way of writing programs as compared to if, and no because in certain situations we are left with no choice but to use if. The disadvantage of switch is that one cannot have a case in a switch which looks like: case i <= 20 : Page 23

All that we can have after the case is an int constant or a char constant or an expression that evaluates to one of these constants. Even a float is not allowed. The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable. (h) We can check the value of any expression in a switch. Thus the following switch statements are legal. switch ( i + j * k ) switch ( 23 + 45 % 4 * k ) switch ( a < 4 && b > 7 ) Expressions can also be used in cases provided they are constant expressions. Thus case 3 + 7 is correct, however, case a + b is incorrect. (i) The break statement when used in a switch takes the control outside the switch. However, use of continue will not take the control to the beginning of switch as one is likely to believe. (j) In principle, a switch may occur within another, but in practice it is rarely done. Such statements would be called nested switch statements. (k) The switch statement is very useful while writing menu driven programs. (l) The break statement is optional, that is, two or more case labels may belong to the same statement. (m) The default label is optional. If present, it will be executed when the expression does not find a matching case label. There can be at most one default label. (n) The default may be placed anywhere but usually placed at the end. If the default is not placed in the end, then we must place break statement at the end of default case. switch Versus if- Ladder There are some things that you simply cannot do with a switch. These are: (a) A float expression cannot be tested using a switch. (b) Cases can never have variable expressions (for example it is wrong to say case a+3: ) Page 24

(c) Multiple cases cannot use same expressions. Thus the following switch is illegal: switch ( a ) case 3 :... case 1 + 2 :... Your Turn : Q.1: Find error, if any, in each of the following segments: (a) if( x + y = z && y > 0) printf( ); (b) if( code > 1); a = b + c a = 0 (c) if (p < 0) (q < 0) printf( Sign is negative ); (d) if(x >= 10 ) then printf( \n ); (e) if x >= 10 printf ( OK ); (f) if( x = 10) printf( Good ); (g) if( x =< 10) printf( welcome ); Q.2: Rewrite each of the following without using compound relations: (a) if( grade <= 59 && grade >= 50) second = second + 1; Page 25

(b) if( number > 100 number < 0) printf( Out of range ); sum = sum + number; (c) if ( ( M1 > 60 && M2 > 60 ) T > 200) printf ( Admitted \n ); printf( Not Admitted\n ); Q.3: Write a program to determine whether a given number is odd or even and print the message: NUMBER IS EVEN or NUMBER IS ODD (a) without using option, and (b) with option. Q.4: Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters. Q.5: Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and. Note: Leap years are years with an extra day (February 29); this happens almost every four years. Generally, leap years are divisible by four. Q.6: Find the absolute value of a number entered through the keyboard. Page 26