0% found this document useful (0 votes)
6 views73 pages

User-Defined Functions in C Programming

Chapter 5 of Programming for Problem Solving discusses user-defined functions, including their prototypes, definitions, and the process of calling them. It explains the distinction between predefined and user-defined functions, parameter passing methods (call by value and call by reference), and provides examples of various function types and their usage. The chapter emphasizes the importance of functions in promoting code reusability and organization.

Uploaded by

sujalkadam213
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)
6 views73 pages

User-Defined Functions in C Programming

Chapter 5 of Programming for Problem Solving discusses user-defined functions, including their prototypes, definitions, and the process of calling them. It explains the distinction between predefined and user-defined functions, parameter passing methods (call by value and call by reference), and provides examples of various function types and their usage. The chapter emphasizes the importance of functions in promoting code reusability and organization.

Uploaded by

sujalkadam213
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

Programming for Problem Solving (PPS)

Chapter-5
User-Defined Functions, Structure and Unions
Functions
In Functions, you will learn about
• Introduction to function
• Concepts of User define function
 Function prototype (declaration)
 Function definition
 Function call and return
• Parameters
 Actual and Formal
• Parameter Passing
• Calling a function
• Recursive function
• Macros
• Pre-Processing
Introduction to Function
• A function is a block of code which is used to perform a
specific task.
• It can be written in one program and used by another
program without having to rewrite that piece of code.
Hence, it promotes usability!!!
• Functions can be put in a library. If another program
would like to use them, it will just need to include the
appropriate header file at the beginning of the program
and link to the correct library while compiling.
Introduction to Function
Functions can be divided into two categories :
• Predefined functions (standard functions)
 Built-in functions provided by C that are used by
programmers without having to write any code for
them. i.e: printf( ), scanf( ), etc
• User-Defined functions
 Functions that are written by the programmers
themselves to carry out various individual tasks.
Predefined (Standard) Functions
• Standard functions are functions pre-defined by C and
put into standard C libraries.
 Example: printf(), scanf(), pow(), ceil(), rand(), etc.
• We need to include the appropriate header files.
 Example: #include <stdio.h>, #include <math.h>
• What contained in the header files are the prototypes of
the standard functions. The function definitions (the
body of the functions) has been compiled and put into a
standard C library which will be linked by the compiler
during compilation.
User defined functions
• A programmer can create his/her own function(s).
• It is easier to plan and write our program if we divide it into several
functions instead of writing a long piece of code inside the main
function.
• A function is reusable and therefore prevents us (programmers)
from having to unnecessarily rewrite what we have written before.
• In order to write and use our own function, we need to do the
following:
 create a function prototype (declare the function)
 define the function somewhere in the program (implementation)
 call the function whenever it needs to be used
Function Prototype (Declare the function)
• A function prototype will tell the compiler that there
exist a function with this name defined somewhere in
the program and therefore it can be used even though
the function has not yet been defined at that point.
• Function prototypes need to be written at the beginning
of the program.
• If the function receives some arguments, the variable
names for the arguments are not needed. State only the
data types
Function Prototype (Declare the function)
• Function prototypes can also be put in a header file. Header
files are files that have a .h extension.
• The header file can then be included at the beginning of our
program.
• To include a user defined header file, type:
• #include “header_file.h”
• Notice that instead of using < > as in the case of standard
header files, we need to use “ ”. This will tell the compiler to
search for the header file in the same directory as the
program file instead of searching it in the directory where
the standard library header files are stored.
Function Prototype (Declare the function) Example
• A function prototype Consists of the following elements:
• function’s name
• Parameters
• Return type.
• It must appear before the function is called.

Example:
int add(int, int); // function prototype
Function Definitions
• Is also called as function implementation
• A function definition is where the actual code for the
function is written. This code will determine what the
function will do when it is called.
• A function definition consists of the following elements:
 A function name
 An optional list of formal parameters enclosed in
parentheses (function arguments)
 A function return data type (return value)
 A compound statement ( function body)
Function Definition
• A function definition has this format:
return_data_type FunctionName(data_type variable1, data_type
variable2, data_type variable3, …..)
{
local variable declarations;
statements;
}
• The return data type is the type of data that will be returned to the
calling function. There can be only one return value.
• Any function not returning anything must be of type ‘void’.
• If the function does not receive any arguments from the calling
function, ‘void’ is used in the place of the arguments.
Function Definition Example 1
This is where the actual code of the function is written.
The definition must match the prototype.

Example:
int add(int a, int b) {
return a + b;
}
Function Definition Example 2
• A simple function is :
void print_message (void)
{
printf(“Hello, are you having fun?\n”);
}
• Note the function name is print_message. No arguments are
accepted by the function, this is indicated by the keyword void
enclosed in the parentheses. The return_value is void, thus data is
not returned by the function.
• So, when this function is called in the program, it will simply
perform its intended task which is to print Hello, are you having
fun?
Function Definition Example 3
• Consider the following example:
int calculate (int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
• The above code segments is a function named calculate. This function accepts
two arguments i.e. num 1 and num2 of the type int. The return_value is int,
thus this function will return an integer value.
• So, when this function is called in the program, it will perform its task which is to
calculate the sum of any two numbers and return the result of the summation.
• Note that if the function is returning a value, it needs to use the keyword
‘return’.
Function Call and Return
Any function (including main) could utilize any other
function definition that exist in a program – hence it is said
to call the function (function call).
To call a function (i.e. to ask another function to do
something for the calling function), it requires the
FunctionName followed by a list of actual parameters (or
arguments), if any, enclosed in parenthesis.
Function Call and Return: Example
If the function requires some arguments to be passed along,
then the arguments need to be listed in the bracket ( )
according to the specified order.
For example:
void Calc(int, double, char, int);
void main(void) {
int a, b;
double c;
char d; Function Call

Calc(a, c, d, b);
}
Function Call and Return: Example
If the function returns a value, then the returned value need to be
assigned to a variable so that it can be stored. For example:
int GetUserInput (void); /* function prototype*/
void main(void) {
int input;
input = GetUserInput( );
}
However, it is perfectly okay (syntax wise) to just call the function
without assigning it to any variable if we want to ignore the returned
value.
We can also call a function inside another function. For example:
printf(“User input is: %d”, GetUserInput( ));
Basic Skeleton
#include <stdio.h>
void fn1(void)
//function prototype {
//global variable declaration local variable declaration;
statements;
void main(void) }
{
void fn2(void)
local variable declaration; {
local variable declaration;
statements;
statements;
fn1( ); }
fn2( );
}
Examples
A function may
Receive no input parameter and return nothing
Receive no input parameter but return a value
Receive input parameter(s) and return nothing Receive
input parameters(s) and return a value
Example 1: Receive nothing and Return nothing
#include <stdio.h>
void greeting(void); /* function
In this example, function
prototype */ greeting does not receive any
arguments from the calling
void main(void) function (main), and does not
{ return any value to the calling
greeting( ); function, hence type ‘void’ is
greeting( );
used for both the input
}
arguments and return data type.
void greeting(void) The output of this program is:
{
printf("Have fun!! \n"); Have fun!!
} Have fun!!
Example 2: Receive nothing and Return a value
#include <stdio.h> int getInput(void)
int getInput(void); {
int number;
printf("Enter a number:");
void main(void) scanf("%d",&number);
{
return number;
int num1, num2, sum;
}
num1 = getInput( );
num2 = getInput( ); Sample Output:
Enter a number: 3
sum = num1 + num2; Enter a number: 5
printf("Sum is %d\n",sum); Sum is 8
}
Example 3: Receive parameters and Return nothing
#include <stdio.h> int getInput(void)
int getInput(void); {
void displayOutput(int); int number;
void main(void) printf("Enter a number:");
{ scanf("%d",&number);
int num1, num2, sum; return number;
}
num1 = getInput();
num2 = getInput(); void displayOutput(int sum)
{
printf("Sum is %d \n",sum);
sum = num1 + num2;
}
Sample Output:
displayOutput(sum); Enter a number: 3
} Enter a number: 5
Sum is 8
Example 4: Receive parameters and Return a value
#include <stdio.h> int calSum(int val1, int val2)
int calSum(int,int); /*function protototype*/ /*function definition*/
{
void main(void) int sum;
{ sum = val1 + val2;
int sum, num1, num2;
return sum;
printf("Enter two numbers to calculate its sum:\n"); }

scanf("%d%d",&num1,&num2); Sample Output:


Enter two numbers to calculate
its sum:
sum = calSum(num1,num2); /* function call */ 3
printf("\n %d + %d = %d", num1, num2, sum); 5
}
3+5=8
Example 4: Explanation
 In this example, the calSum function receives input parameters of
type int from the calling function (main).
 The calSum function returns a value of type int to the calling
function.
 Therefore, the function definition for calSum:
int calSum(int val1, int val2)
 Note that the function prototype only indicates the type of
variables used, not the names.
int calSum(int,int);
 Note that the function call is done by (main) calling the function
name (calSum), and supplying the variables (num1,num2) needed
by the calSum function to carry out its task.
Function – Complete Flow
#include<stdio.h>
int calSum(int, int);
void main( )
{
int num1, num2, sum;
printf("Enter 2 numbers to calculate its sum:\n");
scanf("%d %d", &num1, &num2);
sum = calSum (num1, num2);
printf ("\n %d + %d = %d", num1, num2, sum);
} Sample Output:
int calSum(int val1, int val2) Enter two numbers to calculate
its sum:
{
3
int sum;
5
sum = val1 + val2;
return sum; 3+5=8
}
Function with Parameter/Argument
Formal and Actual Parameter
• When a function calls another function to perform a task,
the calling function may also send data to the called
function. After completing its task, the called function may
pass the data it has generated back to the calling function.
• Two terms used:
◦Formal parameter
Variables declared in the formal list of the function header (written
in function prototype & function definition)
◦Actual parameter
Constants, variables, or expression in a function call that correspond
to its formal parameter
Function with Parameter/Argument
The three important points concerning functions with parameters are:
(number, order and type)
• The number of actual parameters in a function call must be
the same as the number of formal parameters in the
function definition.
• A one-to-one correspondence must occur among the
actual and formal parameters. The first actual parameter
must correspond to the first formal parameter and the
second to the second formal parameter, an so on.
• The type of each actual parameter must be the same as
that of the corresponding formal parameter.
Formal and Actual Parameter: Example
#include <stdio.h>
int calSum(int,int);/*function prototype*/ int calSum(int val1, int val2)
/*function definition*/
// val1 and val2 are formal parameters
void main(void)
{
{ int sum;
int sum, num1, num2; sum = val1 + val2;
printf("Enter two numbers to calculate its return sum;
sum:\n"); }
scanf("%d%d",&num1,&num2); Sample Output:
sum = calSum(num1,num2); /* function call */ Enter two numbers to calculate
its sum:
// num1 and num2 are actual parameters 3
printf("\n %d + %d = %d", num1, num2, sum); 5
}
3+5=8
Parameter Passing
There are 2 ways to call a function:
Parameter/argument Passing to a function
Call by value
 In this method, only the copy of variable’s value (copy of actual
parameter’s value) is passed to the function. Any modification to
the passed value inside the function will not affect the actual
value.
 In all the examples that we have seen so far, this is the method
that has been used.
Call by reference
 In this method, the reference (memory address) of the variable is
passed to the function. Any modification passed done to the
variable inside the function will affect the actual value.
 To do this, we need to have knowledge about pointers and arrays,
which will be discussed in chapter pointer.
Call by value: Example
#include <stdio.h>
void change(int data);
int main()
{ Output:
int data = 3; Value of the data is: 3
change(data);
printf("Value of the data is: %d\n", data);
return 0;
}
void change(int data)
{
data = 5;
}
Call by reference/pointer: Example
#include <stdio.h>
void swap(int *x, int *y)
{
int temp;
temp = *x; Output:
*x = *y; Value of x is: 100
*y = temp; Value of y is: 500
}
int main()
{
int x = 500, y = 100;
swap(&x, &y); // passing address to function (call by reference)
printf("Value of x is: %d\n", x);
printf("Value of y is: %d\n", y);
return 0;
}
Calling a function without Argument: Example
#include <stdio.h>

void greet() {
printf("Hello from the greet function!\n");
}
Output:
int main() { Hello from the greet function!

greet(); // Calling the greet function


return 0;}
Calling a function with Arguments and Return Value: Example
#include <stdio.h>
int add(int a, int b) {
return a + b;
} Output:
The sum is: 15
int main() {
int num1 = 5;
int num2 = 10;
int sum_result;
sum_result = add(num1, num2); // Calling the add function with arguments and return value
printf("The sum is: %d\n", sum_result);
return 0;
}
Recursive Function
• Recursion is a programming technique where a function
calls itself repeatedly until a specific base condition is
met.
• A function that performs such self-calling behavior is
known as a recursive function, and each instance of the
function calling itself is called a recursive call.
• It typically consists of two main parts:
Base Case – the condition under which the recursion stops.
Recursive Case – where the function calls itself with
modified arguments, gradually approaching the base case.
Recursive Function Syntax
returntype function(parameters) {

// base case
if (base condition) {
return base value;
}
// recursive case
return recursive expression involving function(modified
parameters);
}
Recursive Function: Example
#include <stdio.h>
void rec(int n) {
// Base Case Output:
if (n == 6) return; Recursion Level 1
Recursion Level 2
printf("Recursion Level %d\n", n); Recursion Level 3
rec(n + 1); Recursion Level 4
} Recursion Level 5

int main() {
rec(1);
return 0;
}
Recursive Function: Factorial Example
#include <stdio.h> int main() {
// Recursive function to calculate factorial int num;
// Prompt user to enter a non-negative integer
long long int factorial(int n) printf("Enter a non-negative integer: ");
{ scanf("%d", &num);
// Base case: factorial of 0 is 1 // Validate input

if (n == 0) { if (num < 0) {
return 1; printf("Factorial is not defined for negative numbers.\n");
} else
} else {
{
// Recursive case: n * factorial of (n-1) // Calculate and print the factorial
return n * factorial(n - 1); printf("Factorial of %d is %lld\n", num, factorial(num));
} }
} return 0;
} Enter a non-negative integer: 5
Factorial of 5 is 120
Macros
• In C programming, a macro is a segment of code that is
assigned a name and processed by the preprocessor
before the actual compilation.
• Macros are defined using the #define directive.
• When the preprocessor encounters a macro name in the
code, it replaces it with the corresponding code segment,
a process known as macro expansion.
Macros: Object-Like
There are primarily two types of macros:
Object-like Macros:
• These macros are used to define constants or simple values.
• They don't take any arguments.
Example: Output:
#include <stdio.h> Value of PI: 3.141590
#define PI 3.14159 // Defining a constant PI
int main() {
printf("Value of PI: %f\n", PI);
return 0;
}
In this example PI will be replaced by 3.14159 during preprocessing
Macros: Function-Like
Function-like Macros:
• These macros resemble functions and can take
arguments.
• They are often used for code reusability or to
create inline functions for performance
optimization.
Macros: Function-Like
Example In this example,
#include <stdio.h> SQUARE(num) expands to
#define SQUARE(x) ((x) * (x)) // Defining a macro to calculate square ((num) * (num)), and
int main() {
MAX(a, b) expands to ((a)
int num = 5;
int result = SQUARE(num); // Macro expansion: ((num) * (num))
> (b) ? (a) : (b)) during
printf("Square of %d is %d\n", num, result); preprocessing.
int a = 3, b = 7; The parentheses in
#define MAX(a, b) ((a) > (b) ? (a) : (b)) // Macro to find maximum of function-like macros are
two numbers

int largest = MAX(a, b);


crucial to prevent
printf("The largest of %d and %d is %d\n", a, b, largest); unexpected behavior due
return 0; to operator precedence
} issues during expansion.
Pre Processing
• Preprocessing in C refers to the phase that occurs
before the actual compilation of a C program.
• The C preprocessor is a macro processor that modifies
the source code based on preprocessor directives.
• These directives always begin with a hash symbol (#).
• The preprocessor does not understand C syntax; it
performs text-based substitutions and manipulations.
Pre Processing Directives
Common Preprocessor Directives:
•#include: Used to include the content of a specified file (usually a
header file) into the current source file. This is crucial for using
functions and declarations defined in other files.
#include <stdio.h> // Includes standard input/output library functions
#include "myheader.h" // Includes a user-defined header file

•#define: Used to define macros, which are symbolic names or


code snippets that the preprocessor replaces with their defined
values before compilation.
#define PI 3.14159 // Object-like macro for a constant value
#define SQUARE(x) ((x) * (x)) // Function-like macro for squaring a number
Pre Processing: Example
#include <stdio.h> // Include standard input/output library
#define PI 3.14159 // Define PI as a constant macro
#define CIRCLE_AREA(r) (PI * (r) * (r)) // Define a function-like macro for circle area

int main() {
float radius;
float area; Output:
printf("Enter the radius of the circle: "); Enter the radius of the circle: 5
scanf("%f", &radius); The area of the circle is: 78.54
// Calculate area using the defined macro
area = CIRCLE_AREA(radius);
printf("The area of the circle is: %.2f\n", area);
return 0;
}
Local and Global Variables
 Local variables only exist within a function. After leaving the
function, they are ‘destroyed’. When the function is called
again, they will be created (reassigned).
 Global variables can be accessed by any function within the
program. While loading the program, memory locations are
reserved for these variables and any function can access these
variables for read and write (overwrite).
 If there exist a local variable and a global variable with the
same name, the compiler will refer to the local variable.
Local Variables: Example
#include <stdio.h>
int main() {
void displaySum() //function prototype and definition displaySum(); // Function call

{ return 0;
int a, b, sum; // Local variables }

printf("Enter two numbers: \n"); Output:


scanf("%d%d", &a, &b); Enter num1 and num2:
5
3
Sum is 8
sum = a + b;

printf("Sum = %d\n", sum);


}
Global Variables: Example
#include <stdio.h>
void initialise(void); void initialise(void) Output:
{ Enter num1 and num2:
void getInputs(void); sum = 0; 5
void calSum(void); } 3
Sum is 8
int sum, num1, num2; // Global Variables
void getInputs(void)
void main(void) {
{ printf("Enter num1 and num2:\n");
/* initialise sum to 0 */
scanf("%d%d",&num1,&num2);
}
initialise( );
/* read num1 and num2 */ void calSum(void)
getInputs( ); {
sum = num1 + num2;
calSum( ); }
printf("Sum is %d\n",sum);
}
Global Variables Explained
 In the previous example, no variables are passed between
functions.
 Each function could have access to the global variables, hence
having the right to read and write the value to it.
 Even though the use of global variables can simplify the code
writing process (promising usage), it could also be dangerous
at the same time.
 Since any function can have the right to overwrite the value in
global variables, a function reading a value from a global
variable can not be guaranteed about its validity.
Global Variables: The Dangerous Side
#include <stdio.h>
void initialise(void)
void initialise(void); { Output:
Enter num1 and num2:
void getInputs(void); sum = 0; 5

void calSum(void);
} 3
void getInputs(void) Sum is 0
int sum, num1, num2; // Global Variables {
void main(void) printf("Enter num1 and num2:\n");
scanf("%d%d",&num1,&num2);
{ }
/* initialise sum to 0 */ void calSum(void)
initialise( ); {
sum = num1 + num2;
/* read num1 and num2 */
initialise( );
getInputs( );
calSum( ); } Imagine what would be the output of this
program if someone ‘accidently’ write the
printf("Sum is %d\n",sum); following function call inside calSum?
}
Structures and Unions
• Structures
 Introduction to Structures
 Structure Definition
 Declaring and Initializing Structure variables
 Accessing Structure members
 Copying and comparison of Structures
 Array of Structures
 Arrays within Structures
 Structures within structures
 Structures and functions
• Unions
Introduction to Structure
What is a Structure?
• A structure in C is a user-defined data type that allows you to
group different types of data together under one name.
• It is used when you want to store information about a single
entity that has multiple attributes of different data types.
Introduction to Structures:
• Heterogeneous data to be stored together e.g student’s result
data
• Group logically related items to make the complex design more
meaningful
• Structure and unions are two different data types which hold
other data types in turn
Example Situation
Suppose you want to store information
about a student:
• Roll number (integer)
• Name (string)
• Marks (float)
You could use a structure to group these
together instead of using separate variables.
Structure Syntax (Definition)
struct structure_name {
data_type member1;
data_type member2;
...
data_type memberN;
};
Declaring and initializing Structure Variables
You can declare variables in two ways:

1. After the structure definition:


struct student s1, s2;

2. Together with the definition:


struct student {
int roll_no;
char name[20];
float marks;
} s1, s2;
Structure Syntax (Definition and Declaration): Example
Accessing Structure members
Using the dot (.) operator:

s1.roll_no = 101;
strcpy([Link], "Alice");
[Link] = 89.5;

printf("Name: %s\n", [Link]);


Example Program
int main() {
#include <stdio.h> struct student s1; Output:
#include <string.h> Enter roll number,
printf("Enter roll number, name and name and marks:
//structure definition marks:\n"); 1 Anil 74
struct student { scanf("%d %s %f", &s1.roll_no, [Link],
int roll_no; &[Link]); Student Details:
char name[20];
Roll No: 1
float marks; printf("\nStudent Details:\n"); Name: Anil
}; printf("Roll No: %d\n", s1.roll_no); Marks: 74.00
printf("Name: %s\n", [Link]);
printf("Marks: %.2f\n", [Link]);

return 0;
}
Copying and Comparison of Structures

• Two variables of the same structure type can be


copied the same way as ordinary variables.
• If person1 and person 2 belong to same
structure, then the following statement is valid.

Person1=person2; Example: If person1 and person2


are structure variables of the same
Person2=person1; type, person1 = person2 will copy
all the member values from
person2 to person1.
Copying and Comparison of Structures: Example
#include <stdio.h>
#include <string.h>
struct Person { What's Copied: This is a "shallow copy,"
char name[50]; meaning all the member values are copied
int age;
};
directly from the source structure to the
destination.
int main(){
struct Person person1;
[Link] = 25; OutPut
strcpy([Link], "Alice");
printf("Person1 Age and Name: %s %d\n", [Link],
[Link]); Person1 Age and Name: Alice 25
struct Person person2; Person2 Age and Name: Alice 25
person2 = person1; // Copies the values from person1 to
person2
printf("Person2 Age and Name: %s %d\n", [Link],
[Link]);
}
Copying and Comparison of Structures: Example
#include <stdio.h> • Member-by-Member Comparison:
#include <string.h>
• Direct comparison of structure
struct Student {
int id;
variables with == or != is not
char name[50]; allowed in C.
int score; • You must compare each
}; corresponding member individually.
int main(){
struct Student student1 = {1, "Bob", 90}; Example: To check if student1 and
struct Student student2 = {2, "Charlie", 85}; student2 are equal, you'd check:
struct Student student3 = {1, "Bob", 90};
// To compare student1 and student3:
if ([Link] == [Link] && [Link] == [Link]
strcmp([Link], [Link]) == 0 && // [Link] == [Link]
For strings [Link] == [Link]
[Link] == [Link]) {
printf("student1 and student3 are equal\n");
} Output: student1 and student3 are equal
}
Arrays of Structures
for(i=0; i<3; ++i) // Loop from 0 to 2 for 3 inputs
#include <stdio.h> {
printf("\nEnter name, price and pages for book %d\n", i + 1);
struct book { scanf(" %[^\n]s", b[i].name); // Use scanset to read a line with spaces
char name[50]; // Use a scanf("%f", &b[i].price);
character array for the book title scanf("%d", &b[i].pages);
float price; while (getchar() != '\n'); // Clear the input buffer
int pages; }
};
printf("\nBook Details:\n");
int main() { for(i=0; i<3; ++i) // Loop from 0 to 2 for 3 outputs
struct book b[100]; {
int i; printf("Book %d: Name: %s, Price: %.2f, Pages: %d\n", i + 1,
b[i].name, b[i].price, b[i].pages);
}
return 0;
}
Arrays of Structures
Output:
Enter name, price and pages for book 1
Anil
20.50
10

Enter name, price and pages for book 2


Shail
41.00
20

Enter name, price and pages for book 3


Hinal
10.25
5

Book Details:
Book 1: Name: Anil, Price: 20.50, Pages: 10
Book 2: Name: Shail, Price: 41.00, Pages: 20
Book 3: Name: Hinal, Price: 10.25, Pages: 5
Arrays within Structures
#include <stdio.h> // Assign values to the array of marks
#include <string.h> [Link][0] = 95;
[Link][1] = 88;
// Define a structure named Student [Link][2] = 92;
struct Student {
int roll_number; // --- Calculating and assigning the average ---
char name[50]; for (int i = 0; i < 3; i++) {
int marks[3]; // An array of integers to store marks for 3 subjects total_marks += [Link][i];
float average; }
}; [Link] = (float)total_marks / 3;
int main() { // --- Printing the data ---
// Declare a single variable of type struct Student printf("--- Student Information ---\n");
struct Student s1; printf("Roll Number: %d\n", s1.roll_number);
int total_marks = 0; printf("Name: %s\n", [Link]);
printf("Marks in 3 subjects: %d, %d, %d\n", [Link][0],
// --- Assigning values to the structure members --- [Link][1], [Link][2]);
printf("Average Marks: %.2f\n", [Link]);
// Assign a roll number
s1.roll_number = 101; return 0;
}
// Use strcpy to assign a string to the character array 'name'
strcpy([Link], "Alice");
Arrays within Structures
Output:

--- Student Information ---


Roll Number: 101
Name: Alice
Marks in 3 subjects: 95, 88, 92
Average Marks: 91.67
Structure within Structures
#include <stdio.h> // Assign values to the array of marks
#include <string.h> [Link][0] = 95;
[Link][1] = 88;
// Define a structure named Student [Link][2] = 92;
struct Student {
int roll_number; // --- Calculating and assigning the average ---
char name[50]; for (int i = 0; i < 3; i++) {
int marks[3]; // An array of integers to store marks for 3 subjects total_marks += [Link][i];
float average; }
}; [Link] = (float)total_marks / 3;
int main() { // --- Printing the data ---
// Declare a single variable of type struct Student printf("--- Student Information ---\n");
struct Student s1; printf("Roll Number: %d\n", s1.roll_number);
int total_marks = 0; printf("Name: %s\n", [Link]);
printf("Marks in 3 subjects: %d, %d, %d\n", [Link][0],
// --- Assigning values to the structure members --- [Link][1], [Link][2]);
printf("Average Marks: %.2f\n", [Link]);
// Assign a roll number
s1.roll_number = 101; return 0;
}
// Use strcpy to assign a string to the character array 'name'
strcpy([Link], "Alice");
Structure and functions
#include <stdio.h> // 3. A function that takes a struct by int main() {
#include <string.h> reference (pointer) // Call the function that returns a struct
// This is more memory-efficient for large struct Student student1 = createStudent(101,
// 1. Define the `Student` structure structs. "Alice", 95.5);
// This groups a student's ID, name, and // It uses the arrow operator `->` to
marks into a single data type. access members. // Call the function that takes a struct by value
struct Student { void updateMarks(struct Student *s, float displayStudent(student1);
int id; new_marks) {
char name[50]; s->marks = new_marks; // Call the function that takes a struct by
float marks; } reference to modify it
}; printf("\nUpdating Alice's marks...\n");
// 4. A function that returns a struct updateMarks(&student1, 98.0);
// 2. A function that takes a struct by // It creates and returns a new `Student`
value struct. // Display the updated struct
// It receives a copy of the struct and struct Student createStudent(int id, const displayStudent(student1);
displays its contents. char *name, float marks) {
void displayStudent(struct Student s) { struct Student new_student; return 0;
printf("--- Student Details ---\n"); new_student.id = id; }
printf("ID: %d\n", [Link]); strcpy(new_student.name, name); Output: Updating Alice's
printf("Name: %s\n", [Link]); new_student.marks = marks; --- Student Details --- marks...
printf("Marks: %.2f\n", [Link]); return new_student; ID: 101 --- Student Details ---
} } Name: Alice ID: 101
Marks: 95.50 Name: Alice
Marks: 98.00
Structure and functions
#include <stdio.h> // 2. A function that takes a struct by value
#include <string.h> // It receives a copy of the struct and displays
its contents.
// 1. Define the `Student` Function Name: displayStudent
structure Parameter Passed: struct Student s (s is the
// This groups a student's member of Structure Student)
ID, name, and marks into a Return type: void
single data type. void displayStudent(struct Student s) {
Structure Name: Student printf("--- Student Details ---\n");
struct Student { printf("ID: %d\n", [Link]);
int id; printf("Name: %s\n", [Link]);
char name[50]; printf("Marks: %.2f\n", [Link]);
float marks; }
};
Structure and functions
// 3. A function that takes a struct by // 4. A function that returns a struct
reference (pointer) // It creates and returns a new `Student`
// This is more memory-efficient for large struct.
structs. Function Name: createStudent
// It uses the arrow operator `->` to access Parameter Passed: int id, const char *name,
members. float marks
Function Name: updateMarks Return type: struct Student
Parameter Passed: struct Student *s, float struct Student createStudent(int id, const char
new_marks (*s is pointer structure *name, float marks) {
student’s member s) struct Student new_student;
Return type: void new_student.id = id;
void updateMarks(struct Student *s, float strcpy(new_student.name, name);
new_marks) { new_student.marks = marks;
s->marks = new_marks; return new_student;
} }
Union
• A union in C is a user-defined data type that allows different data
types to be stored in the same memory location.
• Unlike structures, where each member has its own distinct
memory space, all members of a union share the same memory.
• The size of a union is determined by the size of its largest
member.
• At any given time, only one member of a union can hold a
meaningful value; assigning a value to one member overwrites the
value of any previously assigned member.
Syntax of Union: union UnionName {
dataType member1;
dataType member2;
// ... more members
};
Union: Example
#include <stdio.h> // Assign a value to the string member this overwrites the
#include <string.h> // Required for strcpy float value)
// Define a union named Data strcpy([Link], "C Programming");
union Data { printf("String value: %s\n", [Link]);
int i; // Attempting to access other members after assigning to 'str‘
float f; // will yield undefined behavior as their memory has been
char str[20]; // Character array to store a string overwritten.
}; printf("Integer value after string assignment (undefined
behavior): %d\n",myUnion.i);;
int main() { printf("Float value after string assignment (undefined
// Declare a union variable union Data behavior): %f\n", myUnion.f);
myUnion;
union Data myUnion; printf("Size of union Data: %lu bytes\n",
// Assign a value to the integer member sizeof(union Data));
myUnion.i = 10; Integer value: 10
printf("Integer value: %d\n", myUnion.i); return 0; Float value: 220.500000
} String value: C Programming
// Assign a value to the float member (this Integer value after string assignment (undefined behavior):
1917853763
overwrites the integer value)
Float value after string assignment (undefined behavior):
myUnion.f = 220.5; 4122360580327794860452759994368.000000
printf("Float value: %f\n", myUnion.f); Size of union Data: 20 bytes
Difference Between Structure and Union
#include <stdio.h>
int main(){
//defining a union
printf("size of union = %d",sizeof(u));
union job {
printf("\nsize of structure = %d", sizeof(s));
char name [32];
return 0;
float salary;
}
int worker_no;
}u;
Output:
struct job1 {
char name [32]; size of union = 32
float salary; size of structure = 40
int worker_no;
}s;
Difference Between Structure and Union
[Link]

You might also like