JAVA (30 points) TASK 3: Use different loops to print the odd / negative numbers
ID: 3678914 • Letter: J
Question
JAVA (30 points) TASK 3: Use different loops to print the odd / negative numbers 1 to 101. All programs will print the same output in the same order.
Using a for loop that increments the loop control variable by 2 each iteration
Using a for loop whose loop control variable goes from 0 to 50.
Using a for loop whose loop control variable goes from 100 down to 0.
Using an infinite for loop with no conditional expression and exiting the loop with a break statement.
Using a while loop.
Using a do-while loop.
There should be 6 different Snipping photos. One photo for each program A – F.
-1
-3
-5
-7
…
-101
Explanation / Answer
Please find below the 6 progras as per the requirement.
----------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P1
{
public static void main (String[] args) throws java.lang.Exception
{
for(int i = 1 ; i<= 101 ; i = i+2 )
System.out.println(-i);
}
}
-----------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P2
{
public static void main (String[] args) throws java.lang.Exception
{
for(int i = 0 ; i<= 50 ; i++ )
System.out.println(-2*i-1);
}
}
-----------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P3
{
public static void main (String[] args) throws java.lang.Exception
{
for(int i = 100 ; i>= 0 ; i = i-2 )
System.out.println(i-101);
}
}
------------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P4
{
public static void main (String[] args) throws java.lang.Exception
{
for(int i = -1 ; ; i = i-2 ){
if(i<-101)
break;
System.out.println(i);
}
}
}
-----------------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P5
{
public static void main (String[] args) throws java.lang.Exception
{
int i = -1;
while(i>=-101){
System.out.println(i);
i = i-2;
}
}
}
--------------------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
class Task3_P6
{
public static void main (String[] args) throws java.lang.Exception
{
int i = -1;
do{
System.out.println(i);
i = i-2;
}while(i>=-101);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.