Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

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

πŸŒ™