0% found this document useful (0 votes)
20 views37 pages

23cse201 - Unit III Notes

The document outlines the course 'Procedural Programming Using C' for B.Tech. CSE students at Amrita School of Computing, detailing course objectives, outcomes, and a comprehensive syllabus. It covers essential programming concepts in C, including data types, control structures, functions, arrays, structures, and unions, with practical examples and exercises. Additionally, it provides references and textbooks for further reading and understanding of the subject matter.

Uploaded by

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

23cse201 - Unit III Notes

The document outlines the course 'Procedural Programming Using C' for B.Tech. CSE students at Amrita School of Computing, detailing course objectives, outcomes, and a comprehensive syllabus. It covers essential programming concepts in C, including data types, control structures, functions, arrays, structures, and unions, with practical examples and exercises. Additionally, it provides references and textbooks for further reading and understanding of the subject matter.

Uploaded by

ADVAITH.S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Department of Computer Science and Engineering

Amrita School of Computing

III Semester [Link]. CSE

23CSE201- PROCEDURAL PROGRAMMING

USING C

AY 2025-2026

Theory Notes

Prepared by
[Link] Raja, AP/CSE

Dr. V. Thanammal Indu, AP/CSE

1
23CSE201 PROCEDURAL PROGRAMMING USING C L-T-P-C: 3-0-2-4
Course Objectives
This course aims to provide the procedural/imperative programming principles to the
students through C programming language. The language will be taught in the context of
Physical Computing using Arduino
Course Outcomes
• CO1: Understand the typical programming constructs: data (primitive and compound),
control, modularity, recursion etc. thereby to understand a given program.
• CO2: Analyse a given program by tracing, identify coding errors and debug them.
• CO3: Apply the programming constructs appropriately and effectively while
developing computer program.
• CO4: Develop computer programs that implement suitable algorithms for problem
scenarios and applications.
CO-PO Mapping
PO/PSO PO PO PO PO PO PO PO PO PO9 PO1 PO1 PO1 PSO1 PSO2
& CO 1 2 3 4 5 6 7 8 0 1 2
CO1 2 1 - - - - - - - - - - 2 2
CO2 2 1 1 - 2 - - - - - - - 2 2
CO3 2 2 2 - 2 - - - - - - - 2 2
CO4 3 2 3 - 3 - - - - - - - 2 2
Syllabus
Unit 1
Review of Physical Computing, Understanding Arduino Hardware and Software Architecture
- Verifying Hardware and Software - Loading and Running your First Program
Introduction to C - Structure of C programs - Data types - I/O - control structures.
Unit 2
Arrays - Functions - Storage Classes and Scope - Recursion - Pointers: Introduction, pointer
arithmetic, arrays and pointers, pointer to functions, dynamic memory allocation.
Unit 3
Structures, Unions and Data Storage - Strings: fixed length and variable length strings, strings
and characters, string manipulation functions - Files and Streams - C Preprocessor - Command
line arguments.
Textbook(s)
1. Jack Purdum, “Beginning C for Arduino”, Second Edition, APress, 2015.
Reference(s)
1. Peter Linz and Tony Crawford, “C in a Nutshell: The Definitive Reference”,
Second Edition, O'Reily Media, 2016.
2. Jens Gustedt, “Modern C”, Manning Publications, 2019.
3. Robert C. Seacord, Effective C - “An Introduction to Professional C
Programming”, No Starch Press, 2020.
4. Daniel Gookin, “Tiny C Projects”, Manning Publications, 2022.

2
Unit 3

Structures, Unions and Data Storage - Strings: fixed length and variable length strings, strings
and characters, string manipulation functions - Files and Streams - C Preprocessor - Command
line arguments.

1. Structures
What is a Structure?
• Collection of one or more variables of different data types, grouped together under
a single name.
• It is a user defined data type that hold different types of elements.
• Each element is a member.
• Used to store student information,employee information etc.
Defining a Structure
“struct” keyword is used.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type membern;
};
Example
struct student
{
int roll_no;
char name[20];
float gpa;
};
struct → keyword
student → structure name
roll_no,name,gpa → members

Declaring a structure variable


• Inside main() function
struct student
{
int roll_no;
char name[20];
float gpa;
};
int main ()
{
struct student s1,s2,s3;
-------------
-------------
}
3
• In structure definition
struct student
{
int roll_no;
char name[20];
float gpa;
} s1,s2;
Accessing structure
• Structure uses dot operator (.) to access members
• [Link]
• Example:

Example 1
#include <stdio.h>
#include <string.h>
// Define a structure for Student
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
// Declare a structure variable
struct Student s1;
// Assign values to members
[Link] = 101;
strcpy([Link], "Arun");
[Link] = 89.5;
// Print structure details
printf("Student Details:\n");
printf("Roll No: %d\n", [Link]);
printf("Name : %s\n", [Link]);
printf("Marks : %.2f\n", [Link]);
return 0;
}

Output
Student Details:
Roll No: 101
Name : Arun
Marks : 89.50
Structure Initialization
4
The initialization of a struct variable is done by placing the value of each element inside
curly brackets.
struct book{
char title[50];
char author[50];
double price;
int pages;
} book1;
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
Example 2
#include <stdio.h>
struct book{
char title[10];
char author[20];
double price;
int pages;
};
int main(){
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
printf("Title: %s \n", [Link]);
printf("Author: %s \n", [Link]);
printf("Price: %lf\n", [Link]);
printf("Pages: %d \n", [Link]);
printf("Size of book struct: %d", sizeof(struct book));
return 0;
}
Output
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
Copying Structures
The assignment (=) operator can be used to copy a structure directly.
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325}, book2;
strcpy([Link], [Link]);
strcpy([Link], [Link]);
[Link] = [Link];
[Link] = [Link];
Example 3
#include <stdio.h>
#include <string.h>
struct book{
char title[10];
char author[20];
double price;
int pages;
};
int main(){
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325}, book2;
book2 = book1;
printf("Title: %s \n", [Link]);

5
printf("Author: %s \n", [Link]);
printf("Price: %lf \n", [Link]);
printf("Pages: %d \n", [Link]);
printf("Size of book struct: %d", sizeof(struct book));
return 0;
}
Output
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
Nested structure
• Nested structure in C is nothing but structure within structure.
• One structure can be declared inside other structure as we declare structure
members inside a structure.
Defining nested structure
• The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
By a separate structure
• Create two structures (main and dependent)
• The dependent structure should be used inside the main structure as a member.
Example
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
Embedded structure
• The embedded structure enables us to declare the structure inside the structure.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;

Accessing Nested Structure

6
We can access the member of the nested structure by:
Outer_Structure.Nested_Structure.member
Example:
[Link]
[Link]
[Link]
Example 4
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;

int main( )
{
//storing employee information
[Link]=101;
strcpy([Link], "Sonoo Jaiswal");//copying string into char array
[Link]=10;
[Link]=11;
[Link]=2014;
//printing first employee information
printf( "employee id : %d\n", [Link]);
printf( "employee name : %s\n", [Link]);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", [Link],[Link],e1
.[Link]);
return 0;
}

Passing structure to function


• Just like other variables, a structure can also be passed to a function.
• We may pass the structure members into the function or pass the structure variable
at once.
Example
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];

7
struct address add;
};
void display(struct employee);
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",[Link],[Link], &[Link], [Link]);
display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....\n");
printf("%s %s %d %s",[Link],[Link],[Link],[Link]);
}
Array of structures
• An array is a collection of similar datatypes
• We can also define array of structure
• Every element is of structure type
Declaration
struct time
{
int second;
int minute;
int hour;
} t1[3];
(OR)
struct time t2[3];
Accessing members
Structure-array-variable[index].member-name
Example 5
#include <stdio.h>
struct book{
char title[20];
char author[30];
double price;
int pages;
} books[3];
int main()
{ double total=0;
for(int i=0;i<3;i++)
{ printf("\nEnter title:");
scanf("%s",&books[i].title);
printf("\nEnter author:");
scanf("%s",&books[i].author);
printf("\nEnter price:");
scanf("%lf",&books[i].price);
printf("\nEnter pages:");
scanf("%s",&books[i].pages);
}
for(int i=0;i<3;i++)
{

8
printf("\nTitle: %s",books[i].title);
printf("\nAuthor: %s",books[i].author);
printf("\nPrice: %lf",books[i].price);
printf("\nPages: %d",books[i].pages);
total+=books[i].price;

}
printf("Total price=%.2lf",total);
return 0;
}
Structures and Pointers
• Pointer is a variable that holds the address of another variable.
• Pointers can be defined to structure
• These pointers point to the starting address of the member variables.
• Such pointers are called structure pointers
Example
struct book
{
char name[50];
char author[25];
float price;
};
struct book b1;
struct book *ptr;
ptr=&b1;
Accessing members of structure using pointers
• Using * and . Dot operator
• Using -> operator
Using * and . Dot operator

Using -> operator

Example Program
#include <stdio.h>
9
#include <string.h>
struct book {
char name[50];
float price;
};
int main() {
struct book b1 = {"Programming in C", 300};
struct book *ptr;
ptr = &b1;
printf("Book name: %s\n", ptr->name);
printf("Book price: %f\n", ptr->price);
// Changing name and price
strcpy(ptr->name, "Python Programming");
ptr->price = 250;
printf("Book name: %s\n", ptr->name);
printf("Book price: %f\n", ptr->price);
return 0;
}
Output
Book name: Programming in C
Book price: 300.000000
Book name: Python Programming
Book price: 250.000000
Self Referential structures
• Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.

Types of Self Referential Structures


• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
Self Referential Structure with Single Link
• These structures can have only one self-pointer as their member.

Self Referential Structure with Multiple Links


10
• Self referential structures with multiple links can have more than one self-pointers.

2. Unions and Data Storage


Union
• A union is a user-defined data type 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 point in time.
• The value of a union variable can be accessed using the dot (.) operator.
• A value can be assigned to the union variable using the assignment operator (=).
Union Declaration
• A union is declared similarly to a structure.
• Provide the name of the union and define its member variables:
union union_name{
type1 member1;
type2 member2;
type3 member3;
. .
. .
};
union_name variable_name;

Declare a variable at the declaration of union

union union_name{
type1 member1;
type2 member2;
type3 member3;
. .
. .
} variable_name;

Size of Union
• The size of the union will always be equal to the size of the largest member of the
union.
• All the less-sized elements can store the data in the same space without any
overflow.
Example
#include <stdio.h>
union A{
int x;
char y;
};
union B{
int arr[10];

11
char y;
};
int main() {
// Finding size using sizeof() operator
printf("Sizeof A: %ld\n", sizeof(union A));
printf("Sizeof B: %ld\n", sizeof(union B));
return 0;
}

Output
Sizeof A: 4
Sizeof B: 40

How unions use memory in C


• In a struct, all members get their own memory, so the total size is (approximately)
the sum of the members.
• In a union, all members share the same memory space, so the size of the union =
size of the largest member.
• At any given time, only one member’s value is valid (the last one you assigned)
Example 2
#include <stdio.h>
#include <string.h>
union data {
int x;
float y;
};
int main() {
union data d;
d.x = 10; // store int
printf("x = %d\n", d.x);
d.y = 20.5; // now store float
printf("y = %f\n", d.y);
// checking x after assigning y
printf("x = %d\n", d.x);
12
return 0;
}

Output
• Memory Usage
• int x; → needs 4 bytes
• float y; → needs 4 bytes
• So union data uses 4 bytes total (the max of 4 and 4, not 8).
• Output (depends on compiler, but typically):
x = 10
y = 20.500000
x = 1103626240 // garbage value (because y overwrote x’s memory)
So if 2 members in a union both have values, in reality only the last written value is
valid. The previous one is overwritten because they share memory.
Example 3
#include <stdio.h>
#include <string.h>
union Data{
int i;
float f;
char str[20];
};
int main(){
union Data data;
data.i = 10;
data.f = 220.5;
strcpy([Link], "C Programming");
printf("data.i: %d \n", data.i);
printf("data.f: %f \n", data.f);
printf("[Link]: %s \n", [Link]);
return 0;
}
Output
• data.i: 1917853763
• data.f: 4122360580327794860452759994368.000000
• [Link]: C Programming
• Here, we can see that the values of i and f (members of the union) show garbage
values because the final value assigned to the variable has occupied the memory
location and this is the reason that the value of str member is getting printed very
well.
Example 4
#include <stdio.h>
#include <string.h>
union Data{
int i;
float f;
char str[20];
};
int main(){
union Data data;
data.i = 10;
printf("data.i: %d \n", data.i);

13
data.f = 220.5;
printf("data.f: %f \n", data.f);
strcpy([Link], "C Programming");
printf("[Link]: %s \n", [Link]);
return 0;
}
Output
• data.i: 10
• data.f: 220.500000
• [Link]: C Programming
• Here, the values of all the Union members are getting printed very well because one
member is being used at a time.
Real time applications of Unions
• Unions have important real-time applications where memory efficiency and data
reinterpretation are needed.
• Memory Optimization in Embedded Systems
• In network programming, protocols, file formats
• Variant Data Structures
• Communication Protocols & Device Drivers
Nested Union
• In C, we can define a union inside another union like structure.
• This is called nested union and is commonly used when you want to efficiently
organize and access related data while sharing memory among its members.
union name1{
// Data members
union name2{
// Data members
};
};
[Link]

Example 5
#include <stdio.h>
union Student {
int rollNo;
union Academic{
int marks;
} performance;
};
int main() {
union Student abc;
[Link] = 21;
printf("%d\n", [Link]);
[Link] = 91;
printf("%d", [Link]);
return 0;
}

Difference between Structure and Union


• Both structures and unions are composite data types in C programming.
• The most significant difference between a structure and a union is the way they store
their data.
14
• A structure stores each member in separate memory locations, whereas a union stores
all its members in the same memory location.
union myunion{
int a;
double b;
char c;
};
struct mystruct{
int a;
double b;
char c;
};
• The main difference between a struct and a union is the size of the variables.
• The compiler allocates the memory to a struct variable, to be able to store the values for
all the elements.
• In mystruct, there are three elements − an int, a double, and char, requiring 13 bytes (4
+ 8 + 1). Hence, sizeof(struct mystruct) returns 13.
• On the other hand, for a union type variable, the compiler allocates a chunk of memory
of the size enough to accommodate the element of the largest byte size.
• The myunion type has an int, a double and a char element.
• Out of the three elements, the size of the double variable is the largest, i.e., 8.
Hence, sizeof(union myunion) returns 8.
Memory Allocation for Individual Members
Each data type inside a structure occupies memory according to its size and alignment
requirements:
Data Type Typical Size (on 32-bit/64-bit systems)
int 4 bytes
float 4 bytes
double 8 bytes
These sizes can vary slightly depending on the compiler and system architecture.

How a Structure Allocates Memory


When you define a structure, the compiler allocates memory for each member sequentially,
but it also adds padding bytes to satisfy alignment requirements (i.e., each type should start
at an address that’s a multiple of its size).

For example:

struct Example {
int a; // 4 bytes
float b; // 4 bytes
double c; // 8 bytes
};

int a: starts at offset 0 → occupies 4 bytes

float b: starts at offset 4 → occupies 4 bytes

double c: starts at offset 8 → occupies 8 bytes

Total size: 4 + 4 + 8 = 16 bytes


15
Padding and Alignment
If the order of members is changed, padding may be added to align memory properly:

struct Example2 {
char x; // 1 byte
double y; // 8 bytes
int z; // 4 bytes
};

Memory layout:

char x: 1 byte (offset 0)

Padding: 7 bytes (to align double at 8-byte boundary)

double y: 8 bytes (offset 8)

int z: 4 bytes (offset 16)

Padding: 4 bytes (to align structure size to largest member, 8)

Total size: 1 + 7 + 8 + 4 + 4 = 24 bytes


Structure as a Whole
• The size of the structure is the sum of all member sizes plus padding.
• The alignment of the structure is usually equal to the alignment requirement of its
largest member.
• This ensures arrays of the structure are also properly aligned in memory.

Summary Table:
Member Typical Size Notes on Allocation
int 4 bytes Aligned to 4 bytes
float 4 bytes Aligned to 4 bytes
double 8 bytes Aligned to 8 bytes
Structure ≥ sum of all Includes padding to satisfy alignment rules
A structure stores each member one after another, but the compiler may insert padding to
align each variable according to its size. The total size of the structure is always a
multiple of the largest member’s alignment requirement.

3. Strings
• A C string is a variable-length array of characters that is delimited by the null
character.

Type of string
16
• No explicit type, instead strings are maintained as arrays of characters
• Representing strings in C
• stored in arrays of characters
• array can be of any length
• end of string is indicated by a delimiter, the zero character ‘\0’

A string literal is enclosed in double quotes.

Declare a string
• There are two ways to declare a string in c language.
• By char array
• By string literal
Example:
• char s[5];
• char s[ ]=“hello”;

Initialize strings
• char c[] = "abcd";
• char c[50] = "abcd";
• char c[] = {'a', 'b', 'c', 'd', '\0'};
• char c[5] = {'a', 'b', 'c', 'd', '\0'};

Error
• char c[100];
• c = "C programming"; // Error! array type is not assignable.
scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
17
return 0;
}
Enter name: Dennis Ritchie
Your name is Dennis.
To read a line of text
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%[^\n]s",s);
printf("Your name is %s.", name);
return 0;
}
Enter name: Dennis Ritchie
Your name is Dennis Ritchie
fgets function to read a line
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Enter name: Tom Hanks
Name: Tom Hanks
4. Fixed length and Variable length strings
Fixed-Length Strings
• A string where memory is allocated with a fixed size (predefined length).
• Characteristics:
• The maximum size is known in advance.
• If the actual string is shorter, unused space is filled with padding (often nulls or
blanks).
• Access is fast because indexing is straightforward.
• Wastage of memory can happen if the string stored is much smaller than the
allocated length.
Example
• char name[20]; // Fixed length: always reserves 20 bytes
• strcpy(name, “Hello");
• Even though “Hello” is 5 characters, memory for 20 characters is reserved.
Variable-Length Strings
• A string where memory allocation is dynamic, depending on the actual content.
• Characteristics:
• Length is not fixed at compile time—it can change at runtime.
• Memory is used efficiently (no large unused space).
• More complex to manage because of dynamic allocation.
• Access speed may be slower compared to fixed-length strings.
Example in C (Dynamic Allocation)
• char *name;
18
• name = (char*) malloc(5 * sizeof(char));
• strcpy(name, “Hello"); // Allocates only required memory
Difference
Variable-Length
Aspect Fixed-Length String
String
Predefined, at Dynamic, based on
Memory Allocation
compile-time actual content
May waste memory Efficient, no unused
Memory Usage
(padding) space
Faster (direct Slightly slower
Access Speed
indexing) (needs management)
Rigid (size can’t Flexible (size can
Flexibility
change) grow/shrink)
Example char s[20]; char *s = malloc(n);

5. Strings and characters


Characters in C
• A character is a single symbol, letter, or digit.
• In C, characters are represented using char data type.
• Size: usually 1 byte (can store 256 different values in ASCII).
• A character is enclosed in single quotes ' ‘
• Internally, these are stored as their ASCII values (e.g., 'A' = 65).
Example
• char ch1 = 'A'; // character A
• char ch2 = '9'; // digit character
• char ch3 = '#'; // special character
Strings in C
• A string is a sequence of characters terminated by a null character '\0'.Declared as
an array of char.
• char str1[] = "Hello";
• // automatically adds '\0'
• char str2[10] = "Hi";
• // reserves 10 bytes, stores "Hi\0"
• char str3[] = {'C','o','d','e','\0'};
• // explicit way
• "Hello" actually stored in memory as:
'H' 'e' 'l' 'l' 'o' '\0'

6. String manipulation functions

19
• strlen() - calculates the length of a string
• strcpy() - copies a string to another
• strcmp() - compares two strings
• strcat() - concatenates two strings
• strrev() – reverse the string
C strlen()
• The strlen() function calculates the length of a given string.
• This function takes a string as an argument and returns its length.
• It does not count the null character
Example
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
printf("Length of string a = %u \n",strlen(a));
printf("Length of string b = %u \n",strlen(b));
return 0;
}
Length of string a = 7
Length of string b = 7
C strcpy()
• The strcpy() function copies one string to another string.
• char *strcpy(char *str1, const char *str2)
• str1 – This is the destination string where the value of other string str2 is copied.
str2 – This is the source string, the value of this string is copied to the destination
string.
Example
#include <stdio.h>
#include <string.h>
int main () {
char str1[20];
char str2[20];
//copying the string "Apple" to the str1
strcpy(str1, "Apple");

20
printf("String str1: %s\n", str1);
//copying the string "Banana" to the str2
strcpy(str2, "Banana");
printf("String str2: %s\n", str2);
//copying the value of str2 to the string str1
strcpy(str1, str2);
printf("String str1: %s\n", str1);
return 0;
}
String str1: Apple
String str2: Banana
String str1: Banana
C strcat()
• The strcat() function is used for string concatenation. It concatenates the specified
string at the end of the another specified string.
• char *strcat(char *str1, const char *str2)
• This function takes two pointer as arguments and returns the pointer to the destination
string after concatenation.
str1 – pointer to the destination string.
str2 – pointer to the source string which is appended to the destination string.
Example
#include <stdio.h>
#include <string.h>
int main () {
char str1[50], str2[50];
//destination string
strcpy(str1, "This is my initial string");

//source string
strcpy(str2, ", add this");
//concatenating the string str2 to the string str1
strcat(str1, str2);
//displaying destination string
printf("String after concatenation: %s", str1);
return(0);
}
String after concatenation: This is my initial string, add this
C strcmp()
• The strcmp() function compares two strings and returns an integer value based on
the result.
• int strcmp(const char *str1, const char *str2)
• str1 – The first string
• str2 – The second string
Return value of strcmp()
• This function returns the following values based on the comparison result:
➢ 0 if both the strings are equal
➢ >0 if the ASCII value of first unmatched character of string str1 is greater than the
character in string str2
➢ <0 if the ASCII value of first unmatched character of string str1 is less than the
character in string str2
Example
#include <stdio.h>

21
#include <string.h>
int main () {
char str1[20];
char str2[20];
int result;
//Assigning the value to the string str1
strcpy(str1, "hello");
//Assigning the value to the string str2
strcpy(str2, "hEllo");
result = strcmp(str1, str2);
if(result > 0) {
printf("str1 is greater than str2");
} else if(result < 0) {
printf("str1 is less than str2");
} else {
printf("Both the strings str1 and str2 are equal");
}
return 0;
}
str1 is greater than str2

C strrev()
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello World";
printf("Original String: %s\n", str);
strrev(str); // reverse the string
printf("Reversed String: %s\n", str);
return 0;
}
Output:
Original String: Hello World
Reversed String: dlroW olleH
Strings and Pointers in C
• Similar to arrays, In C, we can create a character pointer to a string that points to
the starting address of the string which is the first character of the string.
#include <stdio.h>
int main(){
char str[20] = "Geeks";
// Pointer variable which stores the starting address of the character array str
char* ptr = str;
// While loop will run till the character value is not equal to null character
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
return 0;
}

22
Strings Literals
• A string literal is a sequence of characters enclosed in double quotes, like "Hello"
or "1234". Internally, it is stored as a constant character array terminated by a null
character '\0'.
#include <stdio.h>
int main() {
// pointer to a string literal
const char *str = "Hello World";
printf("%s\n", str);
return 0;
}
Hello World

7. Files and Streams


Need of file handling in C
• In programming, we may require some specific input data to be generated several
numbers of times.
• It is not enough to only display the data on the console.
• The data to be displayed may be very large,
• Only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data
again and again.
• So we may store it onto the local file system which is volatile and can be accessed
every time.
• Here, comes the need of file handling in C.
What is File?
• A file is a sequence of bytes on the disk where a group of related data is stored.
• File is created for permanent storage of data. It is a ready made structure.
• In C language, a structure pointer of file type is used to declare a file.
Why files?
• Files store data permenantly
• Large input data can be given to the program through file
• Using files data can be moved from one computer to another without changes
Types of files
There are two types of files
1. sequential file
23
2. random access file.
[Link] File: In this type of files data is kept in sequential order if we want to read the
last record of the file, we need to read all records before that record so it takes more time.
As example to access the forty fourth record, then first forty three records should be read
sequentially to reach the forty fourth record.
[Link] access Files: In this type of files data can be read and modified randomly .If we
want to read the last record we can read it directly. It takes less time when compared to
sequential file.
Example: in case the forty fourth record can be accessed directly. It takes less time than the
sequential file.

Types of files
There are 2 kinds of files in which data can be stored in 2 ways either in characters coded in
their ASCII character set or in binary format. They are
• Text Files.
• Binary Files
TEXT FILES
A Text file contains only the text information like alphabets ,digits and special symbols. The
ASCII code of these characters are stored in these [Link] uses only 7 bits allowing 8 bit to
be zero.

1.w(write):
This mode opens new file on the disk for [Link] the file exist,disk for [Link] the file
exist, then it will be over written without then it will be over written without any
confirmation.

syntax:
fp=fopen("[Link]","w");

"[Link]" is filename

"w" is writemode.

2. r (read)
This mode opens an preexisting file for [Link] the file doesn’t Exist then the
compiler returns a NULL to the file pointer
syntax:
fp=fopen("[Link]","r");

3. w+(read and write)


This mode searches for a file if it is found contents are destroyed If the file doesn’t
found a new file is created.
syntax:
fp=fopen("[Link]","w+");

4.a(append)
This mode opens a preexisting file for appending the data.
syntax:
fp=fopen("[Link]","a");

5.a+(append+read)
the end of the file.

24
syntax:
fp=fopen("[Link]","a+");

6.r+ (read +write)


This mode is used for both Reading and writing.
BINARY FILES
A binary file is a file that uses all 8 bits of a byte for storing the information .It is the form
which can be interpreted and understood by the computer.
The only difference between the text file and binary file is the data contain in text file can
be recognized by the word processor while binary file data can’t be recognized by a word
processor.
[Link](write)
this opens a binary file in write mode.
syntax:
fp=fopen(“[Link]”,”wb”);
[Link](read)
this opens a binary file in read mode
syntax:
fp=fopen(“[Link]”,”rb”);
[Link](append)
this opens a binary file in a Append mode i.e. data can be added at the end of file.
syntax:
fp=fopen(“[Link]”,”ab”);
4.r+b(read+write)
this mode opens preexisting File in read and write mode.
syntax:
fp=fopen(“[Link]”,”r+b”);
5.w+b(write+read)
this mode creates a new file for reading and writing in Binary mode.
syntax:
fp=fopen(“[Link]”,”w+b”);
6.a+b(append+write)
this mode opens a file in append mode i.e. data can be written at the end of file.
syntax:
fp=fopen(“[Link]”,”a+b”);

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.
• The following operations can be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
Working with files
• When working with files, you need to declare a pointer of type file.
• This declaration is needed for communication between the file and the program.
• FILE *fptr;
• Opening/ Creating a file – fopen()
• FILE *fopen( const char * filename, const char * mode );
• Closing a file – fclose()

25
• int fclose( FILE *fp );
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file.
A list of file functions are given below:
No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

File Modes

26
C fprintf() and fscanf()
• int fprintf(FILE *stream, const char *format [, argument, ...])
• int fscanf(FILE *stream, const char *format [, argument, ...])
Example 1
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("[Link]", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Example 2
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("[Link]", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Example 3
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("[Link]", "w+");/* open for writing */
if (fptr == NULL)

27
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
putw(), getw() functions
putw(), getw() functions are file handling function in C programming language which is
used to write an integer value into a file (putw) and read integer value from a file (getw).
Declaration:
int putw(int number, FILE *fp);
putw function is used to write an integer into a file. In a C program, we can write integer
value in a file as below.
putw(i, fp);
where
i – integer value
fp – file pointer

Declaration: int getw(FILE *fp);


getw function reads an integer value from a file pointed by fp. In a C program, we can read
integer value from a file as below.
getw(fp);
Finding average of numbers stored in sequential access file
#include<stdio.h>
void main()
{
FILE *f1;
int number,i,n,sum=0;
f1 = fopen("[Link]","w");
printf("Enter the number of numbers");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&number);
putw(number,f1);}
fclose(f1);
f1 = fopen("[Link]","r");
printf("THE NUMBERS READ FROM THE FILE\n");
while((number = getw(f1)) != EOF)
{
printf("%d\n ",number);sum +=number;
}
fclose(f1);

28
printf("The average is %f",sum/(float)n);
RANDOM ACCESS TO FILES OF RECORDS
For random access to files of records, the following functions are used.
• fseek()
• ftell()
• rewind()
fseek()
• one can set the position indicator anywhere in the file.
• The function prototype in stdio.h is:
int fseek(FILE *fp, long offset, int origin);
• The argument fp is the FILE pointer associated with the file.
• The distance that the position indicator is to be moved is given by offset in bytes.
• It is the number of bytes to move the fi le pointer. This is obtained from the
formula: the desired record number × the size of one record.
• The argument origin specifies the position indicator’s relative starting point.
• There can be three values for origin, with symbolic constants defined in stdio.h,
stant Value Description
• SEEK_SET -0 -Moves the indicator offset bytes from the beginning of the
file
• SEEK_CUR- 1- Moves the indicator offset bytes from its current position
• SEEK_END- 2- Moves the indicator offset bytes from the end of the file
ftell()
• To determine the value of a file’s position indicator, use ftell().
• The prototype of this function, located in stdio.h, reads
• long ftell(FILE *fp);
• The argument fp is the FILE pointer returned by fopen() when the fi le is opened.
• The function ftell() returns a type long that gives the current fi le position in bytes
from the start of the file (the first byte is at position 0).
rewind()
• To set the position indicator to the beginning of the file, use the library function
rewind(). Its prototype in stdio.h is
void rewind(FILE *fp);
• The argument fp is the FILE pointer associated with the stream.
• After rewind() is called, the file’s position indicator is set to the beginning of the
file (byte 0).
• Use rewind() to read some data from a file and to start reading from the beginning
of the file again without closing and reopening the file.
Deleting a File
• The library function remove() is used to delete a fi le.
• Its prototype in stdio.h is
int remove(const char *fi lename);
Renaming a File
• The rename() function changes the name of an existing disk fi le.
• The function prototype in stdio.h is as follows.
int rename(const char *oldname, const char *newname);
• The filenames pointed to by oldname and newname
STREAMS
A Stream refers to the characters read or written to a program.
The streams are designed to allow the user to access the files efficiently .
• A stream in C is an abstraction that represents a sequence of bytes flowing
between a program and an I/O device, such as a file, keyboard, or display.

29
• This abstraction allows programmers to perform I/O operations without delving
into the specifics of the underlying hardware. Streams are managed using the FILE
data type defined in the <stdio.h> header file.
Types of Streams
• Input Stream – Reads data into the program.
• Output Stream – Writes data from the program.
• Error Stream – Writes error messages.
Standard streams
C provides three standard streams that are automatically opened when a program
starts:
• stdin: Standard input, typically associated with the keyboard.
• stdout: Standard output, typically associated with the display.
• stderr: Standard error, also typically associated with the display, used for error
messages.
Stream-Oriented I/O Functions
1. File Access
• fopen(): Opens a file and associates it with a stream.
• fclose(): Closes an open stream.
• freopen(): Reopens a file with a different mode.
• fflush(): Flushes the output buffer of a stream.
2. Unformatted I/O
• fgetc(), getc(), getchar(): Read a character from a stream.
• fputc(), putc(), putchar(): Write a character to a stream.
• fgets(): Read a string from a stream.
• fputs(): Write a string to a stream.
3. Formatted I/O
• fprintf(), printf(): Write formatted output to a stream or stdout.
• fscanf(), scanf(): Read formatted input from a stream or stdin.
4. Binary I/O
• fread(): Reads data from a stream into an array.
• fwrite(): Writes data from an array to a stream.
5. File Positioning
• fseek(): Moves the file position indicator to a specific location.
• ftell(): Returns the current value of the file position indicator.
• rewind(): Sets the file position indicator to the beginning of the file.
6. Error Handling
• feof(): Checks for the end-of-file indicator.
• ferror(): Checks for a file error indicator.
• clearerr(): Clears the end-of-file and error indicators.
• perror(): Prints a descriptive error message to stderr.
8. C Preprocessor
• Preprocessors are programs that process our source code before compilation.
• The C preprocessor is a macro processor that is used automatically by the C
compiler to transform your program before actual compilation
• It is called a macro processor because it allows you to define macros

30
Features
• Preprocessing directives are lines in your program that start with #.
• It do not end with semicolon
• It is placed before main line
List of preprocessor directives
1. #include
2. #define
3. #undef
4. #ifdef
5. #ifndef
6. #if
7. #else
8. #elif
9. #endif
10. #error
11. #pragma
Main types of preprocessor directives
• Macro substitution (#define)
• File Inclusion (#include)
• Conditional Compilation (#if,#elif, #else,#endif,#ifdef,#ifndef,#undef)
• Other directives (#pragma,#error,#line)
Macro substitution directives
• It is a substitution process in which an identifier is replaced by a predefined
constants/expressions
• The #define statement is used.
• Syntax
#define identifier constant-value
• There are different forms of macro substitution:
1. Simple macro substitution
2. Argumented macro substitution
31
3. Nested macro substitution
Simple macro substitution/object like macros
• It is used to define constants
➢ #define PI 3.1415
➢ #define NULL 0
➢ #define COUNT 100
➢ #define CAPITAL “Delhi”
• It can include expressions aslo
• #define AREA 3.14*3*3
• #define TWO-PI 2*3.1415926
Example
#include <stdio.h>
#define PI 3.1415
main()
{
printf("%f",PI);
}
Output:
3.14000
Argumented macro substitution/Function like macros
• # define preprocessor directive can be used to write macro definitions with
parameters
• Syntax:
• #define identifier (f1,f2,f3….fn) function
• It looks like a function call
• Example:
• #define MIN(a,b) ((a)<(b)?(a):(b))
• #define AREA(r) (3.14*r*r)
• #define CUBE(x) (x*x*x)
Example
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output:
Minimum between 10 and 20 is: 10
Nested macro substitution
• One macro inside another macro is called nesting of macros
• #define M 5
• #define N M+1
• #define SQUARE(x) (x*x)
• #deine CUBE(x) (SQUARE(x)*x)
File inclusion directive
• It is used to include the header file inside the program
• #include is used
• Syntax:
• #include <filename> (for standard header files)
• #include “filename” (for user defined header file)
• The files are searched in standard library
Conditional Directives/Compiler Control Directives
• #undef - To undefine a macro means to cancel its definition.
32
Example:
#include <stdio.h>
#define PI 3.1415
#undef PI
main() {
printf("%f",PI);
}
Ouput:
Compile Time Error: 'PI' undeclared

#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define.
#ifdef MACRO
//code
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code.
#ifndef MACRO
//code
#endif
#if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
#if expression
//code
#endif

#else
• The #else preprocessor directive evaluates the expression or condition if condition
of #if is false.
• It can be used with #if, #elif, #ifdef and #ifndef directives.
#if expression
//if code
#else
//else code
#endif
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif

Example
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);

33
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output:
Value of Number is non-zero
#error
• The #error preprocessor directive indicates error.
• The compiler gives fatal error if #error directive is found and skips further
compilation process.
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
#pragma
• The #pragma preprocessor directive is used to provide additional information to the
compiler.
• The #pragma directive is used by the compiler to offer machine or operating-system
feature.
• #pragma token
#include<stdio.h>
#include<conio.h>

void func() ;

#pragma startup func


#pragma exit func

void main(){
printf("\nI am in main");
getch();
}

void func(){
printf("\nI am in func");
getch();
}
Output
• I am in func
• I am in main
• I am in func
9. COMMAND LINE ARGUMENT IN C

34
Command line argument is a parameter supplied to the program when it is invoked.
Command line argument is an important concept in C programming. It is mostly used when
you need to control your program from outside. Command line arguments are passed to
the main() method.
Command-line arguments are given after the name of the program in command-line shell of
Operating Systems.

To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
Syntax:
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
• argc (ARGument Count) is int and stores number of command-line arguments passed
by the user including the name of the program. So if a value is passed to a program,
value of argc would be 2 (one for argument and one for program name)
• The value of argc should be non negative.
• argv(ARGument Vector) is array of character pointers listing all the arguments.
• If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
• Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
Example:

35
#include <stdio.h>

int main (int argc, char *argv[] )


{
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );

/* fopen returns 0, the NULL pointer, on failure */


if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
}

• The program then checks to see if the file is valid by trying to open it.
• This is a standard operation, and if it results in the file being opened, then the return
value of fopen will be a valid FILE*;
• otherwise, it will be 0, the NULL pointer.
• After that, we just execute a loop to print out one character at a time from the file.

36
References
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

37

You might also like