Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views31 pages

(Lesson 4) Loops

The document provides an overview of iterative statements (loops) in Java, specifically focusing on 'for', 'while', and 'do-while' loops. It explains the structure of loops, including initialization, condition, and incrementation, and offers various examples demonstrating how to use loops for tasks such as printing numbers, calculating sums, and determining prime numbers. Additionally, it includes practical coding examples and exercises for users to practice their understanding of loops.

Uploaded by

sskx55nchb
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)
10 views31 pages

(Lesson 4) Loops

The document provides an overview of iterative statements (loops) in Java, specifically focusing on 'for', 'while', and 'do-while' loops. It explains the structure of loops, including initialization, condition, and incrementation, and offers various examples demonstrating how to use loops for tasks such as printing numbers, calculating sums, and determining prime numbers. Additionally, it includes practical coding examples and exercises for users to practice their understanding of loops.

Uploaded by

sskx55nchb
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
You are on page 1/ 31

Iterative Statements (loops):

(for, while, and do-while)

Dr. Ali Allam Introduction to Programming (BIS227E)


Java Loops: Overview

 Often when you write code, you might want the same block of code to run
over and over again (i.e. repetition). So, instead of adding several almost
identical lines in a program, we can use loops to perform a task like this.
 For example, suppose you want to print numbers from 1 to 100. Without
a loop, the only way to perform this task is to write 100 statements, each
of which prints a different number from 1 to 100. Of course, you can
realize that this is an unrealistic solution.
 So, this is where a loop comes as a realistic solution to perform a task that
requires repetition or iteration.
Java Loops

 In Java, we have the following kinds of loops:


 while
 for
 do-while
Java Loops

 Any loop is composed of three main parts:


1. Initialization → specifies the initial value from which the loop starts.
2. Condition → controls the continuity of the loop, as long as the condition is
true.
3. Incrementation → specifies the incremental or decremental step which
makes the condition turn to false, forcing the loop to stop.
Example: Print numbers from 1 to 100

 For example, a loop that prints numbers from 1 till 100:


1. Initialization → the loop starts counting from 1
2. Condition → the loop keeps repeating as long as the loop counter is
below 100.
3. Incrementation → the loop counter increments by 1.
Example: using while loop

 A while loop that prints numbers from 1 till 100:


Syntax Example Note:
initialization; int i = 1; Curly brackets are
while (condition) while (i <= 100) mandatory in this
{ { example because
statement(s) repeated as System.out.println(i); there are two
long as the condition is true; i++; statements to be
incrementation; } executed in the loop
} body.
Example: using for loop

 A for loop that prints numbers from 1 till 100:


Syntax Example
for (initialization; condition; incrementation) for (int i = 1; i <= 100; i++)
{ {
statement(s) repeated as long as the System.out.println(i);
condition is true; }
}

Note:
Curly brackets are optional in this example
because there is only one statement in the
loop body.
Example: using do-while loop

 A do-while loop that prints numbers from 1 till 100:


Syntax Example Note:
initialization; int i = 1; Curly brackets are
do do mandatory in this
{ { example because
statement(s) repeated as System.out.println(i); there are two
long as the condition is true; i++; statements to be
incrementation; } executed in the loop
} while (i <= 100); body.
while (condition);
More Examples

Example (1) Example (2) Example (3)


2, 4, 6, 8, … 20 2, 4, 8, 16, 32, … 1024 100, 90, 80, 70, … 10
int i = 2; int i = 2; int i = 100;
while (i <= 20) while (i <= 1024) while (i >= 10)
{ { {
System.out.println(i); System.out.println(i); System.out.println(i);
i = i+2; i = i*2; i = i-10;
} } }

 Practice: re-write them again using for and do-while loops.


How about asking the user to enter the starting and
ending values. So, the program prints all the
numbers in between.
Example (1): Print all numbers between the two
inputs (x) and (y)

import javax.swing.*;
public class Prog1
{
public static void main(String[] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter the first number:"));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter the last number:"));
for (int i=x; i<=y; i++)
System.out.println(i);
}
}
Example (1): Print all numbers between the two
inputs (x) and (y)
Output console
5
6
7
8
9
10
11
12
13
14
15
How about printing out these numbers
in one message box
Example (2): Print all numbers between the two
inputs (x) and (y), in one message box
Example (2): Print all numbers between the two
inputs (x) and (y), in one message box

import javax.swing.*;
public class Prog2
{
public static void main(String[] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter the first number:"));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter the last number:"));
JTextArea msg = new JTextArea();
for (int i=x; i<=y; i++)
msg.append(i + "\n");
JOptionPane.showMessageDialog(null, msg);
}
}
Now, suppose that we want to add up all the numbers
between 1 and 10, instead of just printing them out.
Example (3): Add the numbers between 1 and 10

import javax.swing.*; import javax.swing.*;


public class Prog3A public class Prog3B
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int sum=0; int sum=0;
for (int i=1; i<=10; i++) for (int i=1; i<=10; i++)
{ {
sum += i; sum += i;
} System.out.println("The sum is: " + sum);
System.out.println("The sum is: " + sum); }
} }
} }
What’s the difference between the two previous
programs, Prog3A.php and Prog3B.php ?
Example (4): Display the sum of all the numbers
up to (m), in a table

Enter a number: 7
Num Sum
--------------------
Can you add up all the 1 1
numbers between 1 and m, to 2 3
3 6
get an output that looks like 4 10
this one in a tabular format? 5 15
6 21
7 28
Example (4): Display the sum of all the numbers
up to (m), in a table import java.util.*;
public class Prog4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int m = input.nextInt();
int sum = 0;
System.out.println("Num\t\tSum\n-------------");
for (int i=1; i<=m; i++)
{
sum += i;
System.out.println(i+"\t\t"+sum);
}
}
}
import javax.swing.*;
public class Prog4B{
public static void main(String[] args)
{
int m =
Integer.parseInt(JOptionPane.showInputDialog("Enter the
last number:"));
JTextArea msg = new JTextArea();
msg.append("Number\tSum\n=================\n");
int sum=0;
for (int i=1; i<=m; i++)
{
sum +=i;
msg.append(i + "\t" + sum + "\n");
}
JOptionPane.showMessageDialog(null, msg);
}
}
Can you calculate the factorial of a number entered by the
user? The factorial of m is given by:
m! = 1 * 2 * 3 * … * m
So, it’s simply multiplying all the numbers between 1 and m
Example (5): Calculate the factorial of input (m)

import java.util.*;
public class Prog5
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: "); Enter a number: 7
int m = input.nextInt(); The factorial of 7 is 5040
int fact = 1;
for (int i=1; i<=m; i++)
fact = fact * i;

System.out.println("The factorial of " + m + " is " +fact);


}
}
Can you display the factorial of all the
numbers up to (m), that looks like this one?
Think of it ☺

Enter a number: 7
Num: 1 2 3 4 5 6 7
Fact: 1 2 6 24 120 720 5040
Example (6): Ensuring a valid value

A loop is a common way to ensure that a user inputs a valid value. The program shall
not accept an invalid input from the user. It keeps asking the user to re-enter the
value until it is valid.
Example (6): Ensuring a valid value

import javax.swing.*;
public class Prog6
{
public static void main(String[] args)
{
int mark = Integer.parseInt(JOptionPane.showInputDialog("Enter your total mark: "));
while(mark<0 || mark>100)
mark = Integer.parseInt(JOptionPane.showInputDialog("Invalid. Re-enter your mark: "));

if(mark>=60)
JOptionPane.showMessageDialog(null, "You passed the course!");
else
JOptionPane.showMessageDialog(null, "You failed the course!");
}
}
Example (7): Loan Calculator

A client applies for a bank loan to buy home appliances. The banker enters the
loan amount (e.g. 10000), as well as the monthly interest rate (e.g. 0.02). Then, the
program prints a detailed statement of the total amount required to be paid over
12 months. The following formula is used by the bank to calculate the amount to be
paid according to the number of months:

Amount = Loan  (1 + Interest) month


import java.util.*; Enter the loan amount: 10000
public class Prog7 Enter the monthly interest rate: 0.015
{ Month Amount
public static void main(String[] args) 0 10000.00
{
1 10150.00
Scanner input = new Scanner(System.in);
System.out.print("Enter the loan amount: "); 2 10302.25
int loan = input.nextInt(); 3 10456.78
System.out.print("Enter the monthly interest rate: "); 4 10613.64
double intr = input.nextDouble(); 5 10772.84
System.out.println("Month\tAmount"); 6 10934.43
for(int i=0; i<=12; i++) 7 11098.45
{ 8 11264.93
double amount = loan*Math.pow(1+intr,i);
9 11433.90
System.out.printf("%d\t%.2f\n", i, amount);
} 10 11605.41
} 11 11779.49
} 12 11956.18
Example (8): Decide whether an input is a prime
number or not

Let’s take one more example of using loops … The user is asked
to enter a number and the program tells the user whether it is a
prime number or not.
Tip: A prime number is the one that has exactly divisors, 1 and
itself. (i.e. it is divisible only by 1 and itself, and nothing else).
import javax.swing.*;
public class Prog8
{
public static void main(String[] args)
{
int m = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
boolean status = true;
for (int i=2; i<=m-1; i++)
{
if(m%i==0)
status=false;
}
if(status==true && m!=1)
JOptionPane.showMessageDialog(null, m+ " is a prime number");
else
JOptionPane.showMessageDialog(null, m+ " is NOT a prime number");
}
}
If the user inputs 5 If the user inputs 9 If the user inputs 1

You might also like