[go: up one dir, main page]

0% found this document useful (0 votes)
456 views16 pages

PresentCh03 - Decision and Repetition Statements

This document discusses different types of control flow statements in Java including decision statements (if/else, switch), repetition statements (while, do-while, for), and branching statements (break, continue, return). It provides examples of how to use each statement type and explains their general syntax and usage for selecting or repeating blocks of code conditionally based on logical expressions. The overall purpose is to teach students how to use these fundamental programming constructs that allow changing the sequence of statement execution to achieve different control flows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
456 views16 pages

PresentCh03 - Decision and Repetition Statements

This document discusses different types of control flow statements in Java including decision statements (if/else, switch), repetition statements (while, do-while, for), and branching statements (break, continue, return). It provides examples of how to use each statement type and explains their general syntax and usage for selecting or repeating blocks of code conditionally based on logical expressions. The overall purpose is to teach students how to use these fundamental programming constructs that allow changing the sequence of statement execution to achieve different control flows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 16

Object-Oriented

Programming
Computer Science Year II
Compiled by: Gebreigziabher A.

1
Decision & Repetition
Statements

2
* A running program spends all of its time executing statements. The
order in which statements are executed is called flow control or
(control flow). Flow control in a program is sequential, from one
statement to the next, but may be diverted to other paths by
branch statements.
* Program Control Statements allow us to change the ordering
(sequence) of how the statements in our programs are executed.
 There are different forms of Java statements:
 Declaration statements are used for defining variables.
 Assignment statements are used for simple, algebraic
computations.
 Branching statements are used for specifying alternate paths of
execution, depending on the outcome of a logical condition.
 Loop statements are used for specifying computations, which need
to be repeated until a certain logical
3 condition is satisfied.
*At the end of this chapter students should be able to
Use decision control structures (if, else, switch) which allows
selection of specific sections of code to be executed
Use repetition control structures (while, do-while, for) which
allow executing specific sections of code a number of times
Use branching statements (break, continue, return) which allows
redirection of program flow

4
* Decision statements are Java statements that allows us to select and execute
specific blocks of code while skipping other sections.

2.1.1 The if statement


* The if-statement specifies that a statement (or block of code) will be executed
if and only if a certain boolean statement is true.
* General form: if(expression)
statements;
* The first expression is evaluated. If the outcome is true then statement is
executed. Otherwise, nothing happens.
* Example: When dividing two values, we may want to check that the
denominator is nonzero
if(y!=0)
div=x/y;

5
2.1.2 The if-else statement
*The if-else statement is used to execute a certain statement if a condition is true,
and a different statement if the condition is false.
*General form: if(expression)
statement1;
else
statement2;
*First expression is evaluated. If the outcome is true then statement1 is executed.
Otherwise, statement2 is executed.
*Example: if(score>=50) {
System.out.println("Congratulations! You Passed!”; ");
}
else {
System.out.println(”You Failed!”);
System.out.println(”You Must Take This Course Again!”);
6
}
* The statement in the else-clause of an if-else block can be another if-else structures.
* This cascading of structures allows us to make more complex selections.
* Example:
if(score<0 && score>100) { if(CGPA<0 && CGPA>4) {
System.out.println(“ Score [0-100]”); System.out.println(“CGPA [0-4]”);
} }
if(score>=85 && score<=100) { if(CGPA>=3.5 && CGPA<=4) {
System.out.println(“ A Grade”); System.out.println(“ Excellent!”);
} }
else if(score>=75 && score<85 ){ else if(CGPA>=3.0 && CGPA<3.5){
System.out.println(“ B Grade”); System.out.println(“ Very Good!”);
}
}
else if(CGPA>=2.5 && CGPA<3.0 ) {
else if(score>=65 && score<75 ) {
System.out.println(“ Good!”);
System.out.println(“ C Grade”);
}
} else if(CGPA>=2.0 && CGPA<2.5 ) {
else if(score>=50 && score<65 ) { System.out.println(“Satisfactory!”);
System.out.println(“D Grade”); }
} else {
else { System.out.println(“Poor!”);
System.out.println(“F Grade”); 7 }
}
* Another way to indicate a branch is through the switch keyword.
* The switch construct allows branching on multiple outcomes.
* Multiple-choice, provides a way of choosing between a set of alternatives.
* General form:
switch (expression) {
case: constant1:
statements;
...
case: constantn:
statements;
default:
statements;
}
 
* First expression (called the switch tag) is evaluated, and the outcome is compared to
each of the numeric constants (called case labels), in the order they appear, until a
match is found. The final default case is optional and is exercised if none of the earlier
cases provide a match.
8
switch(op)
// The 4 basic arithmetic operators using switch
{
import java.io.*;
case '+':
public class switch1
{
System.out.println("Sum="+(a+b));
public static void main(String args[])throws IOException break;
{ case '-':
String s; System.out.println("Sub="+(a-b));
char op; break;
int a, b; case '*':
BufferedReader aa=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Mul="+(a*b));
System.out.print("The First Number:="); break;
s=aa.readLine();//to read an input data; case '/':;
a=Integer.parseInt(s);//convert the given string in to integer System.out.println(“Quo="+(a/b));
System.out.print("The Second Number:="); break;
s=aa.readLine();//to accept a string from the use default:
b=Integer.parseInt(s);
System.out.println("Invalid Operator");
System.out.print("An Operator:=");
} } }
op=(char)aa.read();//to accept a character from the user
9
* Repetition statements are Java statements that allows us to execute specific
blocks of code a number of times. There are three types of repetition
statements, the while, do-while and for loops.

2.2.1 The while loop statement


* The while loop is a statement or block of statements that is repeated as long as
some condition is satisfied(holds true).
* General form: while(expression)
statements;
inc/dec;
* First expression (called the loop condition) is evaluated. If the outcome is nonzero
then statement (called the loop body) is executed and the whole process is
repeated. Otherwise, the loop is terminated.
* Example: Adding the first 10 natural numbers(1-10)
int i=1,sum=0;
while(i<=10)
sum+=i; 10
i++;
* The do loop is similar to the while statement, except that its body is executed
first and then the loop condition is examined.
* The statements inside a do-while loop are executed several times as long as the
condition is satisfied.
* General form:
do
statement;
while (expression);
* First statement is executed and then expression is evaluated. If the outcome of
the latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
* Example: int x = 0; int n;
do { do {
System.out.println(x); System.out.println(“Enter n: ”);
x++; n=input.nextInt();
} System.out.println((n*n));
while (x<10); }
11
while (n!=0);
* The for loop allows execution of the same code a number of times.
* General form: for(Initialization; LoopCondition; StepExpression)
statement;
* Initialization -initializes the loop variable.
* LoopCondition - compares the loop variable to some limit value.
* StepExpression - updates the loop variable.
* First Initialization is evaluated. Each time round the loop, LoopCondition is
evaluated. If the condition is true then statement is executed and StepExpression is
evaluated. Otherwise, the loop is terminated.
* Example: int i, sum=0; int i;
for (i = 1; i <= n; i++) { for( i = 0; i < 10; i++ ) {
sum += i; System.out.print(i)
} }
* Loops can be nested:
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
System.ou.println(“(”+i+”, ”+j+”)”); 12
* Branching statements allows us to redirect the flow of program execution.
Java offers three branching statements: break, continue and return.
2.3.1 The continue statement
* The continue statement terminates the current iteration of a loop and instead
causes to jump/proceed to the next iteration of the loop.
* Example:
int i, sum=0;
for ( i = 1; i <= 10; i++ ) { // loop 10 times
if ( i%3 == 0) {// if remainder of i divided by 3 is 0
continue;
}
sum+=i;
System.out.println(i+ “ +“);
} // end for
13
System.out.print( “= “+ sum );
* break causes immediate termination/exit from looping/repetition
statements entirely.
* Example:
public class Break {
public static void main(String[] args) {
int num;
num = 10;
//loop while i is less than 6
for(int i=num; i >=1; i--) {
if(i<6){
break; // terminate loop if i <6
}
System.out.print(i + " ");
}
System.out.println("Countdown Aborted!");
}} 14
* The return statement is used to exit from the current method.
* The flow of control returns to the statement that follows the original method call.
* The return statement has two forms: one that returns a value and one that doesn't.
* General form: return expression;
* To return a value, simply put the value (or an expression that calculates the value
after the keyword return.
* For example: return sum;
public double Sum(double x, double y) {
return sum = x+y;
}
* The data type of the value returned by return must match the type of the method's
declared return value. When a method is declared void, use the form of return that
doesn't return a value.
* For example: return;

15
public class Power {
private int x; // instance variables
private int y;
public Power(int a, int b) { //A constructor to Initializes instance variable
x=a;
y=b;
}
public double computePower() {//a method to access the data members
double z;
z=Math.pow(x,y);
return z;
}
public static void main(String args[]) {
Power p= Power(2,3); //Object creation with a parameterized constructor
double result=p. computePower(); //Assign the return value of the function to the variable res
System.out.println("Output :"+result);
}
} 16

You might also like