C Programming PDF
Document Details
Prathyusha Engineering College
Tags
Summary
This document is a set of lecture notes for a C programming course at PRATHYUSHA Engineering College. It covers fundamental concepts, such as programming paradigms, arrays, strings, functions, pointers, structures, and file processing, providing information about C programming constructs and language features.
Full Transcript
PRATHYUSHA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REGULATION R2021 I YEAR - II SEMESTER CS3251 – PROGRAMMING IN C CS3251 PROGRAMMING IN C L COURSE OBJECTI...
PRATHYUSHA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REGULATION R2021 I YEAR - II SEMESTER CS3251 – PROGRAMMING IN C CS3251 PROGRAMMING IN C L COURSE OBJECTIVES: To understand the constructs of C Language. To develop C Programs using basic programming constructs To develop C programs using arrays and strings To develop modular applications in C using functions To develop applications in C using pointers and structures To do input/output and file handling in C UNIT I BASICS OF C PROGRAMMING Introduction to programming paradigms – Applications of C Language - Structure of C program - C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and Associativity - Expressions - Input/Output statements, Assignment statements – Decision making statements - Switch statement - Looping statements – Preprocessor directives - Compilation process UNIT II ARRAYS AND STRINGS Introduction to Arrays: Declaration, Initialization – One dimensional array – Two dimensional arrays - String operations: length, compare, concatenate, copy – Selection sort, linear and binary search. UNIT III FUNCTIONS AND POINTERS Modular programming - Function prototype, function definition, function call, Built-in functions (string functions, math functions) – Recursion, Binary Search using recursive functions – Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Parameter passing: Pass by value, Pass by reference. UNIT IV STRUCTURES AND UNION Structure - Nested structures – Pointer and Structures – Array of structures – Self referential structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes and Visibility. UNIT V FILE PROCESSING Files – Types of file processing: Sequential access, Random access – Sequential access file - Random access file - Command line arguments. COURSE OUTCOMES: Upon completion of the course, the students will be able to CO1: Demonstrate knowledge on C Programming constructs CO2: Develop simple applications in C using basic constructs CO3: Design and implement applications using arrays and strings CO4: Develop and implement modular applications in C using functions. CO5: Develop applications in C using structures and pointers. CO6: Design applications using sequential and random access file processing. TOTAL : 45 PERIODS TEXT BOOKS: 1. ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016. 2. Kernighan, B.W and Ritchie,D.M, “The C Programming language”, Second Edition, Pearson Education, 2015. REFERENCES: 1. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”, Eighth edition, Pearson Education, 2018. 2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020. 3. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of Programming with C”, McGraw-Hill Education, 1996. 4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”, Second Edition, Oxford University Press, 2013. 5. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition, Pearson Education, 2013. UNIT 1 BASICS OF C PROGRAMMING Introduction to programming paradigms – Applications of C Language - Structure of C program - C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and Associativity - Expressions - Input/Output statements, Assignment statements – Decision making statements - Switch statement - Looping statements – Preprocessor directives - Compilation process. 1. INTRODUCTION TO PROGRAMMING PARADIGMS: C INTRODUCTION: The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell Laboratories. Although C was initially developed for writing system software, today it has become such a popular language that a variety of software programs are written using this language. The greatest advantage of using C for programming is that it can be easily used on different types of computers. Many other programming languages such as C++ and Java are also based on C which means that you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating system. PROGRAMMING PARADIGMS: In computing, a program is a specific set of ordered operation for a computer to perform.The process of developing and implementing various sets of instruction to enable a computer to perform a certain task is called PROGRAMMING. PROGRAMMING PARADIGMS INCLUDE: 1. IMPERATIVE PROGRAMMING PARADIGMS: Command show how the computation takes place, step by step. Each step affects the global state of the computation. 2. STRUCTURED PROGRAMMING PARADIGMS: It is a kind of imperative programming where the control flow is defined by nested loops, conditionals, and subroutines, rather than via gotos. Variables generally local to blocks. 3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS: It is a programming paradigms based on the concepts of objects, which may contain data, in the form of fields, often known as attributes, and code, in the form of procedures, often known as methods. 4. DECLARATIVE PROGRAMMING PARADIGMS: The programmer states only what the results should look like , not how to obtain it. No loops, no assignments, etc. Whatever engines that interprets this code is just supposed go gets the desired information and can use whatever approach its wants. 5. FUNCTIONAL PROGRAMMING PARADIGMS: In functional programming, control flow is expressed by combining functional calls, rather than by assigning values to variables. 6. PROCEDURAL PROGRAMMING PARADIGMS: This paradigms includes imperative programming with procedure calls. 7. EVENT DRIVEN PROGRAMMING PARADIGMS: In which the flow of the program is determined by events such as user action(mouse clicks, key presses), sensor output, or message from other program/threads. It is the dominant paradigms used in GUI and other applications that are centred on performing certain action in response to user input. 8. FLOW DRIVEN PROGRAMMING PARADIGMS: Programming processes communicating with each other over predefined channels. 9. LOGIC PROGRAMMING PARADIGMS: Here programming is done by specifying a set of facts and rules. An engine infers the answer to question. 10. CONSTRAINTS PROGRAMMING PARADIGMS: An engine finds the value that meet the constraints. One of the characteristics of a language is its support for particular programming paradigms. For example: small talks has direct support for programming in the object oriented way, so it might called an object oriented language. Very few language implement a paradigms 100%, when they do, they are “PURE”. It is incredibly rare to have a “pure OOP language” or a “pure functional language”. A lot of language will facilitate programming in one or more paradigms. If a language is purposely designed to allow programming in many paradigms is called a “multi paradigms language”. APPLICATION OF C: 1. OPERATING SYSTEM 2. EMBEDDED SYSTEM 3. GUI(GRAPHICAL USER INTERFACE) 4. NEW PROGRAMMING PLATFORMS 5. GOOGLE 6. MOZILLA FIREBOX AND THUNDERBIRD 7. MYSQL 8. COMPILER DESIGN 9. ASSEMBLERS 10. TEXT EDITORS 11. DRIVERS 12. NETWORK DEVICES 13. GAMING AND ANIMATION FEATURES OF C PROGRAMMING/ADVANTAGES: C is a robust language with rich set of built in function. Programs written in c are efficient and fast. C is highly portable, programs once written in c can be run on another machine with minor or no modification. C is basically a collection of c library functions, we can also create our own function and add it to the c library. C is easily extensible. DISADVANTAGE OF C: C doesnot provide OOP. There is no concepts of namespace in c. C doesnot provides binding or wrapping up of a single unit. C doesnot provide constructor and destructor. STRUCTURE OF C: Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include directive. Definition section: The definition section defines all symbolic constants such using the #define directive. Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. Main () function section: Every C program must have one main function section. This section contains two parts; declaration part and executable part. Declaration part: The declaration part declares all the variables used in the executable part. Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. Subprogram section: If the program is a multi-function program then the subprogram section contains all the user-defined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order. All section, except the main () function section may be absent when they are not required. C PROGRAMMING: DATA-TYPES A data-type in C programming is a set of values and is determined to act on those values. C provides various types of data-types which allow the programmer to select the appropriate typefor the variable to set its value. The data-type in a programming language is the collection of data with values having fixed meaning as well as characteristics. Some of them are integer, floating point, character etc. Usually, programming languages specify the range values for given data-type. C Data Types are used to: Identify the type of a variable when it declared. Identify the type of the return value of a function. Identify the type of a parameter expected by a function. ANSI C provides three types of data types: 1. Primary(Built-in) Data Types:void, int, char, double and float. 2. Derived Data Types:Array, References, and Pointers. 3. User Defined Data Types:Structure, Union, and Enumeration. Primary Data Types: Every C compiler supports five primary data types: void -As the name suggests it holds no value and is generally used for specifyingthe type of function or what it returns. If the function has a void type, it means that the function will not return any value. int-Used to denote an integer type. Char-Used to denote a character type. float, double-Used to denote a floating point type. int*,float*,char*- used to denote a pointer type. Declaration of Primary Data Types with variable name: After taking suitable variable names, they need to be assigned with a data type. This is how the data types are used along with variables: Example: int age; char letter; float height, width; Derived Data Types C supports three derived data types: DATATYPES DESCRIPTION Arrays Arrays are sequences of data items having homogeneous values. They have adjacent memory locations to store values. References Function pointers allow referencing functions with a particular signature. Pointers These are powerful C features which are used to access the memory and deal with their addresses. User Defined Data Types C allows the feature called type definition which allows programmers to define their own identifier that would represent an existing data type. There are three such types: Data Types Description Structure It is a package of variables of different types under a single name. This is done to handle data efficiently. “struct” keyword is used to define a structure. Union These allow storing various data types in the same memory location. Programmers can define a union with different members but only a single member can contain a value at given time. Enum Enumeration is a special data type that consists of integral constants and each of them is assigned with a specific name. “enum” keyword is used to define the enumerated data type. Example for Data Types and Variable Declarations in C #include int main() { int a = 4000; // positive integer data type float b = 5.2324; // float data type char c = 'Z'; // char data type long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type int f = -185; // -ve integer data type short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type double i = 4.1234567890; // double float data type float j = -3.55; // float data type } Let's see the basic data types. Its size is given according to 32 bit architecture. Data Types Memory Size Range Char 1 byte −128 to 127 signed char 1 byte −128 to 127 unsigned char 1 byte 0 to 255 Short 2 byte −32,768 to 32,767 signed short 2 byte −32,768 to 32,767 unsigned short 2 byte 0 to 65,535 Int 2 byte −32,768 to 32,767 signed int 2 byte −32,768 to 32,767 unsigned int 2 byte 0 to 65,535 short int 2 byte −32,768 to 32,767 signed short int 2 byte −32,768 to 32,767 unsigned short int 2 byte 0 to 65,535 long int 4 byte -2,147,483,648 to 2,147,483,647 signed long int 4 byte -2,147,483,648 to 2,147,483,647 unsigned long int 4 byte 0 to 4,294,967,295 float 4 byte double 8 byte long double 10 byte The storage representation and machine instructions differ from machine to Machine. sizeof operator can use to get the exact size of a type or a variable on a particular platform. Example: #include #include int main() { printf("Storage size for int is: %d \n", sizeof(int)); printf("Storage size for char is: %d \n", sizeof(char)); return 0 } CONSTANTS A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming. List of Constants in C Constant Example Decimal Constant 10, 20, 450 etc. Real or Floating-point Constant 10.3, 20.2, 450.6 etc. Octal Constant 021, 033, 046 etc. Hexadecimal Constant 0x2a, 0x7b, 0xaa etc. Character Constant 'a', 'b', 'x' etc. String Constant "c", "c program", "c in javatpoint" etc 2 ways to define constant in C There are two ways to define constant in C programming. 1. const keyword 2. #define preprocessor C const keyword: The const keyword is used to define constant in C programming. Example: const float PI=3.14; Now, the value of PI variable can't be changed. #include int main() { const float PI=3.14; printf("The value of PI is: %f",PI); return 0; } Output: The value of PI is: 3.140000 If you try to change the value of PI, it will render compile time error. #include int main(){ const float PI=3.14; PI=4.5; printf("The value of PI is: %f",PI); return 0; } Output: Compile Time Error: Cannot modify a const object. C #define preprocessor The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type. Syntax: #define token value Let's see an example of #define to define a constant. #include #define PI 3.14 main() { printf("%f",PI); } Output: 3.140000 Backslash character constant: C supports some character constants having a backslash in front of it. The lists of backslash characters have a specific meaning which is known to the compiler. They are also termed as “Escape Sequence”. Example: \t is used to give a tab \n is used to give new line Constants Meaning Constants Meaning \a beep sound \n newline \v vertical tab \\ backslash \b backspace \r carriage return \’ single quote \0 null \f form feed \t horizontal tab \” double quote ENUMERATION CONSTANTS: An enum is a keyword, it is an user defined data type. All properties of integer are applied on Enumeration data type so size of the enumerator data type is 2 byte. It work like the Integer. It is used for creating an user defined data type of integer. Using enum we can create sequence of integer constant value. Syntax: enum tagname{value1,value2,value3,….}; In above syntax enum is a keyword. It is a user defined data type. In above syntax tagname is our own variable. tagname is any variable name. value1, value2, value3,are create set of enum values. It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list. If constant one value is not initialized then by default sequence will be start from zero and next to generated value should be previous constant value one. Example: enum week{sun,mon,tue,wed,thu,fri,sat}; enum week today; In above code first line is create user defined data type called week. week variable have 7 value which is inside { } braces. today variable is declare as week type which can be initialize any data or value among 7 (sun, mon,). Example: #include #include enum abc{x,y,z}; void main() { int a; clrscr(); a=x+y+z; //0+1+2 printf(“sum: %d”,a); getch(); } Output: Sum: 3 KEYWORDS: A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are only 32 reserved words (keywords) in C language. A list of 32 keywords in c language is given below: auto break case Char Const Continue default do Double else enum extern float For Goto If int long register return short signed sizeof Static Struct Switch typedef union unsigned void volatile while OPERATORS : Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation. Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Ternary or Conditional Operators Arithmetic Operators: Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A hold 8 and B hold 3. Operator Example (int A=8, B=3) Result + A+B 11 - A-B 5 * A*B 24 / A/B 2 % A%4 0 Relational Operators: Which can be used to check the Condition, it always return true or false. Lets suppose variable hold 8 and B hold 3. Logical Operator: Which can be used to combine more than one Condition?. Suppose you want to combined two conditions AC, then you need to use Logical Operator like (AC). Here && is Logical Operator. Operator Example (int A=8, B=3, C=-10) Result && (AC) False || (B!=-C) || (A==B) True ! !(Bb?(a>c?a:c):(b>c?b:c); printf(“The largest number is:%d”,large); } Special Operators: C supports some special operators Operator Description sizeof() Returns the size of an memory location. & Returns the address of an memory location. * Pointer to a variable. Expression evaluation In C language expression evaluation is mainly depends on priority and associativity. Priority This represents the evaluation of expression starts from "what" operator. Associativity It represents which operator should be evaluated first if an expression is containing more than one operator with same priority. Precedence of operators : The precedence rule is used to determine the order of application of operators in evaluating sub expressions. Each operator in C has a precedence associated with it. The operator with the highest precedence is operated first. Associativity of operators : The associativity rule is applied when two or more operators are having same precedence in the sub expression. An operator can be left-to-right associative or right-to-left associative. Rules for evaluation of expression: First parenthesized sub expressions are evaluated first. If parentheses are nested, the evaluation begins with the innermost sub expression. The precedence rule is applied to determine the order of application of operators in evaluating sub expressions. The associability rule is applied when two or more operators are having same precedence in the sub expression. EXPRESSION: An expression is a sequence of operators and operands that specifies computation of a value. For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & + Simple Expressions & Compound Expressions: An expression that has only one operator is known as a simple expression. E.g: a+2 An expression that involves more than one operator is called a compound expression. E.g: b=2+3*5. IO STATEMENT: The I/O functions are classified into two types: Formatted Functions Unformatted functions FORMATTED INPUT FUNCTION: SCANF(): It is used to get data in a specified format. It can accept different data types. Syntax: scanf(“Control String”, var1address, var2address, …); EXAMPLE: #include #include Void main() { int a,b,sum; clrscr(); scanf(“%d %d”,&a,&b); sum= a+b; } FORMATTED OUTPUT FUNCTION: PRINTF(): The printf( ) function is used to print data of different data types on the console in a specified format. Syntax: printf(“Control String”, var1, var2, …); EXAMPLE: #include #include Void main() { int a,b,sum; clrscr(); printf(“enter two numbers:”); Enter two numbers: 5 4 scanf(“%d %d”,&a,&b); Sum is 9 sum= a+b; printf(“sum is:%d”,sum); } UNFORMATTED INPUT FUNCTION: getchar() getch() getche() gets() getchar(): This function reads a single character data from the standard input. Syntax: variable_name=getchar(); Example: #include OUTPUT: #include j void main() { Char ch; ch=getchar(); Printf(“%c”,ch); } getch(): getch() accepts only a single character from keyboard. The character entered through getch() is not displayed in the screen (monitor). Syntax: variable_name = getch(); Example: #include #include void main() OUTPUT: { Ch=a Char ch; ch=getch(); Printf(“ch=%c”,ch); } getche(): getche() also accepts only single character, but getche() displays the entered character in the screen. Syntax: variable_name = getche(); Example: #include #include void main() OUTPUT: { a Ch=a Char ch; ch=getche(); Printf(“ch=%c”,ch); } gets(): This function is used for accepting any string through stdin (keyboard) until enter key is pressed. Syntax: gets(variable_name); Example: #include #include void main() { Char ch; OUTPUT: cprogram gets(ch); Ch=cprogram Printf(“ch=%s”,ch); getch(); } UNFORMATTED OUTPUT FUNCTION: putchar() putch() puts() putchar(): This function prints one character on the screen at a time. Syntax : putchar(variable name); Example: #include OUTPUT: #include enter a character: j j void main() { Char ch; printf(“enter a character:”); ch=getchar(); putchar(ch); getch(); } putch(): putch displays any alphanumeric characters to the standard output device. It displays only one character at a time. Syntax: putch(variable_name); Example: include #include void main() { OUTPUT: Press any character: char ch; Pressed character is: e clrscr(); printf(“Press any character: ”); ch = getch(); printf(“\nPressed character is:”); putch(ch); getch(); } puts(): This function prints the string or character array. Syntax: puts(variable_name); Example: include #include void main() { OUTPUT: Enter a string: cprogramming char ch; cprogramming clrscr(); puts(“enter a string”); gets(ch); puts(ch); } ASSIGNMENT STATEMENT: The assignment statement has the following form: Syntax: variable = expression/constant/variable; Its purpose is saving the result of the expression to the right of the assignment operator to the variable on the left. Here are some rules: If the type of the expression is identical to that of the variable, the result is saved in the variable. Otherwise, the result is converted to the type of the variable and saved there. ❖ If the type of the variable is integer while the type of the result is real, the fractional part, including the decimal point, is removed making it an integer result. ❖ If the type of the variable is real while the type of the result is integer, then a decimal point is appended to the integer making it a real number. Once the variable receives a new value, the original one disappears and is no more available. Examples of assignment statements, b = c ; a = 9 ; b = c+5; The expression on the right hand side of the assignment statement can be: An arithmetic expression; ❖ A relational expression; ❖ A logical expression; ❖ A mixed expression. For example, int a; float b,c ,avg, t; avg = (b+c) / 2; a = b && c; a = (b+c) && (b=18) Enter age: 18 Eligible to vote { Enter age: 17 Not eligible to vote printf(“age:%d”,age); printf(“eligible to vote” ); } else { printf(“age:%d”,age); printf(“not eligible to vote” ); } Nested if: When an if else statement is present inside the body of another “if” or “else” then this is called nested if else. Syntax of Nested if else statement: if(condition) { //Nested if else inside the body of "if" if(condition2) { //Statements inside the body of nested "if" } else { //Statements inside the body of nested "else" } } else { //Statements inside the body of "else" } Flowchart: EXAMPLE: #include void main() Output: Enter age and salary: 55 55000 { 65000 int age, salary; printf(“enter age and salary”); scanf(%d %d”, &age,&salary); if(age>50) { if(salary name); printf("\n Enter the Course = "); gets(ptr_stud1 -> course); printf("\n Enter the Fees = "); scanf("%d", &ptr_stud1 -> fees); printf("\n DETAILS OF THE STUDENT"); printf("\n ROLL NUMBER = %d", ptr_stud1 –> r_no); printf("\n NAME = %s", ptr_stud1 –> name); printf("\n COURSE = %s", ptr_stud1 –> course); printf("\n FEES = %d", ptr_stud1 –> fees); return 0; } SELF-REFERENTIAL STRUCTURES Self-referential structures are those structures that contain a reference to the data of its same type. That is, a self-referential structure, in addition to other data, contains a pointer to a data that is of the sametype as that of the structure. For example, consider the structure node given below. struct node { int val; struct node *next; }; Here, the structure node will contain two types of data: an integer val and a pointer next. You must be wondering why we need such a structure. Actually, self-referential structure is the foundation of other data structures. We will be using them throughout this book and their purpose will be clearer to you when we discuss linked lists, trees, and graphs. LINKED LISTS Array is a linear collection of data elements in which the elements are stored in consecutive memorylocations. Its size is fixed. A linked list does not store its elements in consecutive memory locations and the user can add anynumber of elements to it. However, unlike an array, a linked list does not allow random access of data. Elements in a linked listcan be accessed only in a sequential manner. But like an array, insertions and deletions can be done at any point in the list in a constant time. A linked list can be perceived as a train or a sequence of nodes in which each node contains one ormore data fields and a pointer to the next node Start Simply linked list Since in a linked list, every node contains a pointer to another node which is of the same type, it is also called a self-referential data type. START - stores the address of the first node in the list.next - stores the address of its succeeding node. Declaration of node: struct node { int data; struct node *next; } Memory Allocation and De-allocation for a Linked List The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of memory. It is defined by: void *malloc(size_t number_of_bytes); it is usual to use the sizeof() function to specify the number of bytes: Struct node *new_node; new_node = (struct node*)malloc(sizeof(struct node)); SINGLY LINKED Lists A singly linked list is the simplest type of linked list in which every node contains some data and a pointer to the next node of the same data type. By saying that the node contains a pointer to the next node,we mean that the node stores the address of the next node in sequence. A singly linked list allows traversal of data only in one way. Figure 6.7 shows a singly linked list. START Singly linked list Inserting a New Node in a Linked List In this section, we will see how a new node is added into an already existing linked list. We willtake four cases and then see how insertion is done in each case. Case 1: The new node is inserted at the beginning. Case 2: The new node is inserted at the end. Case 3: The new node is inserted after a given node Case 1: Inserting a Node at the Beginning of a Linked List. struct node *insert_beg(struct node *start) { struct node *new_node;int num; printf(“\n Enter the data : “); scanf(“%d”, &num); new_node = (struct node *)malloc(sizeof(struct node)); new_node -> data = num; new_node -> next = start; start = new_node; return start; } Case 2: Inserting a Node at the End of a Linked List struct node *insert_end(struct node *start) { struct node *ptr, *new_node; int num; printf(“\n Enter the data : “); scanf(“%d”, &num); new_node = (struct node *)malloc(sizeof(struct node)); new_node -> data = num; new_node -> next = NULL; ptr = start; while(ptr -> next != NULL)ptr = ptr -> next; ptr -> next = new_node; return start; } case 3: Inserting a Node After a Given Node in a Linked List struct node *insert_after(struct node *start) { struct node *new_node, *ptr, *preptr; int num, val; printf(“\n Enter the data : “); scanf(“%d”, &num); printf(“\n Enter the value after which the data has to be inserted : “); scanf(“%d”, &val); new_node = (struct node *)malloc(sizeof(struct node)); new_node -> data = num; ptr = start; preptr = ptr; while(preptr -> data != val) { preptr = ptr; ptr = ptr -> next; } preptr -> next=new_node; new_node -> next = ptr; return start; } Deleting a Node from a Linked List: Case 1: The first node is deleted. Case 2: The last node is deleted. Case 3: The node equal to a given value is deleted. Case 1: Deleting the First Node from a Linked List struct node *delete_beg(struct node *start) { struct node *ptr;ptr = start; start = start -> next;free(ptr); return start; } Case 2: Deleting the Last Node from a Linked List struct node *delete_end(struct node *start) { struct node *ptr, *preptr;ptr = start; while(ptr -> next != NULL) { preptr = ptr; ptr = ptr -> next; } preptr -> next = NULL;free(ptr); return start; } Case 3: Deleting the Node equal to a Given Value in a Linked List struct node *delete_node(struct node *start) { struct node *ptr, *preptr; int val; printf(“\n Enter the value of the node which has to be deleted : “); scanf(“%d”, &val); ptr = start; if(ptr -> data == val) { start = delete_beg(start); return start; } else { while(ptr -> data != val) { preptr = ptr; ptr = ptr -> next; } preptr -> next = ptr -> next; free(ptr); return start; } } Programming Example Declare a structure to store information of a particular date. struct date { int day; int month; int year; }; Declare a structure to create an inventory record. struct inventory { char prod_name; float price; int stock; }; Write a program, using an array of pointers to a structure, to read and display the data of students. #include #include #include struct student { int r_no; char name; char course; int fees; }; struct student *ptr_stud; int main() { int i, n; printf("\n Enter the number of students : "); scanf("%d", &n); for(i=0;ir_no); printf("\n NAME: "); gets(ptr_stud[i]->name); printf(“\ncourse”); gets(ptr->stud[i]->course); printf(“/n FEES”); scanf(“%d”,&ptr_stud[i]->fees); } printf(“\n DETAILS OF STUDENT”); for(i=0;ir.no); printf(“\n NAME=%s,ptr->stud[i]->name); printf(“\n COURSE=%s,ptr->stud[i]->course); printf(“n FEES=%d”,ptr->stud[i]->fees); } return 0; } Output Enter the number ofstudents : 1 Enter the data forstudent 1 ROLL NO.: 01 NAME: Rahul COURSE:BCA FEES: 45000 DETAILS OF STUDENT SROLL NO. = 01 NAME = Rahul COURSE = BCA FEES = 45000 Write a program that passes a pointer to a structure to a function. #include #include #include struct student { int r_no; char name; char course; int fees; }; void display (struct student *); int main() { struct student *ptr; ptr = (struct student *)malloc(sizeof(struct student)); printf("\n Enter the data for the student "); printf("\n ROLL NO.: "); scanf("%d", &ptr–>r_no); printf("\n NAME: "); gets(ptr–>name); printf("\n COURSE: "); gets(ptr–>course); } printf(“/n FEES”); scanf("%d", &ptr–>fees); display(ptr); getch(); return } void display(struct student *ptr) { printf("\n DETAILS OF STUDENT"); printf("\n ROLL NO. = %d", ptr–>r_no); printf("\n NAME = %s", ptr–>name); printf("\n COURSE = %s ", ptr–>course); printf("\n FEES = %d", ptr–>fees); } Output Enter the data for the student ROLL NO.: 01 NAME: Rahul COURSE: BCA FEES: 45000 DETAILS OF STUDENT ROLL NO. = 01 NAME = Rahul COURSE = BCA FEES = 45000