6 - Loops - Examples
6 - Loops - Examples
Exercise (1):
(int i = 0; i < 5; ) {
System.out.println( );
}
Exercise (2):
Exercise (3):
In the loop, when the value is "4", jump directly to the next value.
9)
public static void main(String[] args) {
int i;
for(i = 3; i != 2; i = i - 1)
System.out.print(i + " ");
}
………………………………………………………………………………………………
10)
public static void main(String[] args) {
for (int i = 0; i <= 100; i += 10){
if (i == 20)
break;
System.out.print(i + "\t");
}
}
………………………………………………………………………………………………
11)
public static void main(String[] args) {
for (int c = 20; c <= 80; c += 20){
if (c == 40)
continue;
System.out.print(c + " ");
}
}
………………………………………………………………………………………………
12)
public static void main(String[] args) {
for (int count = 1; count <= 6; count++ ){
if ( count %2==0 )
continue;
System.out.print(count+" ");
}
}
………………………………………………………………………………………………
13)
public static void main(String[] args) {
int c = 1;
while ( c <= 10){
if ( c == 5 ){
c+=2;
continue;
}
System.out.print(c+" ");
c++;
}
}
*************************************************************
C)
1) How many times is the body of the loop below executed?
int counter;
for (counter =1; counter > 20; counter++)
System.out.println("loop body");
………………………………………………………………………………………………
public static void main(String[] args) { public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { for (int i = 1; i <= 5; i++)
System.out.print('@'); System.out.print('@');
System.out.print('*'); System.out.print('*');
System.out.println(); System.out.println();
}
}
3)
public static void main(String[] args) {
for ( )
System.out.println();
}
Modify the code above to produce the following output:
2 times 1 = 2
2 times 2 = 4
2 times 3 = 6
2 times 4 = 8
*************************************************************
D) Find the errors and correct them:
1)
public static void main(String[] args) {
for (int r = 0; r <= 9; r += 3)
System.out.println(" \t"+ r);
System.out.print(" "+ r);
}
………………………………………………………………………………………………
2)
public static void main(String[] args) {
for(i=100 ; i>=1 ; i-- )
System.out.println( i );
}
………………………………………………………………………………………………
………………………………………………………………………………………………
3)
public static void main(String[] args) {
for(int c=1 ; c<=10 ; c-- )
System.out.println( c );
}
………………………………………………………………………………………………
4)
public static void main(String[] args) {
for (int count = 1; count <= 6; ){
System.out.print(count+" ");
}
}
………………………………………………………………………………………………
*************************************************************
4. Write a program in Java to display n terms of natural number and their sum.
Test Data : 7
Expected Output :
The first 7 natural number is :
1234567
The Sum of Natural Number up to 7 terms : 28
5. Write a program in Java to read 10 numbers from keyboard and find their
sum and average.
Test Data :
Input the 10 numbers :
Number-1 :2
...
Number-10 :2
Expected Output :
The sum of 10 no is : 51
The Average is : 5.100000
$$$$$
$$$$$
$$$$$
$$$$$
$$$$$