Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Nested Loops

Ryan Perlman
Greenhorn
Posts: 23
I just want to say hello to the Ranch and I like the site it has helped me up till now. This is where I am stuck now. Thank you
Ryan Perlman
I have written the code for a factorial program now I am having trouble nesting it into a program to compute the constant e,
the factorial is 5! = 5*4*3*2....
the e is e= 1 +1/1!+1/2!+1/3!....
public class NewFact
{
public static void main (String [] args)
{
String input;
int n;
int fact = 1;

input = JOptionPane.showInputDialog("enter a number to compute");
n = Integer.parseInt(input);

while( n > 1 ){
fact *= n;
n = n-1;
System.out.println(fact);
}
}
}
My second question is:
I have written a for loop to print out a right triangle like so
up to ten '*' but now I want it to print 4 of them side by side
everytime I nest in another for loop I either distort my first triangle or create an infinite loop.
*
**
***
****
*****
My first for loop is
public class Triangle
{
public static void main(String [] args)
{
for( int i = 1; i <= 10; i++){
for ( int j = 1; j <= i; j++){
system.out.print('*');
}
System.out.print();
}
}
}
thanks for any pointers in the right direction
Ryan Perlman

Ryan Perlman
Greenhorn
Posts: 23
The Triangle is spose to end up looking like this
* ***** ***** *
** **** **** **
*** *** *** ***
**** ** ** ****
***** * * *****
Thanks

Michael Bruesch
Ranch Hand
Posts: 158
Oh, I love these school projects, they were my favorite! Alright, first you'll probably need to make your factorial code into a method, say getFactorial (int x) or something, then it will be 10 times easier to nest it into code that will find the value of E:
(Just an example)
double e;
e = 1 / getFactorial (1) + 1 / getFactorial (2) + 1 / getFactorial (3).....etc.
As far as the triangles made of stars, that's just tedious formatting. Do you have to use nested for loops, or was that just your first thought? Cause I wouldn't use nested for loops, just use 4 different for loops. Since this is a school assignment I assume, I'm not gonna post the code, just push you in the right direction.
Good Luck!

------------------
Michael J Bruesch
Codito, ergo sum...
I code, therefore I am.
My Java Games, I'm quite proud

Uma Viswanathan
Ranch Hand
Posts: 126
public class Calculate
{
public Calculate()
{
//get the input
int n = Integer.parseInt(input);
findExpo( n );
}
private void findExpo( int n )
{
double expo = 1.0;
int fact = 1;
for( int iCount = 1; iCount <= n; iCount++ )
{
fact = 1;
for( int jCount = 1; jCount <= iCount; jCount++ )
{
fact *= jCount;
}
expo += 1/(double)fact;
}
System.out.println( "factorial: of " + n + " is: " + fact);
System.out.println( "Value of e of " + n + " is: " + expo );
}
public static void main (String [] args)
{
Calculate calObj = new Calculate();
}
}