Table of contents
while Loop and do-while Loop
while
loops and do-while
loops are used for repetitive tasks. They execute a block of code as long as it satisfies the condition. However, while loops and do while loops differ in execution process.
The while
loop checks the condition before executing the block of code. The block of code will not execute if condition isn't being satisfied. On the other hand. The do-while
loop executes the block of code first, and then checks the condition. The block of code is guaranteed to execute at least once, regardless of whether the condition is true or false initially.
int i = 1, n = 20 ;
while (i < n)
{
System.out.println(i);
i = i*2;
}
It print numbers from 1 to 16.
int i = 1, n = 20;
do
{
System.out.println(i); //debug - directly jumps at the here
i = i*2;
} while (i < n); // then checks the condition
This will also print numbers from 1 to 16. But even if i
were initialized to 20, it would still print 20 before existing the loop.
Most of the time, they work similar.
for Loop
In Java, for
loop is a control flow statement for repeated execution of a block of code. It is used when generally number of iteration is pre fixed (for = for this many times). Imagine, mixing sugar with coffee. You want to add sugar to sweeten your coffee. Now, if you do this task through while
loop, sugar is going to be added in your coffee until it can't make it sweeter. On the other hand, if you use for
loop here, than you know adding 2 spoon of sugar is enough so you add only 2 spoons.
Syntax :
for (initialization; condition; increment/decrement)
{
// code to be executed
}
First, initialization -> condition is checked -> code is executed -> increment/decrement -> condition checking -> code is executed -> increment/decrement -> condition checking...
So, only these 3 part of the for loop is done repeatedly.
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
As I mentioned, the initialization part will be executed only once, and you can declare a variable here too. Then the condition is checked; i
is less than 5, so it will print 1. Then i
will increase to 2. It will check the condition again to see if the updated value of i
fulfills the condition or not. Thus, 1, 2, 3, and 4 will be printed for this code.
Practicing "for loops"
public class Loops
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i*=4)
{
System.out.println(i);
}
}
}
The loop will print the values of i
for each iteration:
First iteration**:**
i = 1
Second iteration**:**
i = 4
(since 1 * 4 = 4)Third iteration**:**
i = 16
(since 4 * 4 = 16)
Since 16 is greater than 10, the loop terminates after the second iteration. Therefore, the output will be 1,4
public class Loop
{
public static void main(String[] args)
{
int i = 1 ;
for (; i > 0 ; i--)
{
System.out.println(i);
}
}
}
Initialization is optional. The loop will print the values of i
for each iteration. The outputs will be 10,9,8,7,6,5,4,3,2,1.
public class Loops
{
public static void main(String[] args)
{
int i = 1;
for (System.put.println("Hello"); i <= 10; i*=4)
{
System.out.println(i);
}
}
}
The loop will print "Hello" once before entering the loop. Then, it will print the value of i
for each iteration. Outputs : Hello, 1, 4
public class Loops
{
public static void main(String[] args)
{
int i = 1;
for (; i <= 10;)
{
System.out.println(i);
i*=4;
}
}
}
Updating is also optional, just like initialization.
Another thing is, you can also remove the condition from the statement, but it will run infinitely. So if you want an infinite loop, then don't write anything/ write true
in the for
statement.
public class Loops
{
public static void main(String[] args)
{
for (int i = 0, j = 1 ; i <= 5; i++, j *= 2)
{
System.out.println(i+ " " +j);
}
}
}
Output:
The loop prints the values of i
and j
for each iteration:
First iteration:
i = 0, j = 1
Second iteration:
i = 1, j = 2
Third iteration:
i = 2, j = 4
Fourth iteration:
i = 3, j = 8
Fifth iteration:
i = 4, j = 16
Sixth iteration:
i = 5, j = 32
Homework
In loop, your observation in important. Again saying, your observation is important.
Display multiplication table.
[Let's say, n=5, so output will be 5*1 = 5, 5*2 = 10....5*10 = 50]
Find sum of n numbers.
[ Let's say, n = 10. So the sum will be 1+2+3+4+...+10. The output will be "Sum of 10 numbers is 55" ]
Factorial of a number.
[ Let's say, n = 5. So, the factorial of n will be 1x2x3x4x5 = 120. The output will be "5! = 120"]
Display Digits
[ Let's say n = 257. Now you have to display digits from it. Take out the remainder by using mod. then divide n by 10, you will be left with the number 25 (new n). then repeat the process again. You need to use while loop here cause you don't know how many times you have to repeat the steps]
Count digits of a number
[ Lets' say, n = 2359. The process is same like the previous. Just maintain a counter here. Each time dividing, increase the counter by 1]
Finding a number is Armstrong or not
[ Armstrong number : Let's say, n = 153. Take out the digits, cube it then add them and if the addition is also 153, that means it's an Armstrong number. Use
Math.pow()
method to cube the digits, or manually add it like, digit*digit*digit. Note:Math.pow()
could through error]Reverse a number
[ same as question 4. Let's say, n = 273. You just need to multiply the remaining n, and the add it with the remainder, simple]
Check a number is palindrome
[ Let's say, n = 12521. If the reverse of n = n, then it's a palindrome. Otherwise, it's not a palindrome ]
Display a number in words even with tailing 0.
[ Let's say, n = 237. You have to print "two three seven". n = 1700, print "one seven zero zero".. First, reverse the n and put it into string (To avoid loosing zero, for example, the number 1700. Then again reverse the string n using for loop. The take a char variable. Take out the characters using
chatAt()
method.]import java.util.*; public class LoopTailing0 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); int n = sc.nextInt(); // 237 String x = ""; int r; while (n>0) { r = n%10; n = n/10; x = x+r; // 732 } System.out.println(x); char c; for (int i = 0; i < x.length(); i++) // Iterate from the beginning to the end { c = x.charAt(i); switch(c) { case '0': System.out.print("Zero "); break; case '1': System.out.print("One "); break; case '2': System.out.print("Tw0 "); break; case '3': System.out.print("Three "); break; case '4': System.out.print("Four "); break; case '5': System.out.print("Five "); break; case '6': System.out.print("Six "); break; case '7': System.out.print("Seven "); break; case '8': System.out.print("Eight "); break; case '9': System.out.print("Nine "); break; default: System.out.print("Invalid "); break; } } sc.close(); } }
Fibonacci
Display AP series
[Arithmetic Progression series.
5,10,15,20
or,3,8,13,18,23
, or7,9,11,13,15
and so on. They have a common difference between them, d = 10-5 = 5. It will take a starting pointa
, a common differenced
, then how many terms you wantn
Formation: a + ad + a2d + a3d ...+ and]
Display GP series
[ Geometric Progression 2,6,18,54..... or, 5,10,20,40. Instead of adding, we are multiplying here. Use common ration instead of common difference
Formation: a + ar + ar^2 + ar^3 +....+ ar^n]
Display Fibonacci series
[ Starts with 0 and 1. Every next term is obtained adding the previous two terms. Google for more.
Formation fib(n) = fib(n-2) + fib(n-1)]
Nested loops
Nested loops in Java are loops within loops. This means you have one loop (the outer loop) containing another loop (the inner loop). Nested loops are useful for tasks that require iteration over multi-dimensional data structures like matrices, grids, or tables.
Example: Nested Loops
Here is a simple example of nested loops in Java.This example prints a multiplication table:
public class NestedLoopExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{ // Outer loop
for (int j = 1; j <= 10; j++)
{ // Inner loop
System.out.print(i * j + "\t"); // Multiply i and j, then print the result with a tab space
}
System.out.println(); // Move to the next line after the inner loop completes
}
}
}
Explanation
Outer Loop (
for (int i = 1; i <= 10; i++)
):This loop runs from
i = 1
toi = 10
.For each iteration of the outer loop, the inner loop runs to completion.
Inner Loop (
for (int j = 1; j <= 10; j++)
):This loop runs from
j = 1
toj = 10
.For each iteration of the inner loop, the product of
i
andj
is calculated and printed.
Printing the Result (
System.out.print(i * j + "\t")
):The product of
i
andj
is printed, followed by a tab space (\t
).This keeps the products of the inner loop on the same line.
Moving to the Next Line (
System.out.println()
):After the inner loop completes,
System.out.println()
moves the cursor to the next line.This starts a new row for the next iteration of the outer loop.
Output
The output of the above code will be a 10x10 multiplication table:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Homework
The homework for nested loops can be a bit tricky to explain in a blog, so I left it out. Don't worry, you don't need to stress about it. I recommend looking up some nested loop problems online and trying to solve 5 or 6 of them. That should be enough.
Previous (Conditional Statements) Homework answer #1
Question 1: Find a is odd or even. Find a person is young or not. Find grades for given marks
Question 2: Find if a person is young or not. If the age is greater than 18 and less than 55, then the person is young.
Question3: Find grades for given marks. Above 90 -> A, Above 50 -> C, Below 50 ->F
Previous (Conditional Statements) Homework answer #2
Find radix (the base of a number system) of a number given in a string. (out of syllabus, will cover later. Topic to learn : Regular expression, String Category)
Find if a given year is a leap year or not. Input will be a year.
Previous (Conditional Statements) Homework answer #3
Display name of a day based on number (Day 1 means Monday)
Find type of website and the protocol used.
( String url = "google.com". you have to find what is there before the colon, take out the substring. If it's http, say "hyper text transfer protocol", if it's ftp then say "file transfer protocol". Next thing you need to do is, you have to take out com. So search for the dot, then take out the leftover and if that's com print commercial website, if it's org print organization, if it's net print network. )
Previous (switch case) Homework answer #4
Question 1. Make a Menu Driven Program for Arithmetic Operations.
That's it for today and be sure to try them out.
In the next blog, i will talk about Arrays. In the meantime, don't forget to stay hydrated! Happy learning!
Reminder : Don't forget about your homework. Don't worry, I will attach the answer in the next blog.