For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Similar documents
For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

The Java language has a wide variety of modifiers, including the following:

AP COMPUTER SCIENCE A

Following is the general form of a typical decision making structure found in most of the programming languages:

Software Practice 1 Basic Grammar

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

H212 Introduction to Software Systems Honors

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Programming Basics. Digital Urban Visualization. People as Flows. ia

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Module - 2 Overview of Java History of Java Technology?

Loops. CSE 114, Computer Science 1 Stony Brook University

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

JAVA OPERATORS GENERAL

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Repetition, Looping. While Loop

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Example: Monte Carlo Simulation 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

PROGRAMMING FUNDAMENTALS

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Loops and Expression Types

Midterm Examination (MTA)

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

1 Short Answer (10 Points Each)

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Oct Decision Structures cont d

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Chapter 3. Selections

Bjarne Stroustrup. creator of C++

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Chapter 4: Control Structures I

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Question: Total Points: Score:

Course Outline. Introduction to java

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

In this chapter, you will:

CS 101 Spring 2007 Midterm 2 Name: ID:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

STUDENT LESSON A12 Iterations

6 COMPUTER PROGRAMMING

Chapter 4: Control structures. Repetition

Decisions (If Statements) And Boolean Expressions

Java Simple Data Types

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Lesson 7 Part 2 Flags

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

CSE 142, Spring 2009, Sample Final Exam #2. Good luck!

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Fundamentals of Programming Data Types & Methods

AP Computer Science A Summer Assignment 2017

Chapter 4: Control structures

AP CS Unit 3: Control Structures Notes

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Computational Expression

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Introduction. C provides two styles of flow control:

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Object Oriented Programming. Java-Lecture 6 - Arrays

Lecture 14. 'for' loops and Arrays

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

DELHI PUBLIC SCHOOL TAPI

CSIS 10A Assignment 4 SOLUTIONS

++x vs. x++ We will use these notations very often.

1. Find the output of following java program. class MainClass { public static void main (String arg[])

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Arithmetic Compound Assignment Operators

Chapter 4 Control Structures

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Controls Structure for Repetition

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Top-down programming design

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Write a program which converts all lowercase letter in a sentence to uppercase.

Full file at

COMPUTER PROGRAMMING LOOPS

Key Java Simple Data Types

Transcription:

Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Java allows usage of different control statements which act as conditional or unconditional according to their usage within a program. The control activates in two modes featuring, Selection and Iteration. Hence the control statements of Java are referred to of two types : (i )Selection / Decision control statements : The Selection control statements refer to transfer of control or execution depending on the given condition and a selection is made depending on the given options. The different course of action are performed according to the given condition. They are also termed as Decision Construct Statements as they help in taking decisions for further execution of the statements/instructions within the program. (ii )Iteration/looping control statements : The Iteration Statements on the other hand act as an automatic looping statements. Here the block/compound statement is executed again and again until a given condition is met.

SELECTION STATEMENTS OF java The Java if statement is used to test the condition. It checks Boolean condition: true or false. There are various types of if statement in java. if if-else if-else-if nested if statement statement ladder statement

Java IF Statement The Java if statement tests the condition. It executes the if block if condition is true. Syntax: if(condition) //code to be executed

public class IfExample public static void main(string[] args) int age=20; if(age>18) System.out.print( You are eligible to vote");

tooltiptext property The tooltip text is the text that appears when The tooltip text is the text that appears when the user moves the cursor over a component, without clicking it. private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility to vote: if (Integer.parseInt(jTextField1.getText())>=18) JOptionPane.showMessageDialog(null,"You are eligible To VOTE");

Java IF-else Statement The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. Syntax: if(condition) //code if condition is true else //code if condition is false

private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility to vote with else condition: if (Integer.parseInt(jTextField1.getText())>=18) JOptionPane.showMessageDialog(null,"You are eligible To VOTE"); else JOptionPane.showMessageDialog(null,"You are NOT eligible To VOTE");

public class IfElseExample public static void main(string[] args) int number=13; if(number%2==1) System.out.println( ODD number"); else System.out.println( EVEN number");

import javax.swing.joptionpane; private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility for scholarship: if (Integer.parseInt(jTextField1.getText())>=75) jtextarea1.settext("congratulation!\nyou Get the SCHOLARSHIP!!"); else jtextarea1.settext("work Hard!\n" + "Make sure that you Get the SCHOLARSHIP in the next Exam!!");

private void jbutton2actionperformed(java.awt.event.actionevent evt) JOptionPane.showMessageDialog(null,"thanks for using This app"); System.exit(0); // to terminate the application

Java IF-else-if ladder Statement The if-else-if ladder statement executes one condition from multiple statements. Syntax: if(condition1) //code to be executed if condition1 is true else if(condition2) //code to be executed if condition2 is true else if(condition3) //code to be executed if condition3 is true... else //code to be executed if all the conditions are false

private void jbutton1actionperformed(java.awt.event.actionevent evt) // To find the day of the week if (jradiobutton1.isselected()) jtextfield1.settext("monday"); else if (jradiobutton2.isselected()) jtextfield1.settext("tuesday"); else if (jradiobutton3.isselected()) jtextfield1.settext("wednesday"); else if (jradiobutton4.isselected()) jtextfield1.settext("thursday"); else if (jradiobutton5.isselected()) jtextfield1.settext("friday"); else if (jradiobutton6.isselected()) jtextfield1.settext("saturday"); else if (jradiobutton7.isselected()) jtextfield1.settext("sunday"); else jtextfield1.settext("day - Not Selected");

public class IfElseIfExample public static void main(string[] args) int marks=65; if(marks<50) System.out.println("fail"); else if((marks>=50 )&& (marks<60)) System.out.println("D grade"); else if(marks>=60 && marks<70) System.out.println("C grade"); else if(marks>=70 && marks<80) System.out.println("B grade"); else if(marks>=80 && marks<90) System.out.println("A grade"); else if(marks>=90 && marks<100) System.out.println("A+ grade"); else System.out.println("Invalid!");

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. switch(expression) case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional... default: code to be executed if all cases are not matched;

public class SwitchExample public static void main(string[] args) int number=20; switch(number) case 10: System.out.println("10") ; break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; default : System.out.println("Not in 10, 20 or 30");

import java.util.scanner; class OddOrEven public static void main(string args[]) int x; System.out.println("Enter an integer to check if it is odd or even "); Scanner a = new Scanner(System.in); x = a.nextint(); if ( x % 2 == 0 ) System.out.println("You entered an even number."); else System.out.println("You entered an odd number.");

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextline() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextline() positions the cursor in the next line. for reading the entire line you can use nextline()

import java.util.scanner; class MaxNum public static void main(string args[]) int x, y, z,max; System.out.println("Enter three integers "); Scanner in = new Scanner(System.in); x = in.nextint(); y = in.nextint(); z = in.nextint(); max=x; if(y>max) max=y; if(z>max) max=z; System.out.println("maximum is = "+max); /* if ( x > y && x > z ) System.out.println("First number is largest."); else if ( y > x && y > z ) System.out.println("Second number is largest."); else if ( z > x && z > y ) System.out.println("Third number is largest."); else System.out.println("Entered numbers are not distinct.");*/

TOTAL_AMMOUNT DIS MORE THAN 30000 15% LESS THAN OR EQUAL TO 30000 BUT > 15000 10% BETWEEN 10000 AND 15000 5% OTHERWISE NIL

A loop statement allows us to execute a statement or group of statements multiple times.

Sr. No. 1 2 3 Loop & Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop Like a while statement, except that it tests the condition at the end of the loop body.

The syntax of a while loop is while(boolean_expression) // Statements // updation public class Test public static void main(string args[]) int x = 1,s=0; while( x < =10) s+=x; //s=s+x; x=x+1; // ++x or x++ System.out.print(" sum=" + s );

for(initialization; Boolean_expression; update) // Statements Here is the flow of control in a for loop The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

public class Test public static void main(string args[]) for(int x = 10; x < 20; x = x + 1) System.out.print("value of x : " + x ); System.out.print("\n");

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax Following is the syntax of a do...while loop do // Statements while(boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

public class Test public static void main(string args[]) int x = 10; do System.out.print("value of x : " + x ); x++; System.out.print("\n"); while( x < 20 );

Enhanced for loop in Java Syntax Following is the syntax of enhanced for loop for(declaration : expression) // Statements

public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) System.out.print( x ); System.out.print(","); System.out.print("\n"); String [] names = "James", "Larry", "Tom", "Lacy"; for( String n : names ) System.out.print( n ); System.out.print(","); 10, 20, 30, 40, 50, James, Larry, Tom, Lacy,

Control Statement & Description break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. OR The break statement in Java programming language has the following two usages 1. When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. 2. It can be used to terminate a case in the switch statement (covered in the next chapter).

public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) break; System.out.print( x ); System.out.print("\n");

Control Statement & Description continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression.

public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) continue; System.out.print( x ); System.out.print("\n");

public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int i=0;i<numbers.length;i++) if( numbers[i] == 30 ) continue; System.out.print( numbers[i] ); System.out.print("\n");