How to Write a for Loop in Java, With Summations

Introduction: How to Write a for Loop in Java, With Summations

For Loops can be used in so many different ways and are often the base of many complex programs, but that does not diminish their complexity at all. Today I will be helping you learn how to write a For Loop in Java, as well as use it to sum up numbers.

You should have some basic experience in coding, specifically the language Java. You should understand variables, ints, basic mathematical implementations with variables, and arrays

This Instruction set should only take 5-10 minutes at most if you follow it step by step

Supplies

  1. A functioning computer
  2. Some form of Java compiler (I will be using https://www.tutorialspoint.com/compile_java_online.php, though any compiler will do)
  3. A good attitude!

Step 1: Step 1: Make Your for Loop Shell

Open a fresh program; then type out

  • for()
  • {
  • }

This basic function (shown in the image) will act as our body for the For Loop, containing all the code it will execute

Step 2: Step 2: Make Your Iterator

Inside the parenthesis of the Loop, type

  • int i = 0;

It does not matter what name we assign the iterator or what value it starts at the moment, in the image I’ve assigned the name “i” and iterators usually start at 0 for most loops.

These naming conventions are typical, but the iterator can take many different variables and names

Step 3: Step 3: Choose Your Endpoint

After the semicolon, type

  • i <= 100;

What this does is it tells the loop that once “i” is bigger than 100, it will end

Later we can change the endpoint to fit your needs, but for right now it works as a placeholder

Step 4: Step 4: Choose Your Increment

After the last semicolon, type

  • i ++

As shown in the figure, this makes it so that after every time the loop executes its code, it increases “i” by one

Step 5: Step 5: Create a Sum Variable

Above the body of the For Loop, type

  • int sum = 0;

This will create your sum variable, which you will use to keep track of the numbers summed in the loop

We place the sum variable outside the loop because each time the loop executes it’s code, it would create a new sum variable and then erase it once the loop goes back to the beginning

  • The first image shows the correct placement outside of the loop
  • The second image shows the incorrect placement inside the loop

Step 6: Step 6: Add “i” to the Sum

Inside the body of your For Loop (between the curly brackets { }) type

  • sum += i;

This will take the iterable “i” that you made for the for loop and add it to the sum

Every time the loop goes through it will then increase your “i” by 1

So what the code does right now is sum every number 0 - 100

Step 7: Step 7: Write Your Print Statement

After the body of your For Loop type

  • System.out.println(sum);

This print statement will print out the sum you found using your For Loop

Step 8: Step 8: Variations

The value 0 for “i” and 100 for the endpoint are just placeholders and can be any number, so have fun with it!

The iterator can be changed depending on what you are summing, and can even be negative

  • Usually, if your increment step is positive, you want your “i” value to be less than your end value

  • And if your increment step is negative the opposite is true, you want your “i” value to be greater than your end value, that way you do not have infinite loops

Step 9: Step 9: Loop Through Arrays

Another common occurrence is looping through arrays, but if you are not worried about that, congratulations! Make sure to look at step 13 for troubleshooting! Otherwise, stick around just a bit longer

Step 10: Step 10: Choose Your Endpoint

Arrays have a definite start and end, so you can look earlier than the start point or later than the endpoint. In order to prevent this, we have to stop the For Loop before it tries to look outside of the array.

As an example, I made an array containing the numbers 4, 638, 15, 524, and 28 and named it example

To keep the loop from looking beyond the confines of the example array, you want to change the

  • i <= 100;

to

  • i < example.length;

Step 11: Step 11: Array Troubleshooting

Because arrays start indexing at 0 and go to their length minus one, you want your loop to stop before it tries to look at the number in the space the same as the length of the array because while the array is length 5, it’s spots are named 0-4, so when you try to look at spot 5, it will throw an error

Step 12: Step 12: Add Example[i] to Sum

The only other change you then have to make is to change

  • sum += i;

to

  • sum += example[i];

Because now instead of adding “i”, you want to add all the numbers inside of the example array and you are using “i” to look at each spot in the array instead of directly representing the numbers themselves

Step 13: Step 13: Troubleshooting

If your code does not run correctly, here are a few things to check

  • Did you put semicolons in the right places?
  • Did you make sure to capitalize correctly?
  • Are all of the brackets and parentheses properly used?
  • Does your loop get stuck in an infinite loop?
  • For Step 3:
    • You can also type
      • i < 101;
    • to get the same result

Step 14: Step 14: Congratulations, You Did It!

Your For Loop is running and correctly sums up the specified numbers! You are well on your way to more complex and interesting tasks.

Be the First to Share

    Recommendations

    • Tinkercad Student Design Contest

      Tinkercad Student Design Contest
    • Robots Contest

      Robots Contest
    • Rocks, Gems, and Stones Speed Challenge

      Rocks, Gems, and Stones Speed Challenge

    Comments

    0
    Elaina M
    Elaina M

    1 year ago

    Thanks for posting your first instructable - It looks really well documented :)