0% found this document useful (0 votes)
13 views8 pages

Unit 2 - Part1

CPDS2

Uploaded by

ohmmurugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

Unit 2 - Part1

CPDS2

Uploaded by

ohmmurugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

UNIT II C PROGRAMMING - ADVANCED FEATURES

Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and
Functions – File Handling – Preprocessor Directives.
1. STRUCTURES
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The ‘struct’ keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type. Additionally, the values of a structure are stored in contiguous memory
locations.
Syntax
structstructure_name
{
data_type member1;
data_type member2;
.
.
data_typememeberN;
};
Create a Structure
Create a structure by using the struct keyword and declare each of its members inside curly
braces:
structMyStructure { // Structure declaration
intmyNum; // Member (int variable)
charmyLetter; // Member (char variable)
}; // End the structure with a semicolon
Declaration and Initialization:
structStructNamevariableName;
Example
#include <stdio.h>
#include <string.h>
// Define the structure
struct Student {
int id;
char name[50];
float grade;
};
1
int main() {
// Declare and initialize a structure variable
struct Student student1;

// Assign values to the structure members


student1.id = 1;
strcpy(student1.name, "Alice");
student1.grade = 89.5;

// Print the structure members


printf("Student ID: %d\n", student1.id);
printf("Student Name: %s\n", student1.name);
printf("Student Grade: %.2f\n", student1.grade);

// Declare and initialize another structure variable using an initializer list


struct Student student2 = {2, "Bob", 92.3};

// Print the second structure's members


printf("\nStudent ID: %d\n", student2.id);
printf("Student Name: %s\n", student2.name);
printf("Student Grade: %.2f\n", student2.grade);
return 0;
}
Output
Student ID: 1
Student Name: Alice
Student Grade: 89.50

Student ID: 2
Student Name: Bob
Student Grade: 92.30

Example 2
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
2
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "SonooJaiswal");//copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;

//printing first employee information


printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : SonooJaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

2. UNION
The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure. But unlike structures, all the members in the C union are
stored in the same memory location. Due to this, only one member can store data at the given
instance.
Basic Syntax
Definition:

3
unionUnionName {
type1 member1;
type2 member2;
// More members
};
Example
#include <stdio.h>
// Define the union
union Data {
intintValue;
floatfloatValue;
charcharValue;
};

int main() {
// Declare and initialize a union variable
union Data data;

// Assign a value to the int member


data.intValue = 10;
printf("data.intValue: %d\n", data.intValue);

// Assign a value to the float member (overwrites the int member)


data.floatValue = 220.5;
printf("data.floatValue: %.2f\n", data.floatValue);

// Assign a value to the char member (overwrites the float member)


data.charValue = 'A';
printf("data.charValue: %c\n", data.charValue);

// Print the int and float values to show that they have been overwritten
printf("After overwriting:\n");
printf("data.intValue: %d\n", data.intValue); // Value is undefined
printf("data.floatValue: %.2f\n", data.floatValue); // Value is undefined

return 0;
}

Key Differences

Feature Structure (struct) Union (union)


Memory Each member has its own All members share the same memory
Allocation memory location. location.
4
Feature Structure (struct) Union (union)
Sum of sizes of all members plus
Size Size of the largest member.
padding.
Simultaneous Can store and access multiple Only one member can hold a value at a
Use members at once. time.
Useful for grouping data where Useful for handling different types of data
Use Case
all pieces are needed. where only one type is needed.
Accessing Only the most recently assigned member
Directly access each member.
Members contains a meaningful value.

3. ENUMERATED DATA TYPES


Enumerated data types (enums) in C are a way to define a variable that can hold a set of
predefined constants. They are useful for creating variables that can only take on a limited set of
values, making the code more readable and manageable.
Syntax
Defining an Enum:
enumEnumName {
Constant1,
Constant2,
Constant3,
// ...
};
EnumName- is the name of the enumeration type.
Constant1, Constant2, etc., are the named integer constants.
Example:
enum Days {
SUNDAY, // By default, SUNDAY = 0
MONDAY, // MONDAY = 1
TUESDAY, // TUESDAY = 2
WEDNESDAY, // WEDNESDAY = 3
THURSDAY, // THURSDAY = 4
5
FRIDAY, // FRIDAY = 5
SATURDAY // SATURDAY = 6
};
Key Points
Default Values: By default, the first name in the enumeration list is assigned the value 0, and
each subsequent name is assigned the next integer value.
Custom Values: You can assign specific values to enumeration constants.
Example:
enum Status {
SUCCESS = 1,
WARNING = 2,
ERROR = 4
};
Using Enums: can declare variables of the enum type and use them in the code.

enum Days today;


today = WEDNESDAY;
Size and Storage: Enums in C are typically stored as integers, but the size can be
implementation-dependent.
Type Safety: While enums make code more readable, they do not provide strong type safety
compared to other languages with enum support.

Example Code
#include <stdio.h>
enum Color {
RED, // RED is assigned the value 0
GREEN, // GREEN is assigned the value 1
BLUE // BLUE is assigned the value 2
};
int main() {
enum Color favorite_color;
favorite_color = GREEN; // This sets favorite_color to 1
if (favorite_color == GREEN) // Condition Check
6
{
printf("Your favorite color is green!\n");
} else {
printf("Your favorite color is not green.\n");
}
return 0;
}
In this example, the Color enum is used to specify colors, and the program checks if the
favorite_color is GREEN.

4. Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type
integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example

In the above figure, pointer variable stores the address of number variable, i.e., fff4. The value
of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
7
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore
printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer
therefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

You might also like