OOP1 Unit-2
OOP1 Unit-2
3140705
Unit 2:
Selections,
Mathematical functions and
loops
Looping
What we will learn
If statement
Two way if statement
Nested if statement
Switch statement
Conditional Expression
While loop
Do-while loop
For loop
Nested loop
Break and continue statement
Common mathematical expression
Decision Making
Compiler executes program statements sequentially.
Decision making statements are used to control the flow of program
execution.
It allows us to control whether a set of program statement should be
executed or not.
It evaluates condition or logical expression first and based on its result
(true or false), the control is transferred to the particular statement.
If result is true then it takes one path else it takes another path.
True conditi False
on
… …
…
Decision Making Statements
Commonly used decision making statements are
One way Decision: if (Also known as simple if)
Two way Decision: if…else
Multi way Decision: if…else if…else if…else
Decision within Decision: nested if
Two way Decision: ?: (Conditional Operator)
n-way Decision: switch…case
if
One way Decision
if
if statement is the most simple decision-making statement also known as
simple if.
An if statement consists of a boolean expression followed by one or more
statements.
If the expression is true, then 'statement-inside' will be executed,
otherwise 'statement-inside' is skipped and only 'statement-outside' will
be executed.
It is used to decide whether a block of statements will be executed or not
i.e ifconditio
a certain condition
False is if(condition)
true then a block of statement is executed
otherwise n not. {
// Statements to execute if condition
True
is true
statement-inside }
WAP to print if a number is positive
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println("number is a
positive");
9. }
10.}
Exercise
Write a program which reads two numbers and based on different
between it prints either of following message DIFFERENCE IS POSITIVE or
DIFFERENCE IS NAGATIVE.
WAP to print if a number is odd or even
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. if( x % 2 == 0 ){
11. System.out.println("number is a
even");
12. }
13.}
if…else
Two way Decision
If…else
For a simple if, if a condition is true, the compiler executes a block of
statements, if condition is false then it doesn’t do anything.
What if we want to do something when the condition is false? if…else is
used for the same.
If the 'expression' is true then the 'statement-block-1' will get executed
else 'statement-block-2' will be executed. if(condition)
{
// statement-block-1
True conditio False // to execute if condition
n is true
}
else
statement- statement-
{
block-1 block-2
// statement-block-2
// to execute if condition
… is false
}
WAP to print if a number is positive or negative
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if (x > 0){
8. System.out.println("Number is
positive");
9. }//if
10. else{
11. System.out.println("Number is
negative");
12. }//else
13. }//main
14.}//class
WAP to print if a number is odd or even
1.import java.util.*;
2.class MyProgram{
3.public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. else{
11. System.out.println("number is a even");
12. }
13.}
Exercise
1. Any year is entered through the keyboard, write a program to determine
whether the year is leap or not.
2. Write a program to check whether a triangle is valid or not, when the
three angles of the triangle are entered through the keyboard. A triangle
is valid if the sum of all the three angles is equal to 180 degrees.
if…else if…else
Multi way Decision
if…else if…else
if…else if…else statement is also known as if- if(condition 1)
else-if ladder which is used for multi way decision {
making. statement-block1;
}
It is used when there are more than two different else if(condition 2)
conditions. {
It tests conditions in a sequence, from top to statement-block2;
}
bottom.
else if(condition 3)
If first condition is true then the associated block {
with if statement is executed and rest of the statement-block3;
conditions are skipped. }
else if(condition 4)
If condition is false then then the next if condition {
will be tested, if it is true then the associated block statement-block4;
is executed and rest of the conditions are skipped. }
Thus it checks till last condition. else
default-statement;
Condition is tested only and only when all previous
conditions are false.
The last else is the default block which will be
if-else-if ladder
if(username==1234){
if(password==987654){
System.out.println("Your Balance is
="+balance);
}
else{
System.out.println("Password is invalid");
}
}
else{
System.out.println("Username is invalid");
}
Exercise
In a company an employee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of basic
salary and DA = 90% of basic salary.
If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500
and DA = 98% of basic salary.
Employee's salary is input through the keyboard, write a program to
find his gross salary.
switch…case
n-way Decision
Switch…case
switch…case is a multi-way decision switch (expression)
making statement. {
case constant 1:
It is similar to if-else-if ladder statement. // Statement-1
break;
It executes one statement from multiple
conditions. case constant 2:
// Statement-2
break;
case constant 3:
// Statement-3
break;
default:
// Statement-default
// if none of the above case
matches then this block would
be executed.
}
Switch…case: WAP to print day based on number entered
6.switch (d) {
1.public class Demo { 7. case 1:
2. public static void 8. System.out.println(“Monday“); break;
main(String[] 9. case 2:
args){ 10. System.out.println(“Tuesday“); break;
3. int d; 11. case 3:
4. Scanner sc= new 12. System.out.println(“Wednesday“); break;
Scanner(System.in); 13. case 4:
5. d = sc.nextInt(); 14. System.out.println(“Thursday“); break;
15. case 5:
16. System.out.println(“Friday“); break;
17. case 6:
18. System.out.println(“Saturday“); break;
19. case 7:
20. System.out.println(“Sunday“); break;
21. default:
22. System.out.println(“Invalid Day“);
23. } //switch
24. }
25.}
Switch…case
switch statement executes one statement from multiple conditions. It is
like if-else-if ladder statement.
public class SwitchExampleDemo {
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;
default:
System.out.println("Not 10 or
20");
}
}
}
Exercise
Write a menu driven program that allows user to enters five numbers and
then choose between finding the smallest, largest, sum or average. Use
switch case to determine what action to take. Provide error message if an
invalid choice is entered.
Points to remember for switch…case
The condition in the switch should result in a constant value otherwise it
would be invalid.
In some languages, switch statements can be used for integer
values only.
Duplicate case values are not allowed.
The value for a case must be of the same data type as the variable in the
switch.
The value for a case must be a constant.
variables are not allowed as an argument in switch statement.
The break statement is used inside the switch to terminate a statement
sequence.
The break statement is optional, if eliminated, execution will continue on
into the next case.
The default statement is optional and can appear anywhere inside the
switch block.
Exercise
Write a Java program to get a number from the user and print whether it is
positive or negative.
Write a program to find maximum no from given 3 no.
The marks obtained by a student in 5 different subjects are input through
the keyboard.
The student gets a division as per the following rules:
Percentage above or equals to 60-first division
Percentage between 50 to 59-second division
Percentage between 40 and 49-Third division
Percentage less than 40-fail
Write a program to calculate the division obtained by the student.
Write a Java program that takes a number from the user and displays the
name of the weekday accordingly (For example if user enter 1 program
should return Monday) .
Introduction to loop
Repeatedly execute a block of statements
Loop
Sometimes we need to repeat certain actions several times or till the
some criteria is satisfied.
Loop constructs are used to iterate a block of statements several times.
Loop constructs repeatedly execute a block of statements for a fixed
number of times or till some condition is satisfied
Flowchart of if Flowchart of while
(true-block executed only once)(true-block executed till condition is true)
true-block true-block
Looping Statements
Following are looping statements in any programming language,
Entry Controlled while, for
Exit Controlled do…while
Unconditional Jump goto (It is advised to never use goto in a
program)
while
Entry Controlled Loop
while
while is a entry controlled loop.
It executes a block of statements till the condition is true.
1.import java.util.*;
2.class BreakDemo{
3.public static void main (String[] args){
4. int a,sum=0;
5. System.out.println("enter numbers_ enter -1 to break");
6. Scanner sc = new Scanner(System.in);
7. while(true){
8. a = sc.nextInt();
9. if(a==-1)
10. break;
11. sum=sum+a;
12. }//while
13. System.out.println("sum="+sum);
14. }
15.}
Types of loops
Entry Control Entry Control Virtual
Exit Control Loop
Loop Loop Loop
int i=1; int i; int i=1; int i=1;
while(i<=10) for(i=1;i<=10;i+ do p: i++;
{ +) { if(i<=10)
i++; { i++; goto p;
} i++; }
} while(i<=10);
False Label
conditi Statement
on Loop Body
True True conditi
True conditi on
Loop Body got
on o
False
False labe
l
nested loop
loop within a loop
WAP to print given pattern (nested loop)
* 1.class PatternDemo{
** 2.public static void main(String[] args) {
*** 3. int n=5;
**** 4. for(int i=1;i<=n;i++){
***** 5. for(int j=1;j<=i;j++){
6. System.out.print("*");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}
WAP to print given pattern (nested loop)
1 1.class PatternDemo{
1 2 2.public static void main(String[] args) {
1 2 3 3. int n=5;
1 2 3 4 4. for(int i=1;i<=n;i++){
1 2 3 4 5. for(int j=1;j<=i;j++){
5 6. System.out.print(j+"\t");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}
Programs to perform (Looping Statements)
Write a program to print first n odd numbers.
Write a program to check that the given number is prime or not.
Write a program to draw given patterns,
Mathematical
functions
Math class
The Java Math class provides more advanced mathematical
calculations other than arithmetic operator.
The java.lang.Math class contains methods which performs basic
numeric operations such as the elementary exponential, logarithm,
square root, and trigonometric functions.
All the methods of class Math are static.
Fields :
Math class comes with two important static fields
E : returns double value of Euler's number (i.e 2.718281828459045).
PI : returns double value of PI (i.e. 3.141592653589793).
Methods of class Math
Methods of class Math (Cont.)
Methods of class Math (Cont.)
Methods of class Math (Cont.)
Methods of class Math (Cont.)
Math Example