Using Loops to print patterns - java

Hey guys so I'm working on a problem where I need to print
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
public class Set_5_P5_18b {
public static void main(String[] args) {
int x;
String y;
x = 1;
y = "";
System.out.println("Pattern B:");
while (x < 7) {
y = y + x + " ";
x++;
}
System.out.println(y);
}
}
What I wrote above print's the first line but I can't figure out how to modify it to print the second, could anyone help me please?

Yuo need the outer for loop to run for say x ranging from values 6 to 1. For each value of x you need a inner loop that runs for values 1 ... x and prints out values in a line.
Keep this in mind and try to come up with pseudo code first and then the implementation code.

you'd have to reset the variables x, when you quit while :P

So commonly when you are writing a for loop and you realize that you want a certain aspect of the for loop to change each time the program iterates, 9/10 times you want to use nested for loops (for loop within a for loop).
So essentially every time that you iterate through the for loop you want to have the duration of the for loop decrease. So...
for (int num =1; num < <number that you want to change>; num++) {}
Here is the code method.
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
This is how you would do call the method.
public class print
{
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
public static void main (String[] args) {
print(6);
}
}

Your output can be observed like a 2-dimensional array where:
index i grows top-to-bottom and represents row index
index j grows left-to-right and represents column index
What you are doing right now is iterating over the columns of the first row and that is it.
As mentioned in the comments, you should add a second loop to iterate over the rows as well.
Here is how you can achieve this with two for loops:
int colSize = 6;
int rowSize = 6;
for(int i = 1; i <= rowSize; i++) {
for(int j = 1; j <= colSize; j++) {
System.out.print(j + " "); // print individual column values
}
System.out.println(); // print new line for the next row
colSize--; // decrement column size since column size decreases after each row
}

java-8 solution:
public static void printPattern(int rows) {
IntStream.range(0, rows).map(r -> rows - r).forEach(x -> {
IntStream.rangeClosed(1, x).forEach(y -> {
System.out.print(String.format("%3d", y));
});
System.out.println();
});
}
Usage:
printPattern(9);
Output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Related

Trying to write a code that goes from 10-1 and back

I am trying to write code that goes from 10-1 and back:
10
9
8
7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
10
I cannot figure it out. I've got this so far:
package numbers;
class Numbers {
protected static Object Numbers;
public static void main(String[] args) {
int n;
for(n=10; n>=0; n--) { //count BACKWARDS
//if n <=0 n = 1
System.out.println(n);
}
}
}
You can use two for loops.
for(int i = 10; i > 0; i--) System.out.println(i);
for(int i = 0; i <= 10; i++) System.out.println(i);
Here is one way. Based on your expected output I presume you mean from ten to zero and back. Go from -10 to 10 inclusive and change the sign when < 0.
uses the ternary operater (?:) (e.g) a ? b : c
given a conditional, if a is true, do b, else to c
for (int i = -10; i <= 10 ; i++) {
System.out.printf("%d ",i < 0 ? -i : i);
}
Prints
10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10
You can also change the print statement to to use the absolute value.
System.out.printf("%d ",Math.abs(i));
But here is the fun one. A recursive solution. Just not very efficient. It keeps printing the adjusted value and calling itself until the condition is met, then returns and prints values on the call stack in ascending order.
tenToOneToTen(10);
public static void tenToOneToTen(int i) {
if (i > 0) {
System.out.printf("%d ",i);
tenToOneToTen(i-1);
}
System.out.printf("%d ", i);
}

Arithmetic Progression in java

i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}

Print a given number pattern from user input using nested for loop

I am new to programming. Am currently learning Java, on nested loop now, and got stuck.
So what I want to do is to write a program that takes an integer from user and
print lines, for example if user input was 4 then the result should be like:
1
1 2
1 2 3
1 2 3 4
Here is my code so far:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
System.out.println(i);
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
}
}
}
But it prints one extra line at the end, like:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
And it is hard for me to figure out why.
I guess it is my first for loop but I don't know how to fix the for loop to get the result I want.
Any help will be appreciated. Thanks!
Don't print anything from the outer loop, only new line
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output
1
1 2
1 2 3
1 2 3 4
To avoid the trailing spaces of the other answers,
rather than printing i at the start of the loop, print 1.
Then start the inner loop from 2 and print a space before each value. And print a new line after the inner loop.
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Prints:
1
1 2
1 2 3
1 2 3 4
The problem is printing a newline and i at the same time... just take care of the new line after your for loop. The inner loop can handle all the prints.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Let's us dry run it
at first you print
1
then newline
then j goes from 1 to 1 nut no newline now 2 is printed by i now newline
so result 1 2
again j goes like 1 , 2 but no newline so again 3 is printed by i then newline
so result 1 2 3
again j goes like 1 , 2, 3, but no newline so again 4 is printed by i then newline
so result 1 2 3 4
again j goes like 1 , 2, 3, 4 // this one is the extra line

how would I print a pattern then print the reverse pattern next to that pattern?

Hey how would I print a pattern then print the reverse pattern next to that pattern? like this:
1 1 2 3 4 5
1 2 1 2 3 4
1 2 3 1 2 3
1 2 3 4 1 2
1 2 3 4 5 1
I know how to print both the patterns I just can't find out how to print the second pattern next to the first one.
package exc3;
public class Exc3 {
public static void main(String[] args) {
int row = 1;
int i = 0;
for (i=1; i<=row; i++){
System.out.print(i + " ");
if (i == row){
System.out.println();
i = 0;
row++;
}
if (row > 5)
break;
}
}
that's the code I have for making the pattern but I don't think I need help with that just with putting the second pattern next to the first I have no idea how to do that
Here is the code that you want!!
import java.io.*;
public class Exc3 {
public static void main(String[] args) {
int row = 1;
int i = 0;
int j = 0;
int max = 5;
for (i = 1; i <= row; i++) {
System.out.print(i);
System.out.print(" ");
if (i == row) {
for (j = 1; j <= max; j++) {
System.out.print(" ");
}
for (j = 1; j <= max; j++) {
System.out.print(j + " ");
}
System.out.println();
i = 0;
row++;
max--;
}
if (row > 5)
break;
}
}
}
Output:-
1 1 2 3 4 5
1 2 1 2 3 4
1 2 3 1 2 3
1 2 3 4 1 2
1 2 3 4 5 1
You have to consider it as one pattern.
triangle of numbers as well as blank space. And you have to print whole line and then only you can go to next line (System.out.print(i + " ");). If you print 1st triangle, there is no way you can move last triangle from down to up.
I won't give you the code, but the some hints and link to help you learn.
You should first of all know how long the string can be. You can then generate two strings, one for the first part of each line and one for the second.
A this point you can use String.Format() using the right padding format

For loop to print the number in sequence and reverse it

How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}

Categories