SlideShare a Scribd company logo
Module 5
Bhargavi Dalal
Course Objective and Outcome
Road Map
• User Defined Functions: Need for User-defined Functions, A Multi-
Function Program, Elements of User defined Functions, Definition of
Functions, Return Values and their Types, Function Calls, Function
Declaration, Category of Functions: No Arguments and no Return Values,
Arguments but No Return Values, Arguments with Return values, No
Arguments but Returns a Value, Functions that Return Multiple Values,
Nesting of Functions, Recursion
• Structures : What is a Structure? Structure Type Declarations, Structure
Declarations, Referencing Structure Members, Referencing Whole
Structures, Initialization of Structures.
C Functions
• A function in C is a set of statements that when called perform some specific
tasks.
• It is the basic building block of a C program that provides modularity and
code reusability.
• The programming statements of a function are enclosed within { } braces,
having certain meanings and performing certain operations.
• They are also called subroutines or procedures in other languages.
Syntax of Functions in C
• The syntax of function can be divided into 3 aspects:
1.Function Declaration
2.Function Definition
3.Function Calls
1. Function Declarations
• In a function declaration, we must provide the function name, its return type,
and the number and type of its parameters.
• A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.
• Syntax
• return_type name_of_the_function (parameter_1, parameter_2);
• The parameter name is not mandatory while declaring functions. We can
also declare the function without using the name of the data variables.
• Note: A function in C must always be declared globally before calling it.
Example
• int sum(int a, int b); // Function declaration with parameter names
• int sum(int , int); // Function declaration without parameter names
Functions and structure in programming c
2. Function Definition
• The function definition consists of actual statements which are executed
when the function is called (i.e. when the program control comes to the
function).
• A C function is generally defined and declared in a single step because the
function definition always starts with the function declaration so we do not
need to declare it explicitly.
• The below example serves as both a function definition and a declaration.
Syntax
• return_type function_name (para1_type para1_name, para2_type
para2_name)
• {
• // body of the function
• }
Functions and structure in programming c
3. Function Call
• A function call is a statement that instructs the compiler to execute the
function.
• We use the function name and parameters in the function call.
• In the below example, the first sum function is called and 10,30 are
passed to the sum function.
• After the function call sum of a and b is returned and control is also
returned back to the main function of the program.
Example
Example of C Function
• // C program to show function call and definition
• #include <stdio.h>
• // Function that takes two parameters a and b as inputs and returns their sum
• int sum(int a, int b)
• {
• return a + b;
• }
• // Driver code
• int main()
• {
• // Calling sum function and storing its value in add variable
• int add = sum(10, 30);
•
• printf("Sum is: %d", add);
• return 0;
• }
Output:
Sum is: 40
Function Return Type
• Function return type tells what type of value is returned after all function is
executed.
• When we don’t want to return a value, we can use the void data type.
• Example:
• int func(parameter_1,parameter_2);
• The above function will return an integer value after running statements inside
the function.
• Note:
• Only one value can be returned from a C function.
• To return multiple values, we have to use pointers or structures.
Function Arguments
• Function Arguments (also known as Function Parameters) are the data that
is passed to a function.
• Example:
• int function_name(int var1, int var2);
How Does C Function Work?
• Working of the C function can be broken into the following steps as mentioned below:
1.Declaring a function: Declaring a function is a step where we declare a function. Here we
specify the return types and parameters of the function.
2.Defining a function: This is where the function’s body is provided. Here, we specify what
the function does, including the operations to be performed when the function is called.
3.Calling the function: Calling the function is a step where we call the function by passing
the arguments in the function.
4.Executing the function: Executing the function is a step where we can run all the
statements inside the function to get the final result.
5.Returning a value: Returning a value is the step where the calculated value after the
execution of the function is returned. Exiting the function is the final step where all the
allocated memory to the variables, functions, etc is destroyed before giving full control back
to the caller.
Types of Functions
• There are two types of functions in C:
1.Library Functions
2.User Defined Functions
1. Library Function
• A library function is also referred to as a “built-in function”.
• A compiler package already exists that contains these functions, each of which has a specific
meaning and is included in the package.
• Built-in functions have the advantage of being directly usable without being defined, whereas
user-defined functions must be declared and defined before being used.
• For Example:
• pow(), sqrt(), strcmp(), strcpy() etc.
• Advantages of C library functions
• C Library functions are easy to use and optimized for better performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.
2. User Defined Function
• Functions that the programmer creates are known as User-Defined functions or
“tailor-made functions”.
• User-defined functions can be improved and modified according to the need of
the programmer.
• Whenever we write a function that is case-specific and is not defined in any
header file, we need to declare and define our own functions according to the
syntax.
• Advantages of User-Defined Functions
• Changeable functions can be modified as per need.
• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.
User Defined Functions:
• A user-defined function is a type of function in C language that is defined
by the user himself to perform some specific task.
• It provides code reusability and modularity to our program.
• User-defined functions are different from built-in functions as their
working is specified by the user and no header file is required for their
usage.
Need for user defined functions in c
• 1. Modularity
• Functions allow you to break down a complex program into smaller,
manageable pieces (modules).
• Each function handles a specific task, making the code more organized.
• 2. Code Reusability
• Once a function is written, it can be reused multiple times in the program or
across different programs.
• This reduces duplication and saves time and effort in coding.
• 3. Improved Readability
• Dividing code into functions makes it easier to understand.
• Each function can be named to reflect its purpose, making the overall logic of
the program clearer.
• 4. Easier Debugging and Maintenance
• Errors can be isolated within specific functions, making debugging more
straightforward.
• Modifying a function doesn't affect the rest of the program if the function's
interface remains unchanged.
• 5. Simplifies Complex Problems
• Complex problems can be broken into smaller sub-problems, each handled by a
separate function.
• This approach aligns with top-down design and stepwise refinement principles.
• 6. Abstraction
• Functions allow programmers to focus on the higher-level logic without
worrying about the implementation details of lower-level tasks.
• 7. Encourages Collaboration
• In larger projects, different developers can work on different functions
simultaneously.
• This promotes teamwork and parallel development.
Example
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int num1 = 5, num2 = 10;
// Function call
int sum = add(num1, num2);
printf("Sum: %dn", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
• Benefits in the Example:
• The add function encapsulates the logic for addition.
• The main function is cleaner and focuses on program flow.
• By leveraging user-defined functions, C programmers can write
efficient, maintainable, and scalable code, which is essential for
both small projects and large-scale software development.
Functions in C play a crucial role in building
real-time applications.
• 1. Embedded Systems:
• Device Drivers:
• Functions are used to interact with hardware peripherals, such as reading
sensor data, controlling actuators, or managing communication interfaces.
• Interrupt Handlers:
• Interrupt Service Routines (ISRs) are functions that respond to hardware
interrupts, allowing for real-time event handling.
• Task Scheduling:
• Real-time operating systems (RTOS) often use functions to define individual
tasks that need to be executed with specific timing constraints.
• 2. Signal Processing:
• Digital Filters:
• Functions implement filtering algorithms to process signals in real-time,
such as removing noise or extracting specific frequencies.
• Audio Processing:
• Functions handle audio input and output, allowing for tasks like audio
playback, recording, or applying effects.
• Image Processing:
• Functions manipulate image data in real-time, enabling tasks like image
recognition, object tracking, or video compression.
• 3. Control Systems:
• PID Controllers:
• Functions implement Proportional-Integral-Derivative (PID) control
algorithms to regulate systems like temperature, speed, or position.
• Feedback Loops:
• Functions process sensor data and adjust control outputs in real-time
to maintain desired system behavior.
• 4. Games and Simulations:
• Physics Engine:
• Functions simulate physics phenomena like collisions, gravity, or fluid
dynamics in real-time.
• Rendering Engine:
• Functions render 3D graphics, update animations, and handle user
input in real-time.
• 5. Networking:
• Packet Handling:
• Functions process network packets, allowing for real-time
communication and data transfer.
• Protocol Implementations:
• Functions implement networking protocols like TCP/IP, enabling real-
time communication over networks.
A Multi-Function Program C
• Multi-function program in C that demonstrates the use of multiple user-
defined functions for various tasks.
• This program performs basic arithmetic operations (addition, subtraction,
multiplication, and division) and uses separate functions for each operation.
Example
#include <stdio.h>
// Function declarations
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
int main() {
int choice, num1, num2;
printf("Simple Calculatorn");
printf("-----------------n");
printf("1. Additionn");
printf("2. Subtractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
// Input numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Perform operation based on user choice
switch (choice) {
case 1:
printf("Result: %dn", add(num1, num2));
break;
case 2:
printf("Result: %dn", subtract(num1, num2));
break;
case 3:
printf("Result: %dn", multiply(num1, num2));
break;
case 4:
if (num2 != 0) {
printf("Result: %.2fn", divide(num1, num2));
} else {
printf("Error: Division by zero is not allowed.
n");
}
break;
default:
printf("Invalid choice.n");
}
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
float divide(int a, int b) {
return (float)a / b;
}
How the Program Works:
1.The program asks the user to choose an arithmetic operation.
2.The user inputs two numbers.
3.Based on the choice, the corresponding user-defined function is called:
•Addition: Calls the add function.
•Subtraction: Calls the subtract function.
•Multiplication: Calls the multiply function.
•Division: Calls the divide function (with a check for division by zero).
Sample Output:
• Simple Calculator -----------------
• 1. Addition
• 2. Subtraction
• 3. Multiplication
• 4. Division
• Enter your choice (1-4): 1
• Enter two numbers: 10 5
• Result: 15
Key Takeaways:
1.Multiple User-Defined Functions: The program demonstrates how to
create and use multiple functions to make the code modular and reusable.
2.Error Handling: Includes a basic check for division by zero.
3.Switch-Case: Simplifies the selection of operations based on user input.
• This modular approach makes the program easy to expand and maintain.
• For instance, you could add more functions like square root, exponentiation,
or other operations in the future.
Category of Functions:
• A function in C can be called either with arguments or without
arguments.
• These functions may or may not return values to the calling functions.
• All C functions can be called either with arguments or without
arguments in a C program.
• Also, they may or may not return any values. Hence the function
prototype of a function in C is as below:
Category of Functions:/ Conditions of Return
Types and Arguments
• In C programming language, functions can be called either with or
without arguments and might return values.
• They may or might not return values to the calling functions.
• Function with no arguments and no return value
• Function with no arguments and with return value
• Function with argument and with no return value
• Function with arguments and with return value
• Functions that Return Multiple Values
Functions and structure in programming c
Function with no arguments and no return value
• In C programming, a function that does not take any arguments and does not return a value is called a void function. The syntax for defining a void
function is as follows:
Syntax:
return_type function_name ( parameter1, parameter2, ... )
{
// body of Statement ;
}
Example :
void function_name ( )
{
// body of Statement ;
}
• Here, the 'void' keyword is used as the return type to indicate that the function does not return any value.
• A void function can be called in the same way as other functions, by simply using the function name followed by empty parentheses:
• function_name ( );
• Here is an example of a void function that prints a message to the console:
• This program defines a void function called add that simply prints the message "Total of a and b" to the console.
• The main function calls the add function, which executes the code inside the function and prints the message.
• Void functions are useful in C programming when you want to perform a specific task without returning any value, such as displaying a message,
initializing a variable or updating a data structure
Example
//No Return Without Argument Function in C
/*
1.Function Declaration
2.Function Definition
3.Function Calling
*/
#include<stdio.h>
//Function Declaration
void add();
int main()
{
//Function Calling
add();
return 0;
}
//Function Definition
void add()
{
int a,b,c;
printf("nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("nTotal : %d",c);
}
Function with no arguments and with return value
• https://
www.tutorjoes.in/c_programming_tutorial/not_return_with_arg_fun
ction_in_c
Function with argument and with no return value
• In C programming, a function that takes one or more arguments but does not return a value is called a void function.
The syntax for defining a void function with arguments is as follows:
• Syntax :
return_type function_name ( data_type argument1, data_type argument2, ... ) // Function Definition
{
// body of Statement ;
}
• Here, the 'void' keyword is used as the return type to indicate that the function does not return any value.
• The function_name is the name of the function, and the argument1, argument2, ... are the input parameters that the
function takes.
• A void function with arguments can be called by providing the values for the arguments in the function call:
• function_name(value1, value2, ...);
• This program is a simple C program that demonstrates how to define and call a void function in C.
• The program defines a void function called add that takes two integer parameters, x and y, and adds them together.
The function then prints the result of the addition.
• The main function first prompts the user to enter two integers, a and b, which are then passed as arguments to the add
function when it is called.
• The add function uses these arguments as its x and y parameters and performs the addition. The result of the addition
is then printed to the console.
Example
• //No Return With Argument Function in C
• #include<stdio.h>
•
• //Function Declaration
• void add(int,int);
•
• int main()
• {
• int a,b;
• printf("nEnter The Value of A & B : ")l
• scanf("%d%d",&a,&b);
• //Function Calling
• add(a,b); // Actual Parameters
• return 0;
• }
• //Function Definition
• void add(int x,int y) //Formal Parameters
• {
• int c;
• c=x+y;
• printf("nTotal : %d",c);
• }
•
Ad

More Related Content

Similar to Functions and structure in programming c (20)

Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
DS functions-1.pptx
DS functions-1.pptxDS functions-1.pptx
DS functions-1.pptx
HarikishnaKNHk
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Functions and Header files ver very useful
Functions and Header files ver very usefulFunctions and Header files ver very useful
Functions and Header files ver very useful
RamSiddesh1
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
sumitbardhan
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
SKUP1
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
LECO9
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
vinay chauhan
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
SzeChingChen
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Basic c++
Basic c++Basic c++
Basic c++
Maria Stella Solon
 
Python Functions
Python FunctionsPython Functions
Python Functions
Sampad Kar
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
Plc part 3
Plc  part 3Plc  part 3
Plc part 3
Taymoor Nazmy
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Functions and Header files ver very useful
Functions and Header files ver very usefulFunctions and Header files ver very useful
Functions and Header files ver very useful
RamSiddesh1
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
sumitbardhan
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
SKUP1
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
LECO9
 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Python Functions
Python FunctionsPython Functions
Python Functions
Sampad Kar
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 

Recently uploaded (20)

acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023
Rajesh Prasad
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
vtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdfvtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdf
RaghavaGD1
 
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
ssuserd9338b
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Journal of Soft Computing in Civil Engineering
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdfGROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
kemimafe11
 
Zeiss-Ultra-Optimeter metrology subject.pdf
Zeiss-Ultra-Optimeter metrology subject.pdfZeiss-Ultra-Optimeter metrology subject.pdf
Zeiss-Ultra-Optimeter metrology subject.pdf
Saikumar174642
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023
Rajesh Prasad
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
vtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdfvtc2018fall_otfs_tutorial_presentation_1.pdf
vtc2018fall_otfs_tutorial_presentation_1.pdf
RaghavaGD1
 
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
ssuserd9338b
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdfGROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
GROUP 2 - MANUFACTURE OF LIME, GYPSUM AND CEMENT.pdf
kemimafe11
 
Zeiss-Ultra-Optimeter metrology subject.pdf
Zeiss-Ultra-Optimeter metrology subject.pdfZeiss-Ultra-Optimeter metrology subject.pdf
Zeiss-Ultra-Optimeter metrology subject.pdf
Saikumar174642
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Ad

Functions and structure in programming c

  • 3. Road Map • User Defined Functions: Need for User-defined Functions, A Multi- Function Program, Elements of User defined Functions, Definition of Functions, Return Values and their Types, Function Calls, Function Declaration, Category of Functions: No Arguments and no Return Values, Arguments but No Return Values, Arguments with Return values, No Arguments but Returns a Value, Functions that Return Multiple Values, Nesting of Functions, Recursion • Structures : What is a Structure? Structure Type Declarations, Structure Declarations, Referencing Structure Members, Referencing Whole Structures, Initialization of Structures.
  • 4. C Functions • A function in C is a set of statements that when called perform some specific tasks. • It is the basic building block of a C program that provides modularity and code reusability. • The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain operations. • They are also called subroutines or procedures in other languages.
  • 5. Syntax of Functions in C • The syntax of function can be divided into 3 aspects: 1.Function Declaration 2.Function Definition 3.Function Calls
  • 6. 1. Function Declarations • In a function declaration, we must provide the function name, its return type, and the number and type of its parameters. • A function declaration tells the compiler that there is a function with the given name defined somewhere else in the program. • Syntax • return_type name_of_the_function (parameter_1, parameter_2); • The parameter name is not mandatory while declaring functions. We can also declare the function without using the name of the data variables. • Note: A function in C must always be declared globally before calling it.
  • 7. Example • int sum(int a, int b); // Function declaration with parameter names • int sum(int , int); // Function declaration without parameter names
  • 9. 2. Function Definition • The function definition consists of actual statements which are executed when the function is called (i.e. when the program control comes to the function). • A C function is generally defined and declared in a single step because the function definition always starts with the function declaration so we do not need to declare it explicitly. • The below example serves as both a function definition and a declaration.
  • 10. Syntax • return_type function_name (para1_type para1_name, para2_type para2_name) • { • // body of the function • }
  • 12. 3. Function Call • A function call is a statement that instructs the compiler to execute the function. • We use the function name and parameters in the function call. • In the below example, the first sum function is called and 10,30 are passed to the sum function. • After the function call sum of a and b is returned and control is also returned back to the main function of the program.
  • 14. Example of C Function • // C program to show function call and definition • #include <stdio.h> • // Function that takes two parameters a and b as inputs and returns their sum • int sum(int a, int b) • { • return a + b; • } • // Driver code • int main() • { • // Calling sum function and storing its value in add variable • int add = sum(10, 30); • • printf("Sum is: %d", add); • return 0; • } Output: Sum is: 40
  • 15. Function Return Type • Function return type tells what type of value is returned after all function is executed. • When we don’t want to return a value, we can use the void data type. • Example: • int func(parameter_1,parameter_2); • The above function will return an integer value after running statements inside the function. • Note: • Only one value can be returned from a C function. • To return multiple values, we have to use pointers or structures.
  • 16. Function Arguments • Function Arguments (also known as Function Parameters) are the data that is passed to a function. • Example: • int function_name(int var1, int var2);
  • 17. How Does C Function Work? • Working of the C function can be broken into the following steps as mentioned below: 1.Declaring a function: Declaring a function is a step where we declare a function. Here we specify the return types and parameters of the function. 2.Defining a function: This is where the function’s body is provided. Here, we specify what the function does, including the operations to be performed when the function is called. 3.Calling the function: Calling the function is a step where we call the function by passing the arguments in the function. 4.Executing the function: Executing the function is a step where we can run all the statements inside the function to get the final result. 5.Returning a value: Returning a value is the step where the calculated value after the execution of the function is returned. Exiting the function is the final step where all the allocated memory to the variables, functions, etc is destroyed before giving full control back to the caller.
  • 18. Types of Functions • There are two types of functions in C: 1.Library Functions 2.User Defined Functions
  • 19. 1. Library Function • A library function is also referred to as a “built-in function”. • A compiler package already exists that contains these functions, each of which has a specific meaning and is included in the package. • Built-in functions have the advantage of being directly usable without being defined, whereas user-defined functions must be declared and defined before being used. • For Example: • pow(), sqrt(), strcmp(), strcpy() etc. • Advantages of C library functions • C Library functions are easy to use and optimized for better performance. • C library functions save a lot of time i.e, function development time. • C library functions are convenient as they always work.
  • 20. 2. User Defined Function • Functions that the programmer creates are known as User-Defined functions or “tailor-made functions”. • User-defined functions can be improved and modified according to the need of the programmer. • Whenever we write a function that is case-specific and is not defined in any header file, we need to declare and define our own functions according to the syntax. • Advantages of User-Defined Functions • Changeable functions can be modified as per need. • The Code of these functions is reusable in other programs. • These functions are easy to understand, debug and maintain.
  • 21. User Defined Functions: • A user-defined function is a type of function in C language that is defined by the user himself to perform some specific task. • It provides code reusability and modularity to our program. • User-defined functions are different from built-in functions as their working is specified by the user and no header file is required for their usage.
  • 22. Need for user defined functions in c • 1. Modularity • Functions allow you to break down a complex program into smaller, manageable pieces (modules). • Each function handles a specific task, making the code more organized. • 2. Code Reusability • Once a function is written, it can be reused multiple times in the program or across different programs. • This reduces duplication and saves time and effort in coding.
  • 23. • 3. Improved Readability • Dividing code into functions makes it easier to understand. • Each function can be named to reflect its purpose, making the overall logic of the program clearer. • 4. Easier Debugging and Maintenance • Errors can be isolated within specific functions, making debugging more straightforward. • Modifying a function doesn't affect the rest of the program if the function's interface remains unchanged.
  • 24. • 5. Simplifies Complex Problems • Complex problems can be broken into smaller sub-problems, each handled by a separate function. • This approach aligns with top-down design and stepwise refinement principles. • 6. Abstraction • Functions allow programmers to focus on the higher-level logic without worrying about the implementation details of lower-level tasks. • 7. Encourages Collaboration • In larger projects, different developers can work on different functions simultaneously. • This promotes teamwork and parallel development.
  • 25. Example #include <stdio.h> // Function declaration int add(int a, int b); int main() { int num1 = 5, num2 = 10; // Function call int sum = add(num1, num2); printf("Sum: %dn", sum); return 0; } // Function definition int add(int a, int b) { return a + b; } • Benefits in the Example: • The add function encapsulates the logic for addition. • The main function is cleaner and focuses on program flow. • By leveraging user-defined functions, C programmers can write efficient, maintainable, and scalable code, which is essential for both small projects and large-scale software development.
  • 26. Functions in C play a crucial role in building real-time applications. • 1. Embedded Systems: • Device Drivers: • Functions are used to interact with hardware peripherals, such as reading sensor data, controlling actuators, or managing communication interfaces. • Interrupt Handlers: • Interrupt Service Routines (ISRs) are functions that respond to hardware interrupts, allowing for real-time event handling. • Task Scheduling: • Real-time operating systems (RTOS) often use functions to define individual tasks that need to be executed with specific timing constraints.
  • 27. • 2. Signal Processing: • Digital Filters: • Functions implement filtering algorithms to process signals in real-time, such as removing noise or extracting specific frequencies. • Audio Processing: • Functions handle audio input and output, allowing for tasks like audio playback, recording, or applying effects. • Image Processing: • Functions manipulate image data in real-time, enabling tasks like image recognition, object tracking, or video compression.
  • 28. • 3. Control Systems: • PID Controllers: • Functions implement Proportional-Integral-Derivative (PID) control algorithms to regulate systems like temperature, speed, or position. • Feedback Loops: • Functions process sensor data and adjust control outputs in real-time to maintain desired system behavior.
  • 29. • 4. Games and Simulations: • Physics Engine: • Functions simulate physics phenomena like collisions, gravity, or fluid dynamics in real-time. • Rendering Engine: • Functions render 3D graphics, update animations, and handle user input in real-time.
  • 30. • 5. Networking: • Packet Handling: • Functions process network packets, allowing for real-time communication and data transfer. • Protocol Implementations: • Functions implement networking protocols like TCP/IP, enabling real- time communication over networks.
  • 31. A Multi-Function Program C • Multi-function program in C that demonstrates the use of multiple user- defined functions for various tasks. • This program performs basic arithmetic operations (addition, subtraction, multiplication, and division) and uses separate functions for each operation.
  • 32. Example #include <stdio.h> // Function declarations int add(int a, int b); int subtract(int a, int b); int multiply(int a, int b); float divide(int a, int b); int main() { int choice, num1, num2; printf("Simple Calculatorn"); printf("-----------------n"); printf("1. Additionn"); printf("2. Subtractionn"); printf("3. Multiplicationn"); printf("4. Divisionn"); printf("Enter your choice (1-4): "); scanf("%d", &choice); // Input numbers printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Perform operation based on user choice switch (choice) { case 1: printf("Result: %dn", add(num1, num2)); break; case 2: printf("Result: %dn", subtract(num1, num2)); break; case 3: printf("Result: %dn", multiply(num1, num2)); break; case 4: if (num2 != 0) { printf("Result: %.2fn", divide(num1, num2)); } else { printf("Error: Division by zero is not allowed. n"); } break; default: printf("Invalid choice.n"); } return 0; } // Function definitions int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } float divide(int a, int b) { return (float)a / b; }
  • 33. How the Program Works: 1.The program asks the user to choose an arithmetic operation. 2.The user inputs two numbers. 3.Based on the choice, the corresponding user-defined function is called: •Addition: Calls the add function. •Subtraction: Calls the subtract function. •Multiplication: Calls the multiply function. •Division: Calls the divide function (with a check for division by zero).
  • 34. Sample Output: • Simple Calculator ----------------- • 1. Addition • 2. Subtraction • 3. Multiplication • 4. Division • Enter your choice (1-4): 1 • Enter two numbers: 10 5 • Result: 15
  • 35. Key Takeaways: 1.Multiple User-Defined Functions: The program demonstrates how to create and use multiple functions to make the code modular and reusable. 2.Error Handling: Includes a basic check for division by zero. 3.Switch-Case: Simplifies the selection of operations based on user input. • This modular approach makes the program easy to expand and maintain. • For instance, you could add more functions like square root, exponentiation, or other operations in the future.
  • 37. • A function in C can be called either with arguments or without arguments. • These functions may or may not return values to the calling functions. • All C functions can be called either with arguments or without arguments in a C program. • Also, they may or may not return any values. Hence the function prototype of a function in C is as below:
  • 38. Category of Functions:/ Conditions of Return Types and Arguments • In C programming language, functions can be called either with or without arguments and might return values. • They may or might not return values to the calling functions. • Function with no arguments and no return value • Function with no arguments and with return value • Function with argument and with no return value • Function with arguments and with return value • Functions that Return Multiple Values
  • 40. Function with no arguments and no return value • In C programming, a function that does not take any arguments and does not return a value is called a void function. The syntax for defining a void function is as follows: Syntax: return_type function_name ( parameter1, parameter2, ... ) { // body of Statement ; } Example : void function_name ( ) { // body of Statement ; } • Here, the 'void' keyword is used as the return type to indicate that the function does not return any value. • A void function can be called in the same way as other functions, by simply using the function name followed by empty parentheses: • function_name ( ); • Here is an example of a void function that prints a message to the console: • This program defines a void function called add that simply prints the message "Total of a and b" to the console. • The main function calls the add function, which executes the code inside the function and prints the message. • Void functions are useful in C programming when you want to perform a specific task without returning any value, such as displaying a message, initializing a variable or updating a data structure
  • 41. Example //No Return Without Argument Function in C /* 1.Function Declaration 2.Function Definition 3.Function Calling */ #include<stdio.h> //Function Declaration void add(); int main() { //Function Calling add(); return 0; } //Function Definition void add() { int a,b,c; printf("nEnter The Value of A & B :"); scanf("%d%d",&a,&b); c=a+b; printf("nTotal : %d",c); }
  • 42. Function with no arguments and with return value • https:// www.tutorjoes.in/c_programming_tutorial/not_return_with_arg_fun ction_in_c
  • 43. Function with argument and with no return value • In C programming, a function that takes one or more arguments but does not return a value is called a void function. The syntax for defining a void function with arguments is as follows: • Syntax : return_type function_name ( data_type argument1, data_type argument2, ... ) // Function Definition { // body of Statement ; } • Here, the 'void' keyword is used as the return type to indicate that the function does not return any value. • The function_name is the name of the function, and the argument1, argument2, ... are the input parameters that the function takes. • A void function with arguments can be called by providing the values for the arguments in the function call: • function_name(value1, value2, ...); • This program is a simple C program that demonstrates how to define and call a void function in C. • The program defines a void function called add that takes two integer parameters, x and y, and adds them together. The function then prints the result of the addition. • The main function first prompts the user to enter two integers, a and b, which are then passed as arguments to the add function when it is called. • The add function uses these arguments as its x and y parameters and performs the addition. The result of the addition is then printed to the console.
  • 44. Example • //No Return With Argument Function in C • #include<stdio.h> • • //Function Declaration • void add(int,int); • • int main() • { • int a,b; • printf("nEnter The Value of A & B : ")l • scanf("%d%d",&a,&b); • //Function Calling • add(a,b); // Actual Parameters • return 0; • } • //Function Definition • void add(int x,int y) //Formal Parameters • { • int c; • c=x+y; • printf("nTotal : %d",c); • } •
  翻译: