Sometimes we want our program to execute a few sets of instructions over and over again.
For example: print 1 to 1000, print multiplication table of 7, etc.
Loops make it easy for us to tell the computer that a given set of instructions need to be executed repeatedly.
Types of Loops
Primarily, there are three types of loops in Java:
- While loop
- do-while loop
- for loop
We will look into these, one by one.
- While loops
/*
while (Boolean condition)
{
// Statements -> This keeps executing as long as the condition is true.
}
*/
If the condition never becomes false, the while loop keeps getting executed. Such a loop is known as an infinite loop.
Quick Quiz : Write a program to print natural numbers from 100 to 200.
package com.company;
public class cwh_21_ch5_loops {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println("Using Loops:");
int i = 100;
while(i<=200){
System.out.println(i);
i++;
}
System.out.println("Finish Running While Loop!");
// while(true){
// System.out.println("I am an infinite while loop!");
// }
}
}
Quick Quiz Answer :
package com.company;
public class javaloop {
public static void main(String[] args) {
int i=100;
while(i<=200){
System.out.println(i);
i++;
}
}
}
/*
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
*/