WHAT'S NEW?
Loading...

Java code that prints highest and the sum of numbers

The user will input the list of numbers and print the highest in java

int counter = 1;
        int number;
        int limit=0;
        int largest = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter limit number");
        limit = input.nextInt();

        System.out.println("Enter the number: ");
        number = input.nextInt();

        while(counter < limit)
        {
            System.out.println("Enter the number: ");
            number = input.nextInt();

            if(largest < number) {
                largest = number;
            }
            counter++;
        }
        System.out.println("The largest number is " + largest);
    }

The user will input the list of number and print the total sum.

 int sum=0,val,n,i;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter number of data points:");
        n=sc.nextInt();
        for(i=0;i<n;i++){
           System.out.print("Values "+i+":");
           val=sc.nextInt();
           sum+=val;
          }
        System.out.println("Total:"+sum);
    }
    static void message(String myText){
        System.out.println(myText);
    } 

Series numbers in java that will get the total sum and average of a number inputted

The program will ask the user to enter the numbers and then will get the total sum and average inputted.

static Scanner scan = new Scanner (System.in);
    public static void main(String[]args){
        int limit=0;
        int number=0;
        int counter=0;
        int sum=0;
        message("Enter how many times");
        limit = scan.nextInt();
        while (counter<limit){
            message("Please enter the following numbers");
            number = scan.nextInt();
            sum += number;
            counter++;
        }
        System.out.println(sum);
    }
    static void message(String myText){
        System.out.println(myText);
    }   

with methods

static Scanner scan = new Scanner (System.in);
    static int sum=0;
    public static void main(String[]args){     
        int limit=0;
        int number=0;
        int counter=0;     
        message("Enter how many times");
        limit = scan.nextInt();
        while (counter<limit){
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);
            counter++;
        }
        /* you can use the following loops below...
        do{
            counter++;
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);  
        }while (counter<limit);

        for (counter=0;counter<limit;counter++){
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);  
        } */
        message("Total Sum is equals to " + sum);
        message("Total Avearage is equals to " + sum/counter);
    }
    static void message(String myText){
        System.out.println(myText);
    } 
    static void getSum(int num){
        sum += num;
    }


Different ways in finding prime and non-prime numbers in java

       A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

The following source code implements different ways in finding a prime numbers.

Source code: 

<option 1>


public static void main(String[]args){
        int num = 29;
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }
        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
    

<option 2 using methods>



public static void main(String args[]){    
        checkPrime(1);  
        checkPrime(3);  
        checkPrime(17);  
        checkPrime(20);  
    }  
      static void checkPrime(int n){  
        int i,m=0,flag=0;      
        m=n/2;      
        if(n==0||n==1){  
         System.out.println(n+" is not prime number");      
        }else{  
         for(i=2;i<=m;i++){      
          if(n%i==0){      
           System.out.println(n+" is not prime number");      
           flag=1;      
           break;      
          }      
         }      
         if(flag==0)  { System.out.println(n+" is prime number"); }  
        }//end of else  
    }  

Lastly:

    public static void main(String[]args){
        get(10);   
    }
    static void get(int n){
        for (int x=0; x<=n; x++){
            for (int j=2; j<x; j++){
                if (x%j==0){
                    message(x +" is not a Prime number, because " + x + "*" + x/j + "=" + x);
                    break;
                }else{
                    message(x + " is a Prime Number");
                    break;
                }
            } 
        }
    }
    static void message(String myText){
        System.out.println(myText);
    } 

Same output:

public static void main(String[]args){
        get(10);   
    }
    static void get(int n){
        for (int x=0; x<=n; x++){
                if (x%2==0){
                    message(x +" is not a Prime number, because " + x + "*" + x/2 + "=" + x);
                    continue;
                }
                message(x + " is a Prime Number");
        }
    }
    static void message(String myText){
        System.out.println(myText);
    }   


Boolean:

public static void main(String[] args)  
    { 
         if(isPrime(11))  
         System.out.println(" true") ; 
          
         else 
         System.out.println(" false"); 
           
    } 
       // is prime or not 
       static boolean isPrime(int n) 
       { 
           // Corner case 
           if (n <= 1
               return false
          
           // Check from 2 to n-1 
           for (int i = 2; i < n; i++) 
               if (n % i == 0
                   return false
          
           return true
       }    

Programming Exercises and Solutions in Java using Loops


Programming Questions and Exercises: Loops
Question 1
Write a program to print numbers from 1 to 10.
Show the answer.
public class PrintNumbers
{
    public static void main(String[] args)
    {
        for(int i=1; i<=10; i++)
        {
            System.out.println(i);
        }
    }
}
Question 2
Write a program to calculate the sum of first 10 natural number.
Show the answer.
public class SumNumbers
{
    public static void main(String[] args)
    {
        int sum = 0;
        for(int i=1; i<=10; i++)
        {
            sum += i;
        }
        System.out.println("Sum: " + sum);
    }
}
Question 3
Write a program that prompts the user to input a positive integer. It should then print the multiplication table of that number. 
Show the answer.
import java.util.Scanner;

public class Table
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
        int num;
       
        System.out.print("Enter any positive integer: ");
        num = console.nextInt();
               
        System.out.println("Multiplication Table of " + num);
       
        for(int i=1; i<=10; i++)
        {
            System.out.println(num +" x " + i + " = " + (num*i) );
        }
    }
}
Question 4
Write a program to find the factorial value of any number entered through the keyboard. 
Show the answer.
import java.util.Scanner;

public class FactorialDemo1
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
        int num; // To hold number
        int fact = 1; // To hold factorial
       
        System.out.print("Enter any positive integer: ");
        num = console.nextInt();
      
        for(int i=1; i<=num; i++)
        {
            fact *= i;
        }
       
        System.out.println("Factorial: "+ fact);
    }
}
Question 5
Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another. (Do not use Java built-in method)
Show the answer.
import java.util.Scanner;

public class PowerDemo
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int base;
        int power;
        int result = 1;
       
        System.out.print("Enter the base number ");
        base = console.nextInt();
       
        System.out.print("Enter the power ");
        power = console.nextInt();

        for(int i = 1; i <= power; i++)
        {
             result *= base;
        }

        System.out.println("Result: "+ result);
    }
}
Question 6
Write a program that prompts the user to input an integer and then outputs the number with the digits reversed. For example, if the input is 12345, the output should be 54321.
Show the answer.
import java.util.Scanner;

public class ReverseNumber
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int number;
        int reverse = 0;
       
        System.out.print("Enter the number ");
        number = console.nextInt();
       
        int temp = number;
        int remainder = 0;
       
        while(temp>0)
        {
             remainder = temp % 10;
             reverse = reverse * 10 + remainder;
            temp /= 10;
        }

        System.out.println("Reverse of " + number + " is " + reverse);
    }
}
Question 7
Write a program that reads a set of integers, and then prints the sum of the even and odd integers.
Show the answer.
import java.util.Scanner;

public class ReadSetIntegers
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int number;
        char choice;
        int evenSum = 0;
        int oddSum = 0;
       
        do
        {
            System.out.print("Enter the number ");
            number = console.nextInt();
       
            if( number % 2 == 0)
            {
                evenSum += number;
            }
            else
            {
                oddSum += number;
            }
       
            System.out.print("Do you want to continue y/n? ");
            choice = console.next().charAt(0);
           
        }while(choice=='y' || choice == 'Y');
       
        System.out.println("Sum of even numbers: " + evenSum);
        System.out.println("Sum of odd numbers: " + oddSum);
    } 
}
Question 8
Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. 
Show the answer.
import java.util.Scanner;

public class TestPrime
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int number;
       
        System.out.print("Enter the positive integer ");
        number = console.nextInt();
       
        boolean flag = true;
       
        for(int i = 2; i < number; i++)
         {
             if(number % i == 0)
            {
                flag = false;
                break;
            }
        }

         if(flag && number > 1)
        {
            System.out.println("Number is prime");
        }
         else
        {
            System.out.println("Number is not prime");
        }
       
    } 
}
Question 9
Write a program to calculate HCF of Two given number.
Show the answer.
import java.util.Scanner;

public class FindHcf
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int dividend, divisor;
        int remainder, hcf = 0;
       
        System.out.print("Enter the first number ");
        dividend = console.nextInt();
       
        System.out.print("Enter the second number ");
        divisor = console.nextInt();       
       
        do
         {
            remainder = dividend % divisor;
           
            if(remainder == 0)
            {
                hcf = divisor;
            }
             else
            {
                dividend = divisor;
                divisor = remainder;
             }
           
        }while(remainder != 0);

        System.out.println("HCF: " + hcf);
    } 
}
Question 10
Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it should terminate. 
Show the answer.
import java.util.Scanner;

public class SumAgain
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
    
        int number1, number2;
        char choice;
       
        do
        {
            System.out.print("Enter the first number ");
            number1 = console.nextInt();
         
            System.out.print("Enter the second number ");
            number2 = console.nextInt();
           
            int sum = number1 + number2;
            System.out.println("Sum of numbers: " + sum);
       
            System.out.print("Do you want to continue y/n? ");
            choice = console.next().charAt(0);
           
            System.out.println();
           
        }while(choice=='y' || choice == 'Y');
    } 
}
Question 11
Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered. 
Show the answer.
import java.util.Scanner;


public class CountNumbers
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number,         
            countPositive = 0,
            countNegative = 0,
            countZero = 0;

        char choice;
        
        do
        {
            System.out.print("Enter the number ");
            number = console.nextInt();
       
            if(number > 0)
            {
                countPositive++;
            }
            else if(number < 0)
            {
                countNegative++;
            }
            else
            {
                countZero++;
            }
       
            System.out.print("Do you want to continue y/n? ");
            choice = console.next().charAt(0);
           
        }while(choice=='y' || choice == 'Y');
       
        System.out.println("Positive numbers: " + countPositive);
        System.out.println("Negative numbers: " + countNegative);
        System.out.println("Zero numbers: " + countZero);
    } 
}
Question 12
Write a program to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered.
Show the answer.
import java.util.Scanner;

public class FindMaxMin
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number;
        int max = Integer.MIN_VALUE;  // Intialize max with minimum value
        int min = Integer.MAX_VALUE;  // Intialize min with maximum value

        char choice;
        
        do
        {
            System.out.print("Enter the number ");
            number = console.nextInt();
       
            if(number > max)
            {
                max = number;
            }
           
            if(number < min)
            {
                min = number;
            }
       
            System.out.print("Do you want to continue y/n? ");
            choice = console.next().charAt(0);
           
        }while(choice=='y' || choice == 'Y');
       
        System.out.println("Largest number: " + max);
        System.out.println("Smallest number: " + min);
    } 
}
Question 13
Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number.
For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )
Show the answer.
public class ArmstrongNumber
{
    public static void main(String[] args)
    {
        int digit1,  // To hold first digit (Ones) of number
            digit2,  // To hold second digit (Tens) of number
            digit3;  // To hold third digit (Hundreds) of number

         for(int number = 1; number <= 500; number++)
         {
            int temp = number;
             digit1 = temp % 10;

            temp = temp / 10;
            digit2 = temp % 10;
           
            temp = temp / 10;
            digit3 = temp % 10;

             if(digit1*digit1*digit1 + digit2*digit2*digit2 + digit3*digit3*digit3 == number)
            {
                 System.out.println(number);
            }
         }
    } 
}
Question 14
Write a program to print Fibonacci series of n terms where n is input by user :
0 1 1 2 3 5 8 13 24 ..... 
Show the answer.
import java.util.Scanner;

public class FibonacciSeries
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number;  // To hold number of terms

        int firstTerm = 0,
            secondTerm = 1,
            thirdTerm;

        System.out.print("Enter number of terms of series : ");
        number = console.nextInt();

        System.out.print(firstTerm + " " + secondTerm + " ");

        for(int i = 3; i <= number; i++)
         {
            thirdTerm = firstTerm + secondTerm;
            System.out.print(thirdTerm + " ");
            firstTerm = secondTerm;
            secondTerm = thirdTerm;
         }
    } 
}
Question 15
Write a program to calculate the sum of following series where n is input by user.
1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n 
Show the answer.
import java.util.Scanner;

public class SumOfSeries
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number;  // To hold number of terms

        double sum = 0;

        System.out.print("Enter number of terms of series : ");
        number = console.nextInt();
 
        for(int i = 1; i <= number; i++)
         {
            sum += 1.0/i;
         }
       
        System.out.println("sum: " + sum);
    } 
}
Question 16
Compute the natural logarithm of 2, by adding up to n terms in the series
1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n
where n is a positive integer and input by user.
Show the answer.
import java.util.Scanner;

public class Ln2
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number;  // To hold number of terms

        System.out.print("Enter number of terms of series : ");
        number = console.nextInt();

        double sum = 0;
        int sign = 1;
       
        for(int i = 1; i <= number; i++)
         {
            sum += (1.0 * sign) / i;
            sign *= -1;
         }
       
        System.out.println("log2: " + sum);
    } 
}
Question 17
Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.
Show the answer.
import java.util.Scanner;

public class GuessMyNumber
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
       
        int number, // To hold the random number
            guess,  // To hold the number guessed by user
            tries = 0; // To hold number of tries
      
        number = (int) (Math.random() * 100) + 1; // get random number between 1 and 100
       
        System.out.println("Guess My Number Game");
        System.out.println();
       
        do
        {
            System.out.print("Enter a guess between 1 and 100 : ");
            guess = console.nextInt();
               
            tries++;
               
        if (guess > number)
        {
            System.out.println("Too high! Try Again");
        }
        else if (guess < number)
        {
            System.out.println("Too low! Try Again");
        }
        else
        {
             System.out.println("Correct! You got it in " + tries + " guesses!");
        }
       
        }while (guess != number);
    } 
}