Help with understanding java 'for' loops - java

I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!
Example #1 (odd number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>
Example #2 (even number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>

a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:
for(counter=0;counter <= iterations;counter++){ }
the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.
if we want to loop from 1 - 10, we do the following:
for(counter=1;counter<=10;counter++){ System.out.println(counter); }
if we want to loop from 10 - 1, we do the following:
for(counter=10;counter>=1;counter--){ System.out.println(counter); }
if we want to loop through a 2 dimensional collection, like...
1 2 3
4 5 6
7 8 9
int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.
you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.
for(i=0;i<grid.length;i++){
//this will loop through all rows...
for(j=0;j<grid[i].length;j++){
//will go through all the columns in the first row, then all the cols in the 2nd row,etc
System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
}
}
In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.
We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.
Please feel free to ask any questions you may have regarding for loops!
EDIT: understanding the question.....
You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.
int lines = 10; //the number of lines
String carat = ">";
for(i=1;i<=lines;i++){
System.out.println(carat + "\n"); // last part for a newline
carat = carat + ">>";
}
The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.
.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.
Edit 3:
Class Test {
public static void main(String[] args) {
int lines = 7;
int half = lines/2;
boolean even = false;
String carat = ">";
int i;
if(lines%2==0){even = true;} //if it is an even number, remainder will be 0
for(i=1;i<=lines;i++){
System.out.println(carat + "\n");
if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
carat = carat.substring(0,carat.length()-2);
}else{
carat = carat + ">>"; //otherwise, going up
}
}
}
}
Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).
Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.
At the hump, if it is even, we have to repeat the string.
We have to then start taking off "<<" each time, since we are going down.
Please ask if you have questions.

I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.
There is a lot of commenting throughout the code that you can follow along to explain the logic.
class ArrowTip {
public void printFigure(int n) { //The user will be asked to pass an integer that will determine the length of the ArrowTip
int half = n/2; //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
String str = ">"; //The String to be printed that will ultimately create the ArrowTip
int endInd; //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip
for(int i = 1; i <= n; i++) { //Print this length (rows)
System.out.print(str + "\n"); //The first carat to be printed, then any following carats.
if (n%2==0) { //If n is even, then these loops will continue to loop as long as i is less than n.
if(i <= half) { //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
str = str + ">>"; //It will continue to add two carats to the string until i is greater than n.
}
endInd = str.length()-2; //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
if((endInd >= 0) && (i >= half)){ //Now, decrement the str while j is greater than half
str = str.substring(0, endInd); //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
}
}
else { //If integer n is odd, this else statement will be called.
if(i < half+1) { //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
}
endInd = str.length()-2; //Serves the same purpose as the above if-loop when n is even.
if((endInd >= 0) && (i > half)) { //This will create the bottom half of the ArrowTip by decrementing the carats.
str = str.substring(0, endInd); //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
}
}
}
}
}
Again, this was for a homework assignment. Happy coding.

Here is a simple answer for you hope it helps! Cheers Logan.
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
for (int i = 10; i > 0; i--) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
}
}

For making a 'for' loop:
public class Int {
public static void main(String[] args) {
for (Long num = 1000000L; num >= 9; num++) {
System.out.print("Number: " + num + " ");
}
}
}
Output:
Number: 1008304 Number: 1008305 Number: 1008306 Number: 1008307 ...

Related

Finding the longest run of duplicate numbers in an ArrayList? (Beginner java)

This is my first time using stack overflow, so I'm so sorry if this is formatted incorrectly in any way. For a comp sci project, I have to do some different things to a 40-item Array List of random numbers.
The task I'm struggling with is this:
Count the longest run of the same number. A run continues only when consecutive numbers
have the same value. The repeated number and the length of the run is then printed. (Ex: Longest run is of number: 3, length is: 5.)
If there is more than one run of maximum length, mark the last one. Print the array with the longest run marked in the following fashion:
1 1 1 6 5 4 6 3 2 3 2 (3 3 3 3 3) 1 5 6 3 4 4 4
I genuinely have no idea how to approach this problem. Even just some pseudocode could be helpful; I know that these should probably be 2 different 'for' loops, one that detects the run and the other that prints it. I have some code from a friend who completed this using Arrays instead of ArrayLists:
public String longestRun()
{
int maxRun=1;
int currentLen = 1;
int repeated = x[0];
for (int i =1; i< 40-1; i++)
{
if (x[i] == x[i+1])
currentLen++;
else
{
if (currentLen >= maxRun)
{
maxRun = currentLen;
repeated = x[i-1];
startRun = i-maxRun;
endRun = i-1;
}
currentLen = 1;
}
}
return "The longest run is " + maxRun + " and the repeated number is " + repeated ;
}
public String printParenth()
{
for(int i = 0; i<40; i++)
{
if(i != startRun+1 && i != endRun+1)
System.out.print(x[i]);
else if(i == startRun+1)
System.out.print("(" + x[i]);
else
System.out.print(x[i] + ")");
}
return "";
}
I know how to create the ArrayList, convert to string & print, etc, it's just this one task that I don't understand. I assume this should be easier with an ArrayList, considering the increased number and utility of ArrayList methods. Thanks so much in advance, I really appreciate it!
Put your numbers in a list or an array.
Set max to 1 (you will always have at least 1 number).
initialize count to 1.
initialize the variable most to the first number in the array
also set the variable last to the first number in the array.
Now iterate thru the list starting with the second number.
If the current number is the same as last, increment count.
then see if count > max.
if it is
set max = count.
set most = last
if it isn't
set count = 1
set last = current number
continue in this fashion until all numbers have been checked.
At the end most will contain the number that was repeated and max will contain the length of the repetition.

Count of random numbers from a string java

This is a homework problem with a rule that we cant use arrays.
I have to make a program that will generate ten random numbers , append it to a string with a comma after each number.
I then have to give a count of each random number and remove the highest frequency number from the string.
The only issue i cannot solve is how to give a count of each number.
Lets say the string is "1,1,2,4,5,6,6,2,1,1" or "1124566211" with the commas removed.
How can I go about an output something like
1 = 4
2 = 2
4 = 1
5 = 1
6 = 2
Removing all numbers of max frequency
245662
Where the left side is the number and the right is the count.
EDIT: Range is 1 between 10, exclusing 10. It is testing the frequency of each digit i.e. how many times does 1 appear, how many times does 2 appear etc. Also its due tonight and my prof doesnt answer that fast :/
I would use a HashMap. A string representation of the num will be used as the key and you will have an Integer value representing the frequency it occurs.
Loop through the string of nums and put them to the HashMap, if the num already exists in the map, update the value to be the (current value + 1).
Then you can iterate through this map and keep track of the current max, at the end of this process you can find out which nums appear most frequently.
Note: HashMap uses Arrays under the covers, so clarify with your teacher if this is acceptable...
Start with an empty string and append as you go, check frequency with regex. IDK what else to tell you. But yeah, considering that a string is pretty much just an array of characters it's kinda dumb.
You can first say that the most common integer is 0, then compare it with the others one by one, replacing the oldest one with the newest one if it written more times, finally you just rewritte the string without the most written number.
Not the most efficient and clean method, but it works as an example!
String Text = "1124566211"; // Here you define the string to check
int maxNumber = 0;
int maxNumberQuantity = 0; // You define the counters for the digit and the amount of times repeated
//You define the loop and check for every integer from 0 to 9
int textLength = Text.length();
for(int i = 0; i < 10; i ++) {
int localQuantity = 0; //You define the amount of times the current digit is written
for(int ii = 0; ii < textLength; ii ++) {
if(Text.substring(ii, ii+1).equals(String.valueOf(i)))
localQuantity ++;
}
//If it is bigger than the previous one you replace it
//Note that if there are two or more digits with the same amount it will just take the smallest one
if(localQuantity > maxNumberQuantity) {
maxNumber = i;
maxNumberQuantity = localQuantity;
}
}
//Then you create the new text without the most written character
String NewText = "";
for(int i = 0; i < textLength; i ++) {
if(!Text.substring(i,i+1).equals(String.valueOf(maxNumber))) {
NewText += Text.charAt(i);
}
}
//You print it
System.out.println(NewText);
This should help to give you a count for each char. I typed it quickly off the top of my head, but hopefully it at least conveys the concept. Keep in mind that, at this point, it is loosely typed and definately not OO. In fact, it is little more than pseudo. This was done intentionally. As you convert to proper Java, I am hoping that you will be able to get a grasp of what is happening. Otherwise, there is no point in the assignment.
function findFrequencyOfChars(str){
for (i=0; i<str; i++){
// Start by looping through each char. On each pass a different char is
// assigned to lettetA
letterA = str.charAt(i);
freq = -1;
for (j=0; j<str; j++){
// For each iteration of outer loop, this loops through each char,
// assigns it to letterB, and compares it to current value of
// letterA.
letterB = str.charAt(j);
if(letterA === letterB){
freq++
}
}
System.Out.PrintLn("the letter " + letterA + " occurs " + freq +" times in your string.")
}
}

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

Why does this merge sort give incorrect results?

My assignment is to merge two arrays using int arrays that the user fills and we have to assume that there will be a maximum of 10000 inputs from the user, and the user inputs a negative number to stop. Then sort the array from least to greatest and print it out. Initially i thought that this would be quite easy but when i finished, i began getting outputs such as:
Enter the values for the first array, up to 10000 values, enter a negative number to quit: 1
3
5
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
2
4
6
-1
First Array:
1
3
5
Second Array:
2
4
6
Merged Array:
6 1 2 3 4 5
as you can see, the six is out of place and i have no idea how to fix it. Here is the source code, i have included copious comments because I really want you guys to help me out to the best of your abilities. IF it's possible to use the same exact technique without implement new techniques and methods into the code please do so. I know there are methods in java that can do all of this in one line but it's for an assignment at a more basic level.
import java.util.Scanner;
public class Merge
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int [] first = new int[10000]; //first array, assume 10k inputs max
int [] second = new int[10000]; //first array, assume 10k inputs max
boolean legal = true; //WILL IMPLIMENT LATER
int end = 0; // set how many elements to put in my "both" array
int end2 = 0;// set how many elements to put in my "both" array
System.out.print("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
//get values
for(int i = 0; i<first.length; i++)
{
first[i] = scan.nextInt(); //fill first with user input
if(first[i] <0) //if negative number, stop loop
{
end = i; //get position of end of user input
break;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
for(int i = 0; i<second.length; i++) //exact same as the first get values loop
{
second[i] = scan.nextInt();
if(second[i] <0)
{
end2 = i;
break;
}
}
System.out.print("First Array:\n");
for(int i = 0; i<first.length; i++) //print first array
{
if(i == end) //this prevents from printing thousands of zeros, only prints values that user inputed
break;
System.out.println(first[i] + " ");
}
System.out.print("Second Array:\n");
for(int i = 0; i<second.length; i++) //same as printing first array
{
if(i == end2)
break;
System.out.println(second[i] + " ");
}
int [] both = new int[(end)+(end2)]; //instanciate an int array to hold only inputted values from first[] and second[]
int [] bothF = new int[(end)+(end2)]; //this is for my simple sorter algotithm loop
for(int i = 0; i<both.length; i++) //fill both with the first array that was filled
{
both[i] = first[i];
}
int temp = end; // see below
for(int i = 0;i<both.length; i++) //fill array with the second array that was filled(starting from the end of the first array so that the first set is not overwritten
{
if(temp<both.length){ //this prevents an out of bounds
both[temp] = second[i];
temp++;}
}
//simple sorting algorithm
for(int d = both.length -1;d>=0;d--)
{
for(int i = 0; i<both.length; i++)
{
if(both[d]<both[i])
{
bothF[d] = both[d];
both[d] = both[i];
both[i] = bothF[d];
}
}
}
System.out.println("Merged Array:"); //print the results
for(int i = 0; i<both.length; i++)
{
System.out.print(both[i] + " ");
}
//System.out.println("ERROR: Array not in correct order");
}
Your sorting algorithm is faulty.
It's similar to selection sort, in that you take two elements and swap them if they're out of place. However, you don't stop the comparisons when you should: when the index d is less than the index i, the comparison-and-swap based on arr[d] > arr[i] is no longer valid.
The inner loop should terminate with i=d.
The logic of your sort goes something like this:
On the d-th loop, the elements at d+1 and to the right are correctly sorted (the larger numbers). This is true at the beginning, because there are 0 elements correctly sorted to the right of the right-most element.
On each of the outer loops (with the d counter), compare the d-th largest element slot with every unsorted element, and swap if the other element is larger.
This is sufficient to sort the array, but if you begin to compare the d-th largest element slot with already-sorted elements to its right, you'll end up with a larger number in the slot than should be. Therefore, the inner loop should terminate when it reaches d.
Sure, you can do it like this
for (int i = 0; i < end; i++) {
both[i] = first[i];
}
for (int i = 0; i < end2; i++) {
both[i + end] = second[i];
}
// simple sorting algorithm
for (int d = both.length - 1; d >= 0; d--) {
for (int i = 0; i < d; i++) {
if (both[i] > both[d]) {
int t = both[d];
both[d] = both[i];
both[i] = t;
}
}
}
Output(s) -
Enter the values for the first array, up to 10000 values, enter a negative number to quit3
5
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
2
4
6
-1
First Array:
3
5
Second Array:
2
4
6
-1
Merged Array:
2 3 4 5 6
First I will start with some recommendations:
1.Give end1 and end2 the initial value as the array lengths.
The printing part - instead of breaking the loop - loop till i == end(if its not changed by the first part it will stay the array length).
One suggestion is to use a "while" statement on the user input to do the reading part (it seems cleaner then breaking the loop- but its OK to do it like you have done too).
Try to use more functions.
now to the main thing- why not to insert the numbers from both arrays to the join array keeping them sorted?
Guiding:
Keep a marker for each array.
Iterate over the new join array If arr1[marker1]> arr2[marker2]
insert arr2[marker2] to the joint array in the current position.
and add 1 to marker2. and the opposite.
(don't forget to choose what happens if the are equal).
This can be achieved because the arrays were sorted in the first place.
Have fun practicing!
I guess you have sort of a reverse "selection sort"-algorithm going on there. I made an class that run your code and printed out the output after every swap. Here is the code which is the same as you got in your application with the addition of print.
for(int d = both.length -1;d>=0;d--)
{
for(int i = 0; i<both.length; i++)
{
if(both[d]<both[i])
{
int temp = both[d];
both[d] = both[i];
both[i] = temp;
printArray(both);
}
}
}
and when we run this on an example array we get this output
[9, 8, 7, 6]=
-> 6879
-> 6789
-> 6798
-> 6978
-> 9678
The algorithm actually had the correct answer after two swaps but then it started shuffling them into wrong order. The issue is the inner for loops end parameter. When you have run the outer loop once, you can be certain that the biggest number is in the end. 'd' is here 3 and it will swap out a bigger number every time it encounters it. the if clause comparisions in the first loop is 6-9 (swap), 9-8, 9-7, 9-9. All good so far.
Potential problems comes in the second iteration with 'd' as 2. Array is now [6,8,7,9] and comparisons are 7-6, 7-8 (swap with result [6,7,8,9]), 8-8, 8-9 (swap!!) resulting in [6,7,9,8]. the last swap was the problematic one. We knew that the biggest number was already in the last spot, but we still compare against it. with every gotrough of the whole inner loop it will always find the biggest number (and all other bigger than both[d] that is already in place) and swap it to some wrong position.
As we know that the biggest number will be last after one iteration of the outer loop, we shouldn't compare against it in the second iteration. You sort of lock the 9 in the array and only try to sort the rest, being in this case [6,8,7] where d = 3, value 7. hence, your inner loop for(int i = 0; i<both.length; i++) becomes for(int i = 0; i<=d; i++). As an added bonus, you know that in the last iteration i==d, and thus the code inside it, if(both[d]<both[i]) will never be true, and you can further enhance the loop into for(int i = 0; i<d; i++).
In your algorithm you always do four comparisons in the inner loop over four iterations of the outer loop, which means there is a total of 16 comparisons. if we use the i<d we'll just do three comparisons in the inner loop on the first iteration of the outer loop, then two, then one. This brings it to a total of six comparisons.
Sorry if too rambling, just wanted to be thorough.

How will the third for loop work out?

I have a question about the third for loop, how does it work please ?
public void outputBarChart()
{
System.out.println("Grade Distribution: \n");
int frequency[] = new int[11];
for(int oneGrade : grade)
{
++frequency[oneGrade / 10];
}
for (int count = 0; count < frequency.length; count++)
{
if (count == 10) {
System.out.println("100");
}
else {
System.out.printf("%02d-%02d: ",
count*10, count*10 + 9);
}
//the third for loop here !
for (int star = 0; star < frequency[count]; star++){
System.out.print("*");
}
System.out.println();
}
}
The problem is I don't know the mechanics how it print out stars.
Well lets go through the code then:
The second for loop which contains the third for-loop will loop 11 times since thats the length of frequencey. Okay that was easy.
Now the third for-loop iterates frequency[count] times, we don't know this value, but we know that it is an integer. So what third loop will do is simply to print out a star frequency[count] times. After that we're done with the third loop and a newline is printed by the second loop.
System.out.println("*" * frequency[count]);
The loop will take the variable star and loop and increment until it reaches the value of frequency[count]. So it will run the loop the same number of times as the value stored in frequency[count].
Each loop iteration it prints a star. At the end it prints a blank line.
The result is printing the number of stars as frequency[count] on a line.

Categories

Resources