Why use loop ?
When you need to execute a block of code several number of times then you need to use looping concept in Java language.
How to print your name 10 times using while?
While loop is Entry Controlled Loop because condition is check at the entrance.
Syntax
initialization; while(condition){ // body of loop increment/decrement; }
Example:Print your name 10 times
public class WhileDemo{ public static void main(String args[]){ int i=1; while(i<=10){ System.out.println(“easytutorial”); i++; } } }Try it Yourself
Solve this!!
10793.How many times is the phrase "In the loop" printed?
public class Test { public static void main(String args[]){ int a = 6; int b = 12; while(a<b) { System.out.println("In the loop"); a+=2; b-=2; } } }
1
2
3
4
How to print even numbers using do-while?
“Do-while Statement” is Exit Controlled Loop because condition is check at the last moment.
Syntax
do{ Statement1; Statement2; Statement3; . . . . StatementN; }while(expression);
*Note : Semicolon at the end of while is mandatory otherwise you will get compile error.
Example:Print even numbers
public class DoWhileDemo{ public static void main(String args[]){ int i=2; do{ System.out.println(i); i=i+2; }while(i<=10); } }Try it Yourself
Solve this!!
10794.What is the output of the following program?
public class Test { public static void main(String[] args){ int i=0; do{ System.out.println(i); }while(i>5); } }
1
2
3
0
How to print square number using for loop?
For Loop contain the following statements such as “Initialization”, “Condition” and “Increment/Decrement” statement.
Syntax
for(initialization; condition ; increment){ Statement1 Statement2 . . . StatementN }
Example:Print square numbers
public class ForDemo{ public static void main(String args[]){ int i; for(i=1;i<=5;i++){ System.out.println(i*i); } } }Try it Yourself
Sove this!!
10795.What is the output of the following program?
public class ForLoop { public static void main(String[] args){ int fact=1; for(int i=1;i<5;i++) { fact=fact*i; } System.out.println(fact); } }
5
120
55
None of the Above
- Collection
- ArrayList
- LinkedList
- Vector
- HashSet
- Conditional Statements
- Classes and Objects
- Inheritance
- Packages
- Exception Handling
- Threads
- TreeSet
- LinkedHashSet
- HashMap
- TreeMap
- LinkedHashMap
- HashTable
- Iterator and ListIterator
- String
- Scanner
- Array Small Programs
- Introduction
- Variables
- DataTypes
- Operators
- Conditional Statements
- Loop
- Arrays
- Object Oriented Programming
- Classes and Objects
- Access Modifiers
- Methods
- Abstraction
- Constructor
- Packages
- StringBuffer
- Inheritance
- StringBuilder
- Encapsulation
- Java IO
- Polymorphism
- Interface
- Types Of Variables
- Static Keyword
- Final Keyword
- Super Keyword
- This Keyword
- Exception Handling