how do I print my array using enhanced loops - java

So as my program runs, it does some calculations for the Fibonacci sequence. I can easily print these 20 Fibonacci sequences out in the for loop, but I just want to do the calculations to fill the Fib array up and do the printing out in an enhanced loop. How can I do this with an enhanced for loop?
public static void main(String[] args) {
int[] Fib = new int[20];
Fib[0] = 0;
Fib[1] = 1;
System.out.printf("%d %d", Fib[0], Fib[1]);
for (int i = 2; i < Fib.length; i++) {
Fib[2] = Fib[0] + Fib[1];
Fib[0] = Fib[1];
Fib[1] = Fib[2];
System.out.print(" "+Fib[2]);
for (int x : Fib) {
x = Fib[2];
System.out.print(" "+x);;
}
}
}

Your code contains a few mistakes, and major are:
Fib[2] = Fib[0] + Fib[1]; this should be Fib[i] = Fib[i - 1] + Fib[i - 2];
Another mistake is nesting for loops. The enhanced for loop should be after the loop with index i.
int[] Fib = new int[20];
Fib[0] = 0;
Fib[1] = 1;
for (int i = 2; i < Fib.length; i++) {
Fib[i] = Fib[i - 1] + Fib[i - 2];
}
for (int number : Fib) {
System.out.print(" " + number);
}
You can use Arrays.toString(Fib) instead of using a loop for printing the array.

Related

How to print a histogram from the values in an array in reverse order with nested for loops

I have assignment where I have to print and fill an array consisting of 50 indices with random integers then print the values out. Then below that print a list of the numbers in the reverse index with a histogram next to each value. Im supposed to use a nested for loop to solve this and only could get the first section of the problem so far. This is my first time using stackoverflow and I am not expecting an upright answer but if someone could help me understand nested for loops a little more, it would be greatly appreciated.
public static void main(String[] args) {
Random ranGen = new Random();
int[] ranArray = new int [SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for(int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
for(int j = 0; j < ranArray[i]; j++) {
System.out.println("Histrogram");
System.out.println(ranArray[i] );
}
}
}
}
How the output of the code should look like
For the second section, you can iterate on each random number again and for each number, print it with System.out.printf("%-5d", number) ("%-5d" pads the number with spaces to the right) and have a nested loop from 0 to number-1 and print the start with System.out.print(stars).
public static void main(String[] args) {
int SIZE = 5;
Random ranGen = new Random();
int[] ranArray = new int[SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for (int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
}
System.out.println("-------------------------");
System.out.println("Histograms:");
for (int i = ranArray.length - 1; i >= 0; i--) {
System.out.printf("%-5d", ranArray[i]);
for (int j=0; j<ranArray[i]; j++) {
System.out.print(stars);
}
System.out.println();
}
}

Numerically listing Arrays

So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest).
The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
System.out.println("\n" + "Organized Array: ");
int[] array2 = new int[i];
for (i = 0; i < array1[i]; i++) {
System.out.println(+array1[i]);
for (int j = 0; j < i; j++) {
int temp;
boolean numerical = false;
while (numerical == false) {
numerical = true;
for (i = 0; i < array1.length - 1; i++) {
if (array2[i] > array2[i + 1]) {
temp = array2[i + 1];
array2[i + 1] = array2[i];
array2[i] = temp;
numerical = false;
}
}
}
}
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
You have several issues that you need to fix to make your program run:
You have forgotten to copy array1 into array2:
The output that you think is coming from sorting array2 is actually from the process of sorting.
int[] array2 = new int[i];
for (int j = 0; j < i; j++) {
array2[j] = array1[j];
}
You placed the output of sorted array inside the loop that does sorting:
Check the level of curly braces, and move the output loop to after the sorting loop
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Your sorting algorithm has an extra loop:
Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting:
for (i = 0; i < array1[i]; i++) { // Remove the loop
... // <<== Keep the body
}
Your innermost loop reuses i incorrectly:
Replace loop variable i with another variable, e.g. m
for (int m = 0 ; m < array2.length - 1; m++) {
if (array2[m] > array2[m + 1]) {
temp = array2[m + 1];
array2[m + 1] = array2[m];
array2[m] = temp;
numerical = false;
}
}
Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong.
you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops
you never copied the array1 values to array2

Number of Comparisons between selection sort and bubble sort keep coming up the same

I have written this program to compare the number of operations needed to sort a random numbers using both selection and bubble sort. However, these numbers keep coming up the same and I can't figure out where my code went wrong.
static int num_comps;
public static void main(String[] args)
{
Random rnd = new Random();
// max size of array
// number of N inputs
int array_size = 32768;
int num_datasets = 12;
// allocate array once to the max size
int[] vals = new int[array_size];
// temp array with allocated array to max size
int[] tvals = new int[array_size];
// array to hold operation counts
int[] op_counts = new int[num_datasets];
int[] op_counts2 = new int[num_datasets];
// array to hold the size of each array
//
int[] arraySizes = new int[num_datasets];
int i;
int j;
int sz;
for (i = 0, sz = 16; i < num_datasets; i++, sz *= 2)
arraySizes[i] = sz;
for (int iter = 0; iter < num_datasets; iter++)
{
int curr_size = arraySizes[iter];
// load array with random values
//
for (i = 0; i < curr_size; i++)
vals[i] = rnd.nextInt(4999);
for (i = 0; i < curr_size; i++)
tvals[i] = vals[i];
// run the bubble sort algorithm
//
num_comps = 0;
bubbleSort(tvals, curr_size);
op_counts[iter] = num_comps;
//System.out.println("Num comps at " + iter + " is " + num_comps);
// run the selection-sort algorithm
num_comps = 0;
selectionSort(tvals, curr_size);
op_counts2[iter] = num_comps;
//System.out.println("Num comps at " + iter + " is " + num_comps);
}
System.out.println("Operation Counts (N vs. op Count): ");
for (int k = 0; k < num_datasets; k++)
System.out.println(arraySizes[k] + "\t\t" + op_counts[k] + "\t\t" + op_counts2[k]);
}
static void bubbleSort(int vals[], int curr_size)
{
int temp;
for (int i = 0; i < curr_size - 1; i++)
{
for (int j = 0; j < curr_size - i - 1; j++)
{
// swap
num_comps = num_comps + 1;
if (vals[j+1] < vals[j])
{
temp = vals[j];
vals[j] = vals[j+1];
vals[j+1] = temp;
}
}
}
}
static void selectionSort(int vals[], int curr_size)
{
int temp;
for(int i=0; i<curr_size - 1; i++)
{
for(int j=i+1; j<curr_size; j++)
{
num_comps = num_comps + 1;
if(vals[i] > vals[j] )
{
temp = vals[j];
vals[j] = vals[i];
vals[i] = temp;
}
}
}
}
Your selection sort algorithm does not search for the lowest value in the list. And swapping it afterwards with the index of the outer loop.
You should do something like this:
static void selectionSort(int vals[], int curr_size)
{
int temp;
for(int i=0; i<curr_size - 1; i++)
{
int lowest = i;
for(int j=i+1; j<curr_size; j++)
{
num_comps = num_comps + 1;
if(vals[lowest] > vals[j] )
{
lowest = j;
}
}
// swap lowest with current index
temp = vals[lowest];
vals[lowest] = vals[i];
vals[i] = temp;
}
}
(of course this can be optimized further)
The strength of this algorithm is not the amount of of comparisons, but this amount of swaps (which is at a minimum, I suppose).
Your bubble sort algorithm seems ok to me.
Both have the same two loops, so comparing the counts of the current implementations indeed result in the same values. But, I think you can optimize the bubble sort, to stop earlier (when no swaps were found). Again, the strength of sorting algorithms depends on the used ones, and are not necessarily the least amount of comparisons. So Using the correct algorithm for your specific task, and thereby circumventing the task-specific high cost operations, is important!

Nested For Loops Dynamic Depth Java

Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}
Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.
here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}
The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.

from loop to Nested loops?

I have this program that returns a factorial of N. For example, when entering 4,,, it will give 1! , 2! , 3!
How could I convert this to use nested loops?
public class OneForLoop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for(int i = 1; i < N; i++)
{
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
If written as nested loops it would look like this:
for (int i = 1; i < N; ++i)
{
int factorial = 1;
for (int j = 1; j <= i; ++j) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
Result:
Enter a number : 10
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
This program gives the same result as yours, it just takes longer to do so. What you have already is fine. Note also that the factorial function grows very quickly so an int will be too small to hold the result for even moderately large N.
If you want to include 10! in the result you need to change the condition for i < N to i <= N.
Right now you are calculating your factorial incrementally. Just recalculate it from scratch every time. Be advised that what you have now is better than what I'm posting, but this does follow your requirements.
public class TwoForLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for (int i = 1; i < N; ++i)
{
factorial = 1;
for(int j = 1; j <= i; j++)
{
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
Rather than just computing everything in a linear fashion, you could consider an inner loop which would do something like what you have in the outer loop. Is that what you are trying to achieve?
Would you consider recursion a nested loop?
public long factorial(int n)
{
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String [] args)
{
//print factorials of numbers 1 to 10
for(int i = 1; i <= 10; i++)
System.out.println(factorial(i));
}

Categories