Session 1.2 (Conditional and Looping)
Session 1.2 (Conditional and Looping)
if statement
Syntax :
if(condition){
stmts;
}
//write a program to check a number and print if it is positive
class IfStatement {
if (number > 0) {
}
2.if else
if else are keywords used to write condition
syntax :
if(condition){
stmt 1;
else{
stmt 2;
}
Flowchart :
//write a program to check a number and print if it is positive or negative
class Main {
if (number > 0) {
else {
}
3. else if ladder
To write more than one condition and only one condition should be executed then we use
else if ladder.
Syntax :
if(condition){
else if{
else if{
else{
}
// write a program to take a value from user and print wheather it is positive/negative/zero
class Main {
int number = 0;
if (number > 0) {
else {
}
4. Switch :
syntax :
switch(condition){
case 1:
stmts;
break;
case 2:
stmts;
break;
case 3:
stmts;
break;
case n:
stmts;
break;
default:
stmts;
}
// write a program to take a number from user, and perform operation as per his choice for
arithmetic operations
package basicPrograms;
import java.util.Scanner;
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
choice = 3; //3
switch(choice){
case 1:
System.out.println(num1+num2);
break;
case 2:
System.out.println(num1-num2);
break;
case 3:
System.out.println(num1*num2);
break;
case 4:
System.out.println(num1-num2);
break;
default:
break;
}
Looping Statements :
To execute some set of code repeatedly we use loops.
while loop :
While is entry controlled loop used to execute some set of code repeatedly.
syntax :
while(condition){
package loopPract;
int i=1;
while(i<=10) {
System.out.println(i);
i++; //11
}
do while loop :
syntax :
do{
}while(condition);
package loopPract;
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
for loop
syntax :
for(initialization;condition;increment/decrement){
package basicPrograms;
/*
sequence
step 1 : initialization
step 2 : condition (if condition is true then next steps will be executed)
step 3 : body
step 4 : increment/decrement
step 5 : repeat step 2 to 4 till loop condition is true
*/
//write a program to print below pattern using nested loop
/*
**
***
****
*****
*/
package loopPract;
//for lines
for(int j=1;j<=i;j++) { //
System.out.print(j);
System.out.println();
}}
for each loop :
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
package basicPrograms;
for(int e : eids) {
System.out.println(e);
}
}
//for…each loop with arraylist :
package basicPrograms;
import java.util.ArrayList;
eids.add(20);
eids.add(30);
eids.add(40);
eids.add(50);
for(int e : eids) {
System.out.println(e);
}