Posted By:
4 Feb, 2014 8:58 am PST

Understanding for loop in Java

 The FOR Loop

 A loop is a repetitive block of code. This block of code is made up of one or more statements. These statements loop repeatedly – for each iteration through the loop. Every time the statements inside a loop run, it is referred to as “one iteration through that loop”.

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for (initialization;Boolean_expression; update)

{

//Statements

}

Here is the flow of control in a for loop:

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

EXAMPLE:

Consider a file Emp.java as shown below:

 

Save the file, compile it and execute the class file. You will see the following output:

Hello

Hello

Hello

The variable q is defined as an int variable. Since it is used inside the for loop, we call it the loop variable.

The main control of the for loop is the statement for(q=1; q<=3; q++).

 

 

 

 

q=1. This is the initialization section. The code here executes only one time, at the start. What this does is that the value 1 is assigned to the local variable q.

   

q<=3. This is the condition section. This will determine if the code inside the loop executes or not. Initially, since q = 1, the loop will execute because q <=3 is correct (or true) – the condition is satisfied.

 

 q++. This is the increment section (or the iteration section). After the loop executes one time, the code comes here. The value q increments by 1.It becomes 2. After this, it goes back to the condition section and rechecks the condition. Is the new value of q still less than or equal to 3? Is q<=3? If yes, the loop executes a second time. During the execution the value of q is 2. When the code inside the loop completes, control is transferred back to the increment section, where q gets incremented by 1 to 3. The condition q<=3 gets checked once again – it is still true? Yes – so, the control goes back inside the loop and the code inside the loop execute, cons. When this code finishes the control goes back to the q++ which makes q=4. Now, the condition q <=3 fails (it evaluates to false), and control comes out of the loop.

Since the loop is executed three times, you see three lines in the output.

Q1. Write a program MyFirstJavaProgram.java to get the following output:

1

1 2
1 2 3
1 2 3 4
1 2 3 4 5

ANSWER

public class MyFirstJavaProgram {

public static void main(String []args) {

int p=1;

for (int i=1;i<=5;i++){

for (int r=1;r<=p;r++)

{

System.out.print(r + " ");

}

p=p+1;

System.out.println( " ");

}

}

}

OUTPUT:


1 2

1 2 3

1 2 3 4

1 2 3 4 5

EXPLANATION:

Observe the inner loop: for(int r=1; r <= p; r++). In the outer loop, the variable I changes from 1 to 5. When the forof the inner loop executes, the value of I used by it will be 1, 2, 3, 4, and 5. The first time the condition will be r < =1; the next time it will be r < = 2; the next time r <= 3; then r <= 4; and finally r <=5. 

So,

When i = 1, b will go from 1 to 1. The inner loop will execute one time only.

When i = 2, b will go from 1 to 2. The inner loop will execute two times only.

When i = 3, b will go from 1 to 3. The inner loop will execute three times only.

When i = 4, b will go from 1 to 4. The inner loop will execute four times only.

When i = 5, b will go from 1 to 5. The inner loop will execute five times only.

Inside the inner for loop, we use print() not println(). After the inner for loop is over, the println() comes into effect.

Note: When we execute a method of a class without using an object reference, from a function such as main(), which is defined with static, then that method being called must also be static.

 Q2. Write a program Emp.java that prints the following:

###

####

#####

Answer

public class  Emp{

public static void main(String[] args){

int q=3;

for (int i=1;i <=3;i++){

for (int p=1; p<=q;p++){

System.out.print("#");

}

System.out.println(" ");

q=q+1;

}

}

}

OUTPUT

                        # # #

                        # # # #

                        # # # # #                     

Q3. Write a program Pattern.java that prints the following:

*****

****

***

**

*

Answer

 public class Pattern{

 public static void main(String[] args){

 int =5;

 for (int i=1;i<=5;i++){

 for (int y=r;y>=1;y--){

 System.out.print("*");

 }

 System.out.println(" ");

 r=r-1;

 }

 }

 }

  OUTPUT

                  *****

                       ****

                       ***

                       **

                       *

Q4.Write a class Q0060 that has a static method SumOfSeries(int n) that returns the sum of the series 1/(2*3) + 2/(3*4) + 3/(4*5) + … + n/((n+1) * (n+2) ).

Answer

 public class Q0060

 {

 public static void main(String[] args)

 {

 double sum;

 sum=sumOfSeries(5);

 System.out.println(sum);

 }

 static double sumOfSeries(int n)

 {

 double sum=0.0;

 for(int i=1;i<=n;i++){

 sum=sum + (i/((i+1)*(i+2)));

 }

 return sum;

 }

 }

 OUTPUT

                        0.7357142857142857

 Q5.Write a program MyFirstJavaProgram.java that has a static method power (int a, int b) that returns the value of a raised to b.

 ANSWER

public class MyFirstJavaProgram {

 public static void main(String []args) {

 System.out.println(power(4,2));

 }

 public static int power(int a, int b)

 {

 int s=1;

 for (int p=1;p<=b; p++)

 {

 s=(a*s);

 }

 return s;

 }

 }

 OUTPUT

                                16

 

Attachment: c.png


 

How to use for loop? 

Java for loop is used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.

 

Syntax of for loop:

 

for(initialization; condition to be checked; increment or decrement in the value)

{

//Statements to be executed

}

 

Example :To calculate the factorial of the number.

 

publicclass ForLoop{

publicstaticvoid main(String[] args) {

int number = 5;

 

/*

* Factorial of any number is !n.

* For example, factorial of 4 is 4*3*2*1.

*/ 

int factorial = number;

for(int i =(number - 1); i > 1; i--)

{

factorial = factorial * i;

}

System.out.println("Factorial of a number is " + factorial);

}

}

 

Attachment: ForLoop.java
Was it useful?  



How to write for loop?

A for loop is a special loop is used when a definite number of loop iterations is required.

Although while loop can also be used to meet this requirement, the for loop  provides you with a shorthand notation for this tyoe of loop.

When you see for loop you indicate the starting value for the loop control variable,the test condition that control loop entry and expression that alter the loop control variableall in one place.

Syntax :

for(initialization; Boolean expression ; update)

{

                        //statements

}

 

//To print word “Java Programming” 5 times

 public class ForExample{

            public static void main(String args[]){

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

                              System.out.println("Java Programming");

                    }          

           }

}

 

Output of the above program is:

Java Programming

Java Programming

Java Programming

Java Programming

Java Programming

Attachment: ForExample.java

Was it useful?  



 The FOR Loop

 A loop is a repetitive block of code. This block of code is made up of one or more statements. These statements loop repeatedly – for each iteration through the loop. Every time the statements inside a loop run, it is referred to as “one iteration through that loop”.

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for (initialization;Boolean_expression; update)

{

//Statements

}

Here is the flow of control in a for loop:

  1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

EXAMPLE:

Consider a file Emp.java as shown below:

 

Save the file, compile it and execute the class file. You will see the following output:

 

Hello
Hello
Hello

 

The variable q is defined as an int variable. Since it is used inside the for loop, we call it the loop variable.

The main control of the for loop is the statement for(q=1; q<=3; q++).

 

 

 

 

q=1. This is the initialization section. The code here executes only one time, at the start. What this does is that the value 1 is assigned to the local variable q.

   

q<=3. This is the condition section. This will determine if the code inside the loop executes or not. Initially, since q = 1, the loop will execute because q <=3 is correct (or true) – the condition is satisfied.

 

q++. This is the increment section (or the iteration section). After the loop executes one time, the code comes here. The value q increments by 1.It becomes 2. After this, it goes back to the condition section and rechecks the condition. Is the new value of q still less than or equal to 3? Is q<=3? If yes, the loop executes a second time. During the execution the value of q is 2. When the code inside the loop completes, control is transferred back to the increment section, where q gets incremented by 1 to 3. The condition q<=3 gets checked once again – it is still true? Yes – so, the control goes back inside the loop and the code inside the loop execute, cons. When this code finishes the control goes back to the q++ which makes q=4. Now, the condition q <=3 fails (it evaluates to false), and control comes out of the loop.

Since the loop is executed three times, you see three lines in the output.

 

Q1. Write a program MyFirstJavaProgram.java to get the following output:

1

12

123

1234

12345

 

ANSWER

 

public class MyFirstJavaProgram {

public static void main(String []args) {

int p=1;

for (int i=1;i<=5;i++){

for (int r=1;r<=p;r++)

{

System.out.print(r + " ");

}

p=p+1;

System.out.println( " ");

}

}

}

 

OUTPUT:

 

1 

1 2

1 2 3

1 2 3 4

1 2 3 4 5

 

 

EXPLANATION:

Observe the inner loop: for(int r=1; r <= p; r++). In the outer loop, the variable I changes from 1 to 5. When the forof the inner loop executes, the value of I used by it will be 1, 2, 3, 4, and 5. The first time the condition will be r < =1; the next time it will be r < = 2; the next time r <= 3; then r <= 4; and finally r <=5. 

So,

When i = 1, b will go from 1 to 1. The inner loop will execute one time only.

When i = 2, b will go from 1 to 2. The inner loop will execute two times only.

When i = 3, b will go from 1 to 3. The inner loop will execute three times only.

When i = 4, b will go from 1 to 4. The inner loop will execute four times only.

When i = 5, b will go from 1 to 5. The inner loop will execute five times only.

Inside the inner for loop, we use print() not println(). After the inner for loop is over, the println() comes into effect.

Note: When we execute a method of a class without using an object reference, from a function such as main(), which is defined with static, then that method being called must also be static.

 

Q2. Write a program Emp.java that prints the following:

###

####

#####

 

Answer

 

public class  Emp{

public static void main(String[] args){

int q=3;

for (int i=1;i <=3;i++){

for (int p=1; p<=q;p++){

System.out.print("#");

}

System.out.println(" ");

q=q+1;

}

}

}

 

OUTPUT

                        

# # #

# # # #

# # # # # 

                    

Q3. Write a program Pattern.java that prints the following:

*****

****

***

**

*

Answer

 

public class Pattern{

 public static void main(String[] args){

 int =5;

 for (int i=1;i<=5;i++){

 for (int y=r;y>=1;y--){

 System.out.print("*");

 }

 System.out.println(" ");

 r=r-1;

 }

 }

 }

 

OUTPUT

*****
****
***
**
*

 

 

Q4.Write a class Q0060 that has a static method SumOfSeries(int n) that returns the sum of the series 1/(2*3) + 2/(3*4) + 3/(4*5) + … + n/((n+1) * (n+2) ).

Answer

 

 public class Q0060

 {

 public static void main(String[] args)

 {

 double sum;

 sum=sumOfSeries(5);

 System.out.println(sum);

 }

 static double sumOfSeries(int n)

 {

 double sum=0.0;

 for(int i=1;i<=n;i++){

 sum=sum + (i/((i+1)*(i+2)));

 }

 return sum;

 }

 }

 

 OUTPUT

0.7357142857142857

 

Q5.Write a program MyFirstJavaProgram.java that has a static method power (int a, int b) that returns the value of a raised to b.

ANSWER

 

public class MyFirstJavaProgram {

 public static void main(String []args) {

 System.out.println(power(4,2));

 }

 public static int power(int a, int b)

 {

 int s=1;

 for (int p=1;p<=b; p++)

 {

 s=(a*s);

 }

 return s;

 }

 }

 

OUTPUT

 16 

 


Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud