Thread: Stack Of Integers (to get factors)

1. Member
Join Date
Apr 2011
Posts
14
Rep Power
0

Stack Of Integers (to get factors)

Hi,
i got the following code which gives the factor.
for example if i type 120
it will give me the factors which are 5 3 2 2 2
the book is now asking to use Stack Of Integers to get reverse as well
so the overall should show
5 3 2 2 2 and 2 2 2 3 5 (when i put in value of 120)
I've been stuck on this for few days now.

public class factors
{
public static void main(String args[])
{
int[] facts = new int[100];
int i = 0, j = 0;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = input.nextInt();
System.out.print("The factors for " + number + " is:");
int factor = 2;
while (factor <= number)
{
if (number % factor == 0)
{
number = number / factor;
facts[i] = factor;
i++;
}
else factor++;
}
for (j = i - 1; j >= 0; j--)
{
System.out.print(" " + facts[j]);

}

2. You have the facts[] array... you could just iterate through it backwards and display each number.

Alternately, you can reverse the array and output it.

3. All you should have to do is print the array in the opposite direction.

Java Code:
```int[] x = {1, 4, 2, 3, 7};
for(int i = 0; i < x.length; ++i){
System.out.print(x[i] + " ");
}
System.out.println();
for(int i = x.length - 1; i >= 0; --i){
System.out.print(x[i] + " ");
}```

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•