For Loop in Java

This tutorial will teach you how to use for loop in java. A For Loop is used to iterate through a condition a certain amount of times. I used this type of looping when I know how many times a task is to be repeated. So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of sampleForLoop.java. 2. Now, we will create a variable sum as Integer to display the sum of numbers from 1 to 10.
  1.         int sum=0;
We will use now for loop in step 3. And here is the syntax on how to use for loop:
  1. for (initialization; termination; increment) {
  2.    code statements;
  3. }
3. Now, we will create a for loop. We will have a local variable of num as integer inside the loop and is equal to 1, this means that this is the initialization. Next, we will have for the termination or up to what number is 1 to be terminated, thus we will put a sample number of 10 here. Next, we will have to terminate it by 1 as we have the ++ keyword.
  1.         for(int num=1;num<=10;num++){
  2.                
  3.                 System.out.println(num);
  4.                 sum = sum + num;
  5.         }
As what you have seen the code above, the code statements tell us to print the variable num. This num variable contains the number 1 as the initialization up to 10 as we have the operator =. Then we have set to add the num variable to the sum. That is, all of the numbers are repeated until 10 only are added in the sum. 4. Then, we will display the output of the sum from numbers 1 to 10. Have this code below:
  1.         System.out.println("The Sum is: " + sum);
Output: output Here's the full code of this tutorial:
  1. public class sampleForLoop {
  2.  
  3.   public static void main (String args[]){
  4.     System.out.println("***For Loop in Java***");
  5.         int sum=0;
  6.        
  7.         for(int num=1;num<=10;num++){
  8.                
  9.                 System.out.println(num);
  10.                 sum = sum + num;
  11.         }
  12.         System.out.println("The Sum is: " + sum);
  13.   }
  14.    
  15. }
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment