[go: up one dir, main page]

0% found this document useful (0 votes)
26 views10 pages

Aha 4

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views10 pages

Aha 4

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Java if statement with Examples
Java if-else
Java if-else-if ladder with Examples
Loops in Java
For Loop in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Continue Statement in Java
Break statement in Java
Usage of Break keyword in Java
return keyword in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Java do-while loop with Examples
Last Updated : 22 Mar, 2023
Loops in Java come into use when we need to repeatedly execute a block of
statements. Java do-while loop is an Exit control loop. Therefore, unlike for or
while loop, a do-while check for the condition after executing the statements of
the loop body.

Syntax:

do
{
// Loop Body
Update_expression
}

// Condition check
while (test_expression);
Note: The test_expression for the do-while loop must return a boolean value , else
we would get compile-time error.

Application of do-while : Its example application is showing some kind of menu to


the users.

For example:

You are implementing a game where you show some options to the user, press 1 to do
this .., press 2 to do this .. etc and press ‘Q’ to quit the game. So here you want
to show the game menu to the user at least once, so you write the code for the game
menu inside the do-while loop.

Illustration:

// Java Program to Illustrate One Time Iteration


// Inside do-while Loop
// When Condition IS Not Satisfied

// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// initial counter variable
int i = 0;

do {

// Body of loop that will execute minimum


// 1 time for sure no matter what
System.out.println("Print statement");
i++;
}

// Checking condition
// Note: It is being checked after
// minimum 1 iteration
while (i < 0);
}
}
Output
Print statement
Output explanation:

In the above code, we figured out that the condition is checked later as the body
inside do will get executed one time without fail as the condition is checked later
onwards. Hence whenever we want to display the menu and later on proceed command on
the terminal, we always use do-while loop.

Components of do-while Loop


A. Test Expression: In this expression, we have to test the condition. If the
condition evaluates to true then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the while loop. For example:

i <= 10
B. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value. For example:

i++;
Execution of do-While loop
Control falls into the do-while loop.
The statements inside the body of the loop get executed.
Updation takes place.
The flow jumps to Condition
Condition is tested.
If Condition yields true, go to Step 6.
If Condition yields false, the flow goes outside the loop
The flow goes back to Step 2.
Flowchart do-while loop:

Implementation:

Example 1: This program will try to print “Hello World” 5 times.

// Java Program to Illustrate Do-while Loop

// Class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initialization expression


int i = 1;

// Do-while loop
do {

// Body of do-while loop


// Print statement
System.out.println("Hello World");

// Update expression
i++;
}

// Test expression
while (i < 6);
}
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World

Auxiliary Space: O(1)

Output explanation:

The program will execute in the following manner as follows:

Program starts.
i is initialized with value 1.
Execution enters the loop
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 < 6 yields true.
Execution enters the loop.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 < 6 yields false.
The flow goes outside the loop.
Example 2

// Java Program to Illustrate Do-while Loop

// Class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring and initializing integer values
int x = 21, sum = 0;

// Do-while loop
do {

// Execution statements(Body of loop)

// Here, the line will be printed even


// if the condition is false
sum += x;
x--;
}

// Now checking condition


while (x > 10);

// Summing up
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 176

Example 3: do-while loop without curly braces {}

/*package whatever //do not write package name here */

import java.io.*;

class GFG {
public static void main (String[] args) {
int i=1;
do
// only single statement in do block
System.out.println("Hello GFG!");
// this condition is false so only do block will execute
while(i>=3);

}
}
Output
Hello GFG!
&list=PLqM7alHXFySF5ErEHA1BXgibGg7uqmA4_&ab_channel=GeeksforGeeks

Related Articles:

Loops in Java
Java For loop with Examples
Java while loop with Examples
Difference between while and do-while loop in C, C++, Java
Difference between for and do-while loop in C, C++, Java

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Hello friends, how are you doing? Welcome to my JavaPlay Video


C

Chinmoy Lenka

42
Previous Article
Java while loop with Examples
Next Article
For-each loop in Java
Read More
Down Arrow
Similar Reads
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement. Syntax : while (boolean condition){ loop
statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using
namespace std; int main() { int i =
2 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as
a repeating if statement. While loop in Java comes into use when we need to
repeatedly execute a block of statements. The while loop is considered as a
repeating if statement. If the number o
4 min read
Difference between for and do-while loop in C, C++, Java
for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping. Syntax: for (initialization condition; testing condition;
increment/decrement) { statement(s) } Flow
2 min read
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a
set of statements a specific number of times. However, there are differences in
their declaration and control flow. Let's understand the basic differences between
a for loop and a while loop. for Loop A for loop provides a concise way of writing
the loop structure.
5 min read
C++ While Loop
While Loop in C++ is used in situations where we do not know the exact number of
iterations of the loop beforehand. The loop execution is terminated on the basis of
the test condition. Loops in C++ come into use when we need to repeatedly execute a
block of statements. During the study of the 'for' loop in C++, we have seen that
the number of itera
3 min read
C++ Do/While Loop
Loops come into use when we need to repeatedly execute a block of statements. Like
while the do-while loop execution is also terminated on the basis of a test
condition. The main difference between a do-while loop and a while loop is in the
do-while loop the condition is tested at the end of the loop body, i.e do-while
loop is exit controlled where
3 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating
if statement. It is mostly used in situations where the exact number of iterations
beforehand. Below is the image to illustrate the while loop: Syntax:
while(test_expression){ // state
6 min read
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program
multiple times. For-loop is the most commonly used loop in java. If we know the
number of iteration in advance then for-loop is the best choice. Syntax:
for( initializationsection ; conditional check ; increment/decrement section) { //
Code to be executed } Curly braces i
5 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a
differential equation. It manages the devices and the systems using control loops.
There are Open-Loop Control System and Closed-Loop Control System. Open-Loop
Control System is used in applications in which no feedback and error handling are
required. It is simple an
3 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases
analyse different aspects of the problem. Case 1 : for (int i = 2; i &lt;=n; i =
pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values
2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less
than or equal to n, an
1 min read
Article Tags :
Java
Misc
School Programming
java-basics
Practice Tags :
Java
Misc
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like