Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

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

πŸŒ™