In: Computer Science
JAVA
Write a for loop which will display this set of values 1,3,5,7,9.
Theory:
for loop
for loop is used for repeat a block of code till perticular time.
Syntax:
for(initialization;condition;increment/decrement)
{
//block of code
}
array
Array is a collection of similar data type elements.
Solution:
Algorithm:
1. Start
2. Create a class with main() method
3. In main() method create an Array with given set of values
4. initialize i variable for index
5. use for loop till the index i.e i will be a last index
6. In for loop display array with each index value.
7. End
Code:
import java.io.*;
import java.util.*;
class forsample
{
//main method
public static void main(String[] args) {
int i; //for index
int arr[]={1,3,5,7,9};//create an array with given
values
System.out.println("The values are:");
for(i=0;i<arr.length;i++)//for loop for display
array values
{
System.out.println(arr[i]);
}
}
}
Output: