For loop within a for loop - java

So I'm working on for loops and nested for loops. So I need to stick to these as my main functions.
I've gotten stuck on one question. I can think of the logic of how I'd solve it...but I can't figure how I'd do it with for loops/nested for loops.
I've got to print Ascii codes in rows of 10
Example:
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
(from 32-122)
Here's my code so far:
public class chars{
public static void main(String[]args){
for( int j = 32; j < 122; j++){
System.out.print((char)j);
//Once above loop is performed 10*...execute a new line..using a for loop..??
System.out.println();
}
}
}

You're outer loop should control what row you're on, and the inner loop what column. Thus, just the outer loop looks like this (there are 9 rows):
for (int i = 1; i <= 9; i++)
{
System.out.println("");
}
This will print 9 newlines, giving you the 9 rows.
Now, your column logic goes inside, but before the println.
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
char print = (char)((i * 10) + 32 + j);
System.out.print(print);
}
System.out.println("");
}
This utilizes a small math trick to generate the numbers of the sequence. Row 1 = 32 to 41, 2 = 42 to 51, etc.
Note also that this is slightly more verbose than other possible answers because I used nested loops like you asked.

A straight forward approach could be to use an if statement as QuakeCore suggested. the code would come to look something like the following:
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char)j);
if (j % 10 == 1) {
System.out.println();
}
}
}
This leaves for some ugly code when working with the Modulus function in the if condition. The reason for it is that we are starting with the number 32 and incrementing from their, thus we get j % 10 == 1 instead of something nicer such as j % 10 == 0.
But, your question states you wish to solve it with For loop inside a for loop, making me think it's a school task. This can be solved by looking at for loops as functions to be performed within the 2D space. Such that the first for loop is handling the rows, while the inner for loop is handling columns (or y and x space respectively). From this we can solve the problem as follows:
public static void main(String[] args) {
// Increment row/counter by 10
for (int row = 32; row < 122; row += 10) {
for (int col = 0; col < 10; col++) {
System.out.print((char)(row + col));
}
System.out.println();
}
}

The syntax for a for loop is:
for ( initialization ; termination condition ; increment ) body
However, each of those items in italics above is optional. The initialization and increment parts can have multiple components, separated by a comma.
Since you know the total number of characters is a multiple of 10, here's what I would do:
public static void main(String[]args){
for( int j = 32; j < 122; /* don't increment j here */){
// print 10 chars per line
for (int col=0; col<10; col++, j++ /* increment j here instead */) {
System.out.print((char)j);
}
System.out.println();
}
}
Note that if the total number of characters wasn't a multiple of 10, then the inner loop might print some extras, since the outer loop's condition is only checked once every 10 characters.

This will print each char 10 times in a row ( with nested for loops ):
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
// print 10 times the same char in the same line
for (int i=0;i<=10;i++){
System.out.print((char) j);
}
// after 10 char : goto next line
System.out.println();
}
}

do it with for loops/nested for loops
Try this-
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char) j);
if((j-32)%10==0){
System.out.println();
}
}
}
Here the inner condition will take care of changing line when you have printed 10 values

If you must use nested loops, then maybe something like this would work:
int lineLength = 10;
int lineCount = (122 - 32) / lineLength;
for (int line = 0; line < lineCount; line++) {
for (int column = 0; column < lineLength; column++) {
int index = (line * lineLength) + column;
System.out.print((char)(32 + index) + " ");
}
System.out.println();
}

Related

Is there any way to make this more efficient/reduce the amount of loops?

Given an int n, print a staircase using #. This is from hacker rank, staircase problem. example:
n = 4.
output:
#
##
###
####
whereas each row has the same amount of columns but the # signs increase and the space decrease as we keep going through the rows.
I've solved the problem, just trying to see if there is a more efficient way
public static void staircase(int n) {
int spaceCounter = 0;
for(int i = 1; i <= n; i++) { // Takes care of the rows
spaceCounter = n - i;
// Takes care of the column by printing a space until a # sign is required then it would print so.
for (int j = 1; j <= spaceCounter; j++) {
System.out.print(" ");
if (j == spaceCounter) {
//Prints as many #s as needed (n minus the number of spaces needed)
for(int k = 1; k <= (n - spaceCounter); k++) {
System.out.print("#");
}
//makes sure it goes to the next life after being done with each row
System.out.println();
}
}
if (i == n) {
for(int j = 1; j <= n; j++) {
System.out.print("#");
}
}
}
}
Using Java 11, you can utilize String#repeat for an efficient solution that uses a single for-loop:
public static void staircase(int n) {
for (int i = 1; i <= n; i++) {
System.out.println(" ".repeat(n - i) + "#".repeat(i));
}
}
All we do is calculate the amount of spaces that are needed for the specific line, and then the number of # characters needed is simply n minus the amount of spaces used.
If n is a large value, you can build a String (using a StringBuilder) and then print it instead of calling System.out.println n times:
public static void staircase(int n) {
var sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(" ".repeat(n - i)).append("#".repeat(i)).append('\n');
}
System.out.print(sb);
}

how to print a triangle in java without inner stars

The following code gives me the results but I want to make it more simple so i can learn logic of different scenario
public class Pyramid {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int x = 0; x < 5 - i; x++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
But now i want to make a triangle without inner stars and i am not getting a logic i am trying and thinking for hours i don't want full coding i just want a logic explanation so i can make it by my self it feels good
You want to print the first and last star in each row, so you need to check if k is the first or last value in your loop. Here's pseudocode:
for (int k = 0; k <= i; k++) {
[if k is first or last possible value]
[print star]
[else]
[print space]
}

Java nested for loop print out

I'm a total beginner to java and need help writing this nested for loop. This is the desired output.
2 3 5
5 10 26
11 31 131
23 94 656
I understand that the increment is 2 times the first number + 1, but I don't understand how to create the loop for it.
public static void main(String[] args) {
for(int i = 2; i <= 5; i++) {
for(int j = i; j <= i; j++) {
System.out.print(j+(i*j));
}
System.out.println();
}
}
Question is so simple it consists of two things read the pattern and use the appropriate loop statements in java to achieve this. Printing them is another task which is not difficult.
#Jonathan your pattern is right but your algorithm is incorrect.
I'm not giving you perfect solution but you have to use proper loop statement to make it efficient. I'm here giving you a thought so that you can think in this way..hope you get it.
public static void main(String[] args) {
/* 2 3 5
5 10 26
11 31 131
23 94 656
*/
int two = 2;
int three = 3;
int five = 5;
int i=0;
//use do-while to print 2 3 5
do{
System.out.println(two +" "+ three +" "+five);
two=two*2+1; // apply math pattern
three= three*3+1;
five= five*5+1;
i++;
}while(i<4);;
}
Please try the following code (I have tested the code, the output is exactly the same as yours):
public static void main(String args[]) {
int[][] results = new int[4][3];
results[0][0] = 2;
results[0][1] = 3;
results[0][2] = 5;
for (int i = 1; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
results[i][j] = results[i - 1][j] * results[0][j] + 1;
}
}
for (int i = 0; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
System.out.print(results[i][j] + "\t");
}
System.out.println();
}
}

2D array trouble finding char element(s)

I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.

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++;
}
}

Categories