Posts

Showing posts from April, 2017

Find sum of digits in java

import java.util.Scanner; public class SumOfDigits{ public static void getSumOfDigits(int enteredNumber){ int remainder=0,sumUp=0; do{ remainder=enteredNumber%10;        //get remainder value enteredNumber=enteredNumber/10;  //get divided value sumUp+=remainder; }while(enteredNumber>10); System.out.println(enteredNumber+sumUp); } public static void main(String [] args){ Scanner sc=new Scanner(System.in); System.out.println("Enter the number: "); int number=sc.nextInt(); getSumOfDigits(number); sc.close();//always close the scanner. } } output: Enter the number: 123 6 output is calculated like this..1+2+3=6;

Print prime numbers in Java OR Check whether the Entered number is prime or not.

import java.util.Scanner; public class PrimeNumber{ public static void listPrimeNumbers(int input){ for(int j=2;j<=input;j++){ checkPrimeNumber(j); } } public static void checkPrimeNumber(int enteredNumber){ int count=0; for(int i=2;i<=enteredNumber;i++){ if(enteredNumber%i==0){ count++; } } /*if(count>=2){ System.out.println(enteredNumber+ " is not a prime number."); }else { System.out.println(enteredNumber+ " is prime number"); }*/ if(count System.out.println(enteredNumber); } } public static void main(String [] args){ Scanner sc=new Scanner(System.in); System.out.println("Enter the number:"); int number=sc.nextInt(); listPrimeNumbers(number); } } output: Enter the number 11 2 3 5 7 11 Note: I have created two methods, either you list the prime numbers based on your input or you can chec...

Java Program Find Second highest number in an integer array

public class FindSecondHighest{ public static void main(String [] args){ int [] numberList={9,15,6,15,18,13,11,4,12,23}; int arrayLength=0,arrayValue=0,arrayMatch=0,count=0,secondLeastValue=0;   arrayLength=numberList.length;   for(int i=0;i   arrayValue=numberList[i];//takes the first value from array;   for(int j=0;j   arrayMatch=numberList[j]; //takes the first value from array;     if(arrayValue count++;   //if the condition is matched counting starts.   }   }     //One of the way for finding seconding least number   else if(count==(arrayLength-2)){   secondLeastValue=arrayValue;   }   count=0;//resetting the counter     }   System.out.println("The second Least Value "+secondLeastValue); } } output: The second Least Value 9