Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
-
Upload
austin-small -
Category
Documents
-
view
234 -
download
2
Transcript of Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Introduction to Programming G51PRG
University of NottinghamRevision 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” Statementsclass 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” Statementsclass 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 Statementclass 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 Statementclass 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 components1. 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 Callclass 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
method1main method2
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