Fri. Nov 15th, 2024

For Loop

This loop can be used for executing the statements multiple times. A for loop has to be used when we know the exact number of interations.

Syntax

for(initialization; condition; increment/decrement){
  statements;
}

Program

class ForDemo {
public static void main (String[] args) {
int n=6;
for (int i=1; i<=10; i++){
  system.out.println(n+"*"+i+"="+(n*i));
    }
  }
}

Rule1: All the three sections of the for loop are optional. If we do not specify any initialization and if do not specify any inc/dec, then the compiler will not specify any initialization and will not specify any inc/dec, but if we do not specify any condition then the complier will automatically specify a Boolean value true.

Rule2: Specifying the section separators(;) in a for loop are mandatory. for (;;) will execute for infinite times.

Rule3: In the for loop, initialization section and the inc/dnc section can contain any number of valid java statements, but the condition section must contain a value of only of Boolean type.

Rule4: The initialization section can contain multiple initializations separated by a comma(,) all should be of same time and the data type should be specified only one time.

Rule5: The condition section can contain any number of conditions, but they must be joined by using logical operators(& && | || ^)

Rule6: The inc/dec section can contain multiple increments or decrements but separated by a comma(,)

Rule7: If a variable is declared inside for loop, then it can be used only in that for loop.

Rule8: Specifying the { } is optional. If we don’t specify the { } then it will consider only one statement, and that one statement is mandatory. If we want to consider multiple statements then specifying the { } is mandatory. Within the { } we can specify any number of statements.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *