loops - How Do I Print Out The Sum Of A Palindrome in Java? -


i having trouble printing out sum of palindrome without using ant string methods , using mathematical methods. have figured out how calculate sum , when try print out sum gives me list of of numbers. example, number 11, output 1 3 6 10 15 21 28 36 45 55 66

i want figure out how print out last number, 66, sum of numbers 1 11 , how make program print out "1 11" since numbers user inputted using scanner method. below code have included output should like. thank much!

import java.util.scanner;  public class palindrome {     public static void main (string args []) {         system.out.println("please enter integer > 0:");         scanner keyboard=new scanner(system.in);         int palindrome=keyboard.nextint();         int palindrome1=palindrome;         int num;         int sum;          int rev=0;         if (palindrome<=0) {             system.out.println("sorry, must enter integer greater zero.");         }           while (palindrome!=0) {             rev=rev*10 + palindrome % 10;             palindrome/=10;             system.out.println("the integer "+palindrome1+ " palindrome");         }         if (palindrome1==rev) {             system.out.println("palindrome");         } else {             system.out.println("not");         }         num=1;         sum=0;         while (num<=palindrome1) {             sum=sum+num;             num++;             system.out.println(sum);         }     } } 

the output should this:

please enter integer > 0: 11 integer 11 palindrome. sum of numbers 1 11 66

you use common math rule describes sum of number 0 n:

enter image description here

this simpler don't have worry accumulating values in loop.

in scenario, you'd need in order print value out compute this.

reduced, it'd be:

system.out.println((n*n) - n))/2); 

alternatively, if want print last item you're adding, print after loop has completed.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -