Loopy Thinking

Optional Node
Collapse Content

A lot of programming involves using loops, so you need to be able to think about them clearly. When looking at loops, you should try to follow the loop on your own (step-by-step) to see what's happening. You want to specifically look at the values of your variables at these times:

  • before the loop begins
  • after each iteration of the loop
  • when the loop terminates

It often helps to go through an example on your own and see how code will handle it.

Question
For example, let's say you want to add up all the numbers from 1 through n (without any formulas). How would you do it?
Think about your solution before reading on.

Answer
Starting with 1, you could manually add each number to the total sum until you reach the nth number. In code, you would create a loop that goes through all the numbers from 1 to n adding them to a sum variable. To make sure this works, let's examine each stage of the loop:

  1. Before the loop begins
    Create a variable sum and set it to 0. This is the sum of 0 elements in the array, so everything is set up correctly.
  2. Each iteration of the loop
    Go through each element in the loop one at a time, and add its value to sum. After each iteration through the loop, sum will hold the value of all the number up to that point.
  3. Loop termination
    n is the last number you add to sum, so sum now equals the sum of all the numbers from 1 through n.

Here's the Java code for this loop:

static int doStuff(int a){
  int sum = 0;
  for(int i=1; i<=a; i=i+1){
    sum = sum + i;
  }
  return sum;
}

Challenge

The factorial of a number a is the product of all the positive integers less than or equal to a, i.e. all the integers from 1 through a. For example, the factorial of 4 is 24 (1*2*3*4 = 24). Can you calculate the factorial of a given number?

In each case, you are given one positive integer a as input. Find the factorial of a by multiplying all the numbers from 1 to a together, and then return the total product. For example, when given a as 4, return 24.

(The factorial is used to get the number of permutations of a items.)

Guidelines for your Loop

Before the loop begins - Create a variable product to store the product of the numbers as you go through the loop. What should you set its initial value to?
Think of the answer, then click below.

product

Each iteration of the loop - Make sure that product now equals the product of all the numbers up to the current one.

Loop termination - Terminate when you reach the end, as in the previous loop.

OK Now, go ahead and code the solution!

Note: To get more practice with loops, see the Math With Loops tutorial.

Challenge

You are given a number a. As explained above, return the factorial of a (the product of all the integers from 1 through a).

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • no comments? has no one finished this yet? its not that difficult...

  • @Mitchell, many people have solved it, just not many commented here. We don't want users to paste solutions or long code samples here, but you can link to your most recent submission instead by clicking on "Load Link" below the comment form.

  • Will the answer that was given run forever since the condition is less than or equal to a.?

  • Bernard, it will stop when 'i' in the for statement increments up to the same number as the 'a'.

  • int kq=1;
    for(int i=a;i>0;i=i-1){
    kq=kq*i;
    }
    return kq;

  • You can solve this with recursion.
    public static int doStuff(int a){
    if (a==0 || a==1) return 1;
    return doStuff(a-1)*a;
    }

  • I just gave 2 as the initial value of the variable i so I think my code will just jump the first useless iteration: 1*1.
    my code

  • import java.util.Scanner;
    public class Factorial {
    public static void main(String[] args){

        Scanner input = new Scanner (System.in);
    
        System.out.print("Enter a number to calculate: ");
    
    cont...
  • int b = a;
    while(a!=1)
    {
    b = b*(a-1);
    a -= 1;
    }
    return b;

  • why don't we get infinate free lessions!?!?!?this is the only good site i have found )=
    )=
    )=

  • Here's a coupon that gives you membership for $2 for the first month: LEARNCODING99
    Enter it at learneroo.com/get-membership before checking out.
    (Membership goes to regular rate afterwards, but you can cancel if you're no longer interested.)

All Node Comments
Contact Us
Sign in or email us at [email protected]