Different variations for using loops to a pattern in java - java

I have been trying different variations of for loops and have no clue how to make these patterns:
Pattern
1
121
12321
1234321
My code is the following but doesn't work like the example above.
for (int i = 1 ; i <= rows ; i++) {
for (int j = (rows + 1 - i) ; j > 0 ; j-- ) {
System.out.print(j);
}
System.out.print("\n");
}

Your code prints only the suffix of each line, you are missing to write 12....i for each line.
In addition, the loop should start from i, not from rows-i+1.
for (int i = 1 ; i <= rows ; i++) {
//add an inner loop that prints the numbers 12..i
for (int j = 1 ; j < i ; j++ ) {
System.out.print(j);
}
//change where j starts from
for (int j = i ; j > 0 ; j-- ) {
System.out.print(j);
}
System.out.println(""); //to avoid inconsistency between different OS
}

First note that 11*11 = 121, 111*111=12321, etcetera.
Then that 10n - 1 is a number that consists of n 9's, so (10n - 1)/9 consists of n 1's.
So we get:
int powerOfTen = 1;
for (int len = 0; len < 5; len++)
{
powerOfTen = powerOfTen*10;
int ones = (powerOfTen-1)/9;
System.out.println(ones*ones);
}

Code explains everything!
public static void main(String[] args) {
String front = "";
String back = "";
int rows = 5;
for (int i = 1; i <= rows; i++) {
System.out.println(front+i+back);
front += i;
back = i + back;
}
}

Try this one: it may seems too much looping, but yet easy to understand and effective.
public static void main(String[] args) {
int rows=5;
int i,j;
for(i=1;i<=rows;i++)
{
/*print left side numbers form 1 to ...*/
for(j=1;j<i;j++)
{
System.out.printf("%d", j);
}
/*Print the middle number*/
System.out.printf("%d", i);
/*print right numbers form ... to 1*/
for(j=i-1;j>0;j--)
{
System.out.printf("%d", j);
}
System.out.println("");
}
}

int n=0;
for(int m =0; m<=5; m++){
for(n= 1;n<=m;n++){
System.out.print(n);
}
for(int u=n;u>=1;u--){
System.out.print(u);
}
System.out.print("");
}

Related

How can I print this using for loops?

How can I print this using for loops?
1
22
333
4444
55555
I have tried this. But it is not printing what I want to print.
public class void main(String[] args) {
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j++) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(k);
}
System.out.println();
}
}
It just prints this.
1
21
321
4321
54321
As you can see the first time you print, it is correct, then is when k is equal to i, so just print i
System.out.print(i);
edit
As per your edited code, do my above change, plsu
for (int j = last; j > i; j--) {
output
1
22
333
4444
55555
final
int last = 5;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Your new problem solution just change k into i System.out.print(i)
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Output:
1
22
333
4444
55555
To get working code, it's helpful to first describe the detailed solution in words. That might be:
To print a triangle of height height, individually print each row from 1 to n.
To print a single row row, determine:
How many spaces it needs.
How many digits it needs.
Which digit to print.
The digit to print is the same as the row number row.
The number of digits digits is also the same as the row number row.
The number of spaces spaces depends on how long the line should be in total.
The number of spaces is width - digits.
To print a character repeatedly, use a for loop counting from 0 up to but excluding the repetition.
This description then translates into this code:
public static void main(String[] args) {
int height = 5;
int width = height; // can also be larger than height
for (int row = 1; row <= height; row++) {
int digit = row;
int digits = row;
int spaces = width - digits;
for (int i = 0; i < spaces; i++) {
System.out.print(' ');
}
for (int i = 0; i < digits; i++) {
System.out.print(digit); // assuming that digit needs only a single character to print
}
System.out.println();
}
}
Sure, this program is longer than the other ones, but when stepping through it using a debugger, you have all the information about the current state captured in the variables. By looking at the variable values, you can always ask yourself: does it make sense, and do spaces and digits and width fit together?
This program also splits up the total work into two phases. In the first phase, determine what to print and how much, and then just print it.
In every loop the number of blanks before a given number i are maxNumber - i and the times the current number is displayed are i:
for (int i = 1; i <= 5; i++)
{
String blanks = "";
for (int j = 1; j <= 5-i; j++)
{
blanks += " ";
}
String number = "";
for(int k = 1; k <= i; k++)
{
number += i;
}
System.out.print(blanks + number);
System.out.println();
}

Can't print the pattern

I created the code that should print a pattern like
12345
2345
345
45
5
I have the code written below, the logic works fine in python but in java the output is different.
class Testing{
public static void main(String args[])
{
for (int i = 1; i<6;i++)
{
for (int j =0; j<i-1;j++)
{
System.out.print(" ");
}
while (i < 6){
System.out.print(k);
System.out.println();
i++;
}
}
}
}
The output is just 12345. I don't understand why does it iterate over first for loop for only once.
Use another variable for while control.
public class Testing {
public static void main(String args[]) {
int k;
for (int i = 1; i < 6; i++) {
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
k = i;
while (k < 6) {
System.out.print(k);
k++;
}
System.out.println();
}
}
}
You can see this in this link
this will show you :
12345
2345
345
45
5
Note: When 'while loop' increases. That increases i value bigger than 6. So next time it terminates the outer loop. That was your mistake.
package com.appointment.api;
class Testing {
public static void main(String args[]) {
for (int i = 1; i < 6; i++) {
System.out.println();
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
int x = i;
while (x < 5) {
System.out.print(i);
x++;
}
}
}
}
Following is a java-8 implementation of the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.rangeClosed(1, MAX)
.mapToObj(j -> j == MAX ? j + "\n" : j >= i ? j : " ")
.forEach(System.out::print)
);
Set MAX = 5 and it will print your pattern.
Output:
12345
2345
345
45
5

Nested For loops to print numbers 11223344556677889900

I am trying to print the sequence of numbers 11223344556677889900 using nested for loops. I am unsure of the algorithm to print the sequence since it ends in 00. I have the following method code but I print the 00 as literals and am sure that there must be a better way. Any help is much appreciated.
public static void drawNumbers(){
for (int line = 1; line <= 2; line++) {
for (int i =1; i <= 9; i++) {
for (int j =1; j<=2; j++) {
System.out.print(i);
}
}
System.out.print("00");
}
}
Run your loop up to 10 and instead of:
System.out.print(i);
do:
System.out.print(i % 10);
public static void drawNumbers(){
for (int line = 1; line <= 2; line++){
for (int i =1; i <= 10; i++){
for (int j =1; j<=2; j++){
System.out.print(i%10);
}
}
}
}
You can run the "i" loop until 10 and print i%10. This would print 0 when the value reaches 10.
One other way would be to insert an if statement inside the for where you would check if the value of i was equal to "10", and if it were, it would print the value "00"
Just only print the last digit of i
for (int i = 1; i <= 10; i++) {
String s = String.valueOf(i);
int lastDigit = s.length() - 1; // last digit position in string
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
}
Output:
11223344556677889900
Changed the logic a little to fit your requirement
public static void drawNumbers() {
for (int line = 1; line <= 1; line++) {
for (int i =1; i <= 10; i++) {
for (int j =1; j<=2; j++) {
if(i==10) {
System.out.print(0);
} else {
System.out.print(i);
}
}
}
}
}
To use only one loop run it like
public static void drawNumbers() {
for(int i = 1 ;i <= 10; i++) {
if(i ==10) {
System.out.print(0 + "" + 0);
} else {
System.out.print(i + "" + i);
}
}
}

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
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();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Simple Java Loop Question

Assume that the int variables i and j have been declared, and that n has been declared and initialized.
Using for loops (you may need more than one), write code that will cause a triangle of asterisks of size n to be output to the screen.
For example, if the value of n is 4, the output should be
*
**
***
****
I won't do your homework, so here is a hint:
The first line is always 1 element long.
The last line is always N elements long.
The are a total of N lines.
Surely, with the above, you can create the necessary program.
Just for fun - single for-loop solution:
public void doIt(int n) {
String temp = String.copyValueOf(char[n]);
for (int i = 1; i <= n; i++)
System.out.println(temp.substring(n-i).replace((char) 0, 'x'));
}
And some recursion - zero for-loop solution:
public void doItAgain(int n, String display) {
if (n==0) return;
System.out.println(display);
doItAgain(n-1, display+'x');
}
(call it with doItAgain(4,"x") for your example)
My answer:
public class loop1
{
public static void main(String[] args)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
}
}
In case you're in school/college and more interested in getting some, more power to you buddy:
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
public class ForLoop {
public static void main(String[] args) {
for(int i = 0;i <= 9;i++){
for(int j = 1;j <= i;j++){
System.out.print("*");
}
System.out.println("\n");
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
simple, easist way to do it using main method --> public static void main (Strings [] args){
for(int i = 1; i <= max; i++){
for(int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println(" ");
}
}

Categories

Resources