How to use for Loop Structure
Submitted by GeePee on Friday, April 3, 2015 - 23:05.
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
Sample Run:
prompts the user to enter the number of first positive integers to be added
The statement 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.
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.
- import java.util.*;
- public class forLooping
- {
- {
- int counter; //loop control variable
- int sum; //variable to store the sum of the numbers
- int n; //first positive integer to be added
- + "integers to be added: ");
- n = concole.nextInt();
- sum=0;
- for(counter = 1; counter <=n; counter ++)
- sum = sum + counter;
- + n + " positive integers is "
- + sum);
- }
- }
Enter the number of positive integers to be added: 100
The sum of the first 100 positive integers is 5050
The statement - + "integers to be added: ");
n = concole.nextInt();
stores the number entered by the user in n and the statement sum=0;
initializes sum to 0.
The statement - for(counter = 1; counter <=n; counter ++)
- sum = sum + counter;
Add new comment
- 26 views