How to get the 101 triangle in the output? - java

been through making a few logical code just cant figure out how to get the output of 01 triangle in the desired form the triangle does print out but not according to the require output.
import java.util.Scanner;
import java.io.*;
public class triangle10{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a number ");
int num =input.nextInt();
while(num > 0){
for(int j=1;j<=num;j++){
System.out.print(num);
}
System.out.print("\n");
num--;
}
}
}
==================================================================
if the user gives input as 6
the out put should be :
111111
00000
1111
000
11
0

Instead of
for(int j=1;j<=num;j++){
System.out.print(num);
}
I think you need to print either a 1 or a 0 (according to your example). So you should compute whether num is even or odd, and decide whether to print 0 or 1. For example
for(int j=1;j<=num;j++){
System.out.print(1 - num%2);
}
Because num%2 = 0 when num is even, and 1 if it is odd - and it seems you want the opposite. So 1 - num%2 should give you what you need.
Before:
Enter a number
6
666666
55555
4444
333
22
1
After:
Enter a number
6
111111
00000
1111
000
11
0

Change you code like this :
boolean flag = false;
while(num > 0){
flag = !flag;
for(int j=1;j<=num;j++){
if(flag==true)
System.out.print("1");
else
System.out.print("0");
}
System.out.print("\n");
num--;
}

You just need to make a small change
From
for(int j=1;j<=num;j++){
System.out.print(num);
}
to
for (int j = 1; j <= num; j++) {
System.out.print((num-1)%2);
}
And then you will get the expected result:
Take entering 6 for example:
Enter a number
6
111111
00000
1111
000
11
0

You are printing out num. Instead you should print out 1 or 0 depending on num.
Try this :
while(num > 0){
for(int j=1;j<=num;j++){
int digit = (num + 1) % 2 ;
System.out.print(digit);
}
System.out.print("\n");
num--;
}

Related

Issue with getting this java program to display the proper whitespace in the answer

So my problem is, my output seems to be correct except it is giving me 0/10 for credit because of the whitespace after the output counts down to one in each situation. It is saying I need a newline after the one but I have tried several things and it's the same output every time.
2.31 LAB: Hailstone sequence
Given a positive integer n, the following rules will always create a sequence that ends with 1, called the hailstone sequence:
If n is even, divide it by 2
If n is odd, multiply it by 3 and add 1 (i.e. 3n +1)
Continue until n is 1
Write a program that reads an integer as input and prints the hailstone sequence starting with the integer entered. Format the output so that ten integers, each separated by a tab character (\t), are printed per line.
The output format can be achieved as follows:
System.out.print(n + "\t");
Ex: If the input is:
25
the output is:
25 76 38 19 58 29 88 44 22 11
34 17 52 26 13 40 20 10 5 16
8 4 2 1
import java.util.Scanner;
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
System.out.print(n + "\t");
count++;
if (count % 10 == 0) {
System.out.print("\n");
}
}
}
This is what I came up with and I am new to java so it is probably something I am overthinking, any thoughts would be appreciated.
"enter image description here" is not an image description
If nothing works, I guess you can trick it by just skipping the tab on the 10'th print. So instead of your normal System.out.print(n + "\t"); print try:
if ((count + 1) % 10 == 0) {
System.out.print(n);
} else {
System.out.print(n + "\t");
}
instead of your normal print.
I figured it out, I just needed to change the order of the code a little and make (n != 1) and System.out.print(n) at the very end. Thanks for the help.
try this, changed the print condition to exclude the tab for end value and when n is 1.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
count++;
if (count % 10 == 0) {
System.out.println(n);
}else{
if(n==1) {
System.out.print(n);
}else{
System.out.print(n + "\t");
}
}
}
}

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

why does displayed number goes above the input number in java?

Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)
Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)
Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}

My logical program is not giving the correct output?

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

Array looping program

I'm supposed to write a program that asks for the number of rows the user wants. For example is the user entered 5 it will display all numbers from 25 to 1 arranged in 5 columns and 5 rows. Something like this should be the output if 5 is entered:
25 24 23 22 21
16 17 18 19 20
15 14 13 12 11
6 7 8 9 10
5 4 3 2 1
As you can see there is a pattern. the first number to appear is the square of the number. then the next number is number squared minus 1. Until it reached 21, 5 will be subtracted bringing 16. Then it will add by 1 until it reach 20. As you can see it is like a snake.
The problem is it works for any number EXCEPT when 1 is entered. 0 is the current result when 1 is entered.
Here's my current codes: please help me thanks
import java.util.*;
public class ArrayOutput2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number = 0;
System.out.print("Enter number of rows: ");
number = input.nextInt();
int[][] num = new int[number][number];
int k=1, i, j;
while(k< (number*number))
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}
for(i=0;i<number;i++)
{
for(j=0;j<number;j++)
System.out.print(num[i][j]+"\t");
System.out.println();
}
}
}
Suppose that the user inputs 1 as a value, therefore number == 1.
You allocate an array num[1][1], that is an array with only one possible cell, number[0][0]
Then the loop is initiated
k=1;
while (k<(number*number)); // which is like while(1<1*1)==FALSE
therefore the loop is never used. You can use:
1) Either a do-while loop to run the loop at least once
2) or add an if statement just after while() loop ends:
// Using an IF statement immediately after the unmodified while()
if (number==1)
{
num[0][0]=1;
}
// or with a loop DO-WHILE
do
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}while(k<(number*number));
when number = 1, the 2D array int[][] num does not get populated as it does not enter the loop while(k<(1*1)), hence bottom for loop which prints the 2D values prints only 0 because array itself does not get initialized.
num[0][0] has not been initialized since you didn't enter the loop. Try this before the loop:
if (number == 1)
num[0][0] = 1;
if(number == 1 ) {
System.out.println("1");
return;
}

Categories