Could someone please explain how this while loop works? - java

I do not understand how the while loop dissects the information. Could someone please explain how it works?
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //<-- ??
sum += rem; //<-- ??
number = number/10; //<-- ??
}
return sum;
}

The key to understanding this code is the use of two operators - the remainder operator % and the integer division operator /.
The % operator produces the remainder from dividing by its right-hand side. In case of % 10 this means "get the last decimal digit of the number"
The / division operator discards the remainder, producing an integer result. Dividing an integer by zero discards its last digit.
For example, if you start with n = 1234 and do
int d = n % 10;
int r = n / 10;
then d would be 4 and r would be 123.
At this point it should be clear how the loop proceeds to termination, and how it accumulates the sum of number's digits as it goes through the iterations.

Filled in the comments where you noted you had trouble
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //rem now contains the remainder of the number / 10
//Keep in mind, number % 10 will give you the rightmost digit in your number
sum += rem; //add the remainder to your running total
number = number/10; //divide your number by 10 so you can find
//the next right most digit in your number
}
return sum;

This example tries to sum all the digits of a number % is used to get the last digit on each while loop and divided by 10 is done to reduce the number and sum is added for all digits see the inline comment by me
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //remainder after division by 10 e.g 12%10=2
sum += rem; //sum=sum+rem //<-- ??
number = number/10;//reduce one number by dividing to 10 //<-- ??
}
return sum;
}

Let's step through the code with an example. Let's call sumDigits(1234).
The first time through the while loop, number equals 1234. rem = 1234 % 10, which evaluates to rem = 4 as the remainder from dividing 1234 by 10 is 4 (which is the rightmost digit in number). sum += rem evaluates to sum += 4, so the value of sum is 4. Since number is an int, storing the value of itself divided by 10 results in 123 being stored in number.
The second time through the while loop, number equals 123. rem = 123 % 10, which evaluates to rem = 3 as the remainder from dividing 123 by 10 is 3 (which is the rightmost digit in number). sum += rem evaluates to sum += 3, so the value of sum is 7, since sum was equal to 4 at the end of the last loop iteration. Since number is an int, storing the value of itself divided by 10 results in 12 being stored in number.
Repeat this two more times, and you'll end up with number equalling zero (as int(1/10) = 0), therefore, you'll exit the loop and sum will contain the sum of the digits in number.

Related

Java Basics - Extract digits from a number

I'm new to Java, so still trying to figure out the syntax and code execution,
I'm working on a very simple algorithm which is basically to return/print true or false statement if a number is divisible by the sum of its digits.
public class Main {
public static void main(String[] args) {
divisableNumber();
}
static void divisableNumber() {
int num = 2250;
int sumOfDigits = 0;
while (num > 0) {
System.out.println(num);
int remainder = num %10 ;
sumOfDigits += remainder;
System.out.println("line17");
System.out.println(sumOfDigits);
num = num /10;
}
System.out.println(num);
// if(num % sumOfDigits == 0) {
// System.out.println( num);
// } else {
// System.out.println(num + "is not divisable by sum of digits");
// }
}
//*****Explanation*********
// java divides by 10 without remainder.
// Hence, can see that with each iteration number is losing its unit digit( it happens end of each loop line21)
// basically with each iteration we are checking what is the remainder of the input divided by 10
// Eventually, we are adding the remainder ( which is the unit digit at each iteration)
}
``
I don't understand why the loop zeros out the variable and how to overcome it ( i could have written another variable inside the loop , but it seems not clean ).
Can anyone help ?
[enter image description here][1]
[1]: https://i.stack.imgur.com/rZbOW.png
Your code prints 0 every time since it divides the number to 10 until it becomes 0 inside the while loop. Remember that any positive number below 10 divided by 10 gives the result 0 in Java.
You calculated the sum of digits correctly but did not check if it divides the number correctly. In order to achieve that, you need to store a copy of number at the start and check if it is divisible by sumOfDigits.
You can achieve the solution with the following code, it is very similar but structured a little better.
class Main
{
// Function to check if the
// given number is divisible
// by sum of its digits
static String divisableNumber(long n)
{
long temp = n; // store a copy of number
// Find sum of digits
int sum = 0;
while (n != 0)
{
int k = (int) n % 10; // get remainder of division of 10
sum += k; // add digit sum
n /= 10; // divide number by 10
}
// check if sum of digits divides n
if (temp % sum == 0)
return "YES";
return "NO";
}
// This is where the execution begins always (main function)
public static void main(String []args)
{
long n = 123; // better to declare number here and give it as a parameter to function
System.out.println(isDivisible(n)); // print the result of divisible or not
}
}

How does this program to calculate Armstrong numbers between two intervals work step by step?

class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
How does this program work? It would be very helpful. Program to find Armstrong between two intervals? Can someone explain step by step? Help me out.
Steb-by-step Explanantion
Initialize the start and end of the interval with 999 and 9999
You can change these numbers but ensure that low is always lesser than high:
int low = 999;
int high = 99999;
for (int number = low + 1; // Create a variable number and assign it one number greater than low
number < high; // This loop should keep repeating until number is less than high(end of the interval)
++number // After each repetition, increment the value of number by 1
) {
Create a variable digits to store the number of digits in number.
For example, if number is 100, this will be later set as 3 as the algorithm proceeds:
int digits = 0;
Create a variable result that will store the sum of powers of numbers:
int result = 0;
Copy the value of number to a local variable originalNumber because it has to be modified:
int originalNumber = number;
The logic of calculating number of digits in a number is keep dividing it by 10 until the number is 0.
Every time you divide any number by 10, the last digit is stripped out. So every time the last digit is stripped out, increment digit by 1 (digit++)
// number of digits calculation
while (originalNumber != 0) // Continue this while loop till originalNumber is not 0
{
originalNumber /= 10; // Divide the number by 10. Dividing a number by 10 removes its last digit.
++digits; // One digit was removed in the above step, which means it has to be counted, so increment digit by 1
}
// For example, for originalNumber = 423,
// 423 / 10 = 42 : digits = 1 (first loop)
// 42 / 10 = 4 : digits = 2 (second loop)
// 4 / 10 = 0 : digits = 3 (third loop)
// Now originalNumber has become 0, so the while loop condition originalNumber != 0 will be false and the loop will stop.
// Now we have digits = 3, which is the number of digits in 423
// When program reaches here, digits will have the number of digits in the
// number "originalNumber"
Copy number again to originalNumber because we want to modify the number
again and originalNumber has become 0 because of the digit counting loop above:
originalNumber = number;
An Armstrong number is a number which is equal to the sum of digits to the power of its number of digits.
e.g.: in 153, (1^3) + (5^3) + (3^3) = 153. We are obtaining the cube of each digit(1, 5, 3) because 153 has 3 digits 1, 5, 3.
If it was say 50, we would check ( 5^2 + 0^2) because 50 has 2 digits (50 is not Armstrong, because 25 + 0 = 25 which is not equal to 50)
We saw above dividing a number by 10 removes the last digit (423 / 10 = 42)
Similarly, if we only want this last digit, we can get it by modulus 10 (% 10): (423 % 10 = 3) (42 % 10 = 2) (4 % 10 = 4)
// Let's assume originalNumber is 153
while (originalNumber != 0) // Same as above, keep looping till the originalNumber is not 0(i.e. all digits have been removed)
{
Extract the last digit to remainder, (for 153: 153 % 10 = 3) (for 15: 15 % 10 = 5)
int remainder = originalNumber % 10;
Now we have the last digit, we need to raise this digit to the number of
digits i.e. 3(for 153): (3^3) = 27. We do this using Math.pow(3, 3). Add this number to result. In the end after each loop's number's power is added, at the end of the loop, result will contain their sum:
result += Math.pow(remainder, digits);
originalNumber /= 10; // Remove the last digit (same as above, for 153: 153 / 10 = 15)
// After this line finishes, one rightmost digit will be removed, this will keep
// happening till originalNumber = 153 becomes 15, then 1, then 0.
// When originalNumber is 0, loop stops and we will have the total sum in result
}
For an Armstrong number like 153, result will also contain 153. For a non-Armstrong number it will contain something else.
if (result == number) // For 153, both will be equal.
System.out.print(number + " "); // This will only execute if result is equal to number, or in other words, only if the number is Armstrong
}
Improvements
As per single responsibility principle, each function or class must exactly do one thing. You have a monolithic main() method that:
Defines the interval
Counts the digit of each number in the interval
Calculate the sum of powers of digits
Check if number is Armstrong and print it.
I would prefer breaking down each operation to a separate method, so that it improves readability and maintainability while respecting single-responsibiliy principle:
class Armstrong {
public static int countDigits(int number) {
int digits = 0;
while (number != 0) {
number /= 10;
++digits;
}
return digits;
}
public static int digitPowerSum(int number, int power) {
int result = 0;
while (number != 0) {
int remainder = number % 10;
result += Math.pow(remainder, power);
number /= 10;
}
return result;
}
public static boolean isArmstrong(int number) {
int digits = countDigits(number);
int sum = digitPowerSum(number, digits);
return sum == number ; // will return true if both numbers are equal else false
}
public static ArrayList<Integer> armstrongNumbersBetween(int low, int high) {
ArrayList<Integer> numbers = new ArrayList<>();
for(int number = low + 1; number < high; number++) {
if (isArmstrong(number)) {
numbers.add(number);
}
}
return numbers;
}
public static void main(String[] args) {
int low = 999, high = 99999;
ArrayList<Integer> numbers = armstrongNumbersBetween(low, high);
for(int number : numbers) {
System.out.print(number + " ");
}
}
}
Here, each method does exactly one thing and this helps in better reusability. You just have to call the required methods to perform a specific operation.
If something is unclear, let me know.

Java Split Number into Digit's Algorithm

package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]

Question about adding three digits with each other in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.
You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}
In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.
The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.
Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)
Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}

print two digit numbers which are less than or equal to 56 and the sum of digits is greater than 10 JAVA

why the following method doesn't work for printing two digit numbers which are less than or equal to 56 and the sum of digits is greater than 10 in JAVA
for (int i = 10; i <= 99; i++) {
String str = Integer.toString(i);
int sum = (str.charAt(0) + str.charAt(1));
if (sum > 10 && sum<=56) {
System.out.println("The first operation " + sum);
}
}
The third line: int sum = (str.charAt(0) + str.charAt(1)); is one of the problems. When i is 10, str.charAt(0) evaluates the the character 1 which has ascii value 49 and str.charAt(1) evaluates to the character 0 which has ascii value 48 producing a sum of 97 instead of the desired 1.
Instead you could use the modulus operator to strip-off the digits as needed. For example: int sum = ( i / 10 ) + (i % 10);.
*also, the range of i in your for loop should be adjusted as other users have commented.
Since you know any number greater than 56 won't pass your criteria, you need to change your loop to go from 10 to 56. Thus, you can exclude the second part of the if statement. Change the for loop to:
for (int i = 10; i <= 56; i++) {
and your if statement to:
if (sum > 10) {

Categories

Resources