Check if Two Arrays are Equal in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Check if Two Arrays are Equal in C: Program to Compare Arrays

šŸ“‘ On this page:
  • Introduction
  • C Program to Check Array Equality
  • Sample Output
  • Program Explanation
  • Algorithm
  • Using memcmp Function
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • How to check if two arrays are equal in C
  • How to compare arrays element by element
  • How to use memcmp for array comparison
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to check if two arrays are equal.

Two arrays are considered equal if they have the same length and all corresponding elements are equal. This is used in many real-world applications, such as:

  • Comparing two data sets for equality
  • Checking if two strings (character arrays) are equal
  • Validating data integrity in file transfers
  • Comparing configuration arrays in software

šŸ’” Key Point: In C, we cannot compare arrays directly using the == operator. We must compare each element individually using a loop or use the memcmp() function from the string.h library.

C Program to Check if Two Arrays are Equal

#include <stdio.h>

int main() {
    int n1, n2, i;
    int equal = 1;  // Flag: 1 = equal, 0 = not equal
    
    // ====== FIRST ARRAY ======
    printf("Enter the number of elements in first array: ");
    scanf("%d", &n1);
    int arr1[n1];
    
    printf("Enter %d elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    // ====== SECOND ARRAY ======
    printf("\nEnter the number of elements in second array: ");
    scanf("%d", &n2);
    int arr2[n2];
    
    printf("Enter %d elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // ====== CHECK EQUALITY ======
    // First check if arrays have same size
    if(n1 != n2) {
        equal = 0;
    } else {
        // Compare each element
        for(i = 0; i < n1; i++) {
            if(arr1[i] != arr2[i]) {
                equal = 0;
                break;  // Exit loop early if mismatch found
            }
        }
    }
    
    // ====== DISPLAY ======
    printf("\nFirst array: ");
    for(i = 0; i < n1; i++) {
        printf("%d ", arr1[i]);
    }
    
    printf("\nSecond array: ");
    for(i = 0; i < n2; i++) {
        printf("%d ", arr2[i]);
    }
    
    if(equal == 1) {
        printf("\n\nāœ… Both arrays are EQUAL.\n");
    } else {
        printf("\n\nāŒ Arrays are NOT equal.\n");
    }
    
    return 0;
}

Sample Output

Enter the number of elements in first array: 5
Enter 5 elements:
10 20 30 40 50

Enter the number of elements in second array: 5
Enter 5 elements:
10 20 30 40 50

First array: 10 20 30 40 50
Second array: 10 20 30 40 50

āœ… Both arrays are EQUAL.

When Arrays are Not Equal:

Enter the number of elements in first array: 5
Enter 5 elements:
10 20 30 40 50

Enter the number of elements in second array: 5
Enter 5 elements:
10 20 30 40 60

First array: 10 20 30 40 50
Second array: 10 20 30 40 60

āŒ Arrays are NOT equal.

When Arrays have Different Sizes:

Enter the number of elements in first array: 4
Enter 4 elements:
10 20 30 40

Enter the number of elements in second array: 5
Enter 5 elements:
10 20 30 40 50

First array: 10 20 30 40
Second array: 10 20 30 40 50

āŒ Arrays are NOT equal.

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n1, n2; — sizes of the two arrays
    • int i; — loop counter
    • int equal = 1; — flag variable (1 = equal, 0 = not equal)
  3. Read Arrays: Reads the size and elements of both arrays.
  4. Check Equality:
    • Step 1: Check if sizes are equal. If not, arrays are not equal.
    • Step 2: If sizes are equal, loop through each element and compare arr1[i] with arr2[i].
    • Step 3: If any mismatch is found, set equal = 0 and break out of the loop.
  5. Display Results: Prints both arrays and a message indicating whether they are equal.
  6. Return: return 0; indicates successful program execution.

šŸ“ Note: The break statement is used to exit the loop early when a mismatch is found. This makes the program more efficient for large arrays where mismatches occur early.

Algorithm to Check Array Equality

Step-by-step algorithm:

  1. Start
  2. Read the elements of first array (arr1) with size n1
  3. Read the elements of second array (arr2) with size n2
  4. If n1 != n2:
    • Print "Arrays are not equal"
    • Exit
  5. For i = 0 to n1-1:
    • If arr1[i] != arr2[i]:
      • Print "Arrays are not equal"
      • Exit
  6. Print "Arrays are equal"
  7. End

Using memcmp Function (More Efficient)

The memcmp() function from string.h library provides a faster way to compare arrays. It compares a block of memory byte by byte.

#include <stdio.h>
#include <string.h>  // Required for memcmp

int main() {
    int n1, n2, i;
    
    printf("Enter the number of elements in first array: ");
    scanf("%d", &n1);
    int arr1[n1];
    printf("Enter %d elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    printf("\nEnter the number of elements in second array: ");
    scanf("%d", &n2);
    int arr2[n2];
    printf("Enter %d elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // Display arrays
    printf("\nFirst array: ");
    for(i = 0; i < n1; i++) {
        printf("%d ", arr1[i]);
    }
    printf("\nSecond array: ");
    for(i = 0; i < n2; i++) {
        printf("%d ", arr2[i]);
    }
    
    // Check equality using memcmp
    if(n1 == n2 && memcmp(arr1, arr2, n1 * sizeof(int)) == 0) {
        printf("\n\nāœ… Both arrays are EQUAL.\n");
    } else {
        printf("\n\nāŒ Arrays are NOT equal.\n");
    }
    
    return 0;
}

Sample Output:

Enter the number of elements in first array: 5
Enter 5 elements:
10 20 30 40 50

Enter the number of elements in second array: 5
Enter 5 elements:
10 20 30 40 50

First array: 10 20 30 40 50
Second array: 10 20 30 40 50

āœ… Both arrays are EQUAL.

How memcmp Works

  • memcmp(arr1, arr2, n1 * sizeof(int)) compares the memory blocks
  • Parameters:
    • arr1 — pointer to first array
    • arr2 — pointer to second array
    • n1 * sizeof(int) — number of bytes to compare
  • Return Value:
    • 0 — arrays are equal
    • < 0 — first difference is smaller in arr1
    • > 0 — first difference is larger in arr1
  • Advantage: Faster than manual loops for large arrays

Time and Space Complexity

Method Time Complexity Space Complexity
Element-by-Element (Loop) O(n) O(1)
memcmp() O(n) O(1)

šŸ’» Practice Exercise

Challenge 1: Modify the program to check if two arrays are equal ignoring order (i.e., same elements but possibly in different positions).

Challenge 2: Compare two arrays of strings (character arrays) for equality.

šŸ” Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n1, n2, i, j;
    int equal = 1;
    
    printf("Enter the number of elements in first array: ");
    scanf("%d", &n1);
    int arr1[n1];
    printf("Enter %d elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    printf("\nEnter the number of elements in second array: ");
    scanf("%d", &n2);
    int arr2[n2];
    printf("Enter %d elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // Check if sizes are equal
    if(n1 != n2) {
        equal = 0;
    } else {
        // For each element in arr1, check if it exists in arr2
        int visited[n2];
        for(i = 0; i < n2; i++) {
            visited[i] = 0;
        }
        
        for(i = 0; i < n1; i++) {
            int found = 0;
            for(j = 0; j < n2; j++) {
                if(arr1[i] == arr2[j] && visited[j] == 0) {
                    found = 1;
                    visited[j] = 1;
                    break;
                }
            }
            if(found == 0) {
                equal = 0;
                break;
            }
        }
    }
    
    if(equal == 1) {
        printf("\nāœ… Both arrays have the same elements (ignoring order).\n");
    } else {
        printf("\nāŒ Arrays do NOT have the same elements.\n");
    }
    
    return 0;
}

Frequently Asked Questions

1. How do you check if two arrays are equal in C?

First, check if both arrays have the same length. Then, compare each corresponding element using a loop. If all elements match, the arrays are equal.

2. Can I use the == operator to compare two arrays in C?

No, the == operator compares the memory addresses of the arrays, not their contents. You must compare each element individually or use memcmp().

3. What is the difference between memcmp and element-by-element comparison?

memcmp() is a library function that compares memory blocks byte by byte. It's often faster and more concise. The element-by-element loop gives you more control and allows you to add custom comparison logic.

4. How do I compare two arrays of different data types?

Arrays of different data types cannot be compared directly because they store different amounts of memory. You would need to convert or cast the data before comparison.

5. How do I check if two arrays are equal ignoring order?

Sort both arrays and then compare them, or use a frequency-based approach (count occurrences of each element). The practice exercise above provides a solution for this.

šŸ’” Tip: For comparing large arrays, memcmp() is generally faster. For arrays with custom comparison logic, use the element-by-element loop.

šŸ“– Related Tutorials

  • Shift Array Elements Left
  • Reverse an Array in C
  • Copy Array Elements in C
  • More Array Assignments

Previous Topic: -->> Shift Array Elements Left   ||   Next topic: -->> Function Assignments


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.