In: Computer Science
Unit 4: Discussion - Part 2
No unread replies.No replies.
Question
Read the lecture for Chapter 4, and then answer the following:
This week covered the many different types of loops in Java: while, do, and for. Think of a brief example where you can use loops and write it in correct Java syntax. You may use the loop example you wrote in pseudo code for the discussion thread 2 during week 2 and convert it to Java, if you think it is appropriate. Be mindful that we are not talking about homework here. Do not post homework in this or any other discussion thread. You should show at least 2 of the 3 different types of Java loops in your posting. You may incorporate both kind of loops in the same example, or alternatively, show how the same example can be written using two different kinds of loops. Try to keep your example short, so others can follow it easily. Also, do not forget to show screen captures of your programs running.
//A simple program to ask for an integer and calculate its factorial.
Using a for loop
//////////////////////
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num;
double factorial = 1;
System.out.print("Enter a number to find factorial: ");
num = sc.nextInt();
for(int i=1;i<=num;i++){
factorial*=i;
}
System.out.print("Factorial of "+num+" is: "+factorial);
}
}
//Using a while loop
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num;
double factorial = 1;
System.out.print("Enter a number to find factorial: ");
num = sc.nextInt();
int i = num;
while(num>0)
{
factorial*=num;
num-=1;
}
System.out.print("Factorial of "+i+" is: "+factorial);
}
}