C Program to Compare Two Strings.

Comparing two strings is a fundamental operation in programming, allowing us to determine whether two sequences of characters are the same or not. In C, strings are arrays of characters, and comparing them involves comparing each character of the arrays.


There are multiple ways to perform string comparison in C programming and here we are going to learn each of them. 


String Comparison Using Loop.

We can manually compare each character of the two strings using a loop. This approach gives you more control and is useful when you need to implement custom comparison logic.

C Code:

// C Program to compare two string using loop
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Apple";
    char str2[] = "Apples";

    int i = 0;
    //comparing two string char by char
    while (str1[i] != '\0' && str2[i] != '\0') {
        if (str1[i] != str2[i]) {
            printf("The strings are not equal.\n");
            return 0;
        }
        i++;
    }

    if (str1[i] == '\0' && str2[i] == '\0') {
        printf("The strings are equal.\n");
    } else {
        printf("The strings are not equal.\n");
    }

    return 0;
}
Output:
The strings are not equal.

Here, we're using a while loop to iterate through the characters of both strings. The loop continues as long as the characters in both strings are not null ('\0'). If at any point we find a character that doesn't match, we conclude that the strings are not equal. If the loop completes successfully without any mismatch and both strings end at the same point, we conclude that the strings are equal.

String Comparison Using strcmp() Function.

In this approach, we're using the strcmp() function from the string.h library. This function compares two strings and returns an integer value indicating their relationship:
  • If the return value is 0, it means the strings are equal.
  • If the return value is negative, it means the first string (str1 in our case) is less than the second string (str2).
  • If the return value is positive, it means the first string is greater than the second string.
C Code:
// C Program to compare two string using strcmp
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";
    //built-in function to compare string
    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("The strings are equal.\n");
    } else if (result < 0) {
        printf("str1 is less than str2.\n");
    } else {
        printf("str1 is greater than str2.\n");
    }

    return 0;
}
Output:
The strings are equal.

You can use the strcmp() function for a simple comparison, and implement a loop to compare characters manually.

C Program to concatenate two strings.

In C programming, concatenating two strings means joining them to create a single string. In this article, we'll explore different approaches to concatenating two strings and provide examples for each method.

Example:

Input: str1 = "Hello" str2 = "World"
Output: HelloWorld

Input: str1 = "Rahul" str2 = "Sharma"
Output: RahulSharm

Approach 1: Using a Loop

In this approach concatenating two strings is to iterate through the characters of the first string and append them to the end of the second string until the null character ('\0') is encountered in the first string.

C Code Implementation:
// C program to concatenate two string using loop
#include <stdio.h>

void concatenateStrings(char first[], char second[]) {
    int i, j;

    // Find the length of the first string
    for (i = 0; first[i] != '\0'; i++) {}

    // Append characters of the second string to the end of the first string
    for (j = 0; second[j] != '\0'; j++) {
        first[i + j] = second[j];
    }
    // Add null character to mark the end of the concatenated string
    first[i + j] = '\0'; 
}

int main() {
    char first[50] = "Hello ";
    char second[] = "AlgoLesson";

    concatenateStrings(first, second);

    printf("Concatenated string: %s\n", first);

    return 0;
}
Output:
Concatenated string: Hello AlgoLesson


Approach 2: Using strcat() Function

C provides a built-in function called strcat() from the <string.h> library to concatenate strings. This function takes two arguments: the destination string and the source string to be appended.

C Code Implementation:
// C program to concatenate two string using strcat function
#include <stdio.h>
#include <string.h>

int main() {
    char first[50] = "Sharma";
    char second[] = "Rahul";

    strcat(first, second);

    printf("Concatenated string: %s\n", first);

    return 0;
}
Output:Output:
Concatenated string: SharmaRahul

Understanding how to concatenate strings is crucial for manipulating and working with textual data in C programming. 

Similar articles:

C Program to Copy One String to Another String.

In C programming, strings are sequences of characters that end with a null character ('\0'). Copying one string to another is a common task, and there are different approaches to achieving this. 


In this article, we will explore three methods to copy one string to another and provide examples for each approach.


Approach 1: Using a loop.

One of the simplest ways to copy a string is to use a loop that iterates through each character of the source string and assigns them to the corresponding positions in the destination string until the null character is encountered.

Below is the C program for the above approach:

// C program copy one string to another string using loop
#include <stdio.h>

void copyString(char source[], char destination[]) {
    int i = 0;

    while (source[i] != '\0') {
        destination[i] = source[i];
        i++;
    }
    // Don't forget to add the null character at the end
    destination[i] = '\0'; 
}

int main() {
    char source[] = "Hello, World!";
    char destination[100]; 

    //function call
    copyString(source, destination);

    printf("Source string: %s\n", source);
    printf("Copied string: %s\n", destination);

    return 0;
}
Output:
Source string: Hello, World!
Copied string: Hello, World!

Approach 2: Using strlen() Function.

C provides a built-in function called strcpy() from the <string.h> library that can be used to copy one string to another. This function takes two arguments: the destination string and the source string.

Below is the C program for the above approach to copy string:

// C program copy one string to another string using strcpy
#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "Hello, Algolesson!";
    char destination[100];
    
    //built-in function to copy string
    strcpy(destination, source);

    printf("Source string: %s\n", source);
    printf("Copied string: %s\n", destination);

    return 0;
}
Output:
Source string: Hello, Algolesson!
Copied string: Hello, Algolesson!

Approach 3: Using Pointer Notation

In this approach we will use pointers, pointers provide another way to copy strings. By using pointer notation, we can copy characters from the source to the destination until the null character is encountered.

Below is the C code implementation to copy string using a pointer:
// C program copy one string to another string using pointer
#include <stdio.h>

// function to copy string using pointer.
void copyString(char *source, char *destination) {

    while (*source != '\0') {
        *destination = *source;
        source++;
        destination++;
    }
    *destination = '\0';
}

int main() {
    char source[] = "Hello Coder!";
    char destination[100];

    copyString(source, destination);

    printf("Source string: %s\n", source);
    printf("Copied string: %s\n", destination);

    return 0;
}
Output:
Source string: Hello Coder!
Copied string: Hello Coder!

C Program to Find Length of a String.

Problem: Write a C program to find the length of a given string. The program should prompt the user to enter a string and then calculate and display the length of the string.

Example:

Input: Hello, World!
Output: 13

Input: Algolesson
Output: 10

There are two different ways to calculate the length of the string in C programming:
  • Using loop.
  • Using buit-in function strlen.

Key Note: Strings in C are represented as arrays of characters, terminated by a null character ('\0'). The length of a string is the number of characters before the null-terminating character. (alert-passed)

Approach 1: Find the Length of the string using a loop.

In this approach, we will calculate the length of a string manually by iterating through each character of the string until we encounter the null-terminating character ('\0').

Below is the code implementation of the above approach:

C Code:
//C Program to Find the length of the given string
#include <stdio.h>

// Function to find the length of a string
int customStringLength(const char *str) {
    int length = 0;
    while (*str != '\0') {
        length++;
        str++;
    }
    return length;
}

int main() {
    char inputString[100];
    
    printf("Enter a string: ");
    scanf("%[^\n]", inputString);
    
    // function to calculate the length
    int length = customStringLength(inputString);
    
    printf("Length of the string: %d\n", length);
    
    return 0;
}
Output:
Enter a string: Welcome to AlgoLesson
Length of the string: 21

Time Complexity: O(n) where n is the number of characters present in the string.
Space Complexity: O(1) as no extra space is required to solve this problem.

Approach 2: Using Built-in Function strlen.

In this approach, we are going to use one built-in function strlen() to find the length of the string. The strlen() function is defined in the string.h header and is used to calculate the length of a given string.

Below is the code implementation for the above approach:

C Code:
// C program to find length of string uisng built-in function
#include <stdio.h>
#include <string.h> 

int main() {
    char inputString[100];
    
    printf("Enter a string: ");
    scanf("%[^\n]", inputString);
    
    // Using strlen() function to calculate the length
    int length = strlen(inputString);
    
    printf("Length of the string: %d\n", length);
    
    return 0;
}
Output:
Enter a string: Hello World
Length of the string: 11

In this code, we include the string.h header and then use the strlen() function directly to calculate the length of the input string. This approach is simpler and more efficient compared to manually iterating through the string.

Time Complexity: O(n)
Space Complexity: O(1)

C Program to Calculate Average of Elements of an Array.

Problem: Given an integer Array of size n, the task is to write C programming code to calculate the average of all the elements present in the given array.

Example:

Input: arr[] = {3, 5, 9, 2, 8}
Output: 5.40

Explanation:
Sum of elements = 3+5+9+2+8 = 27
Total number of elements = 5
Average = 27/5 = 5.40

Algorithm to Calculate Array Average.

Here is a step-by-step algorithm to calculate the average of an array in C language using pseudocode:
  • Declare an integer variable n to store the size of the array.
  • Declare an integer array arr of size n.
  • Declare an integer variable sum and initialize it to 0.
  • Declare a float variable avg and initialize it to 0.
  • Read the value of n from the user.
  • Read the values of the array arr[] from the user.
  • Traverse the array arr from index 0 to index n-1.
  • Add each element of the array arr to the variable sum.
  • Calculate the average of the array by dividing the sum of the elements by the number of elements in the array.
  • Store the result in the variable avg.
  • Display the value of avg.

Pseudocode to Calculate the Average of all elements of an array.

1. Declare n as integer
2. Declare arr[n] as integer
3. Declare sum as float and initialize it to 0
4. Declare avg as float and initialize it to 0
5. Read n from user
6. Read arr from user
7. for i = 0 to n-1 do
8.     sum = sum + arr[i]
9. end for
10. avg = sum / n
11. Display avg

C Program to Calculate the Average of all elements of an array.

C Code:
//C program to find average of array elements
#include <stdio.h>

int main() {
    int size;
    printf("Enter the size of the array: ");
    scanf("%d", &size);

    int arr[size];
    printf("Enter %d elements:\n", size);
    
    // Input array elements and calculate sum
    int sum = 0;
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
        sum += arr[i];
    }

    // Calculate average
    float average = (float) sum / size;

    printf("Average of array elements: %.2f\n", average);

    return 0;
}
Output:
Enter the size of the array: 6
Enter 6 elements:
12 9 3 2 10 5
Average of array elements: 6.83

Time Complexity: O(n) where is the size of the given array
Space Complexity: O(1) as constant extra space is required.

Related Articles:

C Program to Find and Display duplicate Elements in an array.

Problem Statement: Given an array of integers. Your task is to write a C program to find and display the duplicate elements present in the array.

Example:

Input: arr[] = {3, 2, 4, 2, 7, 8, 4, 1, 8}
Output: Duplicate numbers: 2 4 8

Input: arr[] = {1, 4, 1, 3, 2}
Output: Duplicate numbers: 1

Algorithm to Find Duplicate Elements.

Below are the steps that you need to follow:

Step 1: Traverse through the array one element at a time.
Step 2: For each element, check if it appears again later in the array.
Step 3: If the element is found later in the array and is not already marked as a duplicate, mark it as a duplicate and print it.
Step 4: Continue this process for each element.

Below is the C program implementation to find and display duplicate numbers from the given array.

C code:
//C program to find duplicate number from the given array
#include <stdio.h>

int main() {
    int arr[] = {3, 2, 4, 2, 7, 8, 4, 1, 8};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Duplicate elements: ");
    //traverse to find duplicate
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] == arr[j]) {
                printf("%d ", arr[i]);
                break;
            }
        }
    }

    printf("\n");
    return 0;
}
Output:
Duplicate elements: 2 4 8 

Time Complexity: The time complexity of this algorithm is O(n^2) in the worst case, where n is the number of elements in the array. 

Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variables and other variables.

Related Articles:

C Program to Count Odd and Even Elements in an Array.

Problem Statement: Given an array of integers. Your task is to write a C program to count the number of odd and even elements in the array.

  • Even Number: A number that is completely divisible by 2.
  • Odd Number: A number that is not completely divisible by 2.

Example: 

Input: arr[] = {2, 4, 5, 7, 10}
Output: Even Count = 3
        Odd Count = 2

Input: arr[] = {12, 13, 8, 2, 10}
Output: Even Count = 4
        Odd Count = 1

Algorithm to Count Even and Odd Elements.

Below are the steps that need to follow:

Step 1: Initialize two variables, evenCount and oddCount, to keep track of the count of even and odd elements respectively. Set both counts to zero.
Step 2: Traverse through the array one element at a time.
Step 3: For each element, check if it is even or odd.
Step 4: If the element is even, increment the evenCount by 1.
Step 5: If the element is odd, increment the oddCount by 1.
Step 6: After traversing through the entire array, output the values of evenCount and oddCount.

Program to Count numbers of odd and even elements in an Array.

// C program to count even and odd numbers in the array
#include <stdio.h>

int main() {
    int arr[] = {2, 4, 5, 7, 10};
    //size of given array
    int size = sizeof(arr) / sizeof(arr[0]);
    int evenCount = 0, oddCount = 0;
    
    //check even and odd
    for (int i = 0; i < size; i++) {
        if (arr[i] % 2 == 0) {
            evenCount++;
        } else {
            oddCount++;
        }
    }

    printf("Number of even elements: %d\n", evenCount);
    printf("Number of odd elements: %d\n", oddCount);

    return 0;
}
Output:
Number of even elements: 3
Number of odd elements: 2

Time Complexity: The time complexity of this algorithm is O(n) because it needs to traverse through all the elements of the array once.

Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variable and other variables.

Similar articles:

C Program to Search for a given Element in an Array.

Problem Statement: You are given an array of integers and a target element. Your task is to find if the target element exists in the array or not. Write a C program to search the element.

Example:

Suppose we have an array arr[] = {2, 4, 6, 8, 10}, and the target element is 6. The program should output "Element found" since 6 is present in the array.


Linear Searching Algorithm.

Below is the step-by-step algorithm to search for an element from the given array if exists:

Step 1: Start with the first element of the array and compare it with the target element.

Step 2: If the current element is equal to the target element, return "Element found".

Step 3: If the current element is not equal to the target element, move on to the next element in the array.

Step 4: Repeat steps 2 and 3 until you find the target element or reach the end of the array.

Step 5: If the end of the array is reached and the target element is not found, return "Element not found".


Program to search an element in the given array.

//C program to search an element from the given array
#include <stdio.h>

int searchElement(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return 1; // Element found
        }
    }
    return 0; // Element not found
}

int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 6;

    if (searchElement(arr, size, target)) {
        printf("Element found\n");
    } else {
        printf("Element not found\n");
    }

    return 0;
}
Output:
Element found

Time Complexity: The time complexity of this algorithm is O(n) because, in the worst-case scenario, we might have to check all the elements of the array to find the target element.

Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variable and other variables.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson