Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

For second largest ,how can i find?

2 Answers

0 votes
import java.util.Scanner;

public class SecondLargest 
{
	public static void main(String [] args)
	{
		int largest = 0, secondlargest = 0;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter the number :");
		int n=sc.nextInt();
		int s = 0, t;
		while(n!=0)
		{
			t=n%10;
			if(largest<t)
			{
				secondlargest = largest;
				largest=t;
			}
			else if(secondlargest<t)
			{
				secondlargest=t;
			}
	        s = secondlargest;
			n=n/10;
		}
		System.out.print("Second Largest digit : "+s);
	}
}

 

answered Apr 2 by Ranju Kumari

I think you can do it without using an extra variable s.

import java.util.Scanner;

public class SecondLargest
{
     public static void main(String []args)
     {
        int largest = 0, secondlargest = 0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number :");
        int n=sc.nextInt();
        int t;
        while(n!=0)
        {
            t=n%10;
            if(largest<t)
            {
                secondlargest = largest;
                largest=t;
            }
            else if(secondlargest<t)
            {
                secondlargest=t;
            }
            n=n/10;
        }
        System.out.println("Second Largest digit : "+secondlargest);
     }
}

 

0 votes

My code will provide zero if there is no second highest value (num is of only one digit).

For all other case it will provide the second highest value as output.

#include<iostream>

using namespace std;

int main()
{
	cout << "Enter Num: ";
	
	int num;
	cin >> num;
	
	int largest = 0;
	int secondLargest = 0;
	while(num>0)
	{
		int temp = num % 10;
		
		if(largest<temp)
        {
            secondLargest = largest;
            largest=temp;
        }
        else if(secondLargest<temp)
        {
            secondLargest=temp;
        }
		num/=10;
	}
	cout << secondLargest << endl;
	return 0;
}

 

answered Apr 17 by vipulchasta

Please log in or register to answer this question.

...