How to use for Loop Structure

The following java program application uses a for Looping Structure. The initial statement, loop condition, and update statement are enclosed within parenthesis and control the body of the for statement. Note that the for loop control statements are separated by semicolons and that the body of a for loop can have either a simple or compound statement. . I will be using the JCreator IDE in developing the program. To start in this tutorial, first open the JCreator IDE, click new and paste the following code.
  1. import java.util.*;
  2.  
  3. public class forLooping
  4. {
  5. static Scanner concole = new Scanner(System.in);
  6.  
  7. public static void main (String[] args)
  8. {
  9. int counter; //loop control variable
  10. int sum; //variable to store the sum of the numbers
  11. int n; //first positive integer to be added
  12.  
  13. System.out.println("Enter the number of positive "
  14. + "integers to be added: ");
  15.  
  16. System.out.flush();
  17. n = concole.nextInt();
  18. System.out.println();
  19.  
  20. sum=0;
  21.  
  22. for(counter = 1; counter <=n; counter ++)
  23. sum = sum + counter;
  24.  
  25. System.out.println("The sum of the first "
  26. + n + " positive integers is "
  27. + sum);
  28.  
  29.  
  30. }
  31. }
Sample Run:
  1. Enter the number of positive integers to be added: 100
  2.  
  3. The sum of the first 100 positive integers is 5050
The statement
  1. System.out.println("Enter the number of positive "
  2. + "integers to be added: ");
prompts the user to enter the number of first positive integers to be added The statement n = concole.nextInt(); stores the number entered by the user in n and the statement sum=0; initializes sum to 0. The statement
  1. for(counter = 1; counter <=n; counter ++)
  2. sum = sum + counter;
executes the for loop n times. In the for loop, counter is initialized to 1 and is incremented by 1 after each iteration of the loop. Therefore, counter ranges from 1 to n. each time through the loop, the value of counter is added to sum. Because sumwas initialized to 0, counter ranges from 1 to n, and the current value of counter is added to the value of sum. After the for loop executes, sum contains the sum of the first n positive integers, which in the sample run is 100 positive integers. Notice that the program assumes that the user enters a positive value for n.

Add new comment