# Calculate factorials using for loops

Page 1 of 1

## 1 Replies - 13816 Views - Last Post: 04 April 2007 - 09:18 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=26001&amp;s=7f2065a7fd02fc29d386b9847c9a33f4&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 lincolnpark583

Reputation: 1
• Posts: 11
• Joined: 21-March 07

# Calculate factorials using for loops

Posted 04 April 2007 - 08:20 PM

I'm trying to write a small program that just calculates factorials. I'm supposed to write it using a for loop. Here's what I've come up with...

```import java.util.*;

public class CalcFac2
{
static Scanner console = new Scanner(System.in);

public static void main(String[] args)
{
int counter;
int n;
int factorial;
boolean isNegative;

System.out.print("This program asks the user for a positive integer number, \n"
+ "computes the factorial value, and displays the answer.\n"
+ "Please enter a positive number: ");
System.out.flush();
n = console.nextInt();
System.out.println();
factorial = n;

if (n < 0)

{
System.out.println("Negative number found in data.");
isNegative = true;

}

for (counter = 1; counter <= n; counter--)

factorial = factorial * counter;

System.out.println("The factorial of " + n + " is " + factorial);

}
}

```

I'm supposed to be able to enter any integer and have it calculate the correct factorial as well as tell the user if they accidentally entered a negative number. I'm having trouble finding in my book how you end an if statement if it becomes true. So that it doesn't go on with my for loop. I've hit a wall here, I've been sitting here for quite some time now trying to figure out where I went wrong with this because I know I don't have it calculating the factorial correctly. Any guidance would be greatly appreciated!

Is This A Good Question/Topic? 0

## Replies To: Calculate factorials using for loops

### #2 capty99

• i am colt mccoy

Reputation: 99
• Posts: 10,081
• Joined: 26-April 01

## Re: Calculate factorials using for loops

Posted 04 April 2007 - 09:18 PM

well, you can nest your for loop in another if else loop

so ...

```if (n >= 0)
{
for (....)
{
}
}

```

you also want your 'counter' variable to be the same as the 'n' the user entered.

so if they entered 7.

it would be 7*7*(7-1)*(7-2)*(7-n) etc...

if your doing this for a class you will probably be counted off for defining an int n.

most want a descriptive name following the formatting conventions...