I have a fairly decent knowledge of Java in BlueJ programming environment. But I am at a loss to write a looping function to create this
pattern. Any help or pointers would be very helpful.
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
My code thus far...
import java.util.*;
public class scanner {
public static void main(){
Scanner sc = new Scanner(System.in);
int val = 1;
for( int i=1; i < 5; i++){
for(int j = 1; j > i; j--){
System.out.print(j+" ");
if(val != 1) {
System.out.print(1);
}
val +=1;
}
System.out.println();
}
}
}
Your approach is too complicated. I suggest you define the key variables and use them for the algorithm. By the way, you don't need to use java.util.Scanner since you don't receive any input value from a console.
int end = 1;
int step = 2;
int rows = 5;
for (int i=0; i<rows; i++) {
for (int j=0; j<i+1; j++) {
int number = end + i*step - j*step;
System.out.print(number + " ");
}
System.out.println();
}
Output (make sure):
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
Moreover, in your code you have the following line:
for (int j = 1; j > i; j--) { ...
This loop never allows entering its body because of the condition j > i and the j subtracting. I recommend you to debug your program and track the i and j values to understand what is going on.
Related
I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890
I need to be able to get this pattern using for loops:
Q. Write a program to complete the first N rows of the following output. The number of rows N should be read from the keyboard.
Intended output:
1
2 4
3 6 9
4 8 12 16
Result:
1
24
399
4161616
525252525
Attempt:
(I haven't used scanner yet, because I wanted to try understand how to do it without scanner.)
import java.util.Scanner;
public class Test {
public static void main(String [] args){
int odd = 1;
for(int i=1;i<=5;i++)
{
int no=i;
for(int j=1; j<=i;j++)
{
System.out.print(no);
no = i*i;
}
System.out.println();
}
}
}
You were very close!
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
See demo
This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 3 years ago.
public class array1 {
public static void main(String args[]) {
int twod[][] = new int[4][5];
int i, j, k = 0;
for (i=0; i < 4; i++) {
for (j=0; j < 5;j++) {
twod[i][j] = k;
k++;
}
}
for (i=0; i < 4; i++) {
for (j=0; j < 5;j++) {
System.out.println(twod[i][j] + " ");
}
System.out.println();
}
}
}
Can any one tell me how to modify the code to get the output in matrix format? When I compile this program the output is 0 to 19 which is aligned vertically and not as in matrix format. Can any one help me?
Just use print() when you want to print a value, and only use println() when you actually want to print followed by a newline:
for (i=0; i < 4; i++) {
for (j=0; j < 5; j++) {
if (j > 0) System.out.print(" ");
System.out.print(twod[i][j]);
}
// now that a complete row has been printed, go to the next line
System.out.println();
}
Note that this answer might still leave you with a somewhat ratty-looking matrix, because not all numbers in your data set have the same width. We would need to do more work to get everything into nicely formatted columns.
Here is one improvement upon the above using String.format, with a fixed field width of 5:
for (i=0; i < 4; i++) {
for (j=0; j < 5; j++) {
if (j > 0) System.out.print(" ");
System.out.print(String.format("%5s" , String.valueOf(twod[i][j])));
}
System.out.println();
}
This generates:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}
How would i print the following in Java:
5
55
555
55
5
using just nested for loop with no if statements.
What i have so far:
public static void main(String[] args) {
for(int i = 1; i < 6; i++) {
for(int k = 3; k > i; k--) {
System.out.print(" ");
}
for(int k = 3; k < i; k++) {
System.out.print(" ");
}
for(int j = i; j > 0; j--) {
System.out.print("5");
}
System.out.println();
}
}
As you can see, I got the spaces correct but not the number of 5's on each line yet.
I somehow feel that there must be possible to use just 1 for loop for all the spaces?
You need to first break the pattern in two parts :
Upper Half
5
55
555
Lower Half
55
5
In upper half there are 3 rows to be printed. Analyze each row.
For row no. 1 there are 2 blanks and 1 "5".
For row no. 2 there is 1 blank space and 2 "5"s.
For row no. 3 there is no blank space and 3 "5"s.
So if i represents my rows then when i is 1 i.e. row no. 1 no. of blank spaces to be printed is (3-i) i.e. 2 and no. of "5"s to be printed is i i.e. 1.
On similar lines you can break the complete problem.
Solution:
class Main{
public static void main(String args[]) {
for(int i=1;i<=3;i++) {
for(int j=1;j<=(3-i);j++) {
System.out.print(" ");
}
for(int j=1;j<=i;j++) {
System.out.print("5");
}
System.out.println();
}
for(int i=1;i<3;i++) {
for(int j=1;j<=i;j++) {
System.out.print(" ");
}
for(int j=1;j<=(3-i);j++) {
System.out.print("5");
}
System.out.println();
}
}
}
You want the number of spaces you print to decrease up to a point and then start increasing again, so one option is to use abs():
int n = 3; // number of columns
for (int i = 0; i < 2 * n - 1; i++) {
int k = Math.abs(n - i - 1);
for (int j = 0; j < k; j++)
System.out.print(' ');
for (int j = 0; j < n - k; j++)
System.out.print('5');
System.out.println();
}
5
55
555
55
5
Here, k is the number of spaces we want to print (hence n-k is the number of 5s, as can be seen in the second for-loop). k decreases as i approaches n - 1, at which point it becomes 0. As i increases further, the term inside abs() becomes increasingly negative meaning that its absolute value begins growing again.
You can use 1 for loop for the number of rows and a 2nd one for the number of columns. In this way you will need to use 4 for loop ..