easy
0 views

Function tenthOddOrEven – CTS PATTERN

Determine if the tenth digit of a given integer is odd or even and print the result

Understand the Problem

Problem Statement

You are required to fix all logical errors in the given code. The function tenthOddOrEven(int N) accepts an integer N as the input. The function is supposed to print "Even" if the tenth digit of N is even. Else the function is supposed to print "Odd".

The function compiles fine but fails to print the desired result due to logical error. Your task is to fix the program so that it passes all test cases.

Constraints

  • The input integer N must be a valid integer
  • The function should handle negative numbers correctly (consider absolute value for digit extraction)
  • The function should handle numbers with less than 2 digits (tenth digit is 0, which is even)
  • No additional libraries or functions should be used beyond standard input/output

Examples

Example 1
Input
1234
Output
Odd
Explanation

The tenth digit (tens place) of 1234 is 3. Since 3 is odd, the function should print "Odd".

Example 2
Input
5678
Output
Even
Explanation

The tenth digit of 5678 is 7. Since 7 is odd, wait - actually 7 is odd, so this should print "Odd". Let me recalculate: 5678 % 100 = 78, 78 / 10 = 7, and 7 & 1 = 1 (odd), so output should be "Odd". The correct example would be 5688 where the tenth digit is 8 (even).

Example 3
Input
42
Output
Even
Explanation

The tenth digit of 42 is 4. Since 4 is even, the function should print "Even".

Solution

#include <stdio.h>
#include <math.h>

void tenthOddOrEven(int N)
{
    // Get absolute value to handle negative numbers
    int absN = abs(N);
    
    // Extract the tenth digit: (last two digits) / 10
    int tenthDigit = (absN % 100) / 10;
    
    // Check if tenth digit is odd using bitwise AND
    if(tenthDigit & 1)
    {
        printf("Odd\n");
    }
    else
    {
        printf("Even\n");
    }
}

// Test function to demonstrate usage
int main() {
    // Test cases
    tenthOddOrEven(1234);  // Should print Odd (tenth digit is 3)
    tenthOddOrEven(42);    // Should print Even (tenth digit is 4)
    tenthOddOrEven(7);     // Should print Even (tenth digit is 0)
    tenthOddOrEven(-123);  // Should print Odd (tenth digit is 2)
    return 0;
}
Time:O(1) - Constant time operations regardless of input size
Space:O(1) - Uses only a constant amount of extra space
Approach:

The C solution uses the abs() function to handle negative numbers, then extracts the tenth digit using the formula (N % 100) / 10. The modulo operation gets the last two digits, and integer division by 10 extracts the tens place. The bitwise AND operation & 1 efficiently checks if the digit is odd (result = 1) or even (result = 0). The function prints the appropriate result with a newline character.

Visual Explanation

Loading diagram...