In: Computer Science
java code
Question 4:
Iterating with loops
You can process the list using a For loop. The variable in the For loop becomes the index value for each of the items in the loop. Everything you do to an element inside the loop gets done for the entire list. Examine the following loops. Then use what you know to write the following loops.
int[] numbers = new int[100];
for(int i = 0; i < numbers.length; i++){
numbers[i] = i;
}
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
Write a loop to display all the numbers in the list.
Write a loop to display the number in the list in reverse order.
Write a loop with an if statement to print only the even numbers in the list.
Write a loop to subtract the value 50 to every element in the list.
Write a loop to count the number of negative values in the list.
public class Demo {
public static void main(String args[]) {
int[] numbers=new int[100];
for(int i=0;i<numbers.length;i++)
{
numbers[i]=i;
}
int sum=0;
for(int i=0;i<numbers.length;i++)
{
sum+=numbers[i];
}
//Write a loop to display all the numbers in the list.
for(int i=0;i<numbers.length;i++)
{
System.out.print(numbers[i]+" ");
}
//Write a loop to display the number in the list in reverse order.
for(int i=numbers.length-1;i>=0;i--)
{
System.out.print(numbers[i]+" ");
}
//Write a loop with an if statement to print only the even numbers in the list.
for(int i=0;i<numbers.length;i++)
{
if(numbers[i]%2==0)
System.out.print(numbers[i]+" ");
}
//Write a loop to subtract the value 50 to every element in the list.
for(int i=0;i<numbers.length;i++)
{
numbers[i]=numbers[i]-50;
}
//Write a loop to count the number of negative values in the list.
int count=0;
for(int i=0;i<numbers.length;i++)
{
if(numbers[i]<0)
count++;
}
}
}
// If any doubt please comment