1 Replies - 13816 Views - Last Post: 04 April 2007 - 09:18 PM Rate Topic: -----

#1 lincolnpark583   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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: ");
	n = console.nextInt();
	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   User is offline

  • i am colt mccoy
  • member icon

Reputation: 99
  • View blog
  • 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...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1