Printing array elements with a for loop

We Are Going To Discuss About Printing array elements with a for loop. So lets Start this Java Article.

Printing array elements with a for loop

Advertisements
  1. Printing array elements with a for loop

    This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
    for (i = 0; i < NUM_VALS; i++) { System.out.print(courseGrades[i] + " "); }

  2. Printing array elements with a for loop

    This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
    for (i = 0; i < NUM_VALS; i++) { System.out.print(courseGrades[i] + " "); }

Solution 1

Advertisements

This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.

 for (i = 0; i < NUM_VALS; i++) {
     System.out.print(courseGrades[i] + " ");
 }
 System.out.println("");

 for (i = NUM_VALS - 1; i >= 0; i--) {
    System.out.print(courseGrades[i] + " ");
 }

 System.out.println(""); 

Original Author A. Nony Mous Of This Content

Solution 2

Advertisements

Your two loops almost were correct. Try using this code:

for (int i=0; i < NUM_VALS; i++) {
    // this if statement avoids printing a trailing space at the end.
    if (i > 0) {
        System.out.print(" ");
    }
    System.out.print(courseGrades[i]);
}

for (int i=NUM_VALS-1; i >= 0; i--) {
    if (i > 0) {
        System.out.print(" ");
    }
    System.out.print(courseGrades[i] + " ");
}

Original Author Tim Biegeleisen Of This Content

Solution 3

Advertisements

To print backwards you want:

for(i = NUM_VALS - 1; i >= 0; i--) {
    System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");

Original Author Joels Elf Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment