0% found this document useful (0 votes)
84 views4 pages

Java Loops: For, While, Do-While

Uploaded by

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

Java Loops: For, While, Do-While

Uploaded by

Abhinav Ashish
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java - Introduction to Programming

Lecture 4

Loops
A loop is used for executing a block of statements repeatedly until a particular
condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.

For Loop
The syntax of the for loop is :

for (initialization; condition; update) {


// body of-loop
}

for (int i=1; i<=20; i++) {


[Link](i);
}

While Loop
The syntax for while loop is :
while(condition) {
// body of the loop
}

int i = 0;
while(i<=20) {
[Link](i);
i++;
}

Do-While Loop
The syntax for the do-while loop is :
do {
// body of loop;
}
while (condition);

int i = 0;
do {
[Link](i);

Apna College
i++;
} while(i<=20);

Homework Problems
1. Print all even numbers till n.
2. Run
for(; ;) {

[Link]("Apna College");

loop on your system and analyze what happens. Try to think of the reason for
the output produced.

3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.

If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

Because marks don’t matter but our effort does.

(Hint : use do-while loop but think & understand why)

BONUS

Qs. Print if a number is prime or not (Input n from the user).

[In this problem you will learn how to check if a number is prime or not]

Apna College
Homework Solution (Lecture 3)

import [Link].*;

public class Conditions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int operator = [Link]();

/**
* 1 -> +
* 2 -> -
* 3 -> *
* 4 -> /
* 5 -> %
*/

switch(operator) {
case 1 : [Link](a+b);
break;
case 2 : [Link](a-b);
break;
case 3 : [Link](a*b);
break;
case 4 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a/b);
}
break;
case 5 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a%b);
}
break;
default : [Link]("Invalid Operator");
}
}

Apna College
}

Apna College

Common questions

Powered by AI

Handling division by zero explicitly in input-driven applications is crucial because division by zero is undefined and will result in runtime errors that could crash the application. To prevent such interruptions and offer a smooth user experience, input validation checks are implemented to ensure that division operations are only attempted with non-zero divisors, using conditional logic to maintain program stability and provide informative user feedback .

In Java, a for loop is structured with three distinct parts in its signature: initialization, condition, and update, within a single line syntax `for (initialization; condition; update) { // body of loop }`. This allows for a compact iteration control mechanism. A while loop, on the other hand, only includes the condition in its syntax `while(condition) { // body of the loop }`, with initialization and update steps needing to be handled inside the loop body or before the loop begins .

In Java, a program can determine if a number is prime by iteratively checking divisibility from 2 to the square root of the number. If the number is divisible by any number in this range, it is not prime. The significance of prime number functionality lies in its application in a range of fields such as cryptography, where prime numbers are a core element of encryption algorithms, and computational mathematics for solving complex number theory problems .

Using categorical conditions to assess marks is beneficial because it provides a structured way to categorize scores into qualitative feedback. This approach not only makes the interpretation of marks easier for users by associating them with qualitative descriptors but also aligns program logic with decision-making processes that reflect real-world assessment scenarios, offering immediate feedback and enhancing user understanding of performance levels .

The loop `for(;;) { System.out.println("Apna College"); }` is considered an infinite loop because it lacks a condition to terminate. It has no initialization, condition, or update defined, meaning the loop will repeatedly execute with no exit strategy, continuously printing "Apna College" until the program is externally interrupted or manually terminated. This can cause high CPU usage and system resource consumption .

The `switch-case` statement in Java demonstrates the concept of control flow and decision-making. It allows a program to execute different blocks of code based on the value of a variable, enhancing code readability and providing clear decision paths when there are multiple potential execution outcomes. This is typically used for cases where a number of possible discrete values are known, as in selecting operations like addition, subtraction, etc., based on user input .

The scanner object in Java facilitates user interaction by allowing the program to parse primitive types and strings from a provided input stream, typically System.in for console applications. By using methods like `nextInt()` or `nextLine()`, it provides a straightforward means of capturing user input, enabling dynamic interaction where program behavior can adapt based on user-provided data .

Implementing a program that prints even numbers up to a user-defined limit provides educational benefits by strengthening the understanding of loop constructs, conditionals, and arithmetic operations. It encourages problem-solving, algorithmic thinking, and introduces concepts of iteration through practical application, helping to cement foundational programming skills while offering a relatable context for understanding numerical logic and control flow .

In a menu-driven program, a do-while loop is beneficial because it ensures the program enters the loop, displays the menu, and processes at least one user input before checking the exit condition. This aligns with user interaction design by guaranteeing that users can perform at least one operation before choosing to exit, thus facilitating continuous interaction until a defined exit command is issued .

The primary difference between a while loop and a do-while loop in Java is that a while loop checks the condition before executing the loop body, meaning the loop body may not execute at all if the condition is false initially. In contrast, a do-while loop executes the loop body first and checks the condition afterward, ensuring that the loop body runs at least once regardless of the condition .

You might also like