# Count at the Cow barn Java Program Solution

#### 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

#### Solution

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);
}
}
}
Scroll to Top
Scroll to Top