EmSAT Achieve Exam  >  EmSAT Achieve Notes  >  Java for EmSAT Achieve  >  While Loop in Java

While Loop in Java | Java for EmSAT Achieve PDF Download

Introduction

When writing programs, it is often necessary to repeat a set of instructions multiple times until a certain condition is met. This is where loops come into play. In Java, one of the most commonly used loops is the while loop. This article aims to provide a comprehensive guide to understanding while loops, including their syntax, working principles, and practical examples.

What is a while loop?

A while loop is a control flow statement that allows a block of code to be repeated as long as a specified condition is true. It is called a "pre-test loop" because the condition is checked before the block of code is executed. If the condition evaluates to true, the code inside the loop is executed. If the condition evaluates to false, the loop is terminated, and the program continues with the next statement.

Syntax of a while loop

The syntax of a while loop in Java is as follows:

while (condition) {

    // code to be executed

}

The condition is a boolean expression that determines whether the loop should continue or terminate. The code inside the loop is enclosed within curly braces {}.

How does a while loop work?

When a while loop is encountered, the condition is evaluated. If the condition is true, the code block is executed. Afterward, the condition is evaluated again, and if it is still true, the code block is executed again. This process continues until the condition becomes false, at which point the loop terminates, and the program moves on to the next statement.
It's important to ensure that the condition inside the while loop eventually becomes false; otherwise, the loop will run indefinitely, resulting in an infinite loop.

Examples of while loops

Let's explore some examples to illustrate how while loops work.

Example 1: Counting from 1 to 5

int count = 1;

while (count <= 5) {

    System.out.println(count);

    count++;

}

Output

1

2

3

4

5

Explanation: In this example, we start with count initialized to 1. The condition count <= 5 is evaluated, and since it is true, the code block inside the loop is executed. The value of count is printed, incremented by 1, and the condition is evaluated again. This process repeats until count becomes 6, at which point the condition becomes false, and the loop terminates.

Example 2: Summing numbers

int sum = 0;

int number = 1;

while (number <= 10) {

    sum += number;

    number++;

}

System.out.println("Sum: " + sum);

Output

Sum: 55

Explanation: In this example, we initialize sum to 0 and number to 1. The loop continues as long as number is less than or equal to 10. Inside the loop, the value of number is added to sum, and number is incremented. This process repeats until number becomes 11, at which point the loop terminates. Finally, the sum is printed.

Example 3: User input validation

import java.util.Scanner;


Scanner scanner = new Scanner(System.in);

int age = 0;

while (age <= 0) {

    System.out.print("Enter your age: ");

    age = scanner.nextInt();

    if (age <= 0) {

        System.out.println("Invalid age. Please enter a positive value.");

    }

}

System.out.println("Valid age: " + age);

Output

Enter your age: -5

Invalid age. Please enter a positive value.

Enter your age: 25

Valid age: 25

Explanation: In this example, the program prompts the user to enter their age. The input is stored in the age variable. The loop continues as long as the value of age is less than or equal to 0. If the user enters a negative or zero value, an error message is displayed, and the loop repeats. Once the user enters a positive value, the loop terminates, and the valid age is printed.

Sample Problems

1. Write a program that calculates the factorial of a given number using a while loop.

import java.util.Scanner;


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();


int factorial = 1;

int i = 1;

while (i <= number) {

    factorial *= i;

    i++;

}

System.out.println("Factorial of " + number + " is " + factorial);

2. Modify the previous program to validate that the user enters a positive number.

import java.util.Scanner;


Scanner scanner = new Scanner(System.in);

int number = -1;

while (number <= 0) {

    System.out.print("Enter a positive number: ");

    number = scanner.nextInt();

    if (number <= 0) {

        System.out.println("Invalid number. Please enter a positive value.");

    }

}

int factorial = 1;

int i = 1;

while (i <= number) {

    factorial *= i;

    i++;

}

System.out.println("Factorial of " + number + " is " + factorial);

Conclusion

In this article, we have explored the while loop in Java. We discussed its syntax, working principles, and provided examples demonstrating different use cases. Understanding while loops is crucial for building programs that involve repetitive tasks. By practicing and applying while loops effectively, you can create more efficient and dynamic Java programs.

The document While Loop in Java | Java for EmSAT Achieve is a part of the EmSAT Achieve Course Java for EmSAT Achieve.
All you need of EmSAT Achieve at this link: EmSAT Achieve
60 videos|37 docs|12 tests

Top Courses for EmSAT Achieve

60 videos|37 docs|12 tests
Download as PDF
Explore Courses for EmSAT Achieve exam

Top Courses for EmSAT Achieve

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

ppt

,

While Loop in Java | Java for EmSAT Achieve

,

While Loop in Java | Java for EmSAT Achieve

,

Free

,

mock tests for examination

,

Extra Questions

,

Exam

,

practice quizzes

,

Important questions

,

pdf

,

Summary

,

While Loop in Java | Java for EmSAT Achieve

,

shortcuts and tricks

,

past year papers

,

study material

,

MCQs

,

Previous Year Questions with Solutions

,

Semester Notes

,

Objective type Questions

,

video lectures

,

Viva Questions

,

Sample Paper

;