Results 1 to 3 of 3
  1. #1
    vicktorh is offline Member
    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    Default Quick question on for loop

    In this program why is print command not executing once the 1st iteration of for loop is done? Why all the iterations of for loop are done 1st and then print command is executed?

    I am confused because scope of the for loop is not restricted and still it completes the calculation 1st and then print. Kindly help, thanks.

    class arrayavg {
    public static void main(String args[]) {

    double students_marks[] = {10.2, 10.1, 111.334, 34.9826, .9836};
    double result=0;
    int i;

    for(i=0; i<5; i++)
    result = result + students_marks[i];


    System.out.println("Average: " + result/5);

    }}

  2. #2
    kalata is offline Member
    Join Date
    Aug 2011
    Location
    Bulgaria
    Posts
    29
    Rep Power
    0

    Default Re: Quick question on for loop

    Hi, when you have single statement in the body of the for-loop, curly braces {} can be omitted. This is the same as:
    Java Code:
    for(i=0; i<5; i++) {
        result = result + students_marks[i]; 
    }
    Good practice suggest that you always write the curly braces, no matter of the number of statements in the body.

    BR,
    Kalin

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default Re: Quick question on for loop

    The System.out.println( ... ) statement is not part of the for loop body; it is executed after the loop has finished; apply curly brackets { ... } if you want to change that.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Quick Question
    By crmbuddy in forum New To Java
    Replies: 5
    Last Post: 02-11-2013, 06:08 AM
  2. Need some help with quick question
    By stuckonjava in forum New To Java
    Replies: 9
    Last Post: 02-26-2012, 06:17 PM
  3. Really Quick question
    By Ryan10 in forum New To Java
    Replies: 63
    Last Post: 03-02-2011, 03:11 AM
  4. Hello everyone! quick question.
    By irishhokie in forum New To Java
    Replies: 5
    Last Post: 04-03-2009, 05:13 AM
  5. One last quick question
    By jigglywiggly in forum New To Java
    Replies: 7
    Last Post: 01-26-2009, 09:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •