Friday, 14 June 2024

Find Quadrant in C++

Problem Description

Given coordinates of a point (x,y) in 2D plane, Find in which quadrant does this point lie.

Input format
First line contains 2 space separated real numbers - x coordinate, y coordinate.

Output format
Print 1, 2, 3 or 4 depending on in which quadrant does the point lie.

Sample Input 1
-5.5 2

Sample Output 1
2

Explanation
The x-coordinate is negative and the y-coordinate is positive which means the point lies in the 2nd quadrant.

Sample Input 2
1 -1

Sample Output 2
4

Explanation
The x-coordinate is positive and the y-coordinate is negative which means the point lies in the 4th quadrant.

Constraints
-100 < x,y < 100

Neither x nor y is 0.

Solution:
To determine which quadrant a point \((x, y)\) lies in based on its coordinates, we follow the Cartesian coordinate system rules:

- **Quadrant 1**: \( x > 0 \) and \( y > 0 \)
- **Quadrant 2**: \( x < 0 \) and \( y > 0 \)
- **Quadrant 3**: \( x < 0 \) and \( y < 0 \)
- **Quadrant 4**: \( x > 0 \) and \( y < 0 \)

Given these rules, we can write a C++ program that reads the coordinates from the input, checks which conditions the coordinates meet, and prints the corresponding quadrant number.

Here is the C++ code to accomplish this task:

#include <iostream>
using namespace std;

int main() {
double x, y;
cin >> x >> y;
if (x > 0 && y > 0) {
cout << 1 << endl;
} else if (x < 0 && y > 0) {
cout << 2 << endl;
} else if (x < 0 && y < 0) {
cout << 3 << endl;
} else if (x > 0 && y < 0) {
cout << 4 << endl;
}
return 0;
}


### Explanation
1. **Input Handling**: The program reads two real numbers \( x \) and \( y \) from the standard input.
2. **Condition Checks**:
- It checks whether the point lies in Quadrant 1 by verifying if both \( x \) and \( y \) are positive.
- It checks for Quadrant 2 by verifying if \( x \) is negative and \( y \) is positive.
- It checks for Quadrant 3 by verifying if both \( x \) and \( y \) are negative.
- It checks for Quadrant 4 by verifying if \( x \) is positive and \( y \) is negative.
3. **Output**: Depending on which condition is met, the program prints the corresponding quadrant number.

### Sample Run
#### Sample Input 1
-5.5 2
#### Sample Output 1
2
#### Sample Input 2
1 -1
#### Sample Output 2
4

This program correctly determines the quadrant for any given point in a 2D plane within the specified constraints.

No comments:

Post a Comment