Algorithm Programming

Module 1: Introduction to C

This first chapter will cover assignment statements, arithmetic statements, loop statements, conditional statements, and other fundamental rules for writing code in C.

Module 1: Introduction to C

Overview of C

INTRODUCTION TO C LANGUAGE

C is a general-purpose programming language that is closely related to how computer machines work. Although often considered difficult to learn, C is actually a simple language with vast capabilities.

Here are some key points to note in C:


SIMPLE C PROGRAM: PRINTING A LINE OF TEXT

The simplest C program is a program that prints text. Here is an example:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Output:

Hello, World!

Parts of the Program

  1. Comment:

    • Single-line comments use //, while multi-line comments use /* ... */.
    // This is a single-line comment
    /* 
       This is a 
       multi-line comment
    */
    
  2. Header File:

    • Header files like stdio.h are required to use functions such as printf() or scanf().
    #include <stdio.h>
    
  3. Main Function:

    • The main() function is the program’s entry point.
    • int main() indicates that the function returns an integer (0 for success, 1 or more for failure).
    int main() {
        // Program code
        return 0; // Indicates successful program execution
    }
    
  4. The printf() Function:

    • This function is used to print output to the screen.
    • \n is an escape sequence meaning newline (new row).
    printf("Hello, World!\n");
    

VARIABLES AND DATA TYPES

Variables are "containers" for storing values. The data type determines the kind of value that can be stored in a variable.

Types of Data in C

  1. int - For integer values.

    int number1;  // Variable without initialization (random value)
    int number2 = 20;  // Variable initialized with value 20
    
  2. float - For decimal values.

    float decimal = 3.14;
    
  3. char - For storing a single character.

    char letter = 'A';
    

Here is a complete diagram of data types in C:
Alt text

Naming Variables

Example:

int age = 20;      // Valid
float height = 170; // Valid
char initial = 'A'; // Valid
int ageOfFather = 45; // Valid

int 2age = 20;     // Invalid (cannot start with a number)

Complete Example

Here is an example program using variables and data types:

#include <stdio.h>

int main() {
    int age = 25;
    float height = 170.5;
    char initial = 'A';

    printf("Age: %d years\n", age);
    printf("Height: %.2f cm\n", height);
    printf("Initial: %c\n", initial);

    return 0;
}

Output:

Age: 25 years
Height: 170.50 cm
Initial: A
Module 1: Introduction to C

Operator & If-Else Statement

1. Arithmetic Operators

a) Addition (+)

Adds two values.

int a = 5, b = 3;
int result = a + b; // Result: 8
printf("a + b = %d\n", result); // Output: a + b = 8

b) Subtraction (-)

Subtracts one value from another.

int a = 10, b = 4;
int result = a - b; // Result: 6
printf("a - b = %d\n", result); // Output: a - b = 6

c) Multiplication (*)

Multiplies two values.

int a = 7, b = 3;
int result = a * b; // Result: 21
printf("a * b = %d\n", result); // Output: a * b = 21

d) Division (/)

Divides two values.

int a = 15, b = 5;
int result = a / b; // Result: 3
printf("a / b = %d\n", result); // Output: a / b = 3

e) Modulus (%)

Returns the remainder of a division.

int a = 10, b = 3;
int result = a % b; // Result: 1 (since 10 ÷ 3 = 3 remainder 1)
printf("a %% b = %d\n", result); // Output: a % b = 1

f) Increment (++)

Increases the value of a variable by 1.

int a = 5;
a++; // Result: 6
printf("a = %d\n", a); // Output: a = 6

g) Decrement (--)

Decreases the value of a variable by 1.

int a = 8;
a--; // Result: 7
printf("a = %d\n", a); // Output: a = 7

2. Logical Operators

a) Logical AND (&&)

Returns true if both conditions are true.

int a = 5, b = 10;
if (a > 3 && b < 15) {
    printf("Both are true!\n"); // Output: Both are true!
}

b) Logical OR (||)

Returns true if at least one condition is true.

int a = 7, b = 12;
if (a > 10 || b < 5) {
    printf("At least one is true!\n"); // Will not execute since both conditions are false.
}

c) Logical NOT (!)

Reverses the condition’s result.

int a = 10;
if (!(a < 5)) {
    printf("a is not less than 5!\n"); // Output: a is not less than 5!
}

3. Comparison Operators

Comparison operators are used to compare two values and return a boolean (true or false).

a) == (Equal To)

Returns true if both operands are equal.

int a = 5, b = 5;
if (a == b) {
    printf("a and b are equal\n");
}

b) != (Not Equal To)

Returns true if the two operands are not equal.

int a = 5, b = 10;
if (a != b) {
    printf("a and b are different\n");
}

c) > (Greater Than)

Returns true if the left operand is greater than the right.

int a = 10, b = 5;
if (a > b) {
    printf("a is greater than b\n");
}

d) < (Less Than)

Returns true if the left operand is less than the right.

int a = 5, b = 10;
if (a < b) {
    printf("a is smaller than b\n");
}

e) >= (Greater Than or Equal To)

Returns true if the left operand is greater than or equal to the right.

int a = 10, b = 10;
if (a >= b) {
    printf("a is greater than or equal to b\n");
}

f) <= (Less Than or Equal To)

Returns true if the left operand is less than or equal to the right.

int a = 5, b = 10;
if (a <= b) {
    printf("a is smaller than or equal to b\n");
}

4. Assignment Operators

a) Simple Assignment (=)

Assigns a value to a variable.

int a;
a = 10; // a now holds 10
printf("a = %d\n", a); // Output: a = 10

b) Compound Assignment (+=, -=, *=, /=, %=)

Combines arithmetic operations with assignment.

int a = 5;
a += 3; // Equivalent to a = a + 3 → Result: 8
a -= 2; // Equivalent to a = a - 2 → Result: 6
a *= 4; // Equivalent to a = a * 4 → Result: 24
a /= 6; // Equivalent to a = a / 6 → Result: 4
a %= 3; // Equivalent to a = a % 3 → Result: 1
printf("Final result of a = %d\n", a); // Output: Final result of a = 1

5. If-Else Statement Structure

a) If

Executes code if the condition is true.

int number = 10;
if (number > 5) {
    printf("Number is greater than 5!\n"); // Output: Number is greater than 5!
}

b) If-Else

Executes an alternative code block if the condition is false.

int number = 3;
if (number > 5) {
    printf("Number is greater than 5!\n");
} else {
    printf("Number is not greater than 5!\n"); // Output: Number is not greater than 5!
}

c) Else-If

Adds additional conditions.

int number = 7;
if (number < 5) {
    printf("Number is less than 5!\n");
} else if (number == 5) {
    printf("Number is equal to 5!\n");
} else {
    printf("Number is greater than 5!\n"); // Output: Number is greater than 5!
}
Module 1: Introduction to C

Loop & Switch-Case

Loop & Switch-Case

1. While Loop

A while loop is a function used to execute the same block of code repeatedly. The loop continues execution as long as the given condition evaluates to 1 (TRUE) or more. When the condition evaluates to 0 (FALSE), the loop stops and the program proceeds to the next lines of code.

Similar to an if statement, the while loop is built into the C programming language, meaning there is no need to declare or return its value explicitly.


Syntax:

while (condition) {
    // Code to be executed repeatedly
}

The condition is checked before executing the loop body:

Example 1: Counting from 1 to 10

#include <stdio.h>

int main() {
    int n = 1;

    while (n <= 10) {  // Loop runs while n is less than or equal to 10
        printf("%d\n", n);
        n++;  // Increment n by 1 in each iteration
    }

    return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

Infinite Loop

If the condition never changes or is always TRUE, the loop will run indefinitely.

Example 2: Infinite Loop (Press Ctrl+C to Stop)

#include <stdio.h>

int main() {
    while (1) {  // The condition is always TRUE
        printf("This loop will run forever!\n");
    }

    return 0;
}

Output (Repeats Forever):

This loop will run forever!
This loop will run forever!
This loop will run forever!
...

Using break to Exit a While Loop

The break statement can be used to exit a while loop forcefully.

Example 3: Using break to Stop the Loop

#include <stdio.h>

int main() {
    int n = 1;

    while (1) {  // Infinite loop
        printf("%d\n", n);
        if (n == 5) {
            break;  // Exit the loop when n reaches 5
        }
        n++;
    }

    return 0;
}

Output:

1
2
3
4
5

Using continue to Skip an Iteration

The continue statement is used to skip the remaining code in the loop for a specific iteration.

Example 4: Skipping a Number (Skipping 5)

#include <stdio.h>

int main() {
    int n = 0;

    while (n < 10) {
        n++;
        
        if (n == 5) {
            continue;  // Skip printing 5
        }

        printf("%d\n", n);
    }

    return 0;
}

Output:

1
2
3
4
6
7
8
9
10

2. DO-WHILE LOOP

The do-while loop is similar to the while loop. The difference lies in the execution order:

Syntax:

do {
    // Code to be executed
} while (condition);

Example 5: Difference Between While and Do-While

#include <stdio.h>

int main() {
    int n = 0;

    printf("Using while loop:\n");
    while (n > 0) {
        printf("This will NOT be printed.\n");
    }

    printf("\nUsing do-while loop:\n");
    do {
        printf("This WILL be printed at least once.\n");
    } while (n > 0);

    return 0;
}

Output:

Using while loop:

Using do-while loop:
This WILL be printed at least once.

Explanation:


3. FOR LOOP

A for loop is an advanced version of the while loop. It allows for a specific range and controlled iterations.

The for loop consists of three components:

  1. Initialization (init) → Sets the starting value. (e.g., i = 1;)
  2. Condition (condition) → Determines when the loop stops. (e.g., i <= 10;)
  3. Increment (increment) → Updates the loop variable. (e.g., i++)

Syntax:

for (initialization; condition; increment) {
    // Code to be executed
}

Example 6: Printing Numbers 1 to 10

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

Example 7: Loop with Step Size of 2

#include <stdio.h>

int main() {
    for (int i = 0; i <= 10; i += 2) {
        printf("%d\n", i);
    }

    return 0;
}

Output:

0
2
4
6
8
10

4. SWITCH-CASE STATEMENT

A switch-case statement is an alternative to if-else-if for comparing a variable against multiple fixed values.

Syntax:

switch (variable) {
    case value1:
        // Code to execute
        break;
    case value2:
        // Code to execute
        break;
    default:
        // Code if no cases match
}

Example 8: Simple Menu System

#include <stdio.h>

int main() {
    int choice;

    printf("Select an option:\n");
    printf("1. Start\n");
    printf("2. Settings\n");
    printf("3. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            printf("Game Starting...\n");
            break;
        case 2:
            printf("Opening Settings...\n");
            break;
        case 3:
            printf("Exiting Program...\n");
            break;
        default:
            printf("Invalid Choice!\n");
    }

    return 0;
}

Example Output:

Select an option:
1. Start
2. Settings
3. Exit
Enter your choice: 2
Opening Settings...

Example 9: Days of the Week

#include <stdio.h>

int main() {
    int day;

    printf("Enter a number (1-7) for the day of the week: ");
    scanf("%d", &day);

    switch (day) {
        case 1:
            printf("Sunday\n");
            break;
        case 2:
            printf("Monday\n");
            break;
        case 3:
            printf("Tuesday\n");
            break;
        case 4:
            printf("Wednesday\n");
            break;
        case 5:
            printf("Thursday\n");
            break;
        case 6:
            printf("Friday\n");
            break;
        case 7:
            printf("Saturday\n");
            break;
        default:
            printf("Invalid input! Enter a number between 1 and 7.\n");
    }

    return 0;
}

Example Output:

Enter a number (1-7) for the day of the week: 5
Thursday
Module 1: Introduction to C

Nested Statements / Loops

1. NESTED IF STATEMENT

A nested if statement is an if condition inside another if block. This allows checking multiple conditions in a hierarchical manner.

Syntax:

if (condition1) {
    if (condition2) {
        // Code to execute if both conditions are true
    }
}

Example 1: Nested If Statement

#include <stdio.h>

int main() {
    int num = 10;

    if (num > 0) {  // Outer if
        printf("The number is positive.\n");

        if (num % 2 == 0) {  // Inner if
            printf("The number is even.\n");
        }
    }

    return 0;
}

Output:

The number is positive.
The number is even.

2. NESTED WHILE LOOP

A nested while loop is a while loop inside another while loop. The inner loop executes completely for each iteration of the outer loop.

Syntax:

while (condition1) {
    while (condition2) {
        // Code to execute
    }
}

Example 2: Multiplication Table using Nested While Loop

#include <stdio.h>

int main() {
    int i = 1, j;

    while (i <= 5) {
        j = 1;
        while (j <= 5) {
            printf("%d\t", i * j);
            j++;
        }
        printf("\n");
        i++;
    }

    return 0;
}

Output:

1   2   3   4   5
2   4   6   8   10
3   6   9   12  15
4   8   12  16  20
5   10  15  20  25

3. NESTED DO-WHILE LOOP

A nested do-while loop is a do-while loop inside another do-while loop. The inner loop will always execute at least once before checking the condition.

Syntax:

do {
    do {
        // Code to execute
    } while (condition2);
} while (condition1);

Example 3: Number Grid using Nested Do-While

#include <stdio.h>

int main() {
    int i = 1, j;

    do {
        j = 1;
        do {
            printf("%d ", j);
            j++;
        } while (j <= 5);

        printf("\n");
        i++;
    } while (i <= 5);

    return 0;
}

Output:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

4. NESTED FOR LOOP

A nested for loop is a for loop inside another for loop. The inner loop runs completely for each iteration of the outer loop.

Syntax:

for (initialization; condition1; increment) {
    for (initialization; condition2; increment) {
        // Code to execute
    }
}

Example 4: Printing a Square Pattern

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

5. NESTED SWITCH-CASE

A nested switch-case is when a switch statement is placed inside another switch statement.

Syntax:

switch (variable1) {
    case value1:
        switch (variable2) {
            case value2:
                // Code to execute
                break;
        }
        break;
}

Example 5: Nested Switch-Case for User Role and Permission

#include <stdio.h>

int main() {
    int role = 1; // 1 = Admin, 2 = User
    int action = 2; // 1 = View, 2 = Edit

    switch (role) {
        case 1:
            printf("Role: Admin\n");
            switch (action) {
                case 1:
                    printf("Action: Viewing data\n");
                    break;
                case 2:
                    printf("Action: Editing data\n");
                    break;
                default:
                    printf("Invalid action!\n");
            }
            break;

        case 2:
            printf("Role: User\n");
            switch (action) {
                case 1:
                    printf("Action: Viewing data\n");
                    break;
                default:
                    printf("Users cannot edit data!\n");
            }
            break;

        default:
            printf("Invalid role!\n");
    }

    return 0;
}

Example Output:

Role: Admin
Action: Editing data

Module 2: Function and Array

Module 2: Function and Array

Function

In C programming, a function is a block of statements that performs a specific task when called. Functions enhance modularity and code reusability, allowing developers to break down complex problems into manageable sub-tasks. In other programming languages, functions are also referred to as subroutines or procedures.

Advantages of Using Functions

Function Components

A typical function in C consists of:

  1. Return Type --> Specifies the type of value the function returns. If no value is returned, the return type is void.
  2. Function Name --> An identifier for the function, following the same naming conventions as variables.
  3. Parameters (Optional) --> Variables that accept values from the function call. Functions can have zero or more parameters.
  4. Function Body --> A block of code enclosed in {} braces that defines the operations performed by the function.

Function Declaration (Prototype)

A function declaration, or prototype, informs the compiler about a function's name, return type, and parameters before its actual definition. This is essential for ensuring that function calls are correctly matched with their definitions.

Syntax:

return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2, ...);

Example:

int add(int a, int b);

This prototype declares a function named add that takes two integer parameters and returns an integer.

Function Definition

The function definition provides the actual implementation.

Syntax:

return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2, ...) {
    // Function body
    return value; // if return_type is not void
}

Example:

int add(int a, int b) {
    return a + b;
}

This function add takes two integers and returns their sum.

Function Call

To execute a function, you call it by using its name followed by arguments in parentheses.

Syntax:

function_name(argument1, argument2, ...);

Example:

int result = add(5, 3); // result now holds the value 8

Here, the add function is called with arguments 5 and 3, and the returned value is stored in result.

Types of Functions

  1. Standard Library Functions --> Predefined functions provided by C's standard library, such as printf(), scanf(), and strlen(). To use these functions, include the appropriate header files (e.g., #include <stdio.h> for printf()).
  2. User-Defined Functions --> Functions created by the programmer to perform specific tasks within the program.

Function Parameters and Return Values

Functions can be categorized based on their parameters and return values:

Understanding these combinations allows for flexible function design tailored to specific needs.

Inline Functions

In C, an inline function is a special type of function whose function call is replaced with the actual code of the function rather than being invoked through the usual function call mechanism, potentially improving performance by reducing function call overhead. It is declared using the inline keyword and is generally used for small and frequently used functions.

Example:

inline int square(int x) {
    return x * x;
}

In this example, calls to square(y) may be replaced with y * y during compilation, eliminating the function call overhead.

Conclusion

Functions are fundamental to structured programming in C, promoting modularity, reusability, and maintainability. By understanding how to declare, define, and utilize functions, programmers can write efficient and organized code.

Module 2: Function and Array

Arrays in C

In C programming, an array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide a convenient way to manage multiple related variables under a single name, allowing for efficient data manipulation and access.

Declaration and Initialization

To declare an array in C, specify the data type of its elements, the array name, and the number of elements (size) it will hold.

Syntax:

data_type array_name[array_size];

Example:

int numbers[5]; // Declares an array of 5 integers

Arrays can be initialized at the time of declaration:

int numbers[5] = {1, 2, 3, 4, 5};
int cars[5];

If the array size is omitted, the compiler determines it based on the number of initializers:

int numbers[] = {1, 2, 3, 4, 5}; // Compiler sets array size to 5

Accessing Array Elements

Array elements are accessed using their index, starting from 0 up to array_size - 1.

Example:

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    printf("%d\n", numbers[2]); // Outputs: 30
    return 0;
}

In this example, numbers[2] accesses the third element of the array, which is 30.

Types of Arrays

One-Dimensional Arrays

A one-dimensional array is a linear collection of elements.

Declaration:

data_type array_name[size];

Example:

float temperatures[7]; // Array to store temperatures for a week

Multidimensional Arrays

C supports multidimensional arrays, commonly used for matrices or tables. The most common is the two-dimensional array.

Declaration of a 2D Array:

data_type array_name[rows][columns];

Example:

int matrix[3][4]; // 2D array with 3 rows and 4 columns

Initialization:

int matrix[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

Accessing Elements:

int value = matrix[1][2]; // Accesses element at second row, third column (value is 7)

Advantages of Arrays

Limitations of Arrays

Relationship Between Arrays and Pointers

In C, the name of an array acts as a pointer to its first element. This means that array_name is equivalent to &array_name[0]. However, there are differences between arrays and pointers, especially in terms of memory allocation and how they are used in expressions.

Example:

int numbers[] = {10, 20, 30};
int *ptr = numbers; // ptr now points to the first element of numbers

Here, ptr is a pointer to an integer, and it points to the first element of the numbers array.

Module 2: Function and Array

Pass by Value vs Pass by Reference

In C programming, functions can receive arguments through two primary methods: Pass by Value and Pass by Reference. Understanding these methods is crucial for effective function design and data manipulation.

Pass by Value

In the Pass by Value method, a copy of the actual parameter's value is passed to the function. Consequently, modifications made to the parameter within the function do not affect the original variable.

Characteristics:

Example:

#include <stdio.h>

void increment(int num) {
    num++; // This change will not affect the original variable
}

int main() {
    int a = 5;
    increment(a);
    printf("%d\n", a); // Output: 5
    return 0;
}

In this example, the increment function receives a copy of a. Incrementing num does not alter the original value of a.

Pass by Reference

C does not support Pass by Reference directly. However, similar behavior can be achieved using pointers, allowing functions to modify the original variable's value.

Characteristics:

Example:

#include <stdio.h>

void increment(int *num) {
    (*num)++; // This change will affect the original variable
}

int main() {
    int a = 5;
    increment(&a);
    printf("%d\n", a); // Output: 6
    return 0;
}

Here, the increment function receives a pointer to a. Dereferencing num and incrementing it modifies the original value of a.

Key Differences

Pass by Value Pass by Reference
Operates on a copy of the data; original data remains unchanged. Operates on the actual data by accessing its address; original data can be modified.
Default method in C; no special syntax required. Achieved using pointers; requires passing the variable's address.
Suitable when the function should not alter the original data. Suitable when the function needs to modify the original data.

Understanding these parameter passing methods is essential for effective function design and data management in C programming.

Module 6: Searching

Module 6: Searching

Searching Algorithms

Searching is an algorithm used to find a specific data element within a dataset. In this module, we will discuss two common searching methods: Linear Search and Binary Search.

The simplest and most commonly used searching algorithm is the sequential or linear search. The way this algorithm works is by comparing the search key with each element in the list sequentially until the desired data is found or until all elements have been checked.

Below is an illustration of the linear search process. The search key is the number 3, and it is compared one by one until the number 3 is found.

Example Program using Linear Search:

#include <stdio.h>
#define SIZE 10

int main() {
    int arr[SIZE] = {15, 7, 2, 10, 27, 77, 32, 43, 69, 56};
    int i, input;
    
    printf("Enter the number to search: ");
    scanf("%d", &input);
    
    for (i = 0; i < SIZE; i++) {
        if (arr[i] == input) {
            printf("\n%d is located at position %d\n", input, i+1);
            break;
        }
    }
    
    if (i == SIZE) {
        printf("\nNot found in the list!\n");
    }
    
    return 0;
}

Binary search is an algorithm that searches for a data element within a sorted list. This method is faster than Linear Search but requires the list to be sorted in ascending order beforehand. The algorithm repeatedly divides the search range into two halves. If the search key is smaller than the middle element, the search continues in the left half. If the search key is larger, the search continues in the right half.

Below is an illustration of the binary search process. The input key is 8, so the search range is reduced to the right half of the list.

Example Program using Binary Search:

#include <stdio.h>
#define SIZE 7

int main() {
    int arr[SIZE] = {3, 8, 16, 29, 32, 47, 66};
    int left, right, middle, input;
    
    printf("Enter the number to search: ");
    scanf("%d", &input);
    
    left = 0;
    right = SIZE - 1;
    
    while (left <= right) {
        middle = (left + right) / 2;
        
        // Check if the middle element is the target
        if (arr[middle] == input) {
            printf("\n%d is located at position %d\n", input, middle+1);
            break;
        }
        
        // Adjust search range
        if (arr[middle] < input)
            left = middle + 1;
        else
            right = middle - 1;
    }
    
    if (left > right)
        printf("\nNot found in the list!\n");
    
    return 0;
}
Module 6: Searching

Compare String

Introduction

The strcmp function is part of the standard C library and is used to compare two strings. This function determines the lexicographical order of the given strings.

Syntax

#include <string.h>

int strcmp(char str1[], char str2[]);

Explanation

The strcmp function compares two strings character by character in a lexicographical manner. The comparison stops when a difference is found or when the end of one of the strings is reached.

Example Usage

Below is a simple C program demonstrating the use of strcmp:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Geeks";
    char str2[] = "Geeks";
    char str3[] = "GEEKS";

    // Comparing str1 and str2
    int result = strcmp(str1, str2);
    if (result == 0) {
        printf("str1 and str2 are equal.\n");
    } else {
        printf("str1 and str2 are different.\n");
    }

    // Comparing str1 and str3
    result = strcmp(str1, str3);
    if (result == 0) {
        printf("str1 and str3 are equal.\n");
    } else {
        printf("str1 and str3 are different.\n");
    }

    return 0;
}

Expected Output:

str1 and str2 are equal.
str1 and str3 are different.

In the example above, strcmp(str1, str2) returns 0 because both strings are identical. However, strcmp(str1, str3) returns a nonzero value because of the difference in letter casing.

Using strcmp in Searching

The strcmp function can also be used in searching within an array of strings. Below is an example demonstrating how to search for a string in an array using strcmp:

#include <stdio.h>
#include <string.h>
#define SIZE 5

int main() {
    char names[SIZE][20] = {"Alice", "Bob", "Charlie", "David", "Eve"};
    char search[20];
    int found = 0;

    printf("Enter a name to search: ");
    scanf("%s", search);

    for (int i = 0; i < SIZE; i++) {
        if (strcmp(names[i], search) == 0) {
            printf("%s found at position %d\n", search, i + 1);
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("%s not found in the list.\n", search);
    }
    
    return 0;
}

Expected Output:

Enter a name to search: Bob
Bob found at position 2

This program takes user input for a name and searches for it in the predefined list using strcmp.

Important Notes

Module 6: Searching

Searching in Struct

Introduction

In C, structures (struct) allow grouping different types of data together. Sometimes, we need to search for specific records inside an array of structures. This module explains how to perform searching operations on an array of structures in C using both Linear Search and Binary Search.

Defining a Structure

Before searching, let's define a simple structure to store student information:

#include <stdio.h>
#include <string.h>

#define SIZE 5

struct Student {
    int id;
    char name[20];
    float grade;
};

Here, the Student struct contains three fields:

Linear Search on Struct Array

Linear search iterates through each element in the struct array until a match is found.

Example: Searching for a Student by Name

int main() {
    struct Student students[SIZE] = {
        {101, "Alice", 85.5},
        {102, "Bob", 78.0},
        {103, "Charlie", 92.0},
        {104, "David", 88.5},
        {105, "Eve", 90.0}
    };
    
    char searchName[20];
    int found = 0;

    printf("Enter student name to search: ");
    scanf("%s", searchName);

    for (int i = 0; i < SIZE; i++) {
        if (strcmp(students[i].name, searchName) == 0) {
            printf("Student found: ID=%d, Name=%s, Grade=%.2f\n", students[i].id, students[i].name, students[i].grade);
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("Student not found!\n");
    }

    return 0;
}

Output Example:

Enter student name to search: Bob
Student found: ID=102, Name=Bob, Grade=78.00

Binary Search on Struct Array

Binary search is faster than linear search but requires the array to be sorted. It repeatedly divides the array into halves to locate the desired element.

Example: Searching for a Student by ID (Binary Search)

int binarySearch(struct Student students[], int left, int right, int key) {
    while (left <= right) {
        int mid = (left + right) / 2;
        if (students[mid].id == key)
            return mid;
        if (students[mid].id < key)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return -1;
}

int main() {
    struct Student students[SIZE] = {
        {101, "Alice", 85.5},
        {102, "Bob", 78.0},
        {103, "Charlie", 92.0},
        {104, "David", 88.5},
        {105, "Eve", 90.0}
    };
    
    int searchID;
    printf("Enter student ID to search: ");
    scanf("%d", &searchID);
    
    int result = binarySearch(students, 0, SIZE - 1, searchID);
    if (result != -1)
        printf("Student found: ID=%d, Name=%s, Grade=%.2f\n", students[result].id, students[result].name, students[result].grade);
    else
        printf("Student not found!\n");
    
    return 0;
}

Output Example:

Enter student ID to search: 103
Student found: ID=103, Name=Charlie, Grade=92.00

Conclusion