Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

Real World Examples of Struct, Union, Enum, and Nested Struct in C

Real World Examples of Struct, Union, Enum, and Nested Struct in C

πŸ”§ Real-World Examples Using Struct, Union, Enum, and Nested Struct in C

🌑️ 1. IoT Sensor Data (Struct + Union)

#include <stdio.h>

union SensorValue {
    int intValue;
    float floatValue;
};

struct SensorPacket {
    char sensorType;  // 'T' for temp, 'H' for humidity
    union SensorValue value;
};

int main() {
    struct SensorPacket tempSensor = {'T', .value.floatValue = 26.7};
    printf("Sensor Type: %c, Value: %.2f\n", tempSensor.sensorType, tempSensor.value.floatValue);
    return 0;
}
  

🧠 Explanation:

  • We use a union to store either integer or float value.
  • The struct wraps it with sensor type info.

πŸ–₯️ Sample Output:

Sensor Type: T, Value: 26.70
    

🚦 2. Traffic Light (Enum)

#include <stdio.h>

enum TrafficSignal { RED, YELLOW, GREEN };

int main() {
    enum TrafficSignal light = GREEN;
    if (light == GREEN)
        printf("Go now!\n");
    return 0;
}
  

🧠 Explanation:

Enums make traffic signal states readable and easy to manage.

πŸ–₯️ Sample Output:

Go now!
    

πŸŽ“ 3. Student Info with Address (Nested Struct)

#include <stdio.h>

struct Address {
    char city[20];
    int pin;
};

struct Student {
    char name[20];
    struct Address addr;
};

int main() {
    struct Student s1 = {"John", {"Mumbai", 400001}};
    printf("Name: %s, City: %s, PIN: %d\n", s1.name, s1.addr.city, s1.addr.pin);
    return 0;
}
  

🧠 Explanation:

  • Address is a nested struct inside Student.
  • Shows how complex data can be managed hierarchically.

πŸ–₯️ Sample Output:

Name: John, City: Mumbai, PIN: 400001
    

πŸ”‘ Keywords:

struct in C, union in embedded C, nested struct, enum example, traffic signal enum, IoT sensor struct, memory optimization, real world embedded C programs

Comments

Popular Posts

πŸŒ™