Computer Science, asked by rajeshlodhi76128, 2 months ago

4. Explain the working of the for loop with syntax.​

Answers

Answered by aadishijain
0

Answer:

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for loop” in Java.

Syntax of for loop:

for(initialization; condition ; increment/decrement)

{

statement(s);

}

In the following pic, there is a flowchart use that foe the below explanation.

First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition is re-evaluated.

Example of Simple For loop

class ForLoopExample {

public static void main(String args[]){

for(int i=10; i>1; i--){

System.out.println("The value of i is: "+i);

}

}

}

The output of this program is:

The value of i is: 10

The value of i is: 9

The value of i is: 8

The value of i is: 7

The value of i is: 6

The value of i is: 5

The value of i is: 4

The value of i is: 3

The value of i is: 2

In the above program:

int i=1 is initialization expression

i>1 is condition(Boolean expression)

i– Decrement operation

Answered by kamalrajatjoshi94
0

Answer:

Working of for loop:-

  • Value of the variable is initialised
  • Condition is checked if condition is true then the loop is executed else it is terminated.
  • The increment/decrement condition is applied. Ex g++,g=g+2,g=g+3,g--

Syntax:-

for(initialisation; condition;increment/decrement)

{

Statements.

}

Example:-

int a,s=0;

for(a=1;a<=5;a++)

{

s=s+a;

}

System.out.println("The sum of 1st five numbers="+s);

Similar questions