- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Number of animals in a zoo from given number of head and legs in C++
We are given a total number of heads and legs in a zoo and the task is to calculate the total number of animals there in the zoo with the given data. In the below program we are considering animals to be deer and peacocks.
Input −
heads = 60 legs = 200
Output −
Count of deers are: 40 Count of peacocks are: 20
Explanation −
let total number of deers to be : x Let total number of peacocks to be : y As head can be only one so first equation will be : x + y = 60 And deers have 4 legs and peacock have 2 legs so second equation will be : 4x + 2y = 200 Solving equations then it will be: 4(60 - y) + 2y = 200 240 - 4y + 2y = 200 y = 20 (Total count of peacocks) x = 40(Total count of heads - total count of peacocks)
Input −
heads = 80 Legs = 200
Output −
Count of deers are: 20 Count of peacocks are: 60
Explanation −
let total number of deers to be : x Let total number of peacocks to be : y As head can be only one so first equation will be : x + y = 80 And deers have 4 legs and peacock have 2 legs so second equation will be : 4x + 2y = 200 Solving equations then it will be: 4(80 - y) + 2y = 200 320 - 4y + 2y = 200 y = 60 (Total count of peacocks) x = 20(Total count of heads - total count of peacocks)
Approach used in the below program is as follows
Input the total number of heads and legs in a zoo
Create a function to calculate the count of deers
Inside the function, set count to ((legs)-2 * (heads))/2
Return the count
Now, calculate the peacocks by subtracting the total number of deers from the total number of heads in the zoo.
Print the result.
Example
#include <bits/stdc++.h> using namespace std; // Function that calculates count for deers int count(int heads, int legs){ int count = 0; count = ((legs)-2 * (heads))/2; return count; } int main(){ int heads = 80; int legs = 200; int deers = count(heads, legs); int peacocks = heads - deers; cout<<"Count of deers are: "<<deers<< endl; cout<<"Count of peacocks are: " <<peacocks<< endl; return 0; }
Output
If we run the above code we will get the following output −
Count of deers are: 20 Count of peacocks are: 60
Advertisements