any assist in understanding some for-loops? (java) - java

Ok, so I got this program that prints out a pyramid!
Heres the code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("How many rows?: ");
int amountOfRows = keyboard.nextInt();
int maxIndentation = amountOfRows + 2;
for(int row = 0; row < amountOfRows; row++){
int antallx = 2*row;
// indent
for(int column = 0; column < maxIndentation - antallx / 2; column++){
System.out.print(" ");
}
// prints a row
System.out.print("d");
for(int kolonne = 0; kolonne < antallx; kolonne++){
System.out.print("0");
}
System.out.println("b");
}
}
Question: I know a bit about how for-loops etc work, but what I am wondering is if someone could please explain what the for-loops does in this program and also a bit about the choose of the variables, specially when it comes to adding and or multiplying them with a number (that part is confusing me a lot, how they decide if they want to +2 the variables like with amountOfRow, and multiply with 2 like for antallx)?, and im also wondering big time on the second for loop, how do they come up with dividing by 2 etc? any help would be much appreciated! thanks in advance! :)

I took a look at that application, and it is doing it in a way in order to teach you about both loops and mathematics. Specifically look at your example and focus on the following lines
column < maxIndentation - antallx / 2
What is maxIndentation - antallx / 2 equal to? Recall antallx = 2 * row
Then I would test your pyramid program with different inputs (1, 2, 3, ...) to see how each of them changes the final output of the program.
Here is a commented version of your program that I hope shows you how this program works. You can also use an online IDE to see the code compiled, see here
// This program will output the following type of pyramid
// db
// d00b
public static void main(String[] args){
//a scanner is a tool for reading input from a stream
//in this case, you are reading from the user input window (console)
//Scanner keyboard = new Scanner(System.in);
//asks users how many rows of a pyramid they want
System.out.print("How many rows?: ");
//int amountOfRows = keyboard.nextInt();
for(int i = 0; i < 5; i++)
{
printPyramid(i);
System.out.println("\n\n"); //this line essentially prints a newline x3
}
}
public static void printPyramid(int amountOfRows)
{
int maxIndentation = amountOfRows + 2;
for(int row = 0; row < amountOfRows; row++){
int antallx = 2*row;
for(int column = 0; column < maxIndentation - antallx / 2; column++){
System.out.print("|");
//I changed " " to "|" so you can see what this for loop is printing
}
System.out.print("d");
for(int kolonne = 0; kolonne < antallx; kolonne++){
System.out.print("0");
}
System.out.println("b");
}
}

Its all about logic.
1) Just like what you said, It prints a pyramid
2) maxIndention and antallx variables are just used for spacing. The programmer just only wants that logic to be applied into his program. You can do another different logic if you wanted.

Okay, so you have 2 for loop one inside the other.
The first loop: Row =0; is the starting point, so your loop with start at zero.
Then it check for your condition, and if it is true row it will run thr codr below the forloop and will iincremented by 1 so the next row is now 1. It will do this as long as your , condition is true.
The second loop: will do the same thing however when row = 0; column will start at zero and execute until the condiction becomes false, when row =1 the condiction column will again start at zero and execute until the condiction is false. It will do this until the first loop becomes false.
Really life example
You have 20 dollar and you used 10 dollar for a burger, after couple hour you feel hungry again and you buy other burger the same price. You only do that as long as you have more than 10 dollars. If you have less thecondition becomes false.

Related

Problem with logic of this pattern problem

Here is the question. I have to print this pattern eg For n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
I have written logic for this problem but I am not able to solve it.
I can't make the last pattern print i.e. the decrease one 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
Can anyone help me out and tell what's wrong with my logic. How to fix it
My code down below
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row++){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces++){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01++){
System.out.print(ans1);
ans1 = ans1 +1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2++){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.
This is your second loop when you start to count up from row number variable.
You increment 'ans1' by 1 each iteration.
for (int pattern01 = 1; pattern01 <= row;pattern01++) {
System.out.print(ans1);
ans1 = ans1 + 1;
}
One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.
Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.
for(int pattern2 = 1;pattern2 <= row-1; pattern2++){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
I know you can pull it off :) You got this.

how to display in descending reverse order the cells in a 1D array inside a 2d array in java?

I am doing an assignment for class and I cant figure out what I need to change and exactly where. I am starting to understand better how it all works together. However, I have tried quite a few variations that I thought might work, but they never turn out how I had intended.
The first 5 pieces of code I have gotten to work correctly through trail and error, but that 6th code/problem I can't quite figure out.
My initial code to create the 2D array is this:
public static void main(String[] args) {
int[][] numbers = {{1,1,1,1,1},{2,2,2,2,2},{3,3,3,3,3},{4,4,4,4,4},{5,5,5,5,5}};
//made this to go around Scanner to save time/workload
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5; columns++) {
}
}
And the code that I am having trouble with is:
System.out.println("2) Your entered values are now : ");
System.out.println( );
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < rows + 1; columns++) {
System.out.print(numbers [rows][columns]);
} // will replace w/ System.out.print("*"); to get asterisks instead of numbers
System.out.println( );
}
/*needs to Output ***** Outputs 1
**** 22
*** 333
** 4444
* 55555 */
I have separated all 6 problems within the code and they all run off of the same input (int numbers[5][5]) and utilized similiar code. They all are displayed on a single page after each other.
The problem on the way you are using for loops to print your 2d array
you are doing it in the wrong way
you can fix it by changing this condition columns < rows + 1 to columns < 5 - rows at inner loop:
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5 - rows; columns++) {
System.out.print(numbers [rows][columns]);
} // will replace w/ System.out.print("*"); to get asterisks instead of numbers
System.out.println( );
}
You need your rows to count from 4 to 0 instead of 0 to 4. Feel free to comment here and I'll provide additional assistance if needed.
#Maybe_Factor
Figuring that part was easy. We had figured out what the problem was a hour after the original posting.
Here is the new code:
System.out.println("6) Your entered numbers are now : ");
System.out.println( );
for(int rows = 0; rows < 5; rows++) {
for(int columns = 0; columns < 5- rows ; columns++) {
System.out.print("*");

How do you create a java loop that creates a Triangle with squared numbers?

I have searched far and wide for information on this subject to no avail. I am really struggling with Java Loops.
I get the big picture ideas of For/While loops, but when it comes time to actually start programming, I get error after error...
I have tried writing out my program and understanding the logic of it, but I cannot seem to get the program to do what I want it to do.
The task at hand:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console
1
4 1
9 4 1
16 9 4 1
For full credit, each column should be 3 characters wide and the values should be right justified.
So far, I have come close (not including the user input for now, just trying to at least get a grasp on the looping aspect and then I will work on that):
public class MyClass {
public static void main(String args[]) {
int rows = 4; // this is the value that the user will enter for # of rows
for (int i = 1; i <= rows; i++) {
for (int j = i; j >= 1; j--) {
System.out.print((j*j)+" ");
}
System.out.println();
}
}
}
PRINTS:
1
4 1
9 4 1
16 9 4 1
You have two problems.
First, you need the numbers printed with padding on the left to produce the number in the space of 3 characters. Look at System.out.printf("%3d", ...)
Second, you need to print out additional blank columns. 3 blank columns on the first row, two blank columns on the second row, 1 blank column on the third row, and zero blank columns on the last row. Sounds like another inner loop.
int rows = 4; // this is the value that the user will enter for # of rows
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ? " " : String.format("%3d", j * j));
System.out.println();
}
You actually need to print a square table, not a triangle. It's just that some of the cells in the table will be filled with spaces.
This means that your algorithm should be something like this:
for row from 1 to n
for col from n to 1 /* Note: It's not from row to 1 */
if col <= row print square(col)
else print pad
import java.util.Scanner;
public class TriangleOfSquares {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 9: ");
int n = input.nextInt();
for (int i = n; i > 0; i--) {
for (int j = n; j > 0; j--)
System.out.print((n - j + 1) < i ? " " : String.format("%3d", j * j));
System.out.println();
}
}
}

Printing Simple Patterns in Java

Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

How do I print out an hourglass using asterisks?

For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.

Categories