How to reverse a loop - java

So basically my assignment was to print a list of stars.
public class Practice_6_2
{
public static void main (String[] args)
{
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++)
{
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
But when it prints, it is actually the opposite. How would I fix this?
Edit:
When I run the program, it will print one star on the first line, two stars on the second, and so forth until it reaches the tenth line. I need it to print ten stars on the first line, nine on the second, and so forth. Kind of reversing it.

You could reverse the direction you iterate on row. Change
for (int row = 1; row <= MAX_ROWS; row++)
to something like
for (int row = MAX_ROWS; row >= 1; row--)
to start at MAX_ROWS and descend to 1.

Related

'square' whose outline is all *'s and whose interior is filled with the character "."

I need to draw a square whose outline is all *'s and the interior is filled with the character . (dot).
There is also input which will determine the size of the square.
This is what I have so far.
I think I need a "if" statement but don't know how to implement this.
So far this bit of code will draw a square of * by BIO user input.
Thanks in advance :).
public class Main
{
public static void main( String args[] )
{
int stars = BIO.getInt();
int a = 1;
while (a <= stars)
{
int starsNumber = 1;
while (starsNumber <= stars)
{
starsNumber = starsNumber + 1;
System.out.print('*');
}
System.out.println();
a = a +1;
}
}
}
I will break this problem down into steps. Try figuring out the code yourself.
You have to print the following things:
The top of the square. this will be a series of * with a length of stars e.g. *****
stars lots of middle bits. This will be a * at the start, then a series of . with a length of stars - 2, then a * at the end e.g. *...*
The bottom of the square. Exactly the same as the top.
for(int i = 0 ; i < stars ; i++) {
System.out.print("*"); // top
}
System.out.println(); // new line
for (int j = 0 ; j < stars - 2 ; j++) {
System.out.print("*"); // starting * of the middle
for (int i = 0; i < stars - 2; i++) {
System.out.print("."); // the dots for the middle
}
System.out.print("*"); // the star at the end of the middle lines
System.out.println(); // new line for the next middle line
}
for(int i = 0 ; i < stars ; i++) {
System.out.print("*"); // bottom
}
I used a two-dimensional array to store char values of the * and . of the square with a nested loop to generate the array and to print it out. When generating it, use an if-else statement to determine if you are generating the border of the square or not, choosing whether to put a * or . into this index of the array.
Scanner scanner = new Scanner(System.in);
System.out.print("Square size: ");
int size = scanner.nextInt();
char[][] square = new char[size][size]; //two-dimen array helps visualize square shape you want
for (int row=0; row<size; row++) {
for (int col=0; col<size; col++) {
if (row==0 || row == size-1 || col==0 || col==size-1) { //if border of square
square[row][col] = '*';
}
else { //if inside square
square[row][col] = '.';
}
}
}
for (char[] row : square) {
System.out.print("\n");
for (char col : row) {
System.out.print(col);
}
}
Using your basic loop structure:
for (int row = 0; row < stars; row++) {
for (int col = 0; col < stars; col++) {
char c;
if (CONDITION)
c = '*';
else
c = '.';
System.out.print(c);
}
System.out.println();
}
You should figure out CONDITION yourself. Think about what x and y need to be in the cases where you want to print a * instead of a ..

Java pyramid of numbers - version 2

I'm reading a book and before I go to next chapter, I want to solve every exercise from current one. I have a problem with creating this output (the number of rows must be between 11 and 20)
I almost have it, even when I think my code is pretty bad and I could get it in less lines.
public class piramide {
public static void main(String args[]){
int max, n;
max = 20;
n=1;
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
System.out.print(x);
x--;
if (x<0) x=9;
}
System.out.print("A"+n+"A");
for (int j=1; j<min; j++){
System.out.print(x2);
x2--;
if (x2<0) x2=9;
}
System.out.println();
n+=2;
}
}
}
This is my current code and this is the output:
0987654321A1A0987654321
21098765432A3A21098765432
432109876543A5A432109876543
6543210987654A7A6543210987654
87654321098765A9A87654321098765
098765432109876A1A098765432109876
2109876543210987A3A2109876543210987
43210987654321098A5A43210987654321098
654321098765432109A7A654321098765432109
8765432109876543210A9A8765432109876543210
The problem I'm having is that the left part of the pyramid should be reversed. For example in the first row it should start at 0 (from the A1A) and finish in 1 but it starts in 1 and finish in 0, any idea how can I turn it to the other side?
Thanks to all of you who helped me ^^.
Oh, and the caps A are just so I could find the number easier in the output.
Have you worked the problem out?
The code will be much easier to understand with a couple changes...
max, min, and especially the single letter variables like n should have names that help describe what they are. This may also help you think about the problem when you don't have to keep in mind what all those random letters mean.
n I will rename to rowIndex
max I will rename to totalRows
min I will rename to columnIndex
Starting with that we have
public static void main(String args[])
{
int totalRows = 20;
int rowIndex = 1;
int columnIndex = 1;
//we look ready to start at row 1, column 1!
}
Now, this section of your code:
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
You are setting min, or, the columnIndex, to start at 11, because that is the "middle" of the pyramid. Then you print out spaces to catch up to the columnIndex.
x = rowIndex - 1;
x2 = rowIndex - 1;
b = columnIndex - 1;
j and b are now like a second and third column index, which is catching up to the actual columnIndex
Look at this example of how your for loop works:
for (int j=1; j <min; j++) { // j = 1;
while (b<max-1) { // 10 < 19
System.out.print(" "); // print space
b++; // b = 11
// 11 < 19
// print space
// b = ...(*skip to the end*) 19
// j = 2
// b is still 19, doesn't print anything
// j = 3, etc.
}
System.out.print(x);
x--;
if (x<0) x=9;
}
In other words, j and b are unnecessary because we already have a columnIndex we can use. Let's do some more renaming of variables.
x I will rename to printValue
x2 will be unnecessary, we only need one printValue, However, I will be adding a totalColumns to the beginning of our main method.
So now our finished code will look like:
public static void main(String args[])
{
int totalRows = 20;
int totalColumns = (totalRows * 2) - 1; //added totalColumns, notice the number of columns increases by two with each row and we start with 1 column.
int rowIndex = 0;//easier for looping to start with zero
int columnIndex = 0;
int printValue = 0;
while (rowIndex < totalRows) // we will want to spin through every row
{
//notice there is no limit to the length of a variable name!
int numberOfValuesInRow = (rowIndex*2) + 1;
int numberOfSpacesToOffsetOnEachSide = (totalColumns - numberOfValuesInRow) / 2;
//Print Spaces before the numbers in this row
for (int i = 0; i < numberOfSpacesToOffsetOnEachSide; i++) //i is commonly used to stand for index in a single for loop
{
System.out.print(" ");
columnIndex++; //keep track of columnIndex so we know when we are at the middle of the columns
}
//Print numbers in this row
for (int i = 0; i < numberOfValuesInRow; i++)
{
if (columnIndex < (totalColumns/2) + 1) { //depending on columnIndex position, increase or decrease printValue
printValue++;
} else {
printValue--;
}
System.out.print(printValue%10); //Print printValue, the % will return the remainder of (printValue/10)
columnIndex++;
}
System.out.println(); //start next line
columnIndex = 0; //reset columnIndex for the next row
rowIndex++;
}
}

Using nested FOR loop for printing square by numbers

I'm trying to print square by using nested for loop. It is needed square to look like sequence numbers. Actually I didn't receive square. Please see attached file to understand my goal- red border.
public class Day22022014 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
for(int row=1; row<=n; row++){
System.out.printf("%d %n", row);
for(int col=row; col<2*n; col++){
System.out.printf("%d ", col);
}
}}}
You have a few errors there. The first printf is incorrectly outputting a number, you only need to make a new line, all numbers should be outputted inside the inner for.
Secondly, the condition col < 2 * n is wrong, you only want to go up to row + n - 1.
I suggest you go through this and try to understand, how do the indices row and col change in each iteration.
for(int row = 1; row <= n; row++){
for(int col = row; col <= (row + n - 1); col++){
System.out.printf("%d ", col);
}
System.out.println();
}

How would you go through each row and each column seperatly in two dimensional array

I am just curious as to how that is done. I am writing a small program to get a better understanding of two dimensional arrays. I want to know how I can go though each row and then each column separately using for loops.
Lets say I have a 2D array that is made out of different letters. I want to go through each row and each column and check if a certain letter is there. Then I want it to print how many occurrences of this letter happened in each row and then each column.
First index is row and second index is column.
Assuming that the something[][] is an something[] of something-rows (that is something[i] gives us a row, not a column - if it'S the way round, just change the examples):
public static void loopExample (String[][] someTwoDimArray) {
// Looping rows
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
System.out.println(someTwoDimArray[row][col]);
}
}
// looping columns
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
System.out.println(someTwoDimArray[row][col]);
}
}
}
I don't know if the first or second index is considered rows or columns, but this is a pretty standard nested loop for iterating over every element of a 2d array.
for(int column = 0; column < array.length(); ++column) {
for(int row = 0; row < array[column].length(); ++row) {
// do stuff to array[column][row]
}
}
Given your update, let's look for the letter 'N', in a 2d char array called myLetters.
int counter = 0;
for(int i = 0; i < myLetters.length(); ++i) {
for(int j = 0; j < myLetters[i].length(); ++j) {
if('N' == myLetters[i][j]) {
++counter;
}
}
}
System.out.println("N occurs " + counter + " times.");
if you have a 2D array if you want to access each cell you will have to use a nested for loop.
eg:
for(int i = 0; i < length1; i++)
for(int j = 0; j<length2; j++){
// do something
to format column first do array[i][j] = //do something
to format row first do array[j][i] = // do something
}
"I tried using a for loop however i dont have a good understanding of for loops and i was wondering how not just go through array in its entirety but small bits like rows and columns"
A for loop is a java control flow statement. It lets you initialize a variable (i and j) it gives you a condition (i
int i = 0
while (i < length1){
//do something
i++
}
if working with arrays for loops are almost always required.

Decrements a multidimensional array in java

I'm having trouble understanding how to start the first index of array from the bottom to to the top of a multidimensional array. Here's what I've tried to initialize my array from bottom to top (in 2d array table format):
for(int row = arrayName.length - 1; row > 0; row--) {
for(int col = 0; col < arrayName.length; col++) {
arrayName[row][col] = ' ';
}
}
or
for(int row = arrayName.length - 1; row > 0; row--) {
for(int col = arrayName.length - 1; col < 0; col--) {
arrayName[row][col] = ' ';
}
}
i mean..when i run the program, the array always store my values from top to bottom, the opposite of what i wanted it to do. Please help! thanks in advance.
Matrices and Arrays don't really have any inherent sense of direction. Their direction is entirely determined by the order in which you choose to display the information. Depending on how you structure your loop, the contents of the array will be outputted differently. If you want to store elements from the "bottom" to the "top," what that actually means is that your print out loop should be structured in an opposite direction from your assignment loop. So for example (assuming an NxN array),
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
arr[i][j] = <some value here>;
}
}
Say for simplicity's sake you think of vertex (0,0) being in the top left corner, where columns increase as you move right and rows increase as you move down. Then to print from the bottom up, you would want to start from the last row and move to the first row.
for (int i = arr.length - 1; i >= 0; i--) { // Note the >= 0, which was incorrect
// in the code you posted
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
That would start from the bottom row and print out its contents from the first to last column, then move up to the second to last row, etc. all the way up to the first (top) row. So there is no inherent directionality in arrays at all, but because we are printing in the opposite order from the one used in the value assignment, the values will appear to be printed from the "bottom up." If you wanted to also invert the columns, printing the last one first, you could do this:
for (int i = arr.length - 1; i >= 0; i--) {
for (int j = arr.length - 1; j >= 0; j--) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
I hope that explanation was clear. Best of luck~!
PS. As there is no inherent directionality in arrays, you should not necessarily be storing the values in the direction you want to print them. You should store the values in the way that makes the most sense to you and in the way that makes them easy to manage. Then whenever you need to print the values, you can print them however you like.
Try this code, but I see that you are filling the array with empty spaces, how can you realize
that your code is not working good try for example filling numbers to test your code.
for(int row = arrayName.length -1; row >= 0; row--){
for(int col = arrayName.length - 1; row >= 0; col--){
arrayName[row][col] = col;
}
}

Categories