0% found this document useful (0 votes)
12 views32 pages

GXEST204 MOD 3 Programming in C

The document provides an overview of functions in C programming, including their definitions, prototypes, parameters, and types of function calls. It explains concepts such as pass by value vs. pass by reference, recursion, and how to pass arrays as function parameters. Additionally, it discusses macros and their types, emphasizing their utility in making code more maintainable and readable.

Uploaded by

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

GXEST204 MOD 3 Programming in C

The document provides an overview of functions in C programming, including their definitions, prototypes, parameters, and types of function calls. It explains concepts such as pass by value vs. pass by reference, recursion, and how to pass arrays as function parameters. Additionally, it discusses macros and their types, emphasizing their utility in making code more maintainable and readable.

Uploaded by

vr233570
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 32
(=) APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY KTU SPECIAL We can together dream the B tech S ‘APJ ABDUL KALAM Blo A Tat BUS €{3WWW.KTUSPECIAL.IN @)KTUSPECIAL (@t.me/ktuspeciall if FUNCTIONS 3.1 INTRODUCTION The use of a function avoids the need for redundant (repeated) programming of the same instructions. Function carries out some specific, well-defined task. Itis the subpart of a program which can be reused and when required. In other words, function is a named unit of a group of program statements. Function is otherwise called a method or a sub-routine or a procedure. ‘C supports a lot of standard predefined functions known as library functions. The user can also define their own functions, known as user-defined functions, 3.1.1 Function Definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. syntax: return_type function_name(argument list) { /Body of the function } where, 'return_type’ denotes the data type of the value, the function retums, 'function_name! is the actual name of the function. Function body contains a collection of statements that define what the function does. e.g: int sum(int a, int b) { int es c=ath; return ¢; } ‘A funetion will process information that is passed to it from the calling portion of the program and return a single value, The information is passed to the funetion via special identifiers called ‘arguments’ or ‘parameters’ and retuned via return statement. The function name and argument/parameter list are together called ‘function signature™ 3.1.2 Funetion Prototype Itis the declaration of the function that tells the program about the type of the value returned by the function and the number and type of each argument. Function prototype is also called function declaration. It does not have a body. Function prototype is usually written at the beginning of a program, ahead of any programmer-defined functions (including main) ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 1 —_—_Bowntoad front ktuspeciatin syntax: return_type function_name(argument list); eg int sum(int a, int b); Note: Function prototypes are not mandatory in C. 3.1.3 Formal Parameters and Actual Parameters The arguments appearing in the function definition [and in function prototype] are called formal arguments, because they represent the names of data items that are transferred into the function from the calling portion of the program, They are also known as ‘formal parameters! or simply ‘parameters’, The arguments appearing in the function call are referred to as actual arguments/actual parameters or simply ‘arguments’. 3.1.4 Default Arguments When we define a function, we can specify a default value for cach of the last parameters. If such default values are specified for a function, one does not have to specify the corresponding argument when invoking this function: if argument is not specified, the default value will be used. eg: float i(float p, int t, float = 0.24 ); This can be invoked in two ways: i(0.13,6,0.14); dir takes the value 0.14 i(0.13,6); dir takes the value 0.24 Note: Only the trailing arguments can have default values. Therefore, float i(float P = 1000.5 int t, float r); generate an error, But, float i(float P = 1000.5 int t = 5 float r = 0.24 ) can be executed successfully. 3.1.5 Function Call While creating a C function, we provide a definition of what the function has to do. To use a function, we will have to call that function to perform the defined task. A caller is a function that calls another function; a callee is a function that was called. When a program calls a function, the program control is transferred to the called function. A called function performs the defined task and when its return statement is executed or when its funetion-ending brace (curly bracket) is reached, it returns the program control back to the main program. syntax: function_name (argument list); eg: result=sum(5,6); ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 2 —_—_Bowntoad front ktuspeciatin Here, the function sum is called with arguments 5 and 6. That is, (from the example given above in Sections 3.1.1 and 3.1.2), ‘a! will take the value 5 and 'b' will take the value 6. Then, the value of '¢' (c= a + b= 11) will be returned to the caller and will be stored in the variable ‘result The function can also be called by passing variables, ie., without specifying the values as follows: result sum(xy); In this case, values of 'x' and 'y' in the caller function will be passed to ‘a! and 'b’, respectively. 3.1.6 Returning from A Function The return statement is used to exit from the funetion and to return a value to the calling code. A function can return only one value to the calling portion of the program, via ‘return’, syntax: return expression; eg, return 0; Function should include one or more retum statements, in order to return a value to the calling portion of the program. The keyword 'void' can be used as a type specifier when defining a function that does not return anything, In that case we can either avoid the return statement or can use it as return; without any value/expression, If the data type specified in the prototype or the first line of the definition is inconsistent with the expression appearing in the ‘return’ statement, the compiler will attempt to convert the quantity represented by the expression to the data type specified in the prototype. This could result in a compilation error, or it may involve partial loss of data (say, due to truncation). Therefore, such inconsistencies should be avoided. Qn) Program to find the sum of two numbers using function. Finelude Finclude nt sum(int a.int b)_// Function definition int sum(int a,int b); //Function declaration { int main() { return atb; int xy,s-0; } printf("Enter two numbers: ") int main() { scanf("%d%d" 8x,8y); int xy.s=0; s=sum(xy);_//Funetion call printf("Enter two numbers: "); printf("Sum = %d".s); scanti"%d%d" Bex, 8cy); return 0; s-sum(xy);__//Funetion call printf("Sum =%d",s); aint) // Funetion definition return 0; Enter two number: 52 |] } Sbnina return atb; 3 ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 3 —_—_Bowntoad front ktuspeciatin 3.2 PASS BY VALUE vs PASS BY REFERENCE The pass by value/call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. The called function works with the formal arguments. In this case, the value of the corresponding formal argument can be altered within the function, but the changes made to the parameter (formal parameter) inside the function will have no effect on the argument (actual parameter). When this method is used, the memory is wasted for duplication of the same data. Program-I Program-2 T/Swapping two numbers_Call by value method | //Swapping two numbers_Call by value method #include ‘inelude void swap (int x, int y) Void swap (int x, int y) { { int temp; int temp; temp =x; temp x=Y; Output =y y=temp; | 100 200 yetemp; } printf("\nAfter swapping\n’d\t%d", x, y); int main() } t int main) int a=100, b=200; { swap(a.b); int a=100, b=200; printf("%d\t%d", a, b); printf("\nBefore Swappingin’%d\0%d", a, b); return 0; swap(a, b); } return 0; } Output Before Swapping 100 200 After swapping 200 100 The output of the program-1 will be 100 200, not the swapped value as expected. Because the swapping done inside the swap() will not reflect inside main(). If we need the output as 200 100, we will have to print the values inside the swap() function, Check the program-2, Note: In C, by default the parameter passing in functions follows call by value method. The pass by reference/call by reference method of passing arguments to a function copies the address of actual argument into the formal parameter (in other words, the reference to the original arguments is passed). Inside the function, the address is used to access the actual argument used in the call, The changes made to the formal parameter will affect the actual argument. ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 4 —_—_Bowntoad front ktuspeciatin #include void swap(int "x, int *y) { int temp; temp = *x; Output Key: Before swapping “y= temp; 100 200 } After swapping int main) 200 100 { int a=100,b-200; printf” Before swapping\n%d\t%d", a, b); swap( &a,8¢b); printf("\n After swapping\n %d\t%d", a, b); return 0; ‘Comparison between Call by Value and Call by Reference methods ‘CALL BY VALUE CALL BY REFERENCE, ‘A copy of the actual arguments is passed to | The reference to the original arguments is formal arguments passed The called function works with the formal | The called function works with the actual arguments arguments, but with the alias name The changes made in the formal arguments | The changes made in the formal arguments will not affect the actual arguments do affect the actual arguments Memory is wasted for duplication of the| Memory is not wasted as there is no same data duplication 3.3 RECURSION ‘A function is said to be recursive iffa statement in the body of the function calls itself. In other words, recursion is the process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. Many iterative (i.e. repetitive) problems can be written in this form, In order to solve a problem recursively, two conditions must be satisfied: (i) The problem must be written in a recursive form and (ii) The problem statement must include a stopping condition. e.g: factorial(int n) t if{n—l||n—=0) return 1; else return n* factorial(n-1); } ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 5 —_—_Bowntoad front ktuspeciatin retrun 5 * factorial(4) = 120 L_ ——_ retrun 4 factorial) = 24 ——_ |__ retrun 3 * factorial(2) = 6 ——_ | retrun 2 * factorial(y = 2 — |__ retrun 1 * factorial(0) = 1 Qu) Program to print the factorial of a number using recursion, Finclude int factorial(int n); int main(){ int n; printf("Enter a positive integer: "); seanf("%od", &n); printf("Factorial of %d = %d", n, factorial(n)); return 0; Output factorial(int n) t Enter a positive integer: 5 Factorial of 5 = 120 return n * factorial(n - 1); 3.4 ARRAY AS FUNCTION PARAMETERS allows arrays to be passed as function arguments. But array arguments are passed differently than single-valued data items. [fan array name is specified as an actual argument, the individual array elements are not copied. Instead, the location of the array (that is, location of first element) is passed to the function. So, if an element of the array is then accessed within the function, the access will refer to the location of that array element relative to the location of first clement. Thus, any alteration to an array element within the function will carry over to the calling funetion. ‘An entire array can be passed to a function as an argument, To pass an array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument within the function call eg. int main() { intn; float avg; float a[50]; array declaration ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 6 —_—_Bowntoad front ktuspeciatin avg-average(n.a); (/function call 3 The corresponding formal argument is written in the same manner, though it must be declared as an array within the formal argument declarations. When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets and the size of the array is not specified within the formal argument declaration. eg: float average(int num, float arr{]); // function prototype float average(int num, float arr{]) //funetion definition, { float sum =0 , ave = 0; return avg; } To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to one-dimensional arrays). If we know the dimensions of the array, we can pass the array by specifying the size of all but the first dimension. Finclude void display(int arr(3][3}) { for (int i= 0; 1 <3; i++) { Cl (int j = 0; j <3; j++) Output printf("%6d", ar[i][j))s 123 } printf("\n"); oo $ 789 3 int main() { int arr[3][3] = { (1,2, 3}, {4, 5, 6}, 17,8, 9335 display(ar); // Passing the array to the function display(arr); return 0; } ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR —_—_Bowntoad front ktuspeciatin In C, we can also pass arrays with a variable second dimension, In this case, we still need to specify the second dimension (or more) while passing the array. Finclude void display(int arr{][3}, int rows) for (ii rows; i++) : for (int j = 0; j <3; j+¥) * seimt(%ed* ants Output pein"; 123 , } 567 a: main() 91011 { int arr[3][3] = ((1, 2,3}, {5, 6, 7}, {9, 10, 11}}; display(arr, 3); return 0; } 3.5 MACROS In C programming, one can use maeros to repeat a single value or a piece of code in our programs. By defining macros once, we can utilize them again throughout the program, Macro in C is defined by the #define directive. Macro is a name given to a piece of code, so whenever the compiler encounters a macro in a program, it will replace it with the macro value. In the macro definition, the macros are not terminated by the semicolon (;). Macros are processed by the preprocessor before the compilation of the program, Macros help make the code more flexible, readable, and easier to maintain. 3.5.1 Types of macros in C ‘There are primarily two types of macros in C: 1, Object-like Macros (Constant Macros) 2, Function-like Macros Object-like macros are the simplest type of macros, They are used to define constants or values that can be reused throughout the program i. Defining macros Syntax: #define macro_name macro_value; ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 8 —_—_Bowntoad front ktuspeciatin Qn) Program to find the area of a circle using macros. include define P1 3.14159 int main() { float radius, area; Output Enter the radius of the circle: 3 The area of the circle with radius 3.00 is: 28.27 printf("Enter the radius of the circle: "); scanf("96f", &radius); area =PI*radius *radius; return 0; } printf("The area of the circle with radius %.2f is: %.2f\n", radius, area); ii) Passing argument to macros Function-like macros allow you to define a macro that behaves like a function, These macros can take arguments, and the arguments are replaced in the macro definition wherever they appear. Syntax: #define MACRO_NAME(argl, arg2, ...) expression #define SQUARE(x) ((x)*(x)) TiProgram to find the largest of two numbers using macros itinelude define MAX(a, b) (a> b? a: b) int main() { inta=10,b=20; printf("Maximum is: %d", MAX(a, b)); Calling return 0; TProgram to find the sum of two numbers using macros include #define SUM(a, b) (a+b) int main() { int a= 15,b=20; printf('Sum is : %d", SUM(a, b)); Calling return 0; 3 3 Output Output Maximum is: 20 Sumis: 35 ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 9 —_—_Bowntoad front ktuspeciatin Other types of macros are: 1) Variadie Macros: Macros that take a variable number of arguments 2) Conditional Compilation Macros: Macros used for compiling code conditionally. 3). Stringification (#): Converts macro arguments to string literals, 4) Token Pasting (##): Concatenates multiple tokens into a single token. 3.5.2 Predefined Macros In C, there are several predefined macros that are automatically defined by the compiler. These macros provide information about the environment, compilation settings, and the standard libraries being used. Predefined Macros Description _FILE_ Itcontains the current file name -DATE_ It displays the current date _TIME_ It displays the current time _LINE_ Contains the current line number _STDC_ When it is compiled, it will return a nonzero integer value 3.5.3 Advantages of Using Macros © Code Reusability: Macros allow you to reuse common code patterns across the program, © Efficiency: Macros are expanded at compile time, so they don't incur the runtime overhead of function calls. * Readability: When used appropriately, macros can make code easier to read and understand by replacing complicated expressions with meaningful names. These macros can be very powerful tools when used correctly, but it's important to use them. carefully to avoid debugging difficulties, especially with function-like and variadic macros where side effects in arguments can cause unexpected behaviour. Qn) Program to swap two numbers using macros Finclude define SWAP(a, b) { int temp = a; a = int main() { Output int x= 10, y= 20; printf("Before swapping: x =%d y = %d\n", x,y); Before swapping: x =10 y = 20 SWAP(x, y); After swapping: x =20 y =10 printf("Afier swapping: x =%d y =%d", x.y); return 0; ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 10 —_—_Bowntoad front ktuspeciatin Qu) Program to find the circumference of a cirele using macros. #include #define pi 3.14 int main(){ Output float r=4, circum; circum = 2*pi*r; printf("The circumference of a circle is: %f", circum); return 0; } The circumference of a circle is: 25.120001 3.6 COMMAND LINE ARGUMENTS It is possible to pass some values from the command line to the C programs when they are executed. These values are called command line arguments and many times they are important for the program especially when we want to control our program from outside instead of hard coding those values inside the code, First we need to change the structure of main() function, Syntax: int main(int arge, char *argy| |) The command line arguments are handled using main() function arguments where arge refers to the number of arguments passed, and argv/ /is a pointer array which points to each argument passed to the program. arge counts the file name as the first argument. The first argument of argo] Jis always the file name. 1 arge (Argument count) * Stores the number of arguments passed (including the program nam © Example: Ifa program is run as /a.out hello world, then arg. arguments). elf) 3 (program name + two 2. argy (Argument vector) © Anarray of strings (char *argyl]) that stores command-line arguments. © argy{0] — Program name (e.g.,"/a.out") © argv[1] + First argument (e.g., "hello") © argy[2] — Second argument (e.g., "world") Finclude void main(int arge, char *argvf]) { ntf("Program name is: %sin", argv[0]); Marge < Ot ae NP Run in Linux as: printf("No argument passed through command line.\n"); | -/@-0ut hello 3 else { Output printf("First argument is: %s\n", argv[1]); Program name is: /a.cut } First argument is: hello ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR W —_—_Bowntoad front ktuspeciatin 3.7 STRUCTURE Arrays can be used to represent a group of data items belong to the same data type, such as int or float, However, we cannot use an array, if we want to represent a collection of data items of ferent types using a single name. Structure is a user defined data type available in C that allows to combine data items of different kinds. A structure is a convenient tool for handling a ‘group of logically related data item, For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we can make use of this data type. © Individual structure clements are referred to as ‘members’ © struct’ is the keyword used to define a structure. ‘The syntax-: struct tagname { datatype memberl; datatype member2; datatype memberN; bh where, the keyword struct declares a structure to hold the details of data fields called structure element or members. Each member may belong to a different type of data, Tagname is the name of the structure and is called strueture tag. memberl to memberN are the individual member declarations. Members can be ordinary variables, arrays, pointers or even other structures eg: lL. eg: 2. struct student { struct book { char firstName[30]; char title[50}; int roll; int pages; float marks; float prices; 1 i) struct variable ‘Once the structure has been defined, individual structure-type variable can be declared as follows: struct tagname variable_name; egl-: struct book bl; ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 12 —_—_Bowntoad front ktuspeciatin eg2-: struct account { int aceno; char type; char name[40]; }joustomer!; 3.7.1 Accessing a Structure member/elements In array, we can access individual elements of an array using a subscript. In structures, the clements are usually accessed as separate entities and a dot operator (,) is used to access elements in the structure Syntax-: _variablemember egl- customer! .aceno = $41236; eg2-: bl.pages > Ifa structure member is itself a structure, then a member of the embedded structure can be accessed as follows: Syntax-: variable.member.submember egs customer.payment.day Qn) Program of structures Hinclude struct Point { te int x, ys } ‘Output int main) { x=10 y=1 struct Point pl = {0,1}; pl.x=2 printf("x, return 0; %dy = %d", pL.x, ply); 3.7.2 Array of Structures To store data of 50 students, we would be required to use 50 different structure variables from SI to $0. It is not convenient, so we us an array of structures. Ifa structure member is an array, then an individual array element can be accessed as; ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 13 —_—_Bowntoad front ktuspeciatin Syntax-;_variablemember[expression] eg. struct student { int roll; char name[50]; int marks[6); }Sl; SLmarks[1] gives the mark of student SI's second subject, ie., mark at the second position of the array, ‘marks’. Qn) Program for read and display the details of 3 students using array of structures, Finclude struct student { int roll; char name[50]; int marks; hs int main() t struct student s1[50]; inti: printf("Enter number, name and mark students"); for(i=0;i<3;i+4) { scanf("%d%s%d" &s I[i].roll,s [i] name,&es1 [i]. marks); printf("Details are\n"); for(i=0si<3;i++) { printi("%d %s %d\n" I [i).roll,sifi].name,si[i].marks); $ return 0; Output Enter number, name and mark students 200 Anu 35 201 Binu 55 202 Raju 65 Details are 200 Anu 35 201 Binu 55 202 Raju 65 ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 4 —_—_Bowntoad front ktuspeciatin > If the structure variable is an array, then arrayfexpression].member will refer to a specific member within the structure. eg, struct student{ int roll; char name[50]; char dept{50}; float totalmarks; }S[20); S[0].name gives the name of the first student (stored in the first student structure). Qn) Program for array of structures Finclude struct Point intx, ys h Output int mainQ){ struct Point arr{10]; 1020. arr[0].x = 10; arr{0].y = 20; printf("%d %d", arr{0].x, arm{O].y)s return } i) Nested structure A structure can contain another structure or structure variable. When a structure contains another structure, it is called nested structure. syntax: struct structure! { b struct structure? { struct structure! obj; hi ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 15 —_—_Bowntoad front ktuspeciatin eg: struct date { int day; int month; int year; Bb struct account { int aceno; char type; char name[30]; float balance; struct date payment; jeustomer!; Structure ‘account! now contains another structure ‘date’ as one of its members. > The members of a structure variable can be assigned initial values in the same manner as the elements of an array (must appear in order). syntax: struct tag variable= {valuel, value2, valueN}; eg. struct account eustomer= {101,'R’, "Asha", 20000, 20, 2, 2022}; (The last three values corresponds to the members defined in the inner structure, from the previous example, date) Qu) Program for read and display the personal details of a student using nested structures. #include struct date { int dd; int mm; int wy; i‘ struct student { int no; char name[20]; struct date dob; % int main() { struct student st; ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 16 —_—_Bowntoad front ktuspeciatin printf("Students Details\n"); printf("Student No: %d\nName: %s\nDOB: return 0; d printf("Enter student number, name, and date of birth (DD MM YYYY):\n"); scanf("sd9%s96d%d%6d",&st.no,st.name, &st.dob.dd,&st.dob.mm,8st.dob.vy); ‘4d96d%d!"st.no,st.name,st.dob.dd,st.dob.mm,st.dob.yy); Output: 105 Sam 15-8-1985 Students Details Student No: 105 Name: Sam DOB: 15-8-1985 Enter student number, name, and date of birth (DD MM YYYY): Qu) Program to read and display the details ofan employee u ing structures, Finelude struct Address { char HouseNo[25]; char City[25}; char PinCode[25]; B struct Employee { int Id; char Name{25}; float Salary; struct Address Add; u int maing) { inti; struct Employee E; print{("\n\tEnter Employee Id: "); seanf("%d", &E.1d); printf("\n\tEnter Employee Name: "); scant("%s", E.Name); printf("\n\tEnter Employce Salary: scanf("%f", &E Salary); printf("\n\tEnter Employee House No: "); scanf("%s", E.Add.HouseNo); printf("\n\tEnter Employee City: seant("%s", E.Add. City); printf("\n\tEnter Employee Pincode: "); scanf("%s", E.Add, PinCode); printf("\nDetails of Employees"); printf("\n\tEmployee Id: %d ", E.1d); printf("\n\tEmployee Name: %s", E.Name); printf("\n\tEmployee Salary: %f", E.Salary); printi("inltEmployee House No: %s", E.Add. HouseNo); printf("\n\tEmployee City: %s", E.Add. City); printf("\n\tEmployee Pincode: %s", E.Add. PinCode); t Output Enter Employee Id: 101 Enter Employee Name: John Enter Employee Salary: 450000 Enter Employee House No: 619 Enter Employee Kollam Enter Employee Pincode: 689124 Details of Employees Employee Id: 101 Employee Name: John Employee Salary: 450000.000000 Employee House No: 619 Employee City: Kollam Employee Pincode: 689124 ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 17 —_—_Bowntoad front ktuspeciatin Qn) Program to read and display the details of n students using structure, Finclude #include struct student { char first_name{50]; char last_name[50]; int roll_number; float marks; }s[60]; int main(){ int n, i; printf("\nEnter the number of students: "); seanf("%d", &n); printf("\nEnter the students’ details:\n"); for (i=0; i struct student { int no; char name[50]; int mark; Output int display(struct student); Anu 8 int main() { struct student st- display(st); return 0; 3 nt display( struct student st) { printf("%d %s %d",st.no,st.name,st.mark); i 1,"Anu",85}; ii) Passing individual member to function #include int display(int,char[S0] int); struct student { int no; char name[50]; : int mark; Output int main() { 1Binu 95, struct student st={1,"Binu",95}; display(st.no,st.name,st.mark); return 0; i int display(int no, char name{50],int mark) t printf("%d %s %d",no,name,mark); } iti) Passing individual member to function Acomplete structure can be transferred to a function by passing a structure-type pointer as an argument. That is, it will be 'passed by reference’ ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 19 —_—_Bowntoad front ktuspeciatin Finclude ‘Vint display(int no,char *name,int mark); int display(int ,char * int ); struct student { int no; char name[50]; Output int mark; hs int main() { struct student st={1,"Anu",85}; display(st.no,st.name,st.mark); return 0; } Anu 95 int display(int no,char *name, int mark) { printf("%6d %s %d",no,name,mark); } 3.7.4 Self-Referential Structures The structure of type tag will contain a member that points to another structure of type tag. Such structure called self-referential structures. They are useful in application that involved linked data structure such as list and tree. Syntax: struct tagname { datatype member1; datatype member2; struct tagname *name; be where ‘name’ refers to the name of a pointer variable, Thus, the structure of type 'tagname’ will contain a member that points to another structure of type 'tag', Such structures are known as self-referential structures. Finclude struct student { int no; char name[50); int mark; 1 Vinu 8s struct student *ptr; 5 int main() Output ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 20 —_—_Bowntoad front ktuspeciatin struct student st= {1,"Vinu",85}; st.ptr=&st; printf("%d %s %d"st-ptr->no st.ptr->name,st_pt->mark); return Here, C provides an operator “->” called an arrow operator to refer to the structure elements, So, st.ptrno is the way to aecess structure element, 3.8 UNION Union is a concept borrowed from structures and therefore follow the same type as structures, However, there is a major distinction between them in terms of storage. In structures, each member has its own storage location where as all the members of union share the same location, Union may contain many members of different types. But it can handle one member at a time. syntax: union tag { member 1; member m; B Individual union variables can be declared as: union tag variablel, variable2.....,variablen; OR union tag { member 1; member 2; member m; }variablel, variable2,..., variable; where, union is the keyword, tag is the name of the union and variablel...variablen are union variables ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 21 —_—_Bowntoad front ktuspeciatin Egl-: Eg2-: Finclude Finclude int main { int main { union item union item { t inti; inti; float f, float f b ih union item it; union item it; iti-10; iti-10; itf=20.5; it.=20.5; printf("%f" printi("%f" it return 0; return 0; } Output Output 20,500000 0.000000 This declares a variable “it” of type union item. This union contains 3 members. But we can use only one of them at a time. The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union, During accessing we should make sure that we are accessing the member whose value is currently stored. > Aunion may be a member of a structure, and a structure may be a member of a union. Structures and unions may be freely mixed with arrays. eg: union id { char colour{ 15]; int size; hb struct cloth t char manufacturer[25]; float cost; union id description; } shirt, frock Here, shirt and frock are structure variables. Each of them will contain the members: 25- character string (manufacturer), a floating point quantity (cost), and a union( description) which may represent either a string(colour) or an integer(size). 8 ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 2 —_—_Bowntoad front ktuspeciatin This can otherwise be done as, struct cloth t char manufacturer[25]; float cost; union id t char colour{ 15]; int size; description; } shirt, frock; An individual union member can be accessed using the operators . and >. If 'variable’ is a union variable, then variable.member refers toa member of the union, eg, shirt.size; Structure vs Union STRUCTURE UNION Keyword, The keyword struct is used to | The keyword union is used to define a structure, define a union, Size When a variable is associated | When a variables associated with a structure, the compiler | with a union, the compiler allocates the memory for | allocates the memory by each member, The size of | considering the size of the structure is greater than or | largest memory. The size of equal to the sum of sizes of | union is equal to the size of its members. largest member. Memory Each member within a | Memory allocated is shared structure is assigned unique | by individual members of storage area of location, union, Value Altering Altering the value of a Altering the value of any of member will not affect other | the member will alter other members of the structure. | member values. ‘Accessing members Individual member can be | Only one member can be accessed ata time, accessed at a time Initialization of members | Several members of a Only the first member of a structure can initialize at | union can be initialized, once, ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 23 —_—_Bowntoad front ktuspeciatin 3.9 typedef typedef in C is a keyword used to create an alias! new name for existing data types. It doesn’t create a new type, rather, it provides a way to define more meaningful or shorter names for complex data types, making the code more readable and easier to maintain. It can help make code portable, as changes in type declarations are centralized in one place. syntax: typedef datatype new_type; ege typedef int age; Here, age is a user-defined data type. So, if we write, age m,n; then i int ma; is equivalent to writing #include typedef int Number; int main) { Output Number num1, num2, product; printf("Enter two numbers: "); scanf("%od%d",&num 1 ,g&num2); The product of 5 and 2 is: 10 product = num! * num2; printf(" The product of %d and %d is: %ad\n", num, num2, product); return 0; Enter two numbers: 5 2 typedef is particularly convenient when defining structures, since it eliminates the need to repeatedly write struct tag whenever a structure is referenced syntax: typedef struct { member 1; member m; }newtype; eg typedef stryct{ int aceno; char name[30]; float balance; }record: ST THOMAS COLLEGE OF ENGINEERING & TECHNOLOGY, KOZHUVALLOOR 24 —_—_Bowntoad front ktuspeciatin

You might also like