March 11, 201313 yr In class we've been working on loop statements and as part of my homework (this is the only part I don't have done) is to be able to take the odd numbers within a number (so say the number is 32677, take the odd numbers) and add them together (so it would be 17). Maybe I'm just having a brain fart, but I just can't think of how to write this code. Thanks! Finally on here to update that I have officially quit! It's been fun.[hide=Signature]R.I.P Billy Mays and <3 My Friend C.D.S 7/8/09 <360,816th to 99 Fletching 03/07/09|220,309th Person to be Able to Kill Dusties | 10 Year Cape on 12/20/14[/hide]
March 11, 201313 yr Last time you posted, I showed you how to isolate the last digit in an integer. So you want to remove the last digit from the integer each iteration, check if it's odd, and add it to the sum if it is. while(input > 0){ t = input%10; if(t%2==1){sum+=t;} input /= 10; } That's the necessary part in C++. You should be able to figure it out from there.
March 11, 201313 yr That is actually a neat way of doing it, Meredith. The Java equivalent of the above:int number=1234567,sum=0,trimmed; while(number!=0){ sum+=(trimmed=number%10)%2==1?trimmed:0; number/=10; } System.out.println(sum); Isn't a whole lot different then yours. :P. He could, however, use Scanner in which his entire project is only a few lines:int sum=0,trimmed; Scanner number=new Scanner(System.in).useDelimiter(""); System.out.print("Enter an integer: "); while(number.hasNextInt()){sum+=(trimmed=number.nextInt())%2==1?trimmed:0;} System.out.println("The sum of the odd integers is: "+sum);Gets the input and outputs the sum. :P.
March 11, 201313 yr Author Thanks for the help guys, I appreciate it! Finally on here to update that I have officially quit! It's been fun.[hide=Signature]R.I.P Billy Mays and <3 My Friend C.D.S 7/8/09 <360,816th to 99 Fletching 03/07/09|220,309th Person to be Able to Kill Dusties | 10 Year Cape on 12/20/14[/hide]
Create an account or sign in to comment