I would like some help making a table that prints 1-100 - java

So here are my assignment requirements:
Print out all the numbers between 1 and 100 inclusive, 10 numbers per line evenly spaced out using tabs.
Use a max of 2 loops and 1 if statement.
I have a pretty good understanding of how this needs to be done but I'm just having trouble figuring out a way to start a new line after every 10 numbers.
This is what I have so far:
import java.util.Scanner;
public class Table {
public static void main (String[] args) {
int counter, value;
counter = 1;
value = 0;
while (value < 100) {
value += counter;
System.out.print(value + "\t");
}
}
}

To start a new line, print the '\n' character.
if ((value % 10) == 0) {
System.out.print("\n"); // Or really, just System.out.println();, since that makes a new line.
}

There are two ways to approach this:
Work through each row in your table, and for each of these print each of the numbers x1, x2, x3, x4, ..., x + 10 followed by a newline character.
Work through all of the numbers individually, and after each one check to see if it's a round number of tens (think modulo arithmetic), and if is, follow it with a new line character.

Since you already know the span of numbers you need to iterate over, I'd use a for loop, starting at 0 and ending at < 100.
You're missing the increment, counter++ within your loop.
Use an if statement within the for loop, if (i % 10 = 0) {System.out.println(value + "/n";}, else System.out.println(value + " ");
Best of luck on your assignment.

Related

I'm just having hard time understanding the class material from my java class

Can someone explain this code line by line. I just started to learn how to code and I'm learning java right now,but I'm having hard time how this function executes. What does new int[10]; really do? and I don't really get the difference or how repeatedDigits[index] part is used differently from the repeatedDigits[remainder] part.
Write a function that counts the repeated digits in the integer x.
For * example: if x is 999, then your function must print back that 9 occurs 3 * times. Another example, if the integer x is 992121, then your function * must print back that 9 occurs 2 times, 2 occurs 2 times and 1 occurs 2 * times. This was a guideline for the function.
public static void countRepeatedDigitsInANumber(int x) {
int[] repeatedDigits = new int[10];
while (x > 0) {
int remainder = x % 10;
x = x / 10;
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
}
int index = 0;
while (index < 10) {
if (repeatedDigits[index] != 0)
System.out.println("The digit " + index + " occurs " +
repeatedDigits[index]);
index++;
}
}
This is a code that compiles. I'm just posting this because I'm having hard time to understand. I would realy appreciate if someone could give any suggestion to learn java quickly as well!
What does new int[10];
It creates a new array of size 10 that can hold int values. All of the values in the array will be initialized to 0 (this is just how Java handles int primitives).
In this case, it looks like this array is being used to store the number of times that the digit corresponding to its index has been seen.
Hmm, that was confusing to type, and probably even more confusing to read, so let me use an example. For the input 992121, you'd expect the repeatedDigits array to look like this when the program is done:
[0, 2, 1, 0, 0, 0, 0, 0, 0, 2]
i.e. Two 1s, one 2, and two 9s
while (x > 0) {
This starts a loop that will keep going until x is equal to (or smaller than, but that shouldn't happen) zero.
int remainder = x % 10;
This essentially "captures" the right-most digit of the number using modular arithmetic. It divides the number by 10, and any remainder is going to be what's in the "ones place" (i.e. the right-most digit).
x = x / 10;
This shifts digits to the right by one, and throws away the right-most digit (since you've already captured it).
repeatedDigits[remainder] = repeatedDigits[remainder] + 1
This just increments the value in the array at the appropriate location. For example, if you just pushed a 9 off the right end of the number, this will increment the value in repeatedDigits[9] so you know that you just saw an additional 9.
int index = 0;
while (index < 10) {
We're about to do some looping! There are (in my opinion) better ways to do this, but this works just as well. Basically, you want index to start at 0, and loop all the way up to 9, but stop when you get to 10.
if (repeatedDigits[index] != 0)
If the value at a given location in the repeatedDigits array is not zero, then...
System.out.println("The digit " + index + " occurs " + repeatedDigits[index]);
... print it out!
index++;
And finally, increment index so we can check the next number. This is exactly the same as index = index + 1.
Welcome to SO and the beautiful world of Java! I've attached hyperlinks all throughout my answer that could possibly help you out.
int[] repeatedDigits = new int[10];
The above line of code is creating an array with 10 elements, from index: 0 to index: 9.
int remainder = x % 10;
The above line of code is calculating the remainder once 'x' has been divided by 10. For example, if 'x = 9192' then it would be dividing '9192 / 10 = 919.2' And taking the remainder. Which in this case is the '2'. Notice how it's actually looking at the number in reverse? So a number like '9192' is actually being processed as '2919'.
x = x / 10;
The above line of code is dividing the number down by 10- since it's integer division it drops all decimal values. Since we have already calculated the last number. So our '9192' is now just '919'.
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
The above line of code is going to the index of the array of the remainder value that we stored earlier. Remember how our remainder was '2'? It's not going to index: 2 in our array and adding 1 to it's value- which was originally 0. So now our array at index: 2 has the value: 1. Meaning the number 2 was repeated 1 time.
What I've laid out above is just 1 iteration of the while loop that the top half of your code is in. So get a piece of paper and redo everything I did above with the remaining number '919'.
Once you're finished you should notice that your array looks something like this:
index 0: 0
index 1: 1
index 2: 1
index 3: 0
index 4 to 8: 0
index 9: 2
This means that '1' came once. '2' came once. and '9' came twice.
As for advice on learning Java? Read a lot. Google every little question you have, and if you don't understand how something is working get a piece of paper and write it out.
int[] repeatedDigits = new int[10];
//create an array of integers of size 10
while (x > 0) {
//while the integer provided is greater than 0
int remainder = x % 10;
//gets the smallest value digit in a base ten system. 101%10 =1
x = x / 10;
//in base ten this reduces the size of the number by a tens place. 101/10 =10 as 10 can be fully divided into 101 10 times. You've dropped the last digit of the number in this way. This is what will allow you to exit the while loop, as eventually x will be equal to 0.
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
remainder here can be between 0-9. This is because remainder is the remainder of dividing the provided integer by 10. You can't divide a number greater than 0 by ten and have a value less than zero or greater than 9.
The array you created has indexes 0-9, as it is ten spaces long (0,1,2,3,4,5,6,7,8,9). You are assigning the value of the index of repeated Digits that corresponds to your remainder to whatever it was previously plus 1.
What this means is you have found that the last digit in the number is equal to some value X. X must be between 0-9. As you have an array with indexes between 0-9 you get the value associated with repeatedDigits[X], add one to it as you have found another value of X, and set repeatedDigits[X]'s value equal to what is was before you found this new X plus one.
}
int index = 0;
You start at the first value of an array (0)
while (index < 10) {
Go through the values of the array from 0 to 9
if (repeatedDigits[index] != 0)
if the value of the array repeatedDigits at index is not 0. This is the same as saying if there was a value of index found in the input number.
System.out.println("The digit " + index + " occurs " +
repeatedDigits[index]);
index is the number we looked at. The count of how many times it occurred is stored at repeatedDigits[index]. We are printing the value and how many times it occurred.
index++;
Increase the index, examining the next index value.
}
}
Let me see if I can clear a few things up for you. My first suggestion is to format your code so that the lines within loops are indented:
public static void countRepeatedDigitsInANumber(int x) {
int[] repeatedDigits = new int[10];
while (x > 0) {
int remainder = x % 10;
x = x / 10;
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
}
int index = 0;
while (index < 10) {
if (repeatedDigits[index] != 0)
System.out.println("The digit " + index + " occurs " + repeatedDigits[index]);
index++;
}
}
}
This helps us to see the structure of the program. We can now see that the program runs as follows:
Define a new int array: int[] repeatedDigits = new int[10];
Run a while loop: while (x > 0) { ... }
Define an int variable: int index = 0;
Run a second while containing an if statement: while (index < 10) { if ( ... ) { ... } }
I'll try to explain each of the four pieces one at a time.
First we define our int array. new int[10] defines an array with ten spots in it, each of which can hold an integer. You can think of this like ten boxes next to each other, each labeled with an index. This array will be used to keep track of how many times we've seen each integer. repeatedDigits[0] will hold the number of times we've seen a 0 digit in our number; repeatedDigits[6] will hold the number of times we've seen a 6 digit, and so on.
Here's the heart of the program. We're going to break down the number, one digit at a time, and for each digit, we add one to the spot in the array used to keep track of how many times we've seen that digit. This line gets us the rightmost digit in our number: int remainder = x % 10;. % is called the modulo operator, and you can search for that to learn more about it. With the input 992121, this will assign remainder to 1.
The next line uses integer division to remove that last digit from the number, so that the next time through the loop we get the next digit. if x = 992121 then after x = x / 10, x will equal 99212.
Finally, we add one to the spot in the repeatedDigits array corresponding to the digit we saw. So in our example, remainder = 1, so we add 1 to the repeatedDigits[1] spot. This line takes advantage of the fact that an uninitialized int defaults to 0.
We've reached the end of the while loop, so we check the condition, and find that x > 0, so we run the loop again. We repeat this for every digit in the input number`.
The hard work is now done; the rest of the program is there to print out the results.
We assign index to 0. The next while loop will increment this variable from 0 to 9, printing the value of the repeatedDigits array for each digit.
We run the loop from index = 0 to index = 9. For each value, we check to see if we saw that digit in our input number (that's the if statement). We check the value in repeatedDigits[index] to see if it doesn't equal 0. If so, then we must have incremented it in the previous loop, so we know that digit appeared at least once in the original input. In that case, we print a line to the console using System.out.println. Then we increment index and start the loop again.
Please let me know if you have any questions, and good luck!

Methods That Return Values Quiz

I am super new to programming and I had a question on a quiz and the output answer was 36. I don't understand how that outcome came out of this code.
public class Method {
public static int method(int number) {
int result = 0;
while ( number > 0) {
result += number % 10;
number = number / 10;
}
return result;
}
public static void main (String[] args) {
System.out.println(method(9999));
}
}
Clearly within this code the part we need to look at is the while loop, this is the area of interest because it's where all of the calculation occurs.
while(number > 0){
result += number % 10;
number = number/10;
}
So the first line within the loop will add a value to the result:
result += number % 10;
The % operator in Java and many other languages can be thought of as a remainder of division, hence we are adding the remainder of division by 10 to the result.
9999 / 10 = 999 remainder 9.
So result has 9 added.
Then we call:
number = number / 10;
In Java when dividing an int we do not consider the remainder, so 9999/10 = 999.
And then we repeat. So essentially we are adding up the digits of the number.
9 + 9 + 9 + 9 = 36.
Even if you are new at programming, you could try to use an IDE like Eclipse.
Using an IDE you can use the breakpoints and follow the code line by line and the variable line by line. So you will understand what happens.
You could create a watch expression that will show on a tab the variable to you or use the inspect to do this.
A video: https://www.youtube.com/watch?v=drk_ldaRMaY

Write statements in Java reads two integers and displays even numbers between them

Write statements that can be used in a Java Program two integers and display the number of even integers that lie between them. For example, the number of even integers that lie between 12 and 5 are 4
So far below is what i have.... the program outputs all the numbers between the two integers, and not the actual number of even integers.
Can someone please help / tell me what i am doing wrong ?
import java.util.Scanner;
public class evenNumberPrinter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the smaller integer");
int numOne = keyboard.nextInt();
System.out.println("Enter the larger integer");
int numTwo = keyboard.nextInt();
for (int i = numOne; i <= numTwo; i++) {
System.out.println(i + " ");
}
}
}
to calculate count of even numbers you don't have to use for loop, here is the formula:
static long evenCount(long a, long b) {
return ((Math.abs(a - b) + 1) >>> 1) + ((~((a & 1) | (b & 1))) & 1);
}
some clarification:
zero (0) is even number
count of even numbers obviously depends on distance between two values, lets pull some data:
0-0 - 1 number, distance 0 (0)
0-1 - 1 number, distance 1
0-2 - 2 numbers, distance 2 (0, 2)
0-3 - 2 numbers, distance 3
0-4 - 3 numbers, distance 4 (0, 2, 4)
0-5 - 3 numbers, distance 5
0-6 - 4 numbers, distance 6 (0, 2, 4, 6)
1-1 - no even, distance 0
1-2 - 1 number, distance 1 (2)
so, count of even numbers is determined by (distance+1)/2 plus one if both numbers are even
so, if we take distance Math.abs(a-b) + 1 divide it by two (>>>1) and then add 1 if and only if both numbers are even (a&1)==0
Another solution is to use pure math:
round the smaller number to the next even number (e.g. 5 to 6)
round the bigger number to the previous even number (e.g. 13 to 12)
subtract from the bigger rounded the smaller, e.g. 12-6 = 6
since even numbers are every second, divide it by 2 plus add one to count the first number of the range as well, that is 3+1=4
That is:
public static void main(final String[] args) {
final int number1=1;
final int number2=6;
int min=Math.min(number1, number2);
int max=Math.max(number1, number2);
min=min+min%2; // round up
max=max-max%2; // round down
final int evens=(max-min)/2+1; // even range plus the first number
System.out.println(evens); // Look ma, no loops
}
Edited to include explanation
Your for loop is doing nothing more than printing each number between numOne and numTwo. What you want to do is check to see if i is even or odd which can be accomplished using the modulus operator if i modulus 2 equals zero, then that number is even, and you should increment a counter variable each time this is true.
Change your for loop to something like this:
int evenCounter = 0;
for (int i = numOne; i < numTwo; i++){
if (i % 2 == 0){
System.out.print(i + " ");
evenCounter++;
}
}
System.out.println("There are " + evenCounter + " even numbers between " +
numOne + " and " + numTwo);
A little more optimal solution (if you want to print the numbers). Testing for parity (odd vs even) can be done only once, before entering the loop. Afterwards, just stay on even numbers by incrementing by 2.
int n = numOne;
int evenCount = 0;
if ((n%2)==1) { n++; }
while (n <= numTwo) {
System.out.println(n);
n += 2;
evenCount ++;
}
System.out.println( "There are " + evenCount + " even numbers between " + numOne + " and " + numTwo );
However, if your goal is only to determine how many there are (not print them), this is not optimal. A mathematical solution will be much faster.
int n = 0; //this is your counter
for (int i = numOne; i < numTwo; i++) { //use < numTwo instead of <= numTwo
//so it doesn't count numTwo as an int between your range
if (i%2 == 0) {n++;} //checks to see if number is even
// if it is, it adds one to the counter and moves on
}
System.out.println("there are " +n+ "even numbers between " +numOne+ " and " +numTwo); //prints out how many even ints were counted.

Count Binary recursion?

Write a method countBinary that accepts an integer n as a parameter and that prints all binary numbers that have n digits in ascending order, printing each value on a separate line. All n digits should be shown for all numbers, including leading zeros if necessary. You may assume that n is non-negative. If n is 0, a blank line of output should be produced. Do not use a loop in your solution; implement it recursively.
The issue Im having with this is I don't know how I would print the zeros and ones, since n is the only parameter I can have. I also cannot use a for loop and put my recursive call in the loop, so Im sorta stuck. this is what I have so far:
public static void countBinary(int n){
if (n < 0) {
throw new IllegalArgumentException();
}if(n == 0){
System.out.print("");
}else{
countBinary(n - 1);
System.out.println(n ); // I tried doing n + "0" and + "1" did not work
countBinary(n - 1 );
System.out.print(n );
// store += n;
}
}
And here is my output for countBinary(2):
1
12
1
12
When it should be this:
00
01
10
11
I am getting the right amount of "levels" for every other line which is strange, but Im really stuck
Note: this is NOT homework, simply practice. THanks!
You're on the right track with recursing twice. The concept is to print a "0" followed by an (n-1)-digit number, then a "1" followed by an (n-1)-digit number. The trick is to figure out how to handle the fact that for n > 1, there are many (n-1)-digit numbers and they each need to have that "0" or "1" in front of them. The way to handle that is to not actually print the "0" or "1" but to pass it down the recursion until you are ready to print each entire line. For that, you'll need an auxiliary method to do the actual recursion and you can use a char[], a StringBuilder, or even a String for the pending output so far. (I'd use the first and the second is fine too. I'd avoid using a String because it will generate a new String each time you need to add a "0" or "1"—a lot of garbage.)
Here's my solution:
public static void countBinary(int n){
if (n < 0) {
throw new IllegalArgumentException();
}
countBinary(new char[n], n);
}
private static void countBinary(char[] prefix, int n) {
if (n == 0) {
// base case -- no more recursion
System.out.println(prefix);
} else {
// position next digit counting from the right so output is in increasing order
final int i = prefix.length - n;
// prefix a '0' and recurse
prefix[i] = '0';
countBinary(prefix, n-1);
// prefix a '1' and recurse
prefix[i] = '1';
countBinary(prefix, n-1);
}
}
I don't believe the "NOT homework" thing, but anyways.
You want to print binary numbers by recursion. We can not do this by only having n as a single parameter. Because if we want to print a number of n digits haven the first x digits and then letting recursion add the oder y we need to know what the first x digits where.
That means, if someone tells me: "Print all binary numbers with n digits", I say: fine, this can be done by recursively printing all numbers with n digits and adding "" before them.
Now when someone asks me to print all numbers with n digits and adding "s" before it, I ask tell somebody else "Please print all binary numbers with n-1 digits and a "s" and 0 in front of it" because my number could start with 0.
After that I tell someone else "Please print all binary numbers with n-1 digits and a "s" and 1 in front of it" as my nubmer could also start with a 1.
This translates to code as follows:
// print all numbers with n digits
public static void printBinaryNumber(int n){
// print all numbers with n digits recursively adding ""
printBinaryNumbersRec("", n);
}
public static void printBinaryNumbersRec(String s, int n){
if(n < 0) throw new IllegalArgumentException();
if(n == 0) {
// if I should print all numbers with 0 digits and add s before them
// I just print s and am done
System.out.println(s);
return;
}
// add an additional 0 to s and print all numbers with n-1 digits
printBinaryNumbersRec(s + "0", n-1);
// add an additional 1 to s and print all numbers with n-1 digits
printBinaryNumbersRec(s + "1", n-1);
}

Why is my solution to project euler 1 not working?

I decided to just try and get the small example of only going to 10 like the example shown.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 >and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class project1 {
public static void main(String[] args) {
int three=0;
int tot3=0;
int five=0;
int tot5=0;
int total;
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
total=tot3+tot5;
System.out.println("Three's: " + tot3);
System.out.println("Five's: " + tot5);
System.out.println("Combined: " + total);
}
}
My output is as show:
Three's: 18
Five's: 15
Combined: 33
Numbers that are both multiples of 3 and 5 (like 15 for instance), are counted twice - once in each loop.
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
I think you mean
while (tot3<10) {
three += tot3; // Add this multiple of 3 to the total.
tot3+=3; // increment the "next multiple"
}
(same for 5)
Lone nebula also makes a good point - you'd need to add logic to the "5" loop to check it's not already counted in the 3 loop. The mod (%) operator can help there.
First,
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
This should be
while (three<10) {
three+=3;
tot3=tot3+three;
};
while (five<10) {
five+=5;
tot5=tot5+five;
};
Because you're concerned about when you start counting numbers above 10, not when your TOTAL of those numbers is above 10.
Secondly, your solution will count numbers that are a multiple of three and of five twice. For example, 15 will be added twice. Learn about the modulo operator, %, to come up with a solution to this (for example, not adding five to the tot5 count if five % 3 == 0)
I would recommend looking into using the modular operator to solve this problem. In java % will allow you to perform modular arithmetic. For example any multiple of 3 such as 9 % 3 = 0 while 9 % 2 = 1. It can be thought of as what remains after you divide the first number by the second. All multiples of a number modded by that number will return zero.
Keep track of your variables through the loop and you'll see the problem:
for tot3
=3
=9
=18
=30
You're keeping track of the sum, instead of tracking the multiples. This problem is partially solved in by
while(three<10)
Again, keeping track of the variable through the loop you'll see that this is wrong- it stops at 12, not 9 as you want it. Change it to
While(three<9)
//ie the last divisible number before the limit, or that limit if its divisible (in the case of 5)
All said, an infinitely more elegant solution would involve modulus and a nice little if statement. I hope this helps!
public class project1 {
public static void main(String[] args) {
int number = 0;
int total = 0;
while (number < 10) {
System.out.println(number);
if ((number % 3) == 0) {
System.out.println(number + " is a multiple of 3");
total = total + number;
}
else if ((number % 5) == 0) {
System.out.println(number + " is a multiple of 5");
total = total+number;
}
number++;
}
System.out.println("total = "+ total);
}
}
Looking at how slow I was, I did roughly the same thing as everyone else but swapped to a modulus function. The modulus function gives you the remainder(int) of dividing the first number by the second number, and can be compared to another integer. Here I have used it to check if the current number is directly divisible by 3 or 5, and add it to the total if the value is true.
Try this
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong()-1;
System.out.println((n-n%3)*(n/3+1)/2 + (n-n%5)*(n/5+1)/2 - (n-n%15)*(n/15+1)/2);
}
}
}

Categories

Resources