Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.
Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.
Your Output should look like exactly this :
################### output example 1
Enter a number : 96374
I am calculating.....
Step 1 : 9 + 6 + 3 + 7 + 4 = 29
Step 2 : 2 + 9 = 11
Step 3 : 1 + 1 =2
Finally Single digit in 3 steps !!!!!
Your answer is 2.
I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(n);
}
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
}
The output understandably duplicates the code given by the input from the user.
I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.
Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.
What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.
This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
printSingleDightSum(n);
}
public static void printSingleDightSum(int N) {
int sum = 0;
int num = N;
while(num !=0 ){
int a = num%10;
sum + = a;
num = num/10;
}
if(sum < 10) {
System.out.println('single digit sum is '+sum);
return;
} else {
printSingleDightSum(sum);
}
}
Here is the code, I will add comments and an explanation later but for now here is the code:
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.println("################### output example 1");
System.out.print("Enter number: ");
final int n = new Scanner(System.in).nextInt();
System.out.print("\nI am Calculating.....");
sumSums(n, 1);
}
public static int sumSums(int n, int step) {
System.out.print("\n\nStep " + step + " : ");
final int num = sumDigit(n);
System.out.print("= " + num);
if(num > 9) {
sumSums(num, step+1);
}
return num;
}
public static int sumDigit(int n) {
int modulo = n % 10;
if(n == 0) return 0;
final int num = sumDigit(n / 10);
if(n / 10 != 0)
System.out.print("+ " + modulo + " ");
else
System.out.print(modulo + " ");
return modulo + num;
}
}
Related
Everything runs fine in my Java code except at the very end of the code. So basically I can't figure out how to print out the User's Number if it is the same. For example I am prompt the User for a starting number and an ending number (integers). So say the user enters in the same integer "10" for starting number and "10" for ending number. I want the output to only be "10" to be printed only just once. I've tried everything I can think of with trying While Loop, Do-While Loop, and For Loops but I just can't figure it out?
------------------------JAVA CODE BELOW-------------------------------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------OUT PUT BELOW -----------------------------------------------------
Now I'll print whatever numbers you'd like!
Give me a starting number:
10
Give me an ending number:
10
I counted your range of numbers:
10
11
10
----jGRASP: operation complete.
You could restructure your code as follows:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
You can use for loop:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
So you are either counting up, down or there's just one.
So
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
Or put a break in the middle of a for loop. Also there's +=, and a few things we can make more conventional.
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
The issue is in your first two while loops where you are using ">=" and "<=". You can remove "=" from the condition.
However you can improve your code as suggested in other comments.
I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}
i'm having some trouble recursively adding integers in java from 1^2 to n^2.
I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:
return (int) (Math.pow(n, 2));
but i can't incorporate the calling of the recurvMath method correctly in order for it to work.
Any help would be appreciated. Thanks!
In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.
You want to sum all integers from 12 to n2. The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:
The sum of all integers from 12 to (n-1)2, plus n2
That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.
So, now we have to take care of the special base case, 0:
When n is 0, the sum is 0.
So let's let recurvMath(n) be the sum of all integers from 12 to n2. Then, the above directly translates to:
recurvMath(n) = recurvMath(n-1) + n2
recurvMath(0) = 0
And this is pretty easy to implement:
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
} else {
return recurvMath(n-1) + (n * n);
}
}
Note I've chosen to go with n * n instead of Math.pow(). This is because Math.pow() operates on double, not on int.
By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0), or check for a negative input and throw e.g. IllegalArgumentException, or even use Math.abs() appropriately and give it the ability to work with negative numbers.
Also, for completeness, let's take a look at the problem in your original code. Your problem line is:
recurvMath((int) ((int) n+Math.pow(n, 2)))
Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12). Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.
instead of saying:
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
i instead said:
return (int) ((Math.pow(n, 2)+recurvMath(n-1)));
Try this
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 1){
return 1;
}//end if
// More simplified solution
return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes
}//end method
}//end class
I have searched the site, and though it has been answered many times, I still have one more question.
I have the code to do the factorial with recursion. I am just having trouble with the easiest part of it.
When printing, my project requires that it should print:
4! is equal to 4 x 3 x 2 x 1 = 24
How do I get a for loop, or recursive way to get the "(4 x 3 x 2 x 1)" to work with any value of n?
import java.util.Scanner;
public class Factorial
{
public static void main(String args[])
{
System.out.println("Enter an integer:");
Scanner keyboard= new Scanner(System.in);
int num=keyboard.nextInt();
System.out.print(num+ "!"+ " is equal to ");
Print(num);
System.out.print(FactorialCalc(num));
}
public static double FactorialCalc(int number)
{
double result;
if(number<=1)
{
result= 1;
return result;
}
else
{
return result= number * FactorialCalc(number-1);
}
}
public static void Print(int n)
{
for(int i=n; i<=0;i--)
{
System.out.print(n + 'x' + (n-1));
}
}
}
public static void Print(int n) {
for (int i = n; i > 0; i--) {
System.out.print(i);
if (i == 1) {
System.out.print("=");
continue;
}
System.out.print("x");
}
}
And the output:
Enter an integer:
4
4! is equal to 4x3x2x1=24.0
A very simple solution using a for loop will be
int fact=1;
for(int i=1;i<n;i++)
fact=fact*i;
Your code works, you only forgot one thing:
Which is the variable used for counting the iterations of the for loop in the Print method? What are its values inside the loop?
public static void Print(int n)
{
for(int i=n; i<=0;i--) //i minor or equal 0? When does the loop need to finish?
//What happens if you multiply something with 0?
{
System.out.print(n + 'x' + (n-1));
}
}
Try to get it on your own, but if you can't...
...the problem is that you're printing n instead of i. In the loop, the variable that is decremented is i via i--. It starts from num and gets smaller and smaller... That's what you need to print!
Changhe the print to:
System.out.print(i + "x");
Your task is to get rid of the last printed x! ;D
As per the loop condition, your loop must stop when i reaches 1 to have
(num) x (num-1) x .. x 2 x 1 (no 0!!)
So the condition will be for(int i = n; i >= 1;i--)
You could incorporate printing the list of multiplied values directly into the recursion rather than adding a looping print. Put appropriate print() statements in both the if and else clauses of your recursion. For the former, just print "1 = ". For the latter, print number + " x ".
You don't actually need the local variable result. I'd also recommend using Java conventions regarding capitalization: method names should begin with a lower case letter, upper case indicates a class or interface. Finally, I changed the return type to long because factorials are integer-based, even though they can quickly get big.
import java.util.Scanner;
public class Factorial {
public static long printFactorial(int number) {
if(number <= 1) {
System.out.print("1 = ");
return 1;
} else {
System.out.print(number + " x ");
return number * printFactorial(number-1);
}
}
public static void main(String args[]) {
System.out.print("Enter an integer: ");
Scanner keyboard= new Scanner(System.in);
int num=keyboard.nextInt();
System.out.print(num + "! is equal to ");
System.out.println(printFactorial(num));
}
}
Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).