How to make a java program with output a triangle of numbers? - java

I understand that there is a similar post to this one, but based on the answers I can not both apply the answers to my current class, or understand the rest of the answers.
I need to create a program using nested "for loops" that creates an output like this one (just symmetrical). I have been trying to get this to work for two whole evenings now, and can't figure it out...
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I would GREATLY appreciate any help!!!
public class PyramidOfDoom {
public static void main(String[] args)
int k = 2;
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
} else {
System.out.print(k);;
}
}
System.out.println();
}
}
}

I thinks it can be done in simple steps as 1. print leading spaces 2. print increasing numbers 3. print decreasing number 4. print trailing spaces 5 print new line.
Sample code(concept) as below.
int row = 10;
for(int i=1; i<=numRow ; i++){
int num = 1;
for(int j=0; j<numRow- i; j++ ){
System.out.print(" ");
}
for(int j=numRow-i+1; j<=numRow ; j++ ){
System.out.print(num+" ");
num=num*2;
}
num=num/2;
for(int j=numRow+1; j<numRow+i; j++ ){
num=num/2;
System.out.print(num+" ");
}
for(int j=numRow+i+1; j<=numRow*2; j++ ){
System.out.print(" ");
}
System.out.print("\n");
}

You're not changing k at all. You need to keep multiplying it by 2 until you get to the middle of the row, then start dividing it by 2. As it stands, in your System.out.println(k), how can you expect it to print anything but 2 if you never manipulate it? :)
Also, you have two semicolons in your System.out.println(k);;. That seems odd to me, but I suppose it actually makes sense that it would compile.

Related

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+" ");
}
}

How do I fix my java program not stopping running?

I am writing a simple program as some practice for Java. It takes in integers and puts them into a two-dimensional array of R rows and C columns and then simply prints out each element of the array (just for troubleshooting). When I run the code it prints every integer like it should but the program does not stop running. I have to force stop it. Why is it not stopping on its own? I tried some basic debugging and tried to see if I accidentally had an infinite loop in the code but I couldn't find it.
In case it is important I am using IntelliJ Idea Ultimate 2019.3.
Thanks
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt(); //Takes number of test cases
for(int i = 1; i <= T; i++){ //This is the counter for each test case
int R = in.nextInt(); //R is # of rows
int C = in.nextInt(); //C is # of columns
int K = in.nextInt(); //K is the thickness allowed
int numArray[][] = new int[R+1][C+1];
for(int j = 0; j < R; j++){
for(int k = 0; k < C; k++){
numArray[j][k] = in.nextInt();
System.out.println(numArray[j][k]);
}
}
}
in.close();
}//End of main
}//End of main class
Edit: Just for future reference I will include the input and the output I was getting.
Input:
3
1 4 0
3 1 3 3
2 3 0
4 4 5
7 6 6
4 5 0
2 2 4 4 20
8 3 3 3 12
6 6 3 3 3
1 6 8 6 4
Output:
3
1
3
3
4
4
5
7
6
6
2
2
4
4
20
8
3
3
3
12
6
6
3
3
3
1
6
8
6
(and here the cursor is stuck blinking not doing anything and the program doesn't quit on its own)
I solved the issue by manually typing the input instead of copying and pasting it. Not sure what caused that issue but it worked!
This little piece of code requires the user to input 3 integers (R, C and K) T-times:
int T = in.nextInt();
for(int i = 1; i <= T; i++){
int R = in.nextInt();
int C = in.nextInt();
int K = in.nextInt();
// ...
}
Additionally the user has to input an integer R*C-times until i <= T:
for(int j = 0; j < R; j++){
for(int k = 0; k < C; k++){
numArray[j][k] = in.nextInt(); // << requires user-interaction each loop here >>
System.out.println(numArray[j][k]);
}
}
If you use T=1, R=1, C=1, K=1 the user has to input only 1 additional integer, as there is only 1 test-repitition and R*C = 1. With that your program terminates just as expected.
With bigger values of T, R, C, K the required user-interactions grow exponentially, which probably makes you think that your program should have ended but it still waits for additional user-input.
Ok I think I figured out the issue. I was copying and pasting the test inputs from a web page. I tried double checking to make sure the input was valid and then inputting them by hand and it fixed it. Not 100% why but that fixes the problem. Thanks for the help!
your for(int i = 1; i <= T; i++) probably newer ends because you are increasing T.
You need to made some condition in loop to exit. For example
if (xx == yy) break;

Is there any way with which we can print the following pattern?

class pattern
{
public static void main()
{
int i,j,p=1;
for(i=1;i<=5;i++)
{
for(j=1;j<=i; j++)
{
System.out.print(p+" ");
p=p+2;
}
if(i>=2)
p=p-2;
System.out.println ();
}
}
}
I want the below written output
1
3 5
5 7 9
7 9 11 13
9 11 13 15 17
but the output obtained by the above written code is given below
1
3 5
5 7 9
9 11 13 15
15 17 19 21 23
I want last digit of second row to be displayed at the starting of third row and last two digits of third row to be displayed in the beginning of the fourth row and so on.
int length = 5;
for(int start = 1; start < length*2; start += 2){
for(int j = start;j < start*2; j += 2)
System.out.print(j + " ");
System.out.println();
}
As AntoineB said StackOverflow is not a site to do homeworks, you should at least tried to solve the problem by yourself, if there are parts that you don't understand then reach help. don't expect others to do your home works
Note the pattern of the first number in each row:
row 0 -> 1
row 1 -> 3
row 2 -> 5
row 3 -> 7
row 4 -> 9
This is row*2 + 1
So you need to loop for each row and calculate that first number. Then you add 2 to it for every column.
for(int row = 0; row < 5; row++) {
int value = 2*row + 1;
for(int col=0; col <= row; col++) {
System.out.print(value+" ");
value = value+2;
}
System.out.println();
}
It looks to me like your issue is that you're trying to keep of the wrong things, namely the number being printed. Instead, keep track of the current line and current item in the line you're currently at.
loop through all lines
for each line: determine a) starting number b) how many items you need to print
loop starting at the starting number and print the items you need to print
IntStream.range(0, 5)
.mapToObj(line -> IntStream.range(0, line+1)
.map(i -> (line*2+1) + (2 * i))
.mapToObj(Integer::toString)
.collect(Collectors.joining(" ")))
.forEach(System.out::println);

How do you print the sequence one 1, then two 2, three 3, ... n ns?

Write a program that prints a part of the sequence:
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...
(the number is repeated as many times, to what it equals to).
I've used two for loops, however, I can't get 1 to print once, 2 to print twice, instead, I get
1 2 3 4 5 6 1 2 3 4 5 6, etc.
You need two for loops for this.
for (int i = 0; i <= 5; i++) { // This will loop 5 times
for (int j = 0; j < i; j++) { //This will loop i times
System.out.print(i);
}
}
As I remember the goal is to print n numbers (for example 1 2 2 3 3 3 4 for n = 7), diveded by space. Sorry for my java)), I wrote it in Kotlin, tried to change for Java, but main idea is clear. BTW n – the number of the elements, you need to read with Scanner.
int count = 0 //Idea is to create a counter, and to increment it each time of printing
for (int i = 0; i <= n; i++) { //Loops n times
for (int j = 0; j < i; j++) { //Loops i times
if (int count < int n) {
System.out.print(" "+i+" ");
int count++ //Prints 1 one time, 2 two times, etc. stops if reached n number
}
}
}
How about this :
for(int i=1;i<=num;i++){
for(int j=1;j<=i;j++){
System.out.print(" "+i+" ");
}
}
where, num = 1,2,....n
(Also we wont be able to tell why you got that output unless you attach the code. Please attach the code snippets for such questions :) !

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