Java For Loop triangle pattern - java

Hey I' m trying to create a pattern that's suppose to output multiples of 5 in a pattern like this:
5 10 15 20 25
30 40 45 50
55 60 65
70 75
80
but my output is like this
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75
but when i put asterisks in the print :
*****
****
***
**
*
here's my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n = 5;
int x =5;
for(int i = n; i>=1; i--){
for(int j = n-1; j>=i; j--){
System.out.print(" ");
}
for(int k = 1; k<=i; k++){
System.out.print(x+" ");
x+=5;
}
System.out.println();
}
}
}
can somebody help me? i spent almost 3 hours trying to figure this out. any help would be appreciated. thanks!

The cleanest way to achieve what you want is to do is by using printf as shown below:
public class Main {
public static void main(String[] args) {
int n = 5;
int x = 5;
for (int i = n; i >= 1; i--) {
for(int j=1;j<n-i+1;j++)
System.out.printf("%3s"," ");
for (int k = 1; k <= i; k++) {
System.out.printf("%3d",x);
x += 5;
}
System.out.println();
}
}
}
Output:
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75
Update:
If you are not comfortable with printf, you can use the following solution:
public class Main {
public static void main(String[] args) {
int n = 5;
int x = 5;
String space=" ";
for (int i = n; i >= 1; i--) {
for(int j=1;j<(n-i)*3;j++)
System.out.print(space);
for (int k = 1; k <= i; k++) {
System.out.print(x+space);
x += 5;
}
System.out.println();
}
}
}
Output:
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75

You write three characters at a time (space, first digit, second digit), so you need to print three spaces to have the correct results.
Basically your same code, but with three spaces int the System.out.print:
for(int i = n; i>=1; i--){
//This is the same loop, but written in a different way.
for(int j = 0; i < n-i; j++){
System.out.print(" "); //THREE SPACES HERE
}
for(int k = 1; k<=i; k++){
System.out.print(x+" ");
x+=5;
}
System.out.println();
}
Now, you are also printing the 5 at the start, which is one digit long, so you need another space before. So you need a conditional structure in order to do this:
//This is the same loop, but written in a different way.
for(int j = 0; i < n-i; j++){
if(j == 0 && x <= 5) //First cycle (remember 5, which is 1 digit)
System.out.print(" "); //TWO SPACES HERE
else
System.out.print(" "); //THREE SPACES HERE
}
Note that this only works with 2 digits numbers so you need to do a similar thing like the one we used with the number five if you're gonna use also 3 or more digits numbers.

I think this exercise is also a good moment to practice with System.out.printf()
Here is how i would do this:
public static void main(String[] args) {
int x = 5;
int n = 35;
int max = calculateTotalNumbers(n) * x; // calculate the highest number
int maxLenght = String.valueOf(max).length(); //calculate the numbers of digits in the highest number
for(int i = n; i>=1; i--){
for (int j = 0; j < n - i; j++) {
//makes sure you will have the same length spaces everywhere
System.out.printf("%1$"+maxLenght+"s ", "");
}
for (int k = 1; k <= i; k++) {
//this formatting will ensure every digit has the same length with padding included. Check out the javadoc of System.out.printf();
System.out.printf("%" + maxLenght + "d ", x);
x += 5;
}
System.out.println();
}
}
// this method will calculate the total number of numbers you will print in the triangle
private static int calculateTotalNumbers(int n) {
if (n <= 0) return 0;
else return (n + calculateTotalNumbers(n -1));
}

public class temp {
public static void main(String[] args) {
int n = 5;
int p = 1;
for (int i = 0; i < n ; i ++){
String curr = "";
for (int j = 0 ; j < n - (n - i); j ++){
curr += " ";
if (j > 0) {
curr += " ";
}
}
for (int j = i; j < n; j ++){
curr += Integer.toString(n * p);
curr += " ";
p += 1;
}
System.out.println(curr);
}
}
}

Related

Why is the result only 81 when I try to use array

Thanks for reading my question:
public class Gugudan_array {
public static void main(String[] args) {
for(int i = 2; i<10; i++) {
for(int j = 1; j<10; j++) {
System.out.println(i * j);
}
System.out.println();
}
}
}
In the multiplication table above, result comes correctly from 2-9, however:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
In this code with array, the result comes out only 81.
What have I done wrong?
Thank you!
I'll first explain why your code doesn't work, and then go over a correct solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
The main problem lies in this chunk of code:
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
Here, you are constantly overwriting the value of result[h], so that once the loop ends and both i = 9, and j = 9, the code will execute result[h] = 9 * 9 and then continue on to the next h.
My solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
Output:
18
27
36
45
54
63
72
81
0
0
First, notice how I completely got rid of the h loop. That is because we can make the index in terms of i. When we determine the first number, when i = 2, we want to store that number in the 0th index of our array. Similarly, when we get our second number, when i = 3, we want to store the result in the 1st index of our array.
To summarize, whenever we calculate a result, we will want to store it in the i - 2th index of our array.
Better Solution using 2D arrays:
int[][] result = new int[8][9];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2][j - 1] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
for(int b = 0; b < result[a].length; b++){
System.out.print(result[a][b] + " ");
}
System.out.println();
}
Output:
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Note: If you want the output to match your original code, change System.out.print(result[a][b] + " "); to System.out.println(result[a][b])
It would make the most sense to store a multiplication table in a 2D array.
This code works by mapping i * j to the [i - 2][j - 1]'th element of the 2D array, so that 2 * 1, will end up in result[0][0]
I hope this made sense! Please let me know if you need any further help or clarification!
You have to increase h variable after all iteration. Here is whole code:
public static void main(String[] args) {
int[] result = new int[10];
for (int h = 0; h < result.length; h++) {
for (int i = 2; i < 10; i++) {
for (int j = 1; j < 10; j++) {
result[h] = (i * j);
if (h < 9) {
h++;
}
}
}
}
for (int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
The issue is that your current setup with 3 nested loops, the outer loop runs 10 times, the middle loop runs 8 times for each other loop, and the inner loop runs 9 times for each middle loop, which gives a total of 10x8x9=720 times... but I suspect you just want 72 results like you show in your first example, so we need to remove the outer loop first for(int h = 0; h < result.length; h++) {.
Now the issue is that we need to store all 72 results but your current array only fits 10 results int[] result = new int[10];, we can solve this with a bigger array:
int[] result = new int[8 * 9]; //72 spaces
Here is a working solution with a long array and a counter that keeps track of where to store the value, note the code comments for extra details:
//Your loops calculate 8 * 9 results, so you need an array with 72 spaces
int[] result = new int[72];
//Use a variable to track the array location
int counter = 0;
//Youn only need two loops
for(int i = 2; i < 10; i++) {
for(int j = 1; j< 10; j++) {
//Save the result in the correct location
result[counter] = (i * j);
//Incriment the counter
counter++;
}
}
//Print the stored results
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
Some further important reading from the official Java guide on Arrays:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
A better solution would be to use a 2D array.

Java Number Pyramid

I want to create a number pyramid like this,
7
5 6 5
3 4 5 4 3
1 2 3 4 3 2 1
but I couldn't create it. I pasted my code and its output is like this,
7
5 6 7 6 5
3 4 5 6 7 6 5 4 3
1 2 3 4 5 6 7 6 5 4 3 2 1
What should I do to fix this ? Is my code totally wrong or litte changes are enough ?
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner myScan = new Scanner(System.in);
System.out.print("Enter mountain width: ");
int width = myScan.nextInt();
System.out.println("Here is your mountain ");
myScan.close();
System.out.println();
for (int i = width; i >= 1; i=i-2)
{
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
for (int j = i; j <= width; j++)
{
System.out.print(j+" ");
}
for (int j = width-1; j >= i; j--)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
You may compute the row index, then it's easy to get the number ranges
for (int i = width; i >= 1; i -= 2) {
int row_idx = (width - i) / 2;
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
for (int j = i; j <= i + row_idx; j++) {
System.out.print(j + " ");
}
for (int j = i - 1 + row_idx; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
You just need to count the level. You can do this by adding additional count variable. Lets take an example:
On level 0 you just print 7 and count is 0.
On level 1 count is 1. So you need to only print from i's current value + count amount on left and right. But since we counted 1 extra on left so a value will be less on right.
.........
And code will go on like this.
See code for better explanation:
public static void main( String[] args ) {
Scanner myScan = new Scanner(System.in);
System.out.print("Enter mountain width: ");
int width = myScan.nextInt();
System.out.println("Here is your mountain ");
myScan.close();
System.out.println();
int counter = 0;
for (int i = width; i >= 1; i = i - 2) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
for (int j = i; j <= width - counter; j++) {
System.out.print(j + " ");
}
for (int j = width - 1 - counter; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
counter++;
}
}
I just changed a little bit on your code to make it work. Cheers mate !

How can I print a simple multiline numeric pattern opposite of how it is emitted now?

This is the output of the following code:
1
23
345
4567
But I want the output to be in the opposite direction like this.
Not sure how to achieve that.
1
23
345
4567
Code:
import java.util.Scanner;
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while (i <= n) {
int space = n - i + 1;
while (space <= n) {
System.out.print(" ");
space++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}
}
For each line, there are two spaces times the length of the longest line minus the current line number. Then, you count from the current line number one plus the current line number values. Like,
int len = (n / 2) + 1;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 2 * (len - i - 1); j++) {
System.out.print(' ');
}
for (int j = 0; j <= i; j++) {
System.out.print(j + i + 1);
}
System.out.println();
}
Outputs (as requested)
1
23
345
4567
Here it is:
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
int k = 0;
while (i <= n) {
int space = 2*n - i - k ;
k++;
int l=0;
while (l <= space) {
System.out.print(" ");
l++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}

For Loop printing squares without multiplication

I am trying to produce this output without multiplication:
81 100 121 144 169 196 225 256 289
I produced that with this for loop:
for (int k = 9; k <=17; k++){
System.out.print( k * k +" ");
}
But again, I am trying to create a for loop or nested for loops producing the same output without multiplication.
Pseudocode:
Start with value 81
Increment by 19
On the second loop add ++3 to the 19 value
I have not been able to get to the second for loop stage I am confused. Any feedback or push in the right direction is appreciated.
/**
* Created on 8/28/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 2 Self-Check Problems & Exercises
*/
public class Ch2_SelfCheckProblems {
public static void main(String[] args) {
ex2();
}
public static void ex2(){
for (int i = 81; i <= 289; i=i+19){
/*for (int j = 1; j >=( i - 81 );j++){
// System.out.print(j+" ");
// System.out.print(i + " ");
}*/
// System.out.print(i + " ");
}
// System.out.println();
/* for (int k = 9; k <=17; k++){
System.out.print( k * k +" ");
}*/
for (int k = 81; k <=289; k++){
for (int j = 1; j <= 1; j++){
k = k + 8;
}
System.out.print( k +" ");
}
}
If I understand your question, you could use addition instead of multiplication. Something like
public static void main(String[] args) {
for (int k = 9; k <= 17; k++) {
int t = 0;
for (int j = 0; j < k; j++) {
t += k;
}
System.out.print(t + " ");
}
System.out.println();
}
Output is (the requested)
81 100 121 144 169 196 225 256 289
Another option would be Math.pow(double, double)
public static void main(String[] args) {
for (int k = 9; k <= 17; k++) {
System.out.print((int) Math.pow(k, 2) + " ");
}
System.out.println();
}
for the same output. Finally, from #mschauer's comments below, you could also use something like
public static void main(String[] args) {
for (int r = 64, k = 9; k < 18; k++) {
r += k + k - 1;
System.out.printf("%d ", r);
}
System.out.println();
}

Output of 50 - broken up to 10 numbers per line

I am struggling trying to find a way to output this array/loop so that only 10 outputs appear on a line.
public static void main(String[] args) {
double [] alpha = new double[50];
int num=1;
for (int i=0; i < alpha.length; i++) {
alpha[i] = num; //populate index 0-50 w/ 1-50
num++;
if (alpha[i] < 26) // first 25, print ^2
System.out.print(Math.pow(alpha[i],2)+ " ");
else // last 25, print value(3)
System.out.print(alpha[i]*3 + " ");
}
System.exit(0);
}
Add a conditional that prints a break line if i + 1 is multiple of 10.
for (int i=0; i < alpha.length; i++) {
//your code here...
if ( (i + 1) % 10 == 0) {
System.out.println();
}
}
Another way of doing it could be to iterate over the lines u want to print:
// Get the total number of lines you want
int lines = len(alpha) % 10;
for (int i=0; i < lines; i ++) {
for (int j = i * lines; j < i * lines + 10; j++) {
// Print the modified alpha[j]
System.out.print(alpha[j]);
}
System.out.println();
}

Categories