Chapter 5- The for Loop in Java



For loop:

The syntax of a for loop looks like this:


/* for (initialize; check_bool_expression; update){

//code;

} */
A for loop is usually used to execute a piece of code for a specific number of times.




Quick Quiz: Write a program to print first n odd numbers using a for loop.



Decrementing for loop

for (i=7; i!=0; i--){

System.out.println(i);

}
This for loop keeps running until i becomes 0.

Quick Quiz: Write a program to print first n natural numbers in reverse order.

package com.company;

public class cwh_23_for_loop {
    public static void main(String[] args) {
//        for (int i=1; i<=10; i++){
//            System.out.println(i);
//        }
        // 2i = Even Numbers = 0, 2, 4, 6, 8
        // 2i+1 = Odd Numbers = 1, 3, 5, 7, 9
        //int n = 3;
        //for (int i =0; i<n; i++){
        //    System.out.println(2*i+1);
        //}

        for(int i=5; i!=0; i--){
            System.out.println(i);
        }
    }
}

Aryadeep

Welcome to CodeWithARYA. It's My Personal Reference Website. Where You Can Get Amazing Codes. Have a Look.

Post a Comment

Previous Post Next Post