80 likes | 90 Views
Learn about Java for loops with syntax, examples, and exercises to enhance your programming skills. Practice tasks included for better understanding.
E N D
Chapter 4 Day 2
For loop • The for loop in java uses a local variable initialized in the loop header to iterate through the loop • Syntax: for(initialization; condition; increment) { body }
For loop example for(inti = 0; i < 5; i++) { System.out.println(“i = “ + i); }
output i = 0 i = 1 i = 2 i = 3 i = 4
What’s the output? public class Something { public static void main(String[] args) { System.out.println(“Number\tSquare”); for(inti = 1; i <= 9; i++) { System.out.println(i + “\t\t” + i*i); } } }
output Number Square 1 1 2 4 3 9 4 26 5 25 6 36 7 49 8 64 9 81
What’s it do? public class something { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print(“Please enter a String: “); String str = in.nextLine(); for(inti = 0; i < str.length(); i++) System.out.println(str.charAt(i)); } }
Homework • Pg 260 #3 and #9