Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

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

πŸŒ™