Print triangle in java using single for loop - java

1
2 3
4 5 6
I have to print the triangle using single for loop.
I have tried using two for loops and i did it successfully but i have to solve it using single for loop.

The trick is that the last number of the current row is the sum of the previous row last number and the number of the row
In other words: lastNum = prevLastNumber + rowNum
int row = 1;
int last = 0;
for (int i = 1; i < 37; i++) {
if (i < (row + last)) {
System.out.print(i + " ");
} else {
System.out.print(i + "\n");
row++;
last = i;
}
}
And the output is the following:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36

Try this.
public class Pyramid7Floyds {
public static void main(String[] args) {
int nextNumber = 1;
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(nextNumber<10 ? (" " + nextNumber++) : (" " + nextNumber++) ); //2spaces in single digit & 1 space in double digit.
//System.out.format("%3d",nextNumber++ ); //You may use this line for formatting as a replacement of above line. (comment above line before using this)
}
System.out.println();
}
}
}

public class HelloWorld{
public static void main(String []args){
int j=1;
for(int i=1;i<=6;i++){
System.out.print(i+" ");
if (i==j){
System.out.print('\n');
j=2*j+1;
}
}
}
}

Related

how to print pattern where start and end element is not same

How to print a pattern where i and j variable are not supposed to be printed for pattern rows? I try many times I change values without results.
int k = 1, p = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
p += k;
System.out.print(p + " ");
}
k++;
System.out.println();
}
The above code is the generated output:
1
3 5
8 11 14
18 22 26 30
35 40 45 50 55
The desired output:
1
3 5
5 8 11
7 11 15 19
9 14 19 24 29
p must be updated after each i loop, using the current value of k. The following output can be generated using this code:
int k = 0;
for (int i = 1; i <= 5; i++) {
int p = k++;
for (int j = 1; j <= i; j++) {
p += k;
System.out.print(p + " ");
}
System.out.println();
}
For better formatting, you can use
System.out.printf("%-4d", p);
I'd write it this way:
int numRows = 5;
for (int row = 1; row <= numRows; row++) {
for (int col = 1, p = (row*2)-1; col <= row; col++, p+=row) {
System.out.print(p + " ");
}
System.out.println();
}
The pattern I see is as follows:
The first Row is designated as Row #1 (not zero)
The starting number in each row is (Row * 2) - 1
Each Row has the same number of Columns as the current Row number
In each Row, the numbers are incremented by the current Row number

How to print multiplication table using nested loop?

Trying to figure out how to print a multiplication table.
The code I have right now is:
Scanner scan= new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n=scan.nextInt();
if(n<=10)
{
for(int m= 1;m<=n;m++)
{
for(int o= 1;o<=n;o++)
{
System.out.print(m*o+"\t");
}
System.out.println();
}
}
else
System.out.print("INVALID");
It prints out :
I'm trying to get it to print out as :
Please read the comments marked with // CHANGE HERE.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10: ");
int n = scan.nextInt();
// CHANGE HERE - strict checking
if (n >= 1 && n <= 10)
{
// CHANGE HERE - added to print the first (header) row
for (int m = 0; m <= n; m++)
{
if (m == 0)
System.out.print("\t");
else
System.out.print(m + "\t");
}
System.out.println();
for (int m = 1; m <= n; m++)
{
// CHANGE HERE - added to print the first column
System.out.print(m + "\t");
for (int o = 1; o <= n; o++)
{
System.out.print(m * o + "\t");
}
System.out.println();
}
}
else
System.out.println("INVALID");
}
}
Try this.
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n = scan.nextInt();
if (n <= 10) {
for (int i = 1; i <= n; ++i)
System.out.print("\t" + i);
System.out.println();
for (int m = 1; m <= n; m++) {
System.out.print(m);
for (int o = 1; o <= n; o++) {
System.out.print("\t" + m * o);
}
System.out.println();
}
} else
System.out.print("INVALID");
output:
Please enter number 1-10:7
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49

Java print integer in 4 rows and 4 columns in below format without using array

I am suppose to create a program that prints out following:
16 15 14 13
9 10 11 12
8 7 6 5
1 2 3 4
Hers's my current code:
public class Ideone {
public static void main (String[] args) {
int n=16;
int rows = 4;
int cols = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n+" ");
n--;
}
if(i != rows) {
System.out.println();
}
}
}
}
The output is as below
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
Can someone please help to figure out the solution for this one?
The easiest (but most likely not the desired) solution to the problem as stated is this:
System.out.println("16 15 14 13");
System.out.println(" 9 10 11 12");
System.out.println(" 8 7 6 5");
System.out.println(" 1 2 3 4");
Try this.
public class Ideone {
public static void main (String[] args) {
int n=16;
int rows = 4;
int cols = 4;
int flag = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n -cols*flag +(2*j -1)*flag +" ");
n--;
}
if(i != rows) {
System.out.println();
flag = 1 - flag;
}
}
}
}
Keep track of when the numbers need to be printed in reverse in a boolean. Then use one of two loops depending on that boolean.
public class Main {
public static void main(String[] args) {
int n = 16;
final int rows = 4;
final int cols = 4;
boolean reverse = false;
for (int r = 1; r <= rows; ++r) {
if (reverse) {
for (int c = n - cols + 1; c <= n; ++c) {
System.out.print(c + " ");
}
n -= cols;
} else {
for (int c = 1; c <= cols; ++c, --n) {
System.out.print(n + " ");
}
}
System.out.println();
reverse = !reverse;
}
}
}
You could change the outer loop so it iterates row/2 times and have two inner loops, one doing a forward iteration and one backward.

Printing odd numbers in odd sequences

There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> System.out.println());
Output:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}

Java Programming Code

I am trying to produce the following results:
120
200 202
280 284 288
360 366 372 378
440 448 456 464 472
520 530 540 550 560 570
600 612 624 636 648 660 672
680 694 708 722 736 750 764 778
760 776 792 808 824 840 856 872 888
As you can see, each row increases by 80 and difference between consecutive numbers in each row is i*2 (where i row number starting with 0)
I have written this code down which actually makes this result:
public class Triangle
{
public static void main(String [] args)
{
System.out.println(120);
System.out.print(i + " ");
}
System.out.println();
for (int i = 280 ; i <= 288; i = i + 4 ) {
System.out.print(i + " ");
}
System.out.println();
System.out.print(i + " ");
}
System.out.println();
for (int i = 440 ; i <= 472; i = i + 8 ) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 520 ; i <= 570; i = i + 10 ) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 600 ; i <= 672; i = i + 12 ) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 680 ; i <= 778; i = i + 14 ) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 760 ; i <= 888; i = i + 16 ) {
System.out.print(i + " ");
}
System.out.println();
}
}
However, this code is really long. You can see that I add 80 myself every time. Is there a way I could add another forever loop that does that instead? An adds the 2s as well?
Thanks
Not tested, only using my brain:
for(int i=0;i<input;i++){
int firstNumber = 120+80*i;
for(int j=0;j<=i;j++){
System.out.print(firstNumber+2*i*j); //optimalization firstNumber+(i*j<<1)
}
System.out.println();
}
EDIT input
input variable is count of rows
you can pass the variable as parameter from command line, for example:
public static void main(String[] args){
int input=5; //default value
try{
input=Integer.valueOf(args[0]); //trying to get integer from command line
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Missing parameter");
}catch(Exception e){
System.out.println("First parameter is not an integer");
}
//input variable is now parameter or 5 by default
for(int i=0;i<=input;i++){
int firstNumber = 120+80*i;
for(int j=0;j<i;j++){
System.out.print(firstNumber+2*i*j);
}
System.out.println();
}
}
EDIT explanation
The first number is variable in first column, if you will count by i variable, you will see this sequence:
120, 200, 280, 360, 340, ...
Which is really the first column.
Then, you should solve next column, as you see, in each row, the difference is +2 in each, and in each column too +2, so 2*i*j solves this
Try to split your problem in separate parts like
print N lines
in each line print M values
Such loop can look more or less like
for (int line = 1 ; line <= N; line++){
for (int position = 1; position <= M; position++){
print(calculateFor(line, position));
}
printLineSeparator;
}
(I started indexing from 1 but you should get used to indexing from 0 so consider rewriting these loops to be in form for (int x = 0; ...) as homework)
Now our problem is calculating proper value based on line number and its position in line.
Lets start from figuring out formula for first value in each line.
We can calculate it easily since it is linear function f(line)=... where we know that
x | 1 | 2 | 3 |
----+-----+-----+-----+ .....
f(x)| 120 | 200 | 280 |
So after applying some math to
{120 = a*1 + b
{200 = a*2 + b
we can figure out that f(line) is 80 * line + 40.
Now we need to figure out formula for rest of elements in line.
This is quite easy since we know that it increases by 2, which means that it is something in form firstValue + 2*(positionInLine -1)
Now last problem is how to decide how many values should be printed in each line?
If you take a closer look you at your data you will see that each line contains same amount of values as line number. So we should continue printing values in line as long position<=line.
So our final solution can look like
for (int line = 1; line <= 9; line++) {
int firstValueInCurrentLine = 80 * line + 40;
for (int position = 1; position <= line; position++) {
System.out.print(firstValueInCurrentLine + 2 * (position -1) + " ");
}
System.out.println();
}
public class Triangle {
public static void main(String [] args) {
int base_int = 40;
for (int row = 1; row < 10; row++) {
for (int col = 0; col < row; col++) {
int result = base_int + (80 * row) + (2 * (row - 1) * col);
System.out.print(result);
System.out.print(" ");
}
System.out.println();
}
}
}
for (int i = 0, m = 120; i < 9; ++i, m += 80) {
for (int j = 0, s = i + i, n = m; j <= i; ++j, n += s)
System.out.print(n + " ");
System.out.println();
}

Categories

Resources