Question

4.25 Lab9d: Factorials This program will output the factorial of numbers 1 through 10. Recall that...

4.25 Lab9d: Factorials

This program will output the factorial of numbers 1 through 10. Recall that 10! = 10 * 9 * 8 * 7 * … * 2 * 1.

Calculating the factorial will require two loops. The outer loop will iterate from the number 1 up to and including the number n. n will be based on a number the user entered (an int value). The inner loop will calculate the factorial of the number the first loop is currently on--go ahead and work it out on paper first! When the inner loop finishes it will have calculated the n's factorial, so now save the value in an array called factorials. [Note that number 1 will be stored in factorials[0], so this requires a little navigation through the mire of being "off by one".

Finally, use a separate for loop to print all the results from the factorials array in the following format: "The factorial of [current number] is [factorial value]"
Make sure to print out a new line between each print out.

Example input:

10

Example output:

The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
The factorial of 6 is 720
The factorial of 7 is 5040
The factorial of 8 is 40320
The factorial of 9 is 362880
The factorial of 10 is 3628800

The factorials array will contain:

factorials[0] is 1
factorials[1] is 2
factorials[2] is 6
factorials[3] is 24
factorials[4] is 120
factorials[5] is 720
factorials[6] is 5040
factorials[7] is 40320
factorials[8] is 362880
factorials[9] is 3628800

import java.util.Scanner;
public class Factorials
{
public static void main (String args[])
{
Scanner scnr = new Scanner(System.in);
int num = scnr.nextInt();
  
// TODO: Create a new array called "factorials" sized "num" elements

// TODO: Loop to calculate the factorial (from 1 to num)
// Store the result in factorials array
// (watch out for index off by one!)


// TODO: Loop to print the "factorials" array with message form:
// "The factorial of X is Y"
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have designed and developed the program for the given question using Java. I have included the comments for each part of the code and finally added the output screenshot of the program.

Please look at the comments for better understanding of the program.

OUTPUT:

CODE:

*Factorials.java*

import java.util.Scanner;
public class Factorials
{
public static void main (String args[])
{
Scanner scnr = new Scanner(System.in);
int num = scnr.nextInt();

// TODO: Create a new array called "factorials" sized "num" elements
int factorials[] = new int[num];
  
// TODO: Loop to calculate the factorial (from 1 to num)
// Store the result in factorials array
// (watch out for index off by one!)
   for(int i=1; i<=num; i++){ // outer loop numbered from 1 to num
       factorials[i-1]=1; // initialise the product as 1
for(int j =2; j <=i;j++){ // innerloop calculates the factorial.
// this multiplies the product by 2,3,4,......until 'i'
// Suppose i =5.
// Innerloop calculates factorial[4]=120
// Initially factorial[4]=1.
// Innerloop interates from 2 to 'i'.
// we use factorial[i-1] because we store result of i in factorial[i-1]
// It multiplies the factorial[4] by 2 and store the results in factorial[4].
//Later it multiplies the factorial[4] by 3 and repeats until it is multiplied by 5.
  

factorials[i-1] = factorials[i-1]*j;
}
// therefore now after innerloop finishes,
// factorial[i-1]=1*2*3 . . . . . * i
// Hence for eg., 5! = factorials[4] = 1*2*3*4*5 =120 .
  
}
  

// TODO: Loop to print the "factorials" array with message form:
// "The factorial of X is Y"
// System.out.println() function prints the string specified in it in a newline.
for(int i = 1; i<= num; i++){
// We concatenate several strings using '+' operator.
// The first string is concatenated with 'i' value using '+' and then factorials[i-1] is concatenated.
// since factorial of i is stored in factorials[i-1].
System.out.println("The factorial of "+i+" is "+factorials[i-1]);
}
  
//Please note that this program can only calculate factorials for only upto 15.
// This is due to the integer limits in java int has 4 bytes which holds values from -2,147,483,648 to 2,147,483, 647
// you might have to use other data types or other methods.
// However this solution is correct and complete for your question.
}
}

//-------------------------------------------------------------------------------------

**Thank You. Please comment for any further clarification**

Add a comment
Know the answer?
Add Answer to:
4.25 Lab9d: Factorials This program will output the factorial of numbers 1 through 10. Recall that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In C: Write a program that will compute and print a table of the factorials from...

    In C: Write a program that will compute and print a table of the factorials from 1 to 12. The program should define a function called fact to compute the factorial, use loops where appropriate, and produce the following output: 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 39916800 12 479001600

  • Answer in JAVA 1. Complete the method definition to output the hours given minutes. Output for...

    Answer in JAVA 1. Complete the method definition to output the hours given minutes. Output for sample program: 3.5 import java.util.Scanner; public class HourToMinConv {    public static void outputMinutesAsHours(double origMinutes) {       /* Your solution goes here */    }    public static void main (String [] args) {       Scanner scnr = new Scanner(System.in);       double minutes;       minutes = scnr.nextDouble();       outputMinutesAsHours(minutes); // Will be run with 210.0, 3600.0, and 0.0.       System.out.println("");    } } 2....

  • Use the Summation recursive program you did in the class to also work with minus integers....

    Use the Summation recursive program you did in the class to also work with minus integers. For example, the sum of -3 will be -6 which is (-3)+(-2)+(-1)+0. USE THIS CODE package project5; import java.util.Scanner; public class SingleRecursion { /** Main method */ public static long sum(int n) {    if (n<0) throw    new IllegalArgumentException ("Can't calculate factorial of negative");    if (n==1)        return 1;    else if (n==0)        return 1;    else       ...

  • 7.2.3: Printing array elements with a for loop. Write a for loop to print all elements...

    7.2.3: Printing array elements with a for loop. Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10}, print: 7 9 11 10 10 11 9 7 Hint: Use two for loops. Second loop starts with i = courseGrades.length - 1. (Notes) Also note: If the submitted code tries to access an invalid...

  • For the following C# program: Let’s add one more user defined method to the program. This...

    For the following C# program: Let’s add one more user defined method to the program. This method, called ReverseDump is to output the values in the array in revere order (please note that you are NOT to use the Array.Reverse method from the Array class). The approach is quite simple: your ReverseDump method will look very similar to the Dump method with the exception that the for loop will count backwards from num 1 to 0 . The method header...

  • 1. Assign numMatches with the number of elements in userValues that equal matchValue. userValues has NUM_VALS...

    1. Assign numMatches with the number of elements in userValues that equal matchValue. userValues has NUM_VALS elements. Ex: If userValues is {2, 1, 2, 2} and matchValue is 2 , then numMatches should be 3. Your code will be tested with the following values: matchValue: 2, userValues: {2, 1, 2, 2} (as in the example program above) matchValue: 0, userValues: {0, 0, 0, 0} matchValue: 10, userValues: {20, 50, 70, 100} What i am given: import java.util.Scanner; public class FindMatchValue...

  • In this same program I need to create a new method called “int findItem(String[] shoppingList, String...

    In this same program I need to create a new method called “int findItem(String[] shoppingList, String item)” that takes an array of strings that is a shopping list and a string for an item name and searches through the “shoppingList” array for find if the “item” exists. If it does exist print a confirmation and return the item index. If the item does not exist in the array print a failure message and return -1. import java.util.Scanner; public class ShoppingList...

  • . In the method main, prompt the user for a non-negative integer and store it in...

    . In the method main, prompt the user for a non-negative integer and store it in an int variable num (Data validation is not required for the lab). Create an int array whose size equals num+10. Initialize the array with random integers between 0 and 50 (including 0 and excluding 50). Hint: See Topic 4 Decision Structures and File IO slides page 42 for how to generate a random integer between 0 (inclusive) and bound (exclusive) by using bound in...

  • Write a while loop that prints all positive numbers that are divisible by 10 and less...

    Write a while loop that prints all positive numbers that are divisible by 10 and less than a given number n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90. import java.util.Scanner; public class PositiveLess {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        System.out.print("n: ");        int n = in.nextInt();        ...        while (...)        {           ...

  • my goal is to generate a random number every 10 seconds and store in arraylist. when...

    my goal is to generate a random number every 10 seconds and store in arraylist. when I generate the new number every 10 second I want to update the previous number from the arraylist. currently it gets the first current number in main method but when I store after 10 second i'm not getting the update current number. I would appreciate any help. NOTE: ***I want the Runnable to be in the same class, Not in main method. my goal...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT