In: Computer Science
Farmer Ben counted that there are 90 heads and 320 legs among the chickens and dogs on his farm. Assuming that every chicken has 2 legs and every dogs has 4 legs, how many chickens and how many cows is on his farm?
C = chickens
D = dogs
Number of animals =90
Total amount of legs = 320
90 – D = C
4d+2(90-D)=320
Answer: Chicken = 20 Dog =70
Write a C++ Program that prompt the user to entered the amount of heads and number of legs that Farmer Ben counted and output the amount of chicken and dogs in his farm. Note: Output an error message if the user entered an invalid number (a negative number, 0, or a character). Output a separate error message if the user entered a number that does not add up. The numbers given above in the first paragraph is just an example, I want you allow the user to input their own number.
Answer: Hey dear student finds the solution of your query if you have any doubt feel free to ask. Thanks!!
this C++ program asks for legs and heads and validates both if not valid output an error message and exit from the program. Otherwise, the process continues. If dog == 0 then output "There is no solution" else print both dogs and chickens.
C++ Code:
#include<iostream>
using namespace std;
int main()
{
int heads,legs,dogs,chickens,total;
cout<<"Enter number of heads: ";
cin>>heads; //ask from user for heads
if(heads<=0 && cin.fail()) //validate heads
{
cout<<"Invalid Number!!"; //output error message
exit(0);
}
cout<<"Enter number of legs: ";
cin>>legs; //ask for legs from user
if(legs<=0 && cin.fail()) //validate legs
{
cout<<"Invalid Number!!";
exit(0);
}
//find number of dogs and number of chickens
for(int i= 0;i<=heads;i++)
{ //loop 0 to number of heads
chickens = i;
dogs = heads-chickens;//calculate dogs
total = 4*dogs + 2*chickens; //count legs
if(total == legs) //if true
break;
}
if(dogs==0)//if true
{cout<<"There is no solution.";
}
else
{
cout<<"Dogs: "<<dogs<<endl; //print both dogs and
chickens
cout<<"Chikens: "<<chickens;
}
return 0;
}