Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.

Slides:



Advertisements
Similar presentations
Java Control Statements
Advertisements

Control Structures.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa.
Control Structures Corresponds with Chapters 3 and 4.
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany,
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
DAT602 Database Application Development Lecture 5 JAVA Review.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
CPS120: Introduction to Computer Science Decision Making in Programs.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
Flow of Control Chapter 3 Flow of control Branching Loops
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Loops and Logic. Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 4b Repeating With Loops
Java Language Basics.
Control Structures.
JavaScript: Control Statements.
Starting JavaProgramming
In this class, we will cover:
Java Language Basics.
Lab5 PROGRAMMING 1 Loop chapter4.
In this class, we will cover:
Loops CGS3416 Spring 2019 Lecture 7.
Presentation transcript:

Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa

Control Flow Statements The statements inside your source code are generally executed from top to bottom Control flow statements, break up the flow of execution by employing decision making, looping, and branching

Java Control Flow Statements Decision-making statements if if - else switch Looping statements for while do-while Branching statements break continue return

“if” and “if-else” Statements The if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true void applyBrakes() { if (speed > 0) { // car must be moving speed--; // decrease current speed } } void reverse() { if (speed == 0) { // car must not be moving speed--; // move backwards }

“if” and “if-else” Statements if-else statement provides a secondary path of execution when an "if" clause evaluates to false void applyBrakes() { if (speed > 0) { // car must be moving speed--; // decrease current speed } else { System.out.println(“car is already stoped”); }

“if” and “if-else” Statements class Grade { public static void main(String[] args) { int score = 64; char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); }

“if” and “if-else” Statements class Grade { public static void main(String[] args) { int score = 90; char grade; if (score >= 90) { grade = 'A'; } if (score >= 80) { grade = 'B'; } if (score >= 70) { grade = 'C'; } if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } What will be printed to the screen when this program runs?

switch Statement the switch statement allows for any number of possible execution paths. switch works with the byte, short, char, and int primitive data types

switch Statement The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case

switch (experssion) { case 1: case 2: System.out.println(“1 or 2"); break; case 3: System.out.println(“3"); break; default: System.out.println(“other values"); break; } switch Statement Why break is important?

switch Statement Write a program that declares an int named day whose value represents a day out of the week. The program displays the name of the day, based on the day value.

class WeekDay{ public static void main(String[] args) { int day= 3; switch (day) { case 1: System.out.println("Mon"); break; case 2: System.out.println("Tues"); break; case 3: System.out.println("Wed"); break; case 4: System.out.println("Thurs"); break; case 5: System.out.println("Fri"); break; case 6: System.out.println("Sat"); break; case 7: System.out.println("Sun"); break; default: System.out.println("Invalid"); break; }

Loops: for Statement for statement provides a compact way to iterate over a range of values. Repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: keep in mind that: initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression is checked before each iteration through the loop. When it evaluates to false, the loop terminates. increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. for (initialization; termination Condition; increment) { statement(s) }

for Statement The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 class ForCount { public static void main(String[] args){ for(int i=1; i<5; i++){ System.out.println("Count is: " + i); }

while Statement The while statement continually executes a block of statements while a particular condition is true. The expression must return a boolean value The while statement continues testing the expression and executing its block until the expression evaluates to false while (expression) { statement(s) }

while Statement class Count { public static void main(String[] args){ int count = 1; while (count < 5) { System.out.println("Count is: " + count); count++; } System.out.println(“Outside while loop"); }//main end }//class end The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Outside while loop

do-while Statement The while statement continually executes a block of statements while a particular condition is true. The expression must return a boolean value do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once do { statement(s) }while (expression)

do-while Statement class Count { public static void main(String[] args){ int count = 10; do{ System.out.println("Count is: " + count); count++; } while (count < 5) System.out.println(“Outside while loop"); }//main end }//class end The output of this program is: Count is: 10 Outside while loop

Methods A Java method is a set of Java statements which can be included inside a Java class. May be called functions or procedures in other programming languages. Methods enable us to break a class down into a number of smaller units Your statements usually will need to be placed inside a method so far we have been using only the “main” Method as it is the entry point of the program

Methods 1. Most problems naturally break down into sub-problems. 2. Large problems must be implemented by a team, not an individual. 3. Reusability of the parts, is highly appreciated For the program itself For other programs

Defining Methods The only required elements of a method declaration are: the method's return type the method's Name a pair of parentheses, ( ) a body between braces, { } Return_type methodName(optional_parameters) { //method Body here }

Method declarations components 1. Modifiers, such as public, private, and others you will learn about later. 2. return type, the data type of the value returned by the method, or void if the method does not return a value. 3. Method name 4. The parameter list in parenthesis. a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). 5. An exception list (more details later) 6. The method body, enclosed between braces—the method's code, including the declaration of local variables.

Naming a Method a method name can be any legal identifier By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb In multi-word names, the first letter of each of the second and following words should be capitalized Examples: addNumbers moveShape isFound print

Examples of method declarations class Count { public static void count(int maxNum){ int count=0; do{ System.out.println("Count is: " + count); count++; } while (count < maxNum) }//count method end }//class end This code will do nothing so far, we defined the method, However, we must have a call statement to execute it

Method Call class Count { public static void count(int maxNum){ int count=0; do{ System.out.println("Count is: " + count); count++; } while (count < maxNum) }//count method end public static void main(String[] args){ count(10); }//main end }//class end For now, all methods we use have to be static (more on that latter)

Method Flow of Control The main method is invoked by the system when you run your program Each method call returns to the place that called it method1mainmethod2 method1(); Method2();

The method definition we need to identify each of the parameters (if needed), so that we can refer to them and use them from within the code which forms the body of the method. it is conventional to declare any local variables at the start of the body (apart from loop variables). a new copy of them is created every time a method is called (invoked). The rest of the body of the method is dedicated to implementing the logic of the method so that it performs the job we want it to. This can include any java legal statements. At any point we can exit the method using a return statement