Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Loop Statements Java Loop Statements

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

JAVA LOOP

STATEMENTS
Introduction, Java Loops

Java, a versatile and widely-used


programming language, offers several
tools for controlling the flow of a
program.
- Among these, loops are essential
constructs that allow developers to
repeat a specific set of actions.
- In this presentation, we will delve into
the world of Java loops and explore their
types and applications.
Types Of Loops
1. For loop
2. While loop
3. Do-While loop
For Loops

For loops are used to execute a block of


code a fixed number of times. They
consist of an initialization statement, a
condition, and an increment/decrement
statement. For loops are commonly used
when the number of iterations is known
in advance.
Syntax:
for(init; condition; icr/dcr){ //statements
to be repeated }
For Loops Example

// Program to print a text 5 times

class Main {
public static void main(String[] args) {

int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
While Loops

While loops are used to execute a


block of code repeatedly as long as a
certain condition is true. They consist
of a condition and a block of code.
While loops are commonly used when
the number of iterations is not known
in advance.
Syntax
while (testExpression) {
// body of loop
}
While Loops Example

// Program to display numbers from 1 to


5

class Main {
public static void main(String[] args) {

// declare variables
int i = 1, n = 5;

// while loop from 1 to 5


while(i <= n) {
System.out.println(i);
i++;
}
}
}
Do-While Loops

Do-while loops are similar to while loops,


but the block of code is executed at least
once, even if the condition is initially
false. They consist of a block of code and
a condition. Do-while loops are
commonly used when you want to
execute a block of code at least once.

Syntax:
do {
// body of loop
} while(textExpression);
Do-While Looops
Exmaple

// Java Program to display numbers


from 1 to 5

import java.util.Scanner;

// Program to find the sum of natural


numbers from 1 to 100.

class Main {
public static void main(String[] args) {

int i = 1, n = 5;

// do...while loop from 1 to 5


do {
System.out.println(i);
i++;
} while(i <= n);
}
}
Thanks!

VENKITT SURESH
venkittsuresh@gmail.com

You might also like