You are on page 1of 12
Control Structures Dr. H. B. Prajapati ‘Dhornsnh Dean Ue 2 July "20, Core Java Technology Outline of Presentation @ Program Control Program Control © In a computer program also, we need to perform tasks based on decisions or choices @ In a Computer Program, program control specifies the order in which statements are executed in 2 computer program 18 The control structures can be divided into two types: {@ Decision constructs (Either this er that) © Loop constructs (How many times or fill what to pero 18 There are three forms of decision constructs oir @ ice switch 19 There are four forms of Loop const ote O wile @ do while {Q for each (added in Java later) some tsk) IES yn 5 Table of contents @ Program Control @ Decision Constructs @ Loop Constructs @ Keywords break and continue @ Loop Use and Avoid Errors Program Control 1 In real life, we take decisions for some tasks: t Shoulé | become an Engineer or Doctor f [want to watch Matric movie 3 times. 1 | want co eat Ponipuis till my stomach gets fl f L want to perform paragliding at least once, whether I Ike itor do not t Shoulé | travel by train or airplane? If by ean, then Ist AC or 2nd [ACT I by airplane, then Economic class or Executive class? pos 406 Outline of Presentation @ Decision Constructs if and if...else statements 1 Both if and if ese statements include boslean condition 12 The simple if statement executes an action only if the boolean condition is true. 18 The if.else statement includes two actions Q forthe boolean condition is true @ or boolean condition is false a The if...else statement | ctpresion Susteren forte se] Steen rte ae ce} | Figure: Flowchart off.0se [_——/ii---—-~-~—=i[—1s Program: Sessional Exam Status, Slide - | Class Sessionalixanstacust 1 2] “pupite staric void main (String[] args){ 3 int seasionall = 28; int sessional? = 2; 5 int geseionala = S int attendance = 3) 7 int average, total; 4 total = cesgionali+ecesional2+sessional3 average = (int) (tetal/3) ; System. out printin("Minimum 16 marks are required to pass sessional exaz.") ar C(eovai/3.8) ~(ane) (total /3)) >= 0.5) average #21 average f= attendance; if (average >= 16) Simple if statement i 1 The syntax forthe simple if statement is a fellows fase Tithe Fendt r eanExpr 208) «I booleanCxpression evalustes _= 2s true, the statements inside the block are executed 2 IF the booleanExpression evaluates false, nothing happens Figure: Flowchart of simple i The if...else statement 1 The if.lse allows us to provide an alternative action 18 The syntax for ifelse statements is as fellows 17 (booleanbxpression)¢ 2 statement (s) for_true_case sJpeised a] " stavement (2) tor talee case spo Program: Sessional Exam Status, Slide - II Systen-out prinvin("Great! You passed sessional exam with "saverage?" marks"); alee System-out.printin are “taverage+" Sorry! Your marks You did not pass a Nested if Statements ‘2 The statements inside the if or theif. else statements can be any legal Java statements, including another if or if.lse statements, 18 The inner if statement is said to be nested inside the outer if statement, 19 The inner if statement can contain another if statement. (there is no limit to the depth of the nesting) IE Sz sre sy a Nested if Statements 18 The nested if statement can be written in the follwing equivalent structure 1iitecore >= 90,0) 2] grade = 74" jJeise if(acore >= 80.0) grade > 'B sJeise if(score >= 70.0) grade = 'C'; vJease if¢score $= 60.0) a)” "grade =D sJeise of! “grade = 1F 18 The above code is easy to read and can be seen as ese. ladder. awe ye >= __——“‘_OS LY Program: Status based on SPI class SpidndStatust public static void main(String[] args){ float apis String status 5 spi = 8.08; 6 Status = spirss 7 "P. srail ; 7 System.out-println("SPi: "+apit” tetatue); TS Nested if Statements 12 The nested if statement allows us to implement multiple alternative. iF (acore grade = else Jo “ie ¢score grade = else i¢(score >= 70.0) grade = °C") else | it (acore >= 60.0) grade else 30.0) ee 30.0) a rade I uy Sy Shortcut if statement 18 Suppose to a variable, we want to assign one value ifthe condition is ‘rue and another value i the condition is false, such as shown below TF (bool eanbxpressien) ariable = true result expression; sJeise [variable = a1 19 There is a shortcut syntax-temary operator 1 This syntax does not include if and e's keywords varia’! = condition 7 expritrue + @xp Program: Status based on SPI IE sy yer Se Using switch Statements 18 The if statement allows us to vtite decisions based on a single condition 18 The nested if statements can allow us to write multisle conditions and associated actions (beyond some peint it becomes dificult to understand) 18 Java provides switch statement to handle multiple conditions efficiently and with less code. a The switch statement 1 The syntax of switeh statement is as follows: Suitch (switch expression) ( case valuei: statement (s)1 break: case valued: statement (s)2 5 break case valued: statement (2)3. break; valuell: statement (5) break; default at (s) for default; [_——/ii---—-~-~—=i[—1s Program on switch statement: Prepend Mr. or Ms. clase SeivehTeatt public staric void main (String[] args){ String name="Harahad"; String gender = "Male"; svitch (gender) < System. out pr: break; cage "Female" System. out .p Es The switch statement SSS oes fe neat] igure: Flowehart of switch statement The switch statement ‘switch expression must result in a value of char, byte short, and int type ‘The data type of case values must match with that of switch expression and the values should be literals (cannot contain variable). «Later Java added String data type for switch expression 19 The break keyword is optional. statement will be executed is not present, the following case ‘The default case (mu none of the cases i be the last is optional. It wil be executed if Program on switch statement: Prepend Mr. or Ms a Program on switch statement: Test Odd or Even clase SeivehOadivent public static void main(String[] args){ int ne=2s suiten(nod< case 3: case S:case 7: case 8 Systom.out.printin(nor" is odd"); break; case 0: case 2: case 4: case 6 case 8 Systen.out.printin(no+" is Even) breaks 2 In this program, we have combined cases 1, 3, 5, 7, 9 and associated fone action, same way an alternate action for cases 0, 2, 4, 6, and & Outline of Presentation @ Loop Constructs Loop Constructs/Structures 9 In general, any loop constructs have the following associated oF essential parts: «Loop variable or variables Initialization of Loop variable * Loop continue-conditon + Modifeation inthe value of Loop variable 18 Depending upon where we can write these four associated parts, Java provides three types of loop constructs «= for oo while loop dowhile loop TS Program on switch statement: Test Odd or Even Loop Constructs/Structures Loops are constructs or structures that control repeated execution of 2 statement or a block of statements A loop construct has two structural parts: @ Loop head © Loop body ‘The part of the loop that contains the statement called the loop body. One-time execution of the loop body is called an iteration of the loop, which is controled by loop continue condition Loop continue-condition isa boolean expression and controls the ‘execution of the body. After each iteration, the continue-conditon is evaluated. f= Ifthe condition is tue, the body = repested f Ifthe condition i ale, the loop terminates, be repeated is The for Loop 18 The syntax forthe for oop construct is a follows Tor Ganitialization; loop variable updace){ Loop body, > 2 Example: For (0; i<10; Loop’ beay Tt > Figure Flowchart of fr loop sy Parts of the for Loop for (4*0; Leags ante Lgop body Neem et ee Generally, any for loop will have loop body, though itis optional ‘The other three parts are not required to be inside for loop head, i inside round brackets of for. We can bring out Initialization and can place it before for loop, We can bring out update and can place it as part of Loop body We can even bring out condition and can place it as part of Loop body. 0, we can avoid all three parts: initialization, condition, and update. EA IE esse ty a Program: Separating random odd and even numbers Clase RandoadadEventumberet public static void main (String[] args){ String eddies. String evenNos~ for (ane i20;3¢10; 144) ¢ dnt No + Gn) (Math. vanden () #100) ; S£(CaNo21=0) 4 oddoe=oddNos+" “+zo 1 evenlossevenNos+" "+rllo; u y System.out.printin("Even Nos: "+eventles); 3 System out println ("Odd Nos: "toddNos) ; , we we _ ino. | Program: Nested for Loop 19 It is possible to write one for loop as a statement inside another for loop «@ It is called nesting. The frst loop is called outer loop and the contained loop is called inner loop. cer TrianglePatverat public static void main(String() args) 3 int 120,320; For (1=0/1<5;i++){ 5 for ()~0; j

You might also like