Computer Science, asked by moumitakumari27, 4 months ago

write a program in java that reads some numbers until -1 is pressed and prints the maximum of the input numbers​

Answers

Answered by atrs7391
1

package com.company;

import java.util.Scanner;

public class Main

{

   public static void main(String[] args)

   {

       Scanner sc = new Scanner(System.in);

       int infi = 1;

       long max = 0;

       while (infi!=-1) {

           System.out.println("Enter a number: ");

           long n = sc.nextLong();

           if (n==-1) {

               infi = -1;

           }

           else if (n>max){

               max = n;

           }

       }

       System.out.println("The maximum of all the numbers = "+max);

   }

}

Answered by anindyaadhikari13
1

Answer:

This is the Java program to print the maximum of entered number until -1 is entered.

import java.util.*;

public class Java {

 public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

    int max=Integer.MIN_VALUE, a;

    while(true)  {

       System.out.print("Enter a number: ");

       a=sc.nextInt();

       if(a==-1)

          break;

      if(a>max)

          max=a;

    }

    System.out.println("Largest number is: "+max);

    sc.close();

 }

}

Explanation:

  • The Integer.MIN_VALUE stores the minimum value in the integer range. We assume that the largest number is Integer.MIN_VALUE. Then, we will repeatedly ask the user to enter a number. If the number is greater than max, we will store the number in max and max value gets updated.
  • If the user enters -1, the loop is terminated by break statement.

See the attachment for output .

Attachments:
Similar questions