Vikas Bhardwaj Vikas Bhardwaj - 14 days ago 6
Java Question

About output of this loop program

The output of this program this is: iiiii .
and this is because of i++ used after print statement. ++ means increment and without i++ its printing i 10 times .then how it will give this output iiiii .it has to be increment one more

class array_output {

public static void main(String args[])

{

char array_variable [] = new char[10];

for (int i = 0; i < 10; ++i) {

array_variable[i] = 'i';

System.out.print(array_variable[i] + "" );

i++;

}

}

}

Answer

That's an expected output as you are incrementing the i twice. simple solution is to remove last line in the for loop.

output from your program:

i = 0

i = 2

i = 4

i = 6

i = 8

i = 10

After removing the last increment

iiiiiiiiii

Your code should be

 class array_output {

        public static void main(String args[]) 

        {    

            char array_variable [] = new char[10];

            for (int i = 0; i < 10; ++i) {

                array_variable[i] = 'i';

                System.out.print(array_variable[i] + "" );

               // i++; // you are incrementing i again. No need to do if you want  a jump of 1 step.

            }

        } 

    }

Ok. After reading again here is the answer for the question. When you enter forloop for the first time your i is 0 and after entering you said i++ which will be 1 and then ++i which becomes 2 so for every i you are making a jump of 2 steps so that's the reason after 5 iterations you are reaching 10 and your for loop condition i<10 fails. So, the loop further won't execute and exit successfully.

Sorry for the wrong output in my previous answer. Here is the right output. .

 i = 0  

 i = 2 

 i = 4 

 i = 6 

 i = 8
Comments