Loop to Find Sum of Digits - java

I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}

You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------

Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)

because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {

//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}

if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.

Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class

Related

How do you add digits to the front of a number?

How would you add digits to the beginning of a number (left hand side) without using a string?
I know that if you try this:
(Some psuedo code)
Let's say I try to make number 534
int current = 5;
int num = 0;
num = (num*10) +current;
then
int current = 3;
int num = 5
num = (num*10) + current;
would make: 53
then
int current = 4;
int num = 53;
num = (num*10) + current;
would make 534
It would keep adding numbers to the right hand side of the number.
However, I am a bit confused on how you would do the opposite. How would you add numbers on the left, so instead of 534 it makes 435?
int num = 123;
int digits = 456;
int powerOfTen = (int) Math.pow(10, (int) (Math.log10(digits) + 1));
int finalNum = digits * powerOfTen + num;
System.out.println(finalNum); // Output: 456123
The number of digits in digits is calculated using Math.log10 and Math.pow, and then used to determine the appropriate power of 10 to multiply digits by. The result is then added to num to obtain the final number with the added digits.
Multiply the digit to add by increasing powers of 10 before summing with the current number.
int num = 0, pow = 1;
num += 5 * pow;
pow *= 10;
num += 3 * pow;
pow *= 10;
num += 4 * pow; // num = 435 at this point
pow *= 10;
// ...
An example without the use of libraries could be this:
First, get the number of digits. Then calculate the number you have to add to your initial number. The sum of these two numbers is the result you're after.
private int addNumberInFrontOf(int initialNumber, int initialNumberToAdd){
int numberOfDigits = getDigits(initialNumber);
int getActualNumberToAdd = getNumberToAdd(initialNumberToAdd, numberOfDigits);
return initialNumber + getActualNumberToAdd;
}
To calculate the number of digits, you can count the number of times you can divide the initial number by 10. Notice you need to use a do-while loop because otherwise the loop wouldn't be triggered if your initial number was 0.
private int getDigits(int number) {
int count = 0;
do {
number = number / 10;
count += 1;
} while (number != 0);
return count;
}
Calculate the number you need to add to your initial number by multiplying the initial number to add with the magnitude. The magnitude simply is 1 multiplied with 10 for every digit in the initial number.
private int getNumberToAdd(int number, int numberOfDigits) {
int magnitude = 1;
for (int i = 0; i < numberOfDigits; i++) {
magnitude *= 10;
}
return number * magnitude;
}
For example, addNumberInFrontOf(456, 123) would result in 123456. Of course, this method won't work when you use positive and negative numbers combined.
You can use String for example.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : Integer.parseInt(cur + String.valueOf(num));
}
In case you want to avoid working with String, you can use recursion instead.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : addLeft(cur, num / 10) * 10 + num % 10;
}
You can use some math, in python
import math
def addLeft(digit, num):
return digit * 10 ** int(math.log10(num) + 1) + num
Note that this might fail for very large numbers on account of precision issues
>>> addLeft(2, 100)
2100
>>> addLeft(3, 99)
399
>>> addLeft(6, 99999999999999)
699999999999999
>>> addLeft(5, 999999999999999)
50999999999999999 (oops)

How to can I sum some numbers in a random series?

I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:
// Variables
int numRandom = 0, less10, equal15, more70;
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
numRandom = (int) (99 * Math.random());
txtS.append(numRandom + "\n");
}
You could just store the values directly and create variables for each case.
This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).
int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
sumLessThanTen += numRandom;
countLessThanTen++
}

Why sum of odd numbers from 1 to the number entered doesn't match what was expected?

import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
i += 2;
sum +=i;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
}
I wrote this code to sum up the odd numbers from 1 to a number entered.
Now, when I entered 8, I got the output as 24, against the desired output 16.
Can you tell me what went wrong?
You are incrementing the variable before performing summation .
while (i<=num) {
sum +=i;
i += 2;
}
You should add i to sum before adding to 2 to i. Thus, once i goes past num, the while loop will no longer execute.
import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
// add i to sum before adding 2 to i
sum += i;
i += 2;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
Lets debug the code together:
after taking the number it would go to i<=num that while condition. Great, Then instead of getting sum it would + again 2 which cause 3. So what's happen? First case, 1 is not added before and first iteration value 1 is lose. That means whenever, you enter the loop. It goes increases before adding the previous value. So, rewrite the code this way:
while (i<=num) {
sum +=i;
i += 2;
}
You may use for instead:
for(int i=1;i<=num;i+=2){
sum +=i;
}
You're incrementing i before you sum it, instead of afterwards:
while (i <= num) {
sum +=i;
i += 2;
}
It's worth noting, though, that these kind of issues, where the loop variable is incremented by a constant, are often more convenient to write with a for loop:
for (int i = 1; i <= num; i += 2) {
sum += i;
}
Or better yet, if you're using Java 8, by collecting a stream:
int sum = IntStream.rangeClosed(1, num).filter(i -> i % 2 != 0).sum();
The reason why the result for your example with N = 8 gives 24 is because when i reaches value 7, the loop is continued and is added the value 9 to your sum too and you forget to add the first odd number: 1, because you start over from adding directly 3 to your sum.
You can either switch the statements between each other, either use a for loop instead of while:
for(int i = 1; i <= num; i += 2) {
sum += i;
}

Counting by factors of two with a while loop?

I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.

Split number into several numbers

I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.

Categories

Resources