0% found this document useful (0 votes)
4 views

CS3353-UNIT II (1)

This document provides an overview of advanced features in C programming, focusing on structures, unions, enumerated data types, and pointers. It explains how to define and access structures, initialize them, and use nested structures and arrays of structures. Additionally, it covers unions, their operations, and how to work with pointers, including pointers to functions and arrays.

Uploaded by

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

CS3353-UNIT II (1)

This document provides an overview of advanced features in C programming, focusing on structures, unions, enumerated data types, and pointers. It explains how to define and access structures, initialize them, and use nested structures and arrays of structures. Additionally, it covers unions, their operations, and how to work with pointers, including pointers to functions and arrays.

Uploaded by

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

UNIT II

C PROGRAMMING -
ADVANCED FEATURES
C Structure
* Arrays allow to define type of variables that can hold
several data items of the same kind.
* Similarly structure is another user defined data type
available in C that allows to combine data items of
different kinds.
For example, an entity Student may have its name
(string), roll number (int), marks (float).
✔Construct individual arrays for storing names, roll
numbers, and marks.
✔Use a special data structure to store the collection of
different data types.
Defining a Structure
* The ,struct keyword is used to define the
structure.
struct structure_name
{
data_type member1;
data_type member2;
…..
data_type memeberN;
};
In structure, data is stored in form of
records.
Example:
struct employee
{ int id;
char name[20];
float salary;
};
struct is the keyword; employee is the name of the
structure; id, name, and salary are the members or fields
of the structure.
Declaring structure
*variable
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
* 1st way:
To declare the structure variable by struct keyword. It should be declared
within the main function.
struct employee struct Student
{ int id; {
char name[50]; char name[25];
float salary; int age;
}; char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2;
* 2nd way:
To declare variable at the time of defining the
structure.
struct employee struct Student
{ int id; {
char name[50]; char name[25];
float salary; int age;
}e1,e2; char branch[10];
//F for female and M for
male
char gender;
}S1, S2;
If number of variables are not fixed, use the 1st
approach. It provides you the flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It
saves your code to declare a variable in main() function.
Accessing Structure
Members
* To access any member of a structure, we use the
member access operator (.)
* You would use the keyword struct to define
variables of structure type.
/* book 2 specification */
Example strcpy( Book2.title, "Telecom Billing");
#include <stdio.h> strcpy( Book2.author, "Zara Ali");
#include <string.h> strcpy( Book2.subject, "Telecom Billing
struct Books { char title[50]; Tutorial");
char author[50]; Book2.book_id = 6495700;
char subject[100]; /* print Book1 info */
int book_id; }; printf( "Book 1 title : %s\n", Book1.title);
int main( ) printf( "Book 1 author : %s\n",
Book1.author);
{
printf( "Book 1 subject : %s\n",
struct Books Book1; Book1.subject);
/* Declare Book1 of type Book */ printf( "Book 1 book_id : %d\n",
struct Books Book2; Book1.book_id);
/* Declare Book2 of type Book */ /* print Book2 info */
/* book 1 specification */ printf( "Book 2 title : %s\n", Book2.title);
strcpy( Book1.title, "C printf( "Book 2 author : %s\n",
Programming"); Book2.author);
strcpy( Book1.author, "Nuha Ali"); printf( "Book 2 subject : %s\n",
Book2.subject);
strcpy( Book1.subject, "C
printf( "Book 2 book_id : %d\n",
Programming Tutorial"); Book2.book_id);
Book1.book_id = 6495407; return 0;
Structure Initialization
* A variable of any other datatype, structure variable can also
be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
Or
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Nested Structures
* If a structures contains one or more structures as its members, it is
known as a nested structure.
Struct date
{
Int day;
Char month[10];
Int year;
};
This structure date may be used as a member in another structure
as given bellow:
Struct employee
{
Char name[30];
Int age; char sex;
Struct date dob; /*inner structure variable definition */
};
ARRAY OF STRUCTURES
* A group of structures may be organized in an array
resulting in an array of structures. Each element in the
array is a structure . C allows declaring an array of
structures.
Struct employee
{
Char name[25];
Int age;
Char sex;
Struct date dob;
};
Struct employee emp[5];
Defines an array of 5 structures. Each structure variable
emp[0],emp[1],…emp[4] contains structure as its value
UNION
* A union is a special data type available in C that allows to store
different data types in the same memory location.
* You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of
using the same memory location for multiple-purpose.
DEFINING A UNION:
✔To define a union, you must use the union keyword
✔The union statement defines a new data type with more than one
member for your program. union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Memory size occupied by data: 20
Accessing Union Members

* To access any member of a union, we use the member access


operator (.). The member access operator is coded as a period
between the union variable name and the union member that
we wish to access.
* You would use the keyword union to define variables of union
type.
#include <stdio.h>
#include <string.h>
OUTPUT:
union Data
data.i : 1917853763
{
data.f : 4122360580327794860452759994368.0000
int i;
data.str : C Programming
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
#include <stdio.h>
#include <string.h>
union Data
Output:
{
data.i : 10
int i;
data.f : 220.500000
float f;
data.str : C Programming
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
All the members are getting printed very well because one
member is being used at a time.
OPERATIONS OF MEMBERS

* While all the structure members can be accessed at any point of


time, only one member of a union may be accessed at any
given time
* This is because, at any instant only one of the union variables
will have a meaningful value. Only at that point, other variable
will contain garbage.
* It is the responsibility of the programmer to keep track of the
active variable
OPERATIONS ON A UNION
* A Union variable can be assigned to another union variable
* A union variable can be passed to a function as a parameter
* The address of the union variable can be extracted by using the
address of operator (&)
* A function can accept or return a union or pointer to a union
ENUMERATED DATA TYPE
* Enumeration is a user defined datatype in C language.
* It is used to assign names to the integral constants which makes
a program easy to read and maintain.
* The keyword “enum” is used to declare an enumeration.
enum enum_name{const1, const2, ....... };
* The enum keyword is also used to define the variables of enum
type.
* There are two ways to define the variables of enum type as
follows.
enum week{sunday, monday, tuesday, wednesday, thursday,
friday, saturday}; enum week day;
Example
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon ,
Tue, Wed, Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t
%d",Mond , Tues, Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output:
The value of enum week: 10111213101617
The default value of enum day: 0123181112
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.
Accessing the address of a variable
without pointers
#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p * format
specifier and ampersand (&) sign just * before the variable
name like &num. */
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:
Value of variable num is: 10
Address of variable num is: 0x7fff5694dc58
A Simple Example of Pointers in C
* The data type of pointer and the variable must match,
* An int pointer can hold the address of int variable, similarly a pointer
declared with float data type can hold the address of a float variable.
#include <stdio.h>
int main()
{
//Variable declaration int num = 10;
//Pointer declaration
int *p;
//Assigning address of num to the pointer p
p=#
printf("Address of variable num is: %p", p);
return 0;
C Pointers – Operators that are used
with Pointers
* The operators & and * that are used with Pointers in C.
“Address of”(&) Operator
The & operator is also known as “Address of” Operator.
int num = 10;
printf("Address of var is: %p", &num);
%p is a format specifier which is used for displaying the address
in hex format.
“Value at Address”(*) Operator
The * Operator is also known as Value at address operator.
int *p1 /*Pointer to an integer variable*/
double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
Pointer to an Array in C
An array name is a constant pointer to the first
element of the array
Syntax:
data_type (*var_name)[size_of_array];
Example:
double balance[50];
balance is a pointer to &balance[0], which is the address of
the first element of the array balance. Thus, the following program
fragment assigns p as the address of the first element of balance
double *p;
double balance[10];
p = balance;
#include <stdio.h>
int main ()
{
/* an array with 5 elements */ OUTPUT:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, Array values using pointer
50.0};
double *p; int i; p = balance; *(p + 0) : 1000.000000
/* output each array element's value */ *(p + 1) : 2.000000
printf( "Array values using pointer\n"); *(p + 2) : 3.400000
for ( i = 0; i < 5; i++ ) *(p + 3) : 17.000000
{ *(p + 4) : 50.000000
printf("*(p + %d) : %f\n", i, *(p + i) );
} Array values using balance as
printf( "Array values using balance as address
address\n"); *(balance + 0) : 1000.000000
for ( i = 0; i < 5; i++ ) *(balance + 1) : 2.000000
{ *(balance + 2) : 3.400000
printf("*(balance + %d) : %f\n", i,
*(balance + i) ); *(balance + 3) : 17.000000
} *(balance + 4) : 50.000000
return 0;
}
;

Array Name as Pointers


* An array name acts like a pointer constant. The value of this
pointer constant is the address of the first element.
* For example, if we have an array named val then val and
&val[0] can be used interchangeably.
Pointers and Multidimensional Arrays :
int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };
In general, nums[i][j] is equivalent to *(*(nums+i)+j)
Pointer Notation Array Notation Value

*(*nums) nums[0][0] 16

*(*nums + 1) nums[0][1] 18

*(*nums + 2) nums[0][2] 20

*(*(nums + 1)) nums[1][0] 25

*(*(nums + 1) + 1) nums[1][1] 26

*(*(nums + 1) + 2) nums[1][2] 27
POINTER TO FUNCTION
* The general syntax for a pointer to a function
return_type(*pointer_name)(list of parameter)
For example,
void(*p)(float int);
This declaration of a pointer to a function returns void and
takes the two formal arguments of a float and int types
after declaring a pointer to a function the address of the
function must be assigned to a pointer aa follows
p=&function_name;
P-pointer variable
Through pointer to function is called as follows:
a=(*p)(x,y);
#include <stdio.h>
int add(int,int); return 0;
int main() }
{ int add(int a,int b)
int a,b; {
int (*ip)(int,int); int c=a+b;
int result; return c;
printf("Enter the values of a and b : "); }
OUTPUT:
scanf("%d %d",&a,&b); Enter the values of a and
ip=add; b : 4 55
result=(*ip)(a,b); Value after addition is :
59
printf("Value after addition is : %d",res
ult);
FILE HANDLING
STREAMS IN C
* C can handle files as Stream-oriented data (Text)
files and System oriented data (Binary) files.

The data is stored in the same manner as


it appears on the screen. The I/O
Stream-oriented data
operations like buffering, data
files
conversions, etc., take place
automatically.

System-oriented data files are more


System-oriented data closely associated with the OS and data
files stored in memory without converting into
text format
Types of Files in C
Two types of files
* Text file
* Binary file
Text file - User can create these types of files easily while
dealing with file handling in C. It stores information in the
form of ASCII characters internally and when the file is
opened, the content is readable by humans. It can be created
by any text editor with a .txt or .rtf (rich text)extension. Since
text files are simple, they can be edited by any text editor like
Microsoft Word, Notepad, Apple Text edit etc.
Binary file - It stores information in the form of 0’s or 1’s
and it is saved with .bin extension, therefore it takes less
space. Since it is stored in the format of a binary number
system it is not readable by humans. Therefore it is more
secure than a text file.
C FILE OPERATIONS
File handling in C enables us to create, update,
read, and delete the files stored on the local file
system through our C program.
* Creation of the new file
* Opening an existing file
* Reading from the file
* Writing to the file
* Deleting the file
FILE HANDLING IN C
Function Description Syntax
Used to open an
FILE *fopen(“file_name”,
fopen() existing file or to
“mode”);
create a new file
fprintf(FILE *stream, const
Used to write data in
fprintf() char *format [,
existing file
argument, ...])
fscanf(FILE *stream, const
Used to read data
fscanf() char *format [,
from the file
argument, ...])
Used to write
fputc() fputc(int c, FILE *stream)
characters in a file
Used to read
fgetc() fgetc(FILE *stream)
characters from a file
Used to close
fclose() fclose( FILE *fp )
puts the file pointer to fseek(FILE *stream, long int
fseek()
the specified place offset, int whence)

Used to write integral


fputw() fputw(int number,File *fp)
value in the file

Used to read integral


fgetw() fgetw(File *fp)
value from the file

It will return the current


ftell() position of the file ftell(FILE *stream)
pointer in the file

the file pointer is set to


rewind() rewind(FILE *stream)
the start of the file
Modes to Open a File in C
* To open a file we use fopen() with different opening
modes
Mode Description Example
opens a text file in read-
r fopen(“demo.txt”, “r”)
only mode
opens a text file in the fopen(“demo.txt”,
w
write-only mode “w”)
opens a text file in append fopen(“demo.txt”,
a
mode “a”)
opens a text file in read fopen(“demo.txt”,
r+
and write mode “r+”)
opens a text file in read
w+ fopen(“demo.txt”, “w+”)
and write modes
Mode Description Example
opens a text file in read fopen(“demo.txt”,
a+
and write modes “a+”)
opens a binary file in fopen(“demo.txt”,
rb
read mode. “rb”)
opens a binary file in fopen(“demo.txt”,
wb
write mode. “wb”)
opens a binary file in fopen(“demo.txt”,
ab
append mode “ab”)
opens a binary file in fopen(“demo.txt”,
rb+
read and write modes “rb+”)
opens a binary file in fopen(“demo.txt”,
wb+
read and write modes “wb+”)
opens a binary file in fopen(“demo.txt”,
ab+
read and write modes “ab+”)
Opening File: fopen()
#include<stdio.h> Output:
void main( ) #include;
void main( )
{
{
FILE *fp ;
FILE *fp; // file pointer
char ch ; char ch;
fp = fopen("file_handle.c","r") ; fp = fopen("file_handle.c","r");
while ( 1 ) while ( 1 )
{ {
ch = fgetc ( fp ) ; ch = fgetc ( fp ); //Each character of
the file is read and stored in the
if ( ch == EOF ) character file.
break ; if ( ch == EOF )
printf("%c",ch) ; break;
} printf("%c",ch);
fclose (fp ) ; }
fclose (fp );
}
PREPROCESSOR DIRECTIVES

* The C Preprocessor is not a part of the compiler,


but is a separate step in the compilation process.
* All preprocessor commands begin with a hash
symbol (#). It must be the first nonblank character,
and for readability, a preprocessor directive should
begin in the first column.
* Before the compilation process, the source code goes
through preprocessing which is done by the
preprocessor.
S.No. Directive & Description
1 #define-Substitutes a preprocessor macro.

2 #include-Inserts a particular header from another file.

3 #undef-Undefines a preprocessor macro.

4 #ifdef-Returns true if this macro is defined.

5 #ifndef-Returns true if this macro is not defined.

6 #if-Tests if a compile time condition is true.

7 #else-The alternative for #if.

8 #elif-#else and #if in one statement.

9 #endif-Ends preprocessor conditional.

10 #error-Prints error message on stderr.

#pragma-Issues special commands to the compiler, using a standardized


11
method.
Pre-processors Examples

#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of
MAX_ARRAY_LENGTH with 20. Use #define for constants to
increase readability.

#include <stdio.h>
#include "myheader.h"
stdio.h from System Libraries and add the text to the current
source file.
The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
The CPP to undefine existing FILE_SIZE and define it as 42.
Macros in C Language
* The macro in C language is known as the piece of code
which can be replaced by the macro value
* The macro is defined with the help of #define
preprocessor directive and the macro doesn’t end with
a semicolon(;)
* Macro is just a name given to certain values or
expressions it doesn't point to any memory location.
* The syntax of the macro is

#define - Preprocessor Directive


PI - Macro Name
3.14 - Macro Value
#include<stdio.h>
// This is macro definition
#define PI 3.14
void main()
{
// declaration and initialization of radius
int radius = 5;
// declaration and calculating the area
int area = PI * (radius*radius);
// Printing the area of circle
printf("Area of circle is %d", area);
}
OUTPUT:
Area of circle is 78.500000
Types of Macros in C Language
* Object like Macros in C
// Examples of object like macros in C language
#define MAX 100
#define MIN 1
#define GRAVITY 9.8
#define NAME "Scaler“
#define TRUE 1
#define FALSE 0
Function Like Macros in C
#include <stdio.h>
//object like macro
#define PI 3.14
// function like macro
#define Area(r) (PI*(r*r))
void main()
{
// declaration and initialization of radius
float radius = 2.5;
// declaring and assgining the value to area
float area = Area(radius);
// Printing the area of circle
printf("Area of circle is %f\n", area);
// Using radius as int data type
int radiusInt = 5;
printf("Area of circle is %f", Area(radiusInt));
}
Output:
Area of circle is 19.625000
Area of circle is 78.500000
Chain Like Macros in C
When we use one macro inside another macro then it is known
as the chain-like macro.
the example of chain-like macro in the above code example
where we used the PI in Area.
#define PI 3.14
#define Area(r) (PI*(r*r))
Sr. No. Macro Name Description

Value or code segment gets


1 Object Like
replaced with macro name

The macro which takes an


2 Function Like argument and acts as a
function
The macro inside another
3 Chain Like
macro

You might also like