Respuesta :
Answer:
JAVA program to display the array elements both forward and backward is given.
public class MyProgram {
public static void main(String args[]) {
int len = 5;
int[] courseGrades = new int[len];
courseGrades[0] = 7;
courseGrades[1] = 10;
courseGrades[2] = 11;
courseGrades[3] = 9;
courseGrades[4] = 10;
System.out.println("The elements of array are ");
for(int i=0; i<len; i++)
{
System.out.print(courseGrades[i]+" ");
}
// new line is inserted
System.out.println();
System.out.println("The elements of array backwards are ");
for(int i=len-1; i>=0; i--)
{
// elements of array printed backwards beginning from last element
System.out.print(courseGrades[i]+" ");
}
// new line is inserted
System.out.println();
}
}
OUTPUT
The elements of array are
7 10 11 9 10
The elements of array backwards are
10 9 11 10 7
Explanation:
This program uses for loop to display the array elements.
The length of the array is determined by an integer variable, len.
The len variable is declared and initialized to 5.
int len = 5;
The array of integers is declared and initialized as given.
int[] courseGrades = new int[len];
We take the array elements from the question and initialize them manually.
First, we print array elements in sequence using for loop.
for(int i=0; i<len; i++)
To display in sequence, we begin with first element which lies at index 0. The consecutive elements are displayed by incrementing the value of variable i.
The array element is displayed followed by space.
System.out.print(courseGrades[i]+" ");
Next, we print array elements in reverse sequence using another for loop.
for(int i=len-1; i>=0; i--)
To display in reverse sequence, the last element is displayed first. The previous elements are displayed by decrementing the value of variable i.
At the end of each for loop, new line is inserted as shown.
System.out.println();
The length and elements of the array are initialized manually and can be changed for testing the program.
Loops are used to perform operations that would be repeated in a certain number of times; in other words, loops are used to perform repetitive and iterative operations
The loop statements are as follows:
for(int i = 0; i<sizeof(courseGrades)/sizeof(courseGrades[0]);i++){
cout<<courseGrades[i]<<" ";
}
cout<<endl;
for(int i=sizeof(courseGrades)/sizeof(courseGrades[0]) - 1; i >=0; i--){
cout<<courseGrades[i]<<" ";
}
cout<<endl;
The flow of the above loops is as follows
- The first for loop prints the elements in a forward order.
- The second for loop prints the elements in a backward order.
Read more about loops at:
https://brainly.com/question/11857356