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;
}
Related
So the goal was to use a nested for loop to output 6 rows and 10 columns. The thing was though that the inner for loop was supposed to check to see whether the number was even or odd as, if it was even, we would add 2 to it and then print out that number 10 times before moving onto the next output. So this is what were were supposed to get
1 1 1 1 1 1 1 1 1 1
4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3
6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
8 8 8 8 8 8 8 8 8 8
I thought I was on the right track but my output is a complete mess, here's what I have. Thank you to anyone willing to help.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 1; nestedE < 10; nestedE++)
{
if (numberE%2 == 0)
{
numberE += 2;
System.out.printf("%2d", numberE);
} else {
System.out.printf("%2d", numberE);
}
}
System.out.printf("%2d\n", numberE);
}
well to start with your inner loop will only iterate nine times. second you don't need a nested loop, you need one loop and a guard determining when to print.
Don't modify numberE inside the loops. Instead just print numberE + 2.
Also, if your inner loop runs from 0 to <10 you will get 10 iterations and you don't need to print the number again - just a newline.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 0; nestedE < 10; nestedE++) // <-- start at 0 and end <10 for 10 iterations
{
if (numberE%2 == 0)
{
System.out.printf("%2d", numberE + 2); // <-- print the number + 2
} else {
System.out.printf("%2d", numberE);
}
}
System.out.println(); // <-- don't print the value again here
}
I would do it this way. Gives the required result.
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++)
{
int temp = i;
if(temp%2 == 0) {
temp +=2;
}
for(int j=1;j<=10;j++) {
System.out.print(temp+" ");
}
System.out.println();
}
}
}
A brief description of what is happening here:
So, since we need 6 rows, we use the value of 6 as a row counter. The variable i takes care of keeping a count of the rows. Here since the target is 6, we start from row number 1 and go until row no 6. Inside each value of the loop, we save the value of i to temp because we don't want the value of i to change before incrementing in the main for loop. We then check if this temp value is even by doing a modulo division by 2. If it is even, we increment the temp value by 2.
Then, we run a loop from 1 to 10 since we need 10 columns to print the value temp(either the original i or incremented because it was even). After exiting the loop, finally to move to the next row, we do a System.out.println().
I would suggest using a temporary variable to store the current intended value.
The issue with your solution was that you were modifying the value of numberE by using numberE += 2; inside the second for loop, this changes the value globally.
Moving the final column in to the nested for loops also makes it easier as you wouldn't need to define the temporary variable outside of the loop. Using this also meant changing the <10 to <=10.
for (int numberE = 1; numberE <= 6; numberE++) {
for (int nestedE = 1; nestedE <= 10; nestedE++) {
int current = (numberE % 2 == 0) ? numberE + 2 : numberE;
System.out.printf("%2d", current);
}
System.out.printf("\n");
}
You were pretty close though, with practise you'll get better.
I have to write a main program that asks the user for a number between 10 and 20 and its prints the even numbers between that number and 50. If the number is not in the 10 and 20 range, inclusive, the program will keep prompting the user for a valid number.
So far this is what I have
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner keyboard = new Scanner(System.in);
System.out.println("Please choose a number between 10 and 20! ");
int number = keyboard.nextInt();
int newnumber = number;
while (number <= 10 || number >= 20) {
System.out.print("No, between 10 and 20: ");
System.out.println("Please choose a number between 10 and 20! ");
number = keyboard.nextInt();
}
while (number >= 10 || number <= 20) {
int limit = 50;
for (int i= 10; newnumber <= 50; i++) {
if (i% 2 == 0) {
System.out.println(newnumber);
newnumber=newnumber+2;
}
}
}
}
}
Unrelated to your problem, but your first while loop will prevent the user from putting in 10 or 20 because the while loop keeps checking if the input is equal to those two.
Your second while loop isn't doing much and would make more sense as an if statement - If you hadn't already verified that it was in the range in your first while loop.
Now your actual problem is you start your counter as i but increment newnumber. Even if you were incrementing i, it would still never work for odds because your starting number is odd and you increment by 2. Your two options are to
start i at number, unless number is odd then number+1
increment the loop counter by 1 each iteration
Using the first option
while (number < 10 || number > 20) {
System.out.print("No, between 10 and 20: ");
System.out.println("Please choose a number between 10 and 20! ");
number = keyboard.nextInt();
}
for (int i = (number % 2 == 0 ? number : number+1); i <= 50; i+=2) {
System.out.println(newnumber);
}
Notice that I quit checking if each iteration was even because I made sure to start with an even number and increment by 2.
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);
}
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
I'm writing this program with numbers, but I am stuck and need some help.
Code so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Oppgi øvre grense: ");
int Number = in.nextInt();
int tall = 1;
for(int t = 0; tall <=45; tall++){
System.out.println(" " + tall);
}
}
The objective: to get the first line to contain one number, the second to contain two numbers, third line contain three numbers, etc.
The output should look like a pyramid, with different spacing between the numbers on each line.
If anybody can help me with the solution code. Thank you.
Oppgi øvre grense: 45
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
37 38 39 40 41 42 43 44 45
outer loop{
decides number of numbers in one line
inner loop{
prints actual numbers.
Please keep track of the numbers you have printed so far
Inner loop starts at numbers printed so far
It will have passes = number of numbers to print
}
}
You have two distinct tasks here:
1. Decide how many numbers to print in one line
2. Actually print the numbers
Since that is the case, one loop decides how many numbers to print: the outer loop. The Reason it is outer loop is because you need to have a clear picture of how many numbers you need to print before you actually print.
The other loop: inner loop does the actual printing.
So, once you start with the outer loop, your inner loop will begin printing.
It will then see if it has printed the maximum number of numbers for that pass.
If yes, stop. Then, you increment the outer loop. Come back in, print, check and then do the same.
Easy enough ?
public class RareMile {
public static void main (String[] args){
printNum(5);
}
public static void printNum (int n){
int k=1, sum=0;
for (int i=1; i<=n; i++){
sum=0;
for(int j=1; j<=i; j++){
System.out.print(k);
sum = sum+k;
k++;
}
System.out.print(" =" + sum);
System.out.println();
}
}
}
The real question is that how to do it with only one for loop?
Keep track of the line number
e.g.
int line = 1; // line number
int count = 0; // number of numbers on the line
for(int x = 0; x <= 45; x++){
if (count == line){
System.out.println(""); // move to a new line
count = 0; // set count back to 0
line++; // increment the line number by 1
}
System.out.print(x); // keep on printing on the same line
System.out.print(" "); // add a space after you printed your number
count++;
}