Lec 05 Java Fundamental of Computing
Lec 05 Java Fundamental of Computing
I Semester 2008-09
Lecture 5
• If statement
1
Execution of a Program
class anyname
{
public static void main(String args[])
{
⇒ statement1;
⇒ statement2;
⇒ statement3;
· · ·;
· · ·;
⇒ statementk;
}
}
2
Execution of a Program
class anyname
{
public static void main(String args[])
{
⇒ statement1;
⇒ statement2;
⇒ statement3;
· · ·;
· · ·;
⇒ statementk;
}
}
3
Execution of a Program
class anyname
{
public static void main(String args[])
{
⇒ statement1;
⇒ statement2;
⇒ statement3;
· · ·;
· · ·;
⇒ statementk;
}
}
⇒ : Instruction pointer (IP) - the next instruction to be executed
4
I : If statement
Find the minimum of two or more numbers.
class if_example
{
public static void main(String args[])
{
int i,j,min;
.
.
//---write code here so that min
//---stores the minimum of i and j
}
}
5
If statement
Syntax :
if (condition) statement;
6
If statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒ statement c;
7
If statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒ statement c;
8
If statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒statement c;
9
If statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒statement c;
10
Examples : If statement
class if_example
{
public static void main(String args[])
{
int i,j,max;
i=100; j=79;
min = i;
if(j<i) min=j;
System.out.println(‘‘minimum of ‘‘+i+’’ and ‘‘+j+’’ is ‘‘+min);
}
}
11
If-else statement : Example
class IF_Else_example1
{
public static void main(String args[])
{
int i,j;
i = 100; j = 0;
// write code so that
// if j == 0 then we print an error message
// else we print the quotient i/j
i =i+j;
}
}
12
If-else statement
Syntax :
if (condition) statement b;
else statement c;
13
If-else statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒else ⇒statement c;
⇒ statement d;
14
If-else statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒else ⇒statement c;
⇒ statement d;
15
If-else statement
⇒ statement a;
⇒ if (condition) ⇒ statement b;
⇒else ⇒statement c;
⇒statement d;
16
If-else statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒else ⇒statement c;
⇒ statement d;
17
If-else statement
⇒ statement a;
⇒ if(condition) ⇒ statement b;
⇒else ⇒statement c;
⇒statement d;
18
If-else statement : Example
class IF_Else_example1
{
public static void main(String args[])
{
int i,j;
i = 100; j = 0;
if(j==0) System.out.println("Division by error");
else System.out.println(i+" divided by "+j+" is "+(i/j));
i = i+j;
}
}
19
If-else statement for blocks
if(condition)
{
.
statements
.
}
else
{
.
statements
.
}
20