SlideShare a Scribd company logo
Control Statements
Unit1-Chapter4
Contents
• Input charecters from keyboard
• if statement
• Nested if ‘s
• If else if ladder
• Switch statement
• Nested switch statement
• For loop statement
• While loop
• Do while loop
• Break
• Continue
• Nested loops
Input characters from keyboard
• In order to read data from keyboard from user, we use
System.in.read()
• System.in is an input object attached to the keyboard
• read() method waits until the user presses key and then
return the result.
• The character is returned as an integer so it must be
casted back into a character and should be stored in a
character variable
• By default the console input is line buffered.
• Buffer refers to small portion of memory that is used to
hold the characters before they are read by the program
• When the user presses Enter then the value
from buffer will be sent to your program.
Import java.io.*;
class KeyBoardInput{
public static void main(String args[]) throws IOException
{
char ch;
System.out.println("Press a key followed by a letter:");
ch=(char) System.in.read();
System.out.println("Enter letter is :"+ch);
}//end of main
}//end of class
The if statement
if(condition)
{
statement;
}
class IfExam {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if
statement");
}
}
}
If else statement
public class IfElseExam {
public static void
main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This
is if statement");
}else{
System.out.print("This
is else statement");
}
}
}
if(condition)
{
statement;
}
else
{
statement;
}
The if else if ladder
if(condition)
Statement;
else if(condition)
Statement;
else if(Condition)
Statement;
….
else
Statement;
class IfElseIfLadder {
public static void main(String args[]){
int x = 30;
if( x == 10 )
System.out.print("Value of X is 10");
else if( x == 20 )
System.out.print("Value of X is 20");
else if( x == 30 )
System.out.print("Value of X is 30");
else
System.out.print("This is else
statement");
}
}
Nested If statements
• An if statement that is the target of another if or else
class NestedIF {
public static void main(String args[]){
int x = 30, y = 10;
if( x == 30 ){
if( y == 10 )
System.out.print("X = 30 and Y = 10");
else
System.out.println("Y is not 10”);
}
}
}
Switch statement
• It provides multi way branch
• Gives chance to programmer to select among several
alternatives.
• The value of expression is evaluated against list of
constants
• When a match is found, the statement sequence
associated with that is executed.
switch(expression)
{
case constant1 :
Statements
break; //optional
case constant2 :
Statements
break;//optional
……
default : Statements
}
class Result {
public static void main(String args[]){
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :System.out.println("Well
done");
break;
case 'D' :System.out.println("You
passed");
case 'F' :System.out.println("Better try
again");
break;
default : System.out.println("Invalid
grade");
}
System.out.println("Your grade is " +
grade);
}
}
Nested switch statement
• Switch part of the
statement sequence of
an outer switch
• Even if the case
constants of inner and
outer switch
statements contain
common values no
conflicts will arise
class NestedSwitchExample {
public static void main(String[] args) {
int i = 0,j = 1;
switch(i)
{
case 0:switch(j)
{
case 0: System.out.println("i is 0, j is 0");
break;
case 1: System.out.println("i is 0, j is 1");
break;
default: System.out.println("nested default
case!!");
}//end of inner switch
break;
default: System.out.println("No matching case
found!!");
} //end of outer switch
}//end of main
}//end of class
The For loop
for(intialization;condition;iteration)
{
Statement;
}
class ForLoop {
public static void main(String args[]) {
for(int x = 1; x < 5; x++) {
System.out.println("value of x : " + x );
}
}
}
Some variations of for loop
• Multiple loop control varaibles can be used.
class Comma{
public static void main(String args[])
{
int i,j;
for(i=0,j=10;i<j;i++,j--)
System.out.println("i="+i+" j="+j);
}//end of main
}//end of class
• Condition controlling variable can be
any valid boolean expression
import java.io.*;
class ForTest {
public static void main(String args[]) throws
IOException {
for(int x = 0; (char)System.in.read() !='S'; x++)
System.out.println("Pass #" + x );
}
}
• Missing pieces
• In java, any or all of the initialization, condition or
iteration portions of the for loop can be blank.
class Empty {
public static void main(String args[]) {
int x = 0;
for(;x<10;) {
System.out.println("Pass #" + x );
x++;
}
}
}
• Infinite loop-loop that never terminates
• For by leaving the conditional expression
empty
for(; ;)
{
…
}
Loops with no body
• Body of the for loop can be empty
• Null statement is syntactically valid
• Body less loops are less often used.
class Nobody{
public static void main(String args[])
{
int i,sum=0;
for(i=1;i<=5;sum+=i++); //sum+=i and then i++
System.out.println(“Sum is “+sum);
}
}
Declaring loop control variables
inside the for loop
• Variable that controls a for loop used
inside the for loop is needed only for the
purposes of the loop and not used
elsewhere
• In this case , it is better to declare the
variables inside the initialization portion of
the for loop.
class ForVar{
public static void main(String args[])
{
int sum=0,fact=1;
for(int i=1;i<=5;i++)
{
sum+=i;
fact*=i;
}//end of for loop
System.out.print("Sum:"+sum+"nFactorial :"+fact);
}//end of main
}//end of class
Enhanced for loop
for (datatype variable: array_name)
{
//body of the for loop
}
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes)
System.out.println(t);
}
}
class EnhancedForLoop1{
public static void main(String[] args) {
String languages[] = { "C", "C++", "Java", "Python",
"Ruby"};
for (String sample: languages) {
System.out.println(sample);
}
}
}
While loop
while(condition)
statements;
• Where statements may be single statement or block of
statements.
• The condition may be any valid boolean expression
• The loop repeats when the condition is true, when it
becomes false, program control passes to line
immediately after the loop.
class WhileDemo{
public static void main(String args[]){
char ch='a';
while(ch<='d'){
System.out.println(ch);
ch++;
}//end of while loop
}//end of main
}//end of class
Do while loop
do{
Statements;
}while(condition);
• It will execute as long
as condition is true.
import java.io.*;
class DWdemo
{
public static void main(String args[])
throws IOException
{
char ch='a';
do
{
System.out.println(ch);
ch++;
}while(ch!='d');
}
}
Break statement
• When a break statement is encountered inside a loop,
the loop is terminated and program resumes at the next
statement followed by the loop.
class BreakDemo{
public static void main(String args[]){
int num=100;
for(int i=0;i<num;i++)
{
if(i*i>=num)
break;
System.out.print(i+ " ");
}
System.out.print("Loop complete");
}
}
Use break as goto statement
class BreakGoto{
public static void main(String args[]){
int i;
for(i=1;i<4;i++)
{
one: {
two:{
three:{System.out.println("n i is "+i);
if(i==1) break one;
if(i==2) break two;
if(i==3) break three;
//this is never executed
System.out.print("wrong statement");
}System.out.println("After block three");
}System.out.println("After block two");
}System.out.println("After block one");
}System.out.println("After for statement");
}
}
Use continue
• The continue statement forces the next
iteration of the loop take place, skipping
the code between itself and conditional
expression that controls the loop.
• Continue is compliment of break
statement
class ContinueDemo{
public static void main(String args[]){
int i;
for(i=0;i<=10;i++)
{
if((i%2)!=0) continue;
System.out.println(i);
}
}
}
Nested loops
• One loop nested inside of another loop
• Nested for loop to find the factors of the numbers from 2 to 20
class FindFac{
public static void main(String args[]){
for(int i=2;i<=20;i++) {
System.out.print("Factors of "+i+" : ");
for(int j=2;j<i;j++)
if((i%j)==0) System.out.print(j+" ");
System.out.println();
}
}
}
Control statements
Ad

More Related Content

What's hot (20)

CONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGECONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGE
Ideal Eyes Business College
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
MUHAMMAD ALI student of IT at karakoram International university gilgit baltistan
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
Chitrank Dixit
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 
C string
C stringC string
C string
University of Potsdam
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
Danial Mirza
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
Functions in c
Functions in cFunctions in c
Functions in c
kalavathisugan
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
Nitin Jawla
 
Strings
StringsStrings
Strings
Nilesh Dalvi
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
tanmaymodi4
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
Kamal Acharya
 

Viewers also liked (8)

Assignement of c++
Assignement of c++Assignement of c++
Assignement of c++
Syed Umair
 
C++ control loops
C++ control loopsC++ control loops
C++ control loops
pratikborsadiya
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
bsdeol28
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)
Muhammad Tahir Bashir
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
Ahmad Idrees
 
C++ loop
C++ loop C++ loop
C++ loop
Khelan Ameen
 
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Assignement of c++
Assignement of c++Assignement of c++
Assignement of c++
Syed Umair
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
bsdeol28
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)
Muhammad Tahir Bashir
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
Ahmad Idrees
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Ad

Similar to Control statements (20)

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
caswenson
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
Java programs
Java programsJava programs
Java programs
Dr.M.Karthika parthasarathy
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
raksharao
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
university of education,Lahore
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
People Strategists
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
Introduction to java programming part 2
Introduction to java programming  part 2Introduction to java programming  part 2
Introduction to java programming part 2
university of education,Lahore
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
 
Core java day1
Core java day1Core java day1
Core java day1
Soham Sengupta
 
A comparison between C# and Java
A comparison between C# and JavaA comparison between C# and Java
A comparison between C# and Java
Ali MasudianPour
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Ad

More from raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 

Recently uploaded (20)

Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 

Control statements

  • 2. Contents • Input charecters from keyboard • if statement • Nested if ‘s • If else if ladder • Switch statement • Nested switch statement • For loop statement • While loop • Do while loop • Break • Continue • Nested loops
  • 3. Input characters from keyboard • In order to read data from keyboard from user, we use System.in.read() • System.in is an input object attached to the keyboard • read() method waits until the user presses key and then return the result. • The character is returned as an integer so it must be casted back into a character and should be stored in a character variable • By default the console input is line buffered. • Buffer refers to small portion of memory that is used to hold the characters before they are read by the program
  • 4. • When the user presses Enter then the value from buffer will be sent to your program. Import java.io.*; class KeyBoardInput{ public static void main(String args[]) throws IOException { char ch; System.out.println("Press a key followed by a letter:"); ch=(char) System.in.read(); System.out.println("Enter letter is :"+ch); }//end of main }//end of class
  • 5. The if statement if(condition) { statement; } class IfExam { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("This is if statement"); } } }
  • 6. If else statement public class IfElseExam { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("This is if statement"); }else{ System.out.print("This is else statement"); } } } if(condition) { statement; } else { statement; }
  • 7. The if else if ladder if(condition) Statement; else if(condition) Statement; else if(Condition) Statement; …. else Statement; class IfElseIfLadder { public static void main(String args[]){ int x = 30; if( x == 10 ) System.out.print("Value of X is 10"); else if( x == 20 ) System.out.print("Value of X is 20"); else if( x == 30 ) System.out.print("Value of X is 30"); else System.out.print("This is else statement"); } }
  • 8. Nested If statements • An if statement that is the target of another if or else class NestedIF { public static void main(String args[]){ int x = 30, y = 10; if( x == 30 ){ if( y == 10 ) System.out.print("X = 30 and Y = 10"); else System.out.println("Y is not 10”); } } }
  • 9. Switch statement • It provides multi way branch • Gives chance to programmer to select among several alternatives. • The value of expression is evaluated against list of constants • When a match is found, the statement sequence associated with that is executed.
  • 10. switch(expression) { case constant1 : Statements break; //optional case constant2 : Statements break;//optional …… default : Statements } class Result { public static void main(String args[]){ char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' :System.out.println("Well done"); break; case 'D' :System.out.println("You passed"); case 'F' :System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }
  • 11. Nested switch statement • Switch part of the statement sequence of an outer switch • Even if the case constants of inner and outer switch statements contain common values no conflicts will arise class NestedSwitchExample { public static void main(String[] args) { int i = 0,j = 1; switch(i) { case 0:switch(j) { case 0: System.out.println("i is 0, j is 0"); break; case 1: System.out.println("i is 0, j is 1"); break; default: System.out.println("nested default case!!"); }//end of inner switch break; default: System.out.println("No matching case found!!"); } //end of outer switch }//end of main }//end of class
  • 12. The For loop for(intialization;condition;iteration) { Statement; } class ForLoop { public static void main(String args[]) { for(int x = 1; x < 5; x++) { System.out.println("value of x : " + x ); } } }
  • 13. Some variations of for loop • Multiple loop control varaibles can be used. class Comma{ public static void main(String args[]) { int i,j; for(i=0,j=10;i<j;i++,j--) System.out.println("i="+i+" j="+j); }//end of main }//end of class
  • 14. • Condition controlling variable can be any valid boolean expression import java.io.*; class ForTest { public static void main(String args[]) throws IOException { for(int x = 0; (char)System.in.read() !='S'; x++) System.out.println("Pass #" + x ); } }
  • 15. • Missing pieces • In java, any or all of the initialization, condition or iteration portions of the for loop can be blank. class Empty { public static void main(String args[]) { int x = 0; for(;x<10;) { System.out.println("Pass #" + x ); x++; } } }
  • 16. • Infinite loop-loop that never terminates • For by leaving the conditional expression empty for(; ;) { … }
  • 17. Loops with no body • Body of the for loop can be empty • Null statement is syntactically valid • Body less loops are less often used. class Nobody{ public static void main(String args[]) { int i,sum=0; for(i=1;i<=5;sum+=i++); //sum+=i and then i++ System.out.println(“Sum is “+sum); } }
  • 18. Declaring loop control variables inside the for loop • Variable that controls a for loop used inside the for loop is needed only for the purposes of the loop and not used elsewhere • In this case , it is better to declare the variables inside the initialization portion of the for loop.
  • 19. class ForVar{ public static void main(String args[]) { int sum=0,fact=1; for(int i=1;i<=5;i++) { sum+=i; fact*=i; }//end of for loop System.out.print("Sum:"+sum+"nFactorial :"+fact); }//end of main }//end of class
  • 20. Enhanced for loop for (datatype variable: array_name) { //body of the for loop } class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) System.out.println(t); } } class EnhancedForLoop1{ public static void main(String[] args) { String languages[] = { "C", "C++", "Java", "Python", "Ruby"}; for (String sample: languages) { System.out.println(sample); } } }
  • 21. While loop while(condition) statements; • Where statements may be single statement or block of statements. • The condition may be any valid boolean expression • The loop repeats when the condition is true, when it becomes false, program control passes to line immediately after the loop.
  • 22. class WhileDemo{ public static void main(String args[]){ char ch='a'; while(ch<='d'){ System.out.println(ch); ch++; }//end of while loop }//end of main }//end of class
  • 23. Do while loop do{ Statements; }while(condition); • It will execute as long as condition is true. import java.io.*; class DWdemo { public static void main(String args[]) throws IOException { char ch='a'; do { System.out.println(ch); ch++; }while(ch!='d'); } }
  • 24. Break statement • When a break statement is encountered inside a loop, the loop is terminated and program resumes at the next statement followed by the loop. class BreakDemo{ public static void main(String args[]){ int num=100; for(int i=0;i<num;i++) { if(i*i>=num) break; System.out.print(i+ " "); } System.out.print("Loop complete"); } }
  • 25. Use break as goto statement class BreakGoto{ public static void main(String args[]){ int i; for(i=1;i<4;i++) { one: { two:{ three:{System.out.println("n i is "+i); if(i==1) break one; if(i==2) break two; if(i==3) break three; //this is never executed System.out.print("wrong statement"); }System.out.println("After block three"); }System.out.println("After block two"); }System.out.println("After block one"); }System.out.println("After for statement"); } }
  • 26. Use continue • The continue statement forces the next iteration of the loop take place, skipping the code between itself and conditional expression that controls the loop. • Continue is compliment of break statement
  • 27. class ContinueDemo{ public static void main(String args[]){ int i; for(i=0;i<=10;i++) { if((i%2)!=0) continue; System.out.println(i); } } }
  • 28. Nested loops • One loop nested inside of another loop • Nested for loop to find the factors of the numbers from 2 to 20 class FindFac{ public static void main(String args[]){ for(int i=2;i<=20;i++) { System.out.print("Factors of "+i+" : "); for(int j=2;j<i;j++) if((i%j)==0) System.out.print(j+" "); System.out.println(); } } }