9. X and Y Axis Problem

Easy ⏱️ 10 min

Problem Statement

Get a 2 input from user, first one for count of step and 2nd one for direction (only right and left). Find the position after moving by left or right by the number of steps

Input Format:
Enter an Integer and Character as input.
Output Format:
Print the output as two integers in the following format : (x,y)
Constraints:
-10^15 <= INPUT <= 10^15
Sample Input 1:
10 L
Sample Output 1:
(-10,0)
Sample Input 2:
10 R
Sample Output 2:
(10,0)
🗺️ Understanding 2D Coordinate Systems
📊 The Cartesian Coordinate System Explained

What is a 2D coordinate system?

A coordinate system lets us describe positions using two numbers: (x, y)

Y-axis (vertical) ↑ | (0,5)| | (-5,0) ←———————(0,0)———————→ (5,0) Left Origin Right | (0,-5)| | ↓

Key components:

  • Origin (0,0): The starting point where both x and y are zero
  • X-axis: Horizontal line (left-right movement)
    • Moving RIGHT: x increases (positive direction)
    • Moving LEFT: x decreases (negative direction)
  • Y-axis: Vertical line (up-down movement)
    • Moving UP: y increases (positive direction)
    • Moving DOWN: y decreases (negative direction)

In our problem:

  • We start at origin: (0, 0)
  • We can only move LEFT or RIGHT (X-axis only)
  • We never move UP or DOWN (Y stays 0)

💡 This is why Y always remains 0 in our solution!

🎯 Why Y Stays Zero - The Critical Concept

🤔 The confusing part: Why initialize y = 0 if it never changes?

The Answer:

  1. Problem constraint: We can ONLY move left or right (horizontal)
    • No UP movement
    • No DOWN movement
    • Only LEFT ('L') or RIGHT ('R')
  2. What this means:
    • X-coordinate changes based on direction
    • Y-coordinate NEVER changes from starting position
  3. Why we still need y:
    • Output format requires: (x, y)
    • We must print both coordinates
    • Y represents vertical position (even though it's always 0)

Visual representation:

Start: (0,0) | | Move 10 LEFT ↓ (-10,0) ← Y is still 0! Start: (0,0) | | Move 10 RIGHT ↓ (10,0) ← Y is still 0!

What if the problem allowed UP/DOWN?

Then we'd add:

if (ch == 'U') y += a; // Move UP
if (ch == 'D') y -= a; // Move DOWN

💡 Key insight: We initialize y = 0 because it's part of the coordinate system, even though this specific problem doesn't use vertical movement!

🔀 The OR Operator (||) - Either Can Be True

The || (OR) operator returns TRUE if at least one condition is true.

Basic Syntax:

if (condition1 || condition2) {
  // Executes if EITHER or BOTH are true
}

Truth Table for OR:

Condition 1 Condition 2 Result (||)
TRUE TRUE ✅ TRUE
TRUE FALSE ✅ TRUE
FALSE TRUE ✅ TRUE
FALSE FALSE ❌ FALSE

In our problem:

  • ch == 'l' || ch == 'L' → User entered lowercase OR uppercase L
  • ch == 'r' || ch == 'R' → User entered lowercase OR uppercase R

Why we need this:

Users might type:

  • 10 L (uppercase) ← Valid
  • 10 l (lowercase) ← Also valid
  • 10 R (uppercase) ← Valid
  • 10 r (lowercase) ← Also valid

💡 This makes our code case-insensitive and user-friendly!

Short-circuit evaluation:

If ch == 'l' is TRUE, the second condition ch == 'L' is never checked! The result is already TRUE.

🧮 Understanding x += a and x -= a

Compound assignment operators explained:

1. x += a (Add and assign):

  • Short form of: x = x + a
  • Adds a to current value of x
  • Example: If x = 5 and a = 10 → x becomes 15

2. x -= a (Subtract and assign):

  • Short form of: x = x - a
  • Subtracts a from current value of x
  • Example: If x = 5 and a = 10 → x becomes -5

In our coordinate system:

Direction Operation Effect on X Example (a=10)
LEFT x -= a Decreases (negative) 0 → -10
RIGHT x += a Increases (positive) 0 → 10

Why this works:

  • Start at origin: x = 0
  • Move RIGHT 10 steps: x += 10 → x = 0 + 10 = 10
  • Move LEFT 10 steps: x -= 10 → x = 0 - 10 = -10

Other compound operators you'll learn:

  • x *= a → x = x * a (multiply)
  • x /= a → x = x / a (divide)
  • x %= a → x = x % a (modulo)

💡 Compound operators save typing and make code cleaner!

🔍 Step-by-Step Execution Examples

Example 1: Input "10 L" (Move 10 steps left)

  1. Declare variables: long long a; char ch;
  2. Read input: cin >> a >> ch;
    • a = 10
    • ch = 'L'
  3. Initialize position: x = 0, y = 0 (at origin)
  4. Check LEFT condition: if (ch == 'l' || ch == 'L')
    • 'L' == 'l' → FALSE
    • 'L' == 'L' → TRUE ✅
    • Overall: FALSE || TRUE → TRUE ✅
  5. Execute: x -= a; → x = 0 - 10 = -10
  6. Check RIGHT condition: if (ch == 'r' || ch == 'R')
    • 'L' == 'r' → FALSE
    • 'L' == 'R' → FALSE
    • Overall: FALSE || FALSE → FALSE ❌
    • Skip this block
  7. Final position: x = -10, y = 0
  8. Output: (-10,0)

Example 2: Input "10 R" (Move 10 steps right)

  1. Read input: a = 10, ch = 'R'
  2. Initialize: x = 0, y = 0
  3. Check LEFT: 'R' == 'l' || 'R' == 'L' → FALSE || FALSE → FALSE ❌
    • Skip this block
  4. Check RIGHT: 'R' == 'r' || 'R' == 'R' → FALSE || TRUE → TRUE ✅
  5. Execute: x += a; → x = 0 + 10 = 10
  6. Final position: x = 10, y = 0
  7. Output: (10,0)

Example 3: Input "5 l" (lowercase, Move 5 steps left)

  1. Read input: a = 5, ch = 'l'
  2. Initialize: x = 0, y = 0
  3. Check LEFT: 'l' == 'l' || 'l' == 'L' → TRUE || ? → TRUE ✅
    • First condition is TRUE, second not evaluated (short-circuit)
  4. Execute: x -= a; → x = 0 - 5 = -5
  5. Check RIGHT: FALSE (skipped)
  6. Final position: x = -5, y = 0
  7. Output: (-5,0)

Example 4: Starting from non-origin (conceptual)

If we started at (5, 0) and moved 3 LEFT:

  1. Starting position: x = 5, y = 0
  2. Move LEFT 3: x -= 3 → x = 5 - 3 = 2
  3. Final: (2, 0)

💡 This shows how movement is relative to current position!

🎨 Character Comparison in C++

How character comparison works:

1. Character literals use single quotes:

  • 'L' → Character (single letter)
  • "L" → String (text, even if one letter) ← WRONG for char

2. Characters are case-sensitive:

Comparison Result Reason
'L' == 'L' TRUE ✅ Exact match
'L' == 'l' FALSE ❌ Different case
'R' == 'R' TRUE ✅ Exact match
'R' == 'r' FALSE ❌ Different case

3. Why we check both cases:

Without OR operator:

if (ch == 'L') // Only accepts uppercase L
if (ch == 'l') // Only accepts lowercase l

With OR operator:

if (ch == 'l' || ch == 'L') // Accepts BOTH!

Behind the scenes (ASCII values):

  • 'L' has ASCII value 76
  • 'l' has ASCII value 108
  • They're different numbers, so comparison is FALSE

Alternative approach (converting to one case):

ch = toupper(ch); // Convert to uppercase
if (ch == 'L') ... // Now only check uppercase

💡 But using OR is more direct and doesn't modify the input!

❓ Why Two Separate If Statements (Not Else-If)?

🤔 Critical question: Why not use else-if?

Our code structure:

if (ch == 'l' || ch == 'L')
  x -= a;

if (ch == 'r' || ch == 'R') // Separate if!
  x += a;

Why this works perfectly:

  1. Mutually exclusive inputs: User enters EITHER 'L' OR 'R', never both
  2. First if checks LEFT: If true, executes x -= a
  3. Second if checks RIGHT: If true, executes x += a
  4. Only ONE will ever be true!

Could we use else-if?

if (ch == 'l' || ch == 'L')
  x -= a;
else if (ch == 'r' || ch == 'R')
  x += a;

Yes! This would work too!

Why two separate ifs is also valid:

  • ✅ Both conditions are independent checks
  • ✅ Only one can be true at a time (user enters one character)
  • ✅ Code is clear and easy to read
  • ✅ Easy to add more directions later (UP, DOWN)

When to use else-if vs separate ifs:

Use else-if when: Use separate ifs when:
Categories are mutually exclusive Conditions are independent
You want to skip remaining checks Multiple conditions might be true
Efficiency matters (many conditions) Each check has different purpose

In this problem: Both approaches work! Two separate ifs is fine because:

  • Only 2 simple conditions
  • Performance difference is negligible
  • Code clarity is good either way

💡 Best practice for this problem: else-if is slightly better because it makes the mutual exclusivity explicit!

🌍 Real-World Applications

Where this pattern is used in real programming:

1. Game Development - Character Movement:

if (key == 'W' || key == 'w') y += speed; // Move up
if (key == 'A' || key == 'a') x -= speed; // Move left
if (key == 'S' || key == 's') y -= speed; // Move down
if (key == 'D' || key == 'd') x += speed; // Move right

2. Robot Control Systems:

  • Forward/Backward/Left/Right commands
  • Position tracking on a grid
  • Coordinate-based navigation

3. GPS Navigation:

  • Tracking latitude/longitude changes
  • Calculating new positions after movement
  • Distance and direction computations

4. Drawing Applications:

  • Cursor position tracking
  • Pen movement on canvas
  • Shape positioning

5. Map Applications:

  • Pan left/right/up/down
  • Zoom in/out
  • Marker placement

6. Terminal/Console Navigation:

  • Text cursor movement
  • Menu selection (arrow keys)
  • Editor commands (Vim, Emacs)

💡 This is fundamental to any system that tracks position or movement!

💡 Key Takeaways: (1) Y stays 0 because we only move horizontally, (2) OR operator handles both lowercase and uppercase, (3) Coordinate systems are fundamental to positioning in programming!

Solution

#include <iostream>

using namespace std;

int main() {
    long long a;
    char ch;
    
    cin >> a >> ch;
    
    long long x = 0, y = 0;
    
    if (ch == 'l' || ch == 'L')
        x -= a;
    
    if (ch == 'r' || ch == 'R')
        x += a;
    
    cout << "(" << x << "," << y << ")";
    
    return 0;
}