Page 65 - CTS - CSA TP - Volume 2
P. 65
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 88 : Use the For Loop
Objectives
At the end of this exercise you shall be able to
• know the syntax of for loop and its use
• develop Java programs using for loop.
Requirements
Tools/Materials
• PC/Laptop with Window OS
• JDK Software
• Text editor (Visual studio / Sublime / Note pad)
Procedure
TASK 1: Sum of ‘n’ Numbers using for loop
import java.util.Scanner;
public class ForLoopSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter the number of terms: “);
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i<= n; i++) {
System.out.print(“Enter number “ + i + “: “);
int number = scanner.nextInt();
sum += number;
}
System.out.println(“Sum of entered numbers: “ + sum);
scanner.close();
}
}
Output:
50