Count at the Cow barn Program in java



Question:

Tom was standing outside a cow barn. A group of men was appointed to take care of the cattle. All Tom could see was’ heads and ‘n’ feet. Write a program to display the number of cows and the number of men found.

Input consists of the heads as the first input and feet as the second input. If sum of number of cows and number of men is not equal to heads, then display “Invalid Input”.

Sample Input 1

3

10

Sample Output 1

Number of Cows: 2

Number of Men: 1

Sample Input 2

10

44

Sample Output 2
Invalid Input

CODE:

import java.util.*;


     public class Main{
         
         public static void main (String[] args) {
             Scanner sc = new Scanner(System.in);
             int hd = sc.nextInt();
             int lg = sc.nextInt();
             int cow=hd, men=0;
             if(lg>(hd*4))
            {
                System.out.println("Invalid Input");
            }
            else if(lg==(hd*4)){
                System.out.println("Number of Cows: "+hd);
                System.out.println("Number of Men: 0");
           }
            else{
                while(cow>0)
                {
                    if(lg<cow*4){
                        cow--;
                        lg-=2;
                        men++;
                    }
                    else if(lg==cow*4){
                        break;
                    }
                }
                System.out.println("Number of Cows: "+cow);
                System.out.println("Number of Men: "+men);
            }
        }
    }

 

Tags:

java interview programs for experienced | java interview programs for freshers pdf | java coding questions for 5 years experience | java programming interview questions – geeksforgeeks |
java programming interview questions and answers for freshers | java programs asked in interview for automation tester | java coding interview questions for experienced professionals
| java coding interview questions pdf

Previous
Next Post »