How would I get this specific pattern, for loop pattern - java

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

Related

Generate a number-pattern in Java beginning with different numbers

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

How to zigzag numbers in floyd's triangle pattern?

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

bluej program for displaying following pattern for a school project

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.

return incompatible types (java)

Original:
Okay so I have to make a simple number pyramid but the catch is that it has to use two methods. My problem is that return keeps giving me "Incompatible types" and I have no clue as to why.
Okay so I have to make a simple number pyramid but the catch is that it has to use two methods. My problem is that return keeps giving me "Incompatible types" and I have no clue as to why.
public static void main(String[] args)
{
System.out.println(NumPyramid(1,1));
}
public static int NumPyramid(int i, int j)
{
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
{
return System.out.print(j + " ");
}
}
}
Edit: okay so now my new code has the problem of not being a pyramid
public static void main(String[] args)
{
NumPyramid(1,1);
}
public static void NumPyramid(int i, int j)
{
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
}
this prints out
1
2
3
4
5
6
7
removing the Println gives 1 2 3 4 5 6 7
The output should be
1
12
123
etc,
System.out.print is a void method; that is, it returns nothing.
You can't return something from a void method.
Simply remove the return keyword from that line, change the signature of your method from int to void.
Then, change the call in your main method to remove the System.out.println from it.
well, as #makoto points out cleverly, System.out.print being a void method, it returns nothing so:
public static void main(String[] args) {
System.out.println(NumPyramid(1,1));
}
should be changed as well. So you shall make:
public static void NumPyramid(int i, int j) {
for (;i <= 7; i++) {
for (; j <= i; j++) {
System.out.print(j + " ");
}
}
}
a void method, and :
public static void main(String[] args) {
NumPyramid(1,1);
}
not getting printed.
Edit
When you got a new question, you shall not edit your question, removing stuff in the question's post to make it into a new one… But instead accept the best answer, and make a new post. Here we are not answering only to you, but we are building a knowledge base. If you have a new question, make it a new post!
That said, for your new question, what your algorithm is off, it should instead be:
public static void NumPyramid(int max) {
for (int i=1; i<=max; ++i) {
for (int j=1; j<=i; ++j)
System.out.println(j + " ");
System.out.println();
}
}
having a single argument max to specify the number of lines, and the width of the "base" of the pyramid ;
iterate using i for max carriage return output ;
iterate using j for i numbers
start iterations at 1, so we don't output 0 1 2 for max = 3 but 1 2 3
which should output, with max = 3
1
1 2
1 2 3
HTH, again. And please, please, restore your original question.
You want to print this?
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
You need one argument, and it's the method:
public static void NumPyramid(int number)
{
for (int i = 1; i <= number; ++i)
{
for (int x = 1; x <= i; ++x)
{
System.out.print(x + " ");
}
System.out.println();
}
}
I think it's self-explanatory
I guess you're not asking about incompatible return types anymore? Well, I can answer the question you have now, I think.
If you want the code to be in a pyramid, you can't do this:
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
What that code is doing is printing the value of j, then a space, and then printing a new line. A solution is to create a String that you use to store the numbers after each iteration of the for loops.
for (;i <= 7; i++)
{
for (; j <= i; j++)
{
//System.out.print(j + " ");
//The string would take the place of this line
}
//Since println always prints on a new line, you
//could just print the string in this System.out
System.out.println();
}

Nested for loop in java to print the following

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 ..

Categories

Resources