0% found this document useful (0 votes)
3 views36 pages

Chapter 9 Conditional Constructs in Java

The document provides an overview of programming constructs in Java, focusing on conditional or selection statements such as 'if', 'if-else', and 'switch'. It explains the concepts of sequence, selection, and iteration constructs, detailing how they control the flow of execution in a program. Additionally, it includes examples and syntax for implementing these constructs in Java programming.

Uploaded by

celinejohncruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Chapter 9 Conditional Constructs in Java

The document provides an overview of programming constructs in Java, focusing on conditional or selection statements such as 'if', 'if-else', and 'switch'. It explains the concepts of sequence, selection, and iteration constructs, detailing how they control the flow of execution in a program. Additionally, it includes examples and syntax for implementing these constructs in Java programming.

Uploaded by

celinejohncruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Chapter O1 on 92 93 94 95 96 97 98 Introduction Programming Constructs Conditional Or Selection Statements in Java The if’ Statement of Java Nested if Statement The ?: Alternative to if The switch Statement The switch vs. if else Statement Conditional Constructs in Java CHAPTER 9.1 INTRODUCTION Every programming language provides some constructs which are necessary for it to be called as a programming language. Let us talk about these programming. constructs briefly, before talking about selection statements. 11 xc 172 6 COMPUTER APPLICATIONS-IX Ho2 Programming Constructs USO aNy is hee bees In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration. Let us discuss what is meant by sequence, selection or iteration constructs. + Sequence. The sequence construct means the statements are being Seecuted een "This represents the default How of stateme ent (see Fig 9.1). Every Java function execution begins with its first statement. Each statement in turn is executed (sequence construct). When the final statement of the function is executed, the function is done. This construct specifies the normal flow of control in a function and is the Figure 9.1 0 The sequence construct. simplest one. Selection, The selection construct means the execution of statement(s) depending upon a condition-test, If a condition evaluates to true, a course-of-action (a set ‘of statements) is sg _fllowed eerie another courseaaction( ‘different set of statements) if followed. This x Construct (selection construct) is also called decision construct because it helps in making Yo; decision about which set-of-statements is to be executed. Following figure [Fig. 9.2(a)] explains selection construct. { ne course-of-setion —~= 0" && ch <= ‘o) [Link] (“It is a digtt.”) ; ‘The above example reads a character. If the character input is a space, it flashes a message specifying it. If the character input is a digit it flashes a message specifying it. The following example also makes use of an if statement. if (A> 10 8&B < 15) { C=(A-B)* (A+B); ‘[Link] (“The result is” + C) j 3 i ‘The above example uses a compound statement (or a block) in the body of if {All the examples of if'you have seen so far allow you to execute a set of statements if a condition or expression evaluates to true, Whatf there is another course of action to be followedl if the expression evaluates to false. There is another form of if that allows for this kind of tither-or condition by providing an else clause. The syntax ofthe if-else statement is the following if (expression) statement 1 els statement 2 ; If the expression evaluates to true ie, a non-zero value, the slafement-1 is execute Sfatement.2 is executed, The slatement-1 and statement-2 can be a single statement, or a compound statement, or a null statement. Following figure (Fig, 9.4) illustrates if and if-else constructs of Java. Remember, in an if-else 1 ‘ statement, only the code a Test ~ Test ~ associated with if (Le, << Expression >-22® >! Body of ee 1 statement-1) or the code See 2 associated with else (ie, statement-2) | Tue wwe | ‘executes, never both. Body of if Body of apeamr a Coors (a) (b) Figure 9.4 (a) The if statement's operation (b) The if-else statement’s operation. CONDITIONAL CONSTRUCTS IN JAVA 75 cempound stolimot? = Block of Statements The general syntax of if-else allows us to have only a single statement in the if-part (or the else-part). If we want to execute more than one statement in if-part or else-part, we can use a block of statements. A block of statements groups several statements in a single composite statement as per following oe X. The statements in the block are enclosed in curly-braces and executed in sequence. { Java statement Java statement Peo Block of statements are enclosed in curly-braces > For example, consider the following code : int a, b, larger ; Block is shown here shaded if(a>b)| £ larger = a; 4 ‘[Link]("Smalier number is = ” + b) ; 2; In an if-statement, a block may appear in if-part or else-part or in both. Following example programs illustrate the syntax and working of if and if-else statements. Program 9.1 Write a program to compare two given numbers and display which of them is greater or whether they are equal public class CompareTwoNumbers { public static void main(String{] args) { Int num1 = 877 ; Int num2 = 534 ; if(num1 > numa) { ‘[Link](num1 +“ is greater than” + num2) ; + if(numi A number is divisible by 2if the number is ending in an even digit 0, 2, 4,6 or 8. = A number is divisible by 4 if last 2 digits of the number are divisible by 4. = Annumber is divisible by 5 if the number is ending in 0 or 5. import [Link]. Scanner ; public class DivisiblityTest { public static void main(String argstl ) qi Scanner sc = new Scanner(System:in) ; boolean divby2 = false, divby4 = false divby5 = false | int number, lastDigit, last2Digits ; system. [Link](*enter an Integer +” number = [Link]() ; lastDigit = number %10 j Jast2Digits = number % 100 ; CONDITIONAL CONSTRUCTS IN JAVA if (astDigit == 0 || lastDigit == 2 || lastDigit == 4 || lastDigit == 6 || lastDigit divby2 = true ; if (lastDigit == 0 || lastDigit == 5) divby5 = true ; if (last2Digits % 4 divby4 = true ; if (divby. rue && divby4 == true && divby5 == true) [Link](number + "is divisible by all 2, 4 and 5") ; else ‘[Link](number + "is NOT divisible by all 2, 4 and 5") ; 0) : Output produced is: Enter an integer : 840 es 840 is divisible by all 2, 4 and 5 Enter an integer : 844 2 844 is Nor divisible by all 2, 4 and 5 rogram 9.4 Temperature-conversion program that gives the user the option of converting Fahrenheit to Celsius or Celcius to Fahrenheit and depending upon user's choice carries out the conversion. User can choose to execute desired function. public class Temperature { public void tempConversion(int choice) { // 1 for -C to -F and 2 for vice versa // temp to be converted is 98.4-F or 37-C double tempC, tempF ; if (choice == 1) { tempC = 37; // converting 37°C to °F tempF = (tempt *1.8F) +32; [Link](*Temperature in Fahrenheit is” + tempF); 2 else if (choice == 2) {temp = 98.4; // converting 98.4°F to °C tempC = (tempF - 32) / 1.8F; ‘[Link](“Temperature in Celsius is” + tempC); + else ‘[Link]("Enter 1 for C- to -F and 2 for F- to -C conversion”); + Output produced is = x Temperature in Fahrenheit is 98.59999823570251 ‘Temperature in Celsius is 36.88888986611075 mx 1738 COMPUTER APPLICATIONS-IX 9:5 Nested if Statement So now you know that if the condition specified with if statement evaluates to true, then the control enters in if part, and if it evaluates to false then the control enters in else-part. In other words, the statements of if-part will get executed if the condition is true otherwise statements of else-part will get executed. Sometimes, within if statement (if-part or else-part) you need to test another condition. For this, you can write another if inside if-partor else-part or in both depending upon theneed. When you have another if statement inside the if-part or else-part of another if itis called nested if. Programs 9.5 and 9.6 use a nested if . a ' fement | (a) Nested if inside if-part (0) Nested if inside ‘Statement 1 ‘ ee ' ' eee | eee § Statement 1 =, 5 cae it-part and else-part Figure 9.5 Nested if statements. CONDITIONAL CONSTRUCTS IN JAVA 179 1)! Program 9.5 Write a static method named median that accepts three integers as parameters and that returns the middle value of the three. For example, median(7, 3, 9) returns 7 and median(29, -14, 11) returns 11. Test your code with a Test class. Import [Link] ; public class Test { public static void main(String args[]) < ‘Scanner sc = new Scanner([Link]) ; int n1, n2,n3, med =0 ; [Link](“Enter 3 integers below”) ; nl = [Link]() ; n2 = [Link]() ; 3 = [Link]() ; med = median (n1, n2,n3) ; ‘[Link]("Median number of 3 given integers is” + med) ; 3 public static int median(int x, int y,intz) { if(x $3 AK 52 +53 > $1 BH S3+51 > 52) result = true j else result = false ; return result ; ‘Output produced is = o public static void main(String[] args) { Scanner sc = new Scanner ([Link]) 7 int side1, side2, side3 ; [Link]("Enter 3 sides ") ; side1 = [Link]( ) ; side2 = [Link]( ) ; side3 = [Link]( ) ; if (CanMake(side1, side2, side3) == true) [Link](“Given 3 sides will make a triangle”) else [Link]("Given 3 sides CANNOT make a triangle”) ()) Program 9.9 Write a program that takes three angles and states whether these angles form an acute triangle or an obtuse angle or a right-angled triangle. import [Link]-Scanner ; public class TriangleTest { public static boolean CanMake( double a1, double a2, double a3) { boolean result if(al + a2 +23 result = true j 180) else result = false ; return result ; K 182 COMPUTER APPLICATIONS-Ik public static void main(String[ ] args) £ ‘Scanner sc = new Scanner ([Link]) 7 double angle1, angle2, angle3 ; ‘[Link](*Enter 3 angles”) ; [Link](“Anglel : angle = [Link]() ; ‘[Link]("Angle2 :”) ; angle2 = [Link]() ; [Link](“Angle3 =") angle3 = [Link]( ) ; if (CanMake( anglet, angle2, angle3 ) == true) £ if (angle1 > 90 || angle2 > 90 || angle3 > 90) ‘[Link](*Given 3 angles make an Obtuse triangle”) ; else if ( angle1 < 90 && angle2 < 90 &®& angle3 < 90) [Link](%Given 3 angles make an Acute triangle”) + else if (angle == 90 || angle2 == 90 || angle3 == 90 ) é [Link](%Given 3 angles make an Right-angled triangle) ; + else [Link] printin("Given 3 angles CANNOT make a triangle") + 3 angles CONDITIONAL CONSTRUCTS IN JAVA 183 > ()| Program 9.10 Write a program to read three sides of a triangle (base, height, hypotenuse) and determine whether they. form a right angled triangle or not, —s Import [Link] ; public class TriangleTest { public static boolean CanMake( int b, int h, int hy) { boolean result ; if (hy*hy == b*b + h*h) result = true ; else result = false ; return result ; h —_——— A public static vold main(String[ Jargs) — { Scanner sc = new Scanner ([Link]) ; int base, height, hypotenuse ; [Link](“Enter 3 sides“) ; ‘[Link]("Base :") ; base = [Link]( ) j [Link](*Height : ") 7 height = [Link]( ) j - [Link]("Hypotenuse :") ; hypotenuse = [Link]( ) ; if ( CanMake(base, height, hypotenuse) == true) [Link](“Given 3 sides make a Right-angled triangle”) ; else [Link]("Given 3 sides CANNOT make a Right-angled triangle”) ; ay 184 COMPUTER APPLICATIONS-IK 9.6= The 2: Alternative to if ThetiAltemative tpt Java has an operator that can be used as an alternative to if statement: You are familiar with this operator, the conditional operator ? : This operator can be used to replace if-else statements of the general form : if (expression1) expression2 j else ‘expression3 ; ‘The above form of if can be alternatively written using 2: as follows : expressioni 2 expression? : expression3 ; Itworks in the same way as the above given form of if does ie, expressowl is evaluated, if itis true, expression? gets executed (i, its value becomes the value of entire expression) otherwise expression3 gets executed (ie, its value now becomes the value of the entire expression). For instance, the following if statement inte; if (a> b) c=a; can be alternatively written as intc=a>b?arb; idee deel JU Ae See how simple and compact your code has become. But remember that 7: is not as efficient as if. Comparing if and @ 41. Compared to if-else sequence, ?: offers more concise, clean and compact code, but i is less obvious as compared to if, 2, Another difference is that the conditional operator ?: produces an expression, and hence a single value can be assigned or incorporated into a larger expression, whereas, if is more flexible. The if statement can have multiple statements, multiple assignments and expressions (in form of a compound statement) in its body. When ? : operator is used in its nested form, it becomes complex and difficult to understand. This form of ?: is generally used to conceal the purpose of code. Q.7= The switch Statement Java provides a multiple-branch_selection_stal Slatoment successively tests the value of an expression against a lis constants, Java 7 onwards, you can even compare i found, the statements associated wi tant are executed. This. selection

You might also like