While Statement
- Initialization
- Condition
- Task
- Updation
. . int cnt = 1; //Initialization while(cnt < 5) //Condition { SOP("Hello"); //Task cnt++; //Updation } . .
While loop becomes infinite loop if the updating has no effect on while loop condition
Print the numbers divisible by 4 till N
Approach 1
import java.util.Scanner; public class displayWhile { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int count = scn.nextInt(); int cnt = 4; while(cnt < count){ if(cnt % 4 ==0) System.out.println(cnt); cnt++; } } }
Approach 2
import java.util.Scanner; public class displayWhile { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int count = scn.nextInt(); int cnt = 4; while(cnt < count){ System.out.println(cnt + " "); cnt+=4; } } }
Input
40
Output
4 8 12 16 20 24 28 32 36
Approach2 is faster and efficient since count in while jumps in multiples of 4
Printing perfect Square
import java.util.Scanner; public class PerfectSquare { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int cnt = 1; while(cnt*cnt < n){ System.out.println(cnt*cnt + " "); cnt++; } } }
Input
30
Output
1 4 9 16 25
Printing last character in string
import java.util.Scanner; public class PrintIntval { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int number = scn.nextInt(); Character[] arrChar = new Character[]{}; String strCount = String.valueOf(number); int index = strCount.length()-1; while(index >= 0 ) { System.out.println(strCount.charAt(index)); index--; } } }
Input
1365
Output
5 6 3 1
Approach 2
import java.util.Scanner; public class PrintIntval { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int number = scn.nextInt(); while(number> 0 ) { System.out.println(number%10); number = number/10; } } }
Input
1365
Output
5 6 3 1
----------------------------------------------------- n n>0 n%10 n=n/10 ---------------------------------------------------- 1365 Y 5 136 136 Y 6 13 13 Y 3 1 1 Y 1 0 0 N - Loop Stops
Now how will you address if input is 0 por negative and you should get output?
To address above.. .
public class PrintIntval { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int number = scn.nextInt(); if(number < 0) number *= -1; if(number == 0){ System.out.println(number); }else { while (number > 0) { System.out.println(number % 10); number = number / 10; } } } }
Input
-1365
Output
5 6 3 1