How can I print this using for loops? - java

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();
}

Related

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

can't find how to program this number pattern

Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
And this one for rc = 3:
1 2 3
6 4 5
8 9 7

Different variations for using loops to a pattern in 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("");
}

Asterisk in Nested loops, Java

I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}

I'm having trouble making a diamond shape with loops

You have an input of n and that represents half the rows that the diamond will have. I was able to make the first half of the diamond but I'm EXTREMELY frustrated with the second half. I just can't seem to get it. I'm not here to ask for specific code I need, but can you point me in the right direction and give me some tips/tricks on how to write this? Also, if I'm going about this program the wrong way, feel free to tell me and tell me on how I should approach the program.
The diamonds at the bottom represent an input of 5. n-1 represents the spaces to the left of each asterisk. Thank you for your help!
public static void printDiamond(int n)
{
for(int i=0;i<n;i++)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
** What I need ** What I have currently
*--* *--*
*----* *----*
*------* *------*
*--------* *--------*
*--------*
*------*
*----*
*--*
**
public static void main(String[] args) {
int n = 10;
for (int i = 1 ; i < n ; i += 2) {
for (int j = 0 ; j < n - 1 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
for (int i = 7 ; i > 0 ; i -= 2) {
for (int j = 0 ; j < 9 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
}
output
*
***
*****
*******
*********
*******
*****
***
*
Just reverse your loop :
for(int i=n-1;i>=0;i--)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
Since you have half the diamond already formed, simply run the loop again, in reverse, eg:
public static void printDiamond(int n)
{
for (int i = 0; i < n; i++)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
for (int i = n-1; i >= 0; i--)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
Whenever I see a symmetry of a kind, recursions ring to my head. I'm posting only for you and others interesting into learning more. When beginning, recursions can harder to grasp but since you already have loop based solutions, contrasting against recursion will clearly outline advantages and disadvantages. My advice, don't miss out on the chance to get into it :)
A recursive solution:
static int iteration = 0;
public static void printDiamond(int n) {
int numberOfBlanks = n - iteration;
int numberOfDashes = iteration * 2;
String blank = new String(new char[numberOfBlanks]).replace("\0", " ");
String dash = new String(new char[numberOfDashes]).replace("\0", "-");
String star = "*";
String row = blank + star + dash + star + blank;
// printing the rows forward
System.out.println(row);
iteration++;
if (iteration < n) {
printDiamond(n);
}
// printing the rows backward
System.out.println(row);
}
first, don't get confused with the strange new String(new char[numberOfBlanks]).replace("\0", " "); its a neat trick in java to construct a string with repeated chars, eg new String(new char[5]).replace("\0", "+"); would create the following String +++++
The recursion bit explained. The second println won't run until the recursion is stopped. The stop criteria is defined by iteration < n. Up until that point the rows up until that point will be printed. So something like this:
iteration 1. row = **
iteration 2. row = *--*
iteration 3. row = *----*
iteration 4. row = *------*
iteration 5. row = *--------*
than the recursion stops, and the rest of the code is executed but in reversed order. So only the second println is printed, and the value of row variable is like as follows
continuing after 5 iteration row = *--------*
continuing after 4 iteration row = *------*
continuing after 3 iteration row = *----*
continuing after 2 iteration row = *--*
continuing after 1 iteration row = **
I didn't go into mechanics behind it, plenty of resource, this is just to get you intrigued. Hope it helps, best

Categories

Resources