Compare Two Variables (Same or Different)¶
Concept Explanation¶
What is it?¶
This program takes two inputs, which can be numbers or strings, and compares them to determine if their values are identical or distinct. It uses equality operators specific to each programming language.
Why is it important?¶
Comparing values for equality or inequality is a fundamental operation in almost every program. It's essential for control flow, data validation, searching, sorting, and ensuring that program states match expected conditions.
Where is it used?¶
- Data Validation: Checking if two user-entered passwords match.
- Database Operations: Comparing values to filter records or join tables.
- Configuration Management: Ensuring current settings match desired settings.
- Testing: Asserting that expected output matches actual output.
- Game Logic: Checking if two game pieces are in the same position, or if a player has collected a required item.
Real-world example¶
When you log into an online account, the system compares the password you entered with the stored password. If they are the same, you are granted access; otherwise, you are denied. This program performs a similar comparison.
Algorithm¶
- Start.
- Get the first value (
value1) from the user. - Get the second value (
value2) from the user. - Compare
value1andvalue2. - If
value1is equal tovalue2: a. Display that the values are the same. - Else: a. Display that the values are different.
- End.
Edge Cases: - Non-numeric input for numerical comparisons. - Case sensitivity for string comparisons (e.g., "hello" vs "Hello"). - Trailing/leading whitespace for string comparisons. - Floating-point precision issues for numerical equality. - Different data types being compared (some languages allow, some require explicit conversion).
Implementations¶
import java.util.Scanner;
public class SameOrDifferent {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first value: ");
String value1 = scanner.nextLine(); // Reads input as a string
System.out.print("Enter the second value: ");
String value2 = scanner.nextLine(); // Reads input as a string
System.out.println("First Value: " + value1);
System.out.println("Second Value: " + value2);
// For String comparison, always use .equals() in Java
if (value1.equals(value2)) {
System.out.println("The two values are the SAME.");
} else {
System.out.println("The two values are DIFFERENT.");
}
scanner.close();
}
}
# Get two values from the user
value1 = input("Enter the first value: ") # Input is always a string
value2 = input("Enter the second value: ") # Input is always a string
print(f"First Value: '{value1}'")
print(f"Second Value: '{value2}'")
# Python's == operator compares values and handles different types if convertible
if value1 == value2:
print("The two values are the SAME.")
else:
print("The two values are DIFFERENT.")
#include <stdio.h>
#include <string.h> // Required for strcmp()
int main() {
// For numbers
int num1, num2;
printf("--- Numerical Comparison ---");
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
printf("First Number: %d", num1);
printf("Second Number: %d", num2);
if (num1 == num2) {
printf("The two numbers are the SAME.");
} else {
printf("The two numbers are DIFFERENT.");
}
// For strings (more complex in C)
char str1[100], str2[100];
printf("--- String Comparison ---");
printf("Enter the first string: ");
scanf("%s", str1); // Reads single word
printf("Enter the second string: ");
scanf("%s", str2); // Reads single word
printf("First String: %s", str1);
printf("Second String: %s", str2);
// strcmp returns 0 if strings are identical
if (strcmp(str1, str2) == 0) {
printf("The two strings are the SAME.");
} else {
printf("The two strings are DIFFERENT.");
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
val1 VARCHAR2(100) := '&Enter_First_Value';
val2 VARCHAR2(100) := '&Enter_Second_Value';
BEGIN
DBMS_OUTPUT.PUT_LINE('First Value: ' || val1);
DBMS_OUTPUT.PUT_LINE('Second Value: ' || val2);
-- Oracle's = operator works for both numbers and strings (VARCHAR2)
IF val1 = val2 THEN
DBMS_OUTPUT.PUT_LINE('The two values are the SAME.');
ELSE
DBMS_OUTPUT.PUT_LINE('The two values are DIFFERENT.');
END IF;
END;
/
Explanation¶
- Java: For primitive types,
==compares values. For objects (likeString),==compares references. To compare string content,equals()method is used. This example usesequals()asScanner.nextLine()returnsStringobjects. - Python: The
==operator performs value comparison and works intuitively for both numbers and strings. It can also handle comparisons between different numerical types (e.g.,5 == 5.0isTrue). - C: For primitive types (like
int),==compares values directly. For strings (character arrays),strcmp()from<string.h>must be used, which returns 0 if strings are identical. Direct==onchar*would compare memory addresses, not content. - Oracle: Implemented in PL/SQL. The
=operator (or!=for different) is used for both numerical andVARCHAR2comparisons.DBMS_OUTPUT.PUT_LINEis used for display.
Complexity Analysis¶
- Time Complexity: O(L) for strings (where L is the length of the shorter string), O(1) for numbers.
- Space Complexity: O(1) - A fixed number of variables are used (excluding string storage itself).
Flowchart¶
graph TD
A[Start] --> B[Get Value1]
B --> C[Get Value2]
C --> D{Value1 == Value2?}
D -- Yes --> E[Display SAME]
D -- No --> F[Display DIFFERENT]
E --> G[End]
F --> G
Sample Dry Run¶
| Step | value1 | value2 | Comparison (value1 == value2) | Description |
|---|---|---|---|---|
| Input | "apple" | "apple" | - | User enters "apple", "apple" |
| Decision | "apple" | "apple" | True | Values are identical |
| Output | - | - | - | Display "The two values are the SAME." |
| End | - | - | - | Program terminates |
| Input | "Apple" | "apple" | - | User enters "Apple", "apple" |
| Decision | "Apple" | "apple" | False | Values are different (case-sensitive) |
| Output | - | - | - | Display "The two values are DIFFERENT." |
| End | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to compare three values for equality.
- Check if two numbers are not equal.
Medium¶
- Implement a case-insensitive string comparison for two user-entered strings.
- Write a program to check if two arrays/lists are identical (same elements in the same order).
Hard¶
- Compare two objects of a custom class based on a specific attribute (e.g., two Person objects based on age).
- Implement a flexible comparison function that can handle different data types and comparison criteria.
"The only source of knowledge is experience." - Albert Einstein