A function is a block of code that performs a specific task. It takes input, processes it, and returns output. There are two types of functions: library functions provided by the C language, and user-defined functions created by the programmer. Functions allow programmers to divide a large program into smaller, separate, and reusable parts of code. Functions make code more organized and modular.
C programming language working with functions 1Jeevan Raj
A function is a named, independent block of code that performs a specific task. Functions allow programmers to break programs into smaller, reusable pieces of code. A function is defined with a name, parameters, a return type, and a body containing statements. Functions can return values to the code where they were called. Functions make programs more modular and organized.
This document discusses functions in C programming. It begins by explaining why programs should be divided into smaller subprograms or functions for manageability. There are two types of functions: library functions which are pre-defined and cannot be modified, and user-defined functions which are created by the user. Every C program must contain a main() function. Functions allow code reusability and modularity. Parameters are used to pass data between functions. The return statement returns data from a function. Local variables are only accessible within their own function.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Functions are self-contained blocks of code that perform specific tasks. There are library functions provided by the C standard and user-defined functions created by programmers. Functions make programs clearer and easier to debug by separating code into logical units. Functions can call themselves recursively to perform repetitive tasks. Functions are defined with a return type, name, and parameters, and code is passed between functions using call-by-value parameter passing. Function prototypes declare functions before they are used.
This document discusses user-defined functions in C++. It covers defining functions with return types and parameters, using return statements, function prototypes, and the flow of execution when a function is called. Functions help make programs more modular and understandable by breaking tasks into reusable blocks of code. Defining functions properly allows the compiler to understand how to execute function calls within a program.
Functions are blocks of code that perform specific tasks. There are two types of functions: predefined/library functions provided by C, and user-defined functions created by the programmer. Functions make programs more modular and reusable. A function definition includes the function header with its name, parameters, and return type. The function body contains the code to execute. Functions are called by their name and actual parameters are passed in. Parameters in the function header are formal parameters that receive the passed in values. Functions can return values to the calling code.
Functions allow programmers to structure code into modular, reusable units. A function contains a block of code that is executed when the function is called. Functions take parameters as input and can return a value. The example function "addition" takes two integer parameters, adds them together, and returns the result. The main function calls addition, passing it the values 5 and 3, and stores the returned value 8 in the variable z. Functions help avoid duplicating code and make programs easier to design, understand, and maintain.
This document discusses C functions. It defines a function as a block of code that performs a specific task. Functions allow for modular programming by subdividing programs into separate, reusable modules. The key elements of a function are its declaration, which informs the compiler about the function name, parameters, and return type; its definition, which contains the function body; and its call, which transfers program control to the function. Parameters act as placeholders for the arguments passed during a function call. Using functions improves code readability, reusability, testability and maintenance. Standard and user-defined functions are described along with examples.
The document discusses top-down design and functions in C programming. It defines top-down design as breaking a large problem down into smaller, more manageable parts or modules. A C program uses functions to implement top-down design, with each function representing a module. The key aspects covered include function declaration, definition, parameters, return values, and recursion. Functions are classified based on whether they return a value and if they accept parameters. Examples demonstrate different types of functions and how to write recursive functions.
The document introduces functions in C programming. It discusses defining and calling library functions and user-defined functions, passing arguments to functions, returning values from functions, and writing recursive functions. Functions allow breaking programs into modular and reusable units of code. Library functions perform common tasks like input/output and math operations. User-defined functions are created to perform specific tasks. Information is passed between functions via arguments and return values.
The document discusses functions in C++. It defines a function as a named block of code that performs some action. Functions allow code to be reused by calling the function by name. They make programs easier to modify, maintain and develop. The document describes different types of functions like user-defined and built-in functions. It also covers function declaration, definition, scope, passing parameters, and provides examples.
This document discusses functions in C language. It defines what a function is, its properties, types of functions, and how to define, declare and call functions. The key points are:
1. A function is a block of code that performs a specific task and can be called from different parts of a program.
2. Functions have a unique name, are independent units that perform tasks without interfering with other code, and can optionally return a value.
3. Functions are declared with a prototype specifying their return type, name and parameters, and defined with the actual code implementation.
The document presents information about functions in the C programming language. It discusses what a C function is, the different types of C functions including library functions and user-defined functions. It provides examples of how to declare, define, call and pass arguments to C functions. Key points covered include how functions allow dividing a large program into smaller subprograms, the ability to call functions multiple times, and how functions improve readability, debugging and reusability of code. An example program demonstrates a simple C function that calculates the square of a number.
1. A function is a block of code that performs a specific task. Functions allow programmers to split a large program into smaller sub-tasks and call them multiple times.
2. There are two main types of functions - library functions provided by the standard library, and user-defined functions created by the programmer.
3. Functions make programs easier to write, read, update and debug by splitting them into smaller, well-defined tasks.
The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().
This document discusses modular programming and functions in C programming. Modular programming involves separating a program's functionality into independent, interchangeable modules. There are advantages to this approach such as improved manageability, reusability, and collaboration between programmers.
The document then discusses functions in C programming. Functions allow programmers to divide a program into reusable modules. There are two types of functions - standard library functions defined in header files, and user-defined functions. User-defined functions have advantages like making programs easier to understand, maintain, and debug. The key parts of a user-defined function are the declaration, definition, and call. Functions can take arguments, return values, and be used recursively. Arrays and 2D arrays
The document discusses functions in C programming. It defines what a function is and explains that functions can be used to break a large program into smaller modular pieces of code that can be reused. The key points covered include: defining functions with return types, parameters, and bodies; declaring functions; calling functions by passing arguments; and passing arguments by value vs reference. Examples are provided to demonstrate creating, calling, and passing arguments to functions. Recursion is also discussed as a special case where a function calls itself.
1) A function is a block of code that performs a specific task. Functions increase code reusability and improve readability.
2) There are two types of functions - predefined library functions and user-defined functions. User-defined functions are customized functions created by the user.
3) The main() function is where program execution begins. It can call other functions, which may themselves call additional functions. This creates a hierarchical relationship between calling and called functions.
functions in c language_functions in c language.pptxMehakBhatia38
The document discusses different types of functions in C language. It explains that functions are used to group reusable code and reduce repetition. There are two main types of functions - user defined functions which are created by the programmer, and library functions which are predefined. User defined functions provide flexibility but must be declared, while library functions can be used directly after including the header file. The document also covers function definition syntax, parameters, return types, scope, and calling functions.
Functions are blocks of code that perform specific tasks. There are two types of functions: predefined/library functions provided by C, and user-defined functions created by the programmer. Functions make programs more modular and reusable. A function definition includes the function header with its name, parameters, and return type. The function body contains the code to execute. Functions are called by their name and actual parameters are passed in. Parameters in the function header are formal parameters that receive the passed in values. Functions can return values to the calling code.
Functions allow programmers to structure code into modular, reusable units. A function contains a block of code that is executed when the function is called. Functions take parameters as input and can return a value. The example function "addition" takes two integer parameters, adds them together, and returns the result. The main function calls addition, passing it the values 5 and 3, and stores the returned value 8 in the variable z. Functions help avoid duplicating code and make programs easier to design, understand, and maintain.
This document discusses C functions. It defines a function as a block of code that performs a specific task. Functions allow for modular programming by subdividing programs into separate, reusable modules. The key elements of a function are its declaration, which informs the compiler about the function name, parameters, and return type; its definition, which contains the function body; and its call, which transfers program control to the function. Parameters act as placeholders for the arguments passed during a function call. Using functions improves code readability, reusability, testability and maintenance. Standard and user-defined functions are described along with examples.
The document discusses top-down design and functions in C programming. It defines top-down design as breaking a large problem down into smaller, more manageable parts or modules. A C program uses functions to implement top-down design, with each function representing a module. The key aspects covered include function declaration, definition, parameters, return values, and recursion. Functions are classified based on whether they return a value and if they accept parameters. Examples demonstrate different types of functions and how to write recursive functions.
The document introduces functions in C programming. It discusses defining and calling library functions and user-defined functions, passing arguments to functions, returning values from functions, and writing recursive functions. Functions allow breaking programs into modular and reusable units of code. Library functions perform common tasks like input/output and math operations. User-defined functions are created to perform specific tasks. Information is passed between functions via arguments and return values.
The document discusses functions in C++. It defines a function as a named block of code that performs some action. Functions allow code to be reused by calling the function by name. They make programs easier to modify, maintain and develop. The document describes different types of functions like user-defined and built-in functions. It also covers function declaration, definition, scope, passing parameters, and provides examples.
This document discusses functions in C language. It defines what a function is, its properties, types of functions, and how to define, declare and call functions. The key points are:
1. A function is a block of code that performs a specific task and can be called from different parts of a program.
2. Functions have a unique name, are independent units that perform tasks without interfering with other code, and can optionally return a value.
3. Functions are declared with a prototype specifying their return type, name and parameters, and defined with the actual code implementation.
The document presents information about functions in the C programming language. It discusses what a C function is, the different types of C functions including library functions and user-defined functions. It provides examples of how to declare, define, call and pass arguments to C functions. Key points covered include how functions allow dividing a large program into smaller subprograms, the ability to call functions multiple times, and how functions improve readability, debugging and reusability of code. An example program demonstrates a simple C function that calculates the square of a number.
1. A function is a block of code that performs a specific task. Functions allow programmers to split a large program into smaller sub-tasks and call them multiple times.
2. There are two main types of functions - library functions provided by the standard library, and user-defined functions created by the programmer.
3. Functions make programs easier to write, read, update and debug by splitting them into smaller, well-defined tasks.
The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().
This document discusses modular programming and functions in C programming. Modular programming involves separating a program's functionality into independent, interchangeable modules. There are advantages to this approach such as improved manageability, reusability, and collaboration between programmers.
The document then discusses functions in C programming. Functions allow programmers to divide a program into reusable modules. There are two types of functions - standard library functions defined in header files, and user-defined functions. User-defined functions have advantages like making programs easier to understand, maintain, and debug. The key parts of a user-defined function are the declaration, definition, and call. Functions can take arguments, return values, and be used recursively. Arrays and 2D arrays
The document discusses functions in C programming. It defines what a function is and explains that functions can be used to break a large program into smaller modular pieces of code that can be reused. The key points covered include: defining functions with return types, parameters, and bodies; declaring functions; calling functions by passing arguments; and passing arguments by value vs reference. Examples are provided to demonstrate creating, calling, and passing arguments to functions. Recursion is also discussed as a special case where a function calls itself.
1) A function is a block of code that performs a specific task. Functions increase code reusability and improve readability.
2) There are two types of functions - predefined library functions and user-defined functions. User-defined functions are customized functions created by the user.
3) The main() function is where program execution begins. It can call other functions, which may themselves call additional functions. This creates a hierarchical relationship between calling and called functions.
functions in c language_functions in c language.pptxMehakBhatia38
The document discusses different types of functions in C language. It explains that functions are used to group reusable code and reduce repetition. There are two main types of functions - user defined functions which are created by the programmer, and library functions which are predefined. User defined functions provide flexibility but must be declared, while library functions can be used directly after including the header file. The document also covers function definition syntax, parameters, return types, scope, and calling functions.
This document summarizes a mobile application called Job4CSE that was created to help computer science graduates manage the job application process. The application allows users to search for jobs, apply to jobs, and manage interviews. It was built using the Android platform since Android has a large user base in Bangladesh. Key features of the app include searching jobs, applying to jobs, managing applications and interviews, receiving notifications about deadlines, and allowing companies to accept, reject, and schedule interviews with applicants. Screenshots demonstrate functionality for profiles, uploading resumes, viewing jobs, saving jobs, applying, and more. Future enhancements could include showing company locations on a map and automatic email notifications.
This document presents an overview of agile project management. It discusses how agile project management organizes a project into activities and aids decision making with flexible guidelines rather than rigid rules. The document also notes some benefits of agile project management, such as inherent versioning and rapid turnaround, but also potential issues like costly late-stage changes and feature creep if requirements are not properly managed.
This presentation provides an overview of the builder design pattern, including its structure and implementation in Java. The builder pattern separates object construction from representation, allowing the same construction steps to create different types of objects. The presentation defines the key components of the builder pattern - Product, Builder, Concrete Builder, and Director. It then provides a code example to illustrate these components in action, showing how a MealBuilder class can use the builder pattern to construct different meal objects.
1) Doubly linked lists contain nodes with pointers to both the previous and next nodes, allowing traversal in either direction.
2) Common operations on doubly linked lists include insertion and deletion at the beginning, end, or within the list by node value.
3) Insertion and deletion have some special cases to handle when the target node is the first, last, or only node in the list.
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
its all about Artificial Intelligence(Ai) and Machine Learning and not on advanced level you can study before the exam or can check for some information on Ai for project
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
Ad
Lecture_5_-_Functions_in_C_Detailed.pptx
1. Lecture 5 - Functions in C
CSE 1102: Structured Programming Language
Instructor Name: Salim Shadman Ankur
Date: 11 April 2025
2. Introduction to Functions
A function is a block of code that performs a specific task.
Functions promote code reuse and modular programming.
Syntax: return_type function_name(parameters) { ... }
Example: int sum(int a, int b) { return a + b; }
3. Introduction to Functions
• A function in C is a block of organized reusuable code that is performs a
single related action. Every C program has at least one function, which is
main(), and all the most trivial programs can define additional functions.
• When the algorithm of a certain problem involves long and complex logic,
it is broken into smaller, independent and reusable blocks. These small
blocks of code are known by different names in different programming
languages such as a module, a subroutine, a function or a method.
• You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
is such that each function performs a specific task.
4. Modular Programming
Functions are designed to perform a specific task that is a part of an entire process.
This approach towards software development is called modular programming.
Modular programming takes a top-down approach towards software development. The
programming solution has a main routine through which smaller independent modules
(functions) are called upon.
Each function is a separate, complete and reusable software component. When called,
a function performs a specified task and returns the control back to the calling routine,
optionally along with result of its process.
The main advantage of this approach is that the code becomes easy to follow, develop
and maintain.
5. Library Functions in C
C offers a number of library functions included in different header files. For
example, the stdio.h header file includes printf() and scanf() functions.
Similarly, the math.h header file includes a number of functions such as sin(),
pow(), sqrt() and more.
These functions perform a predefined task and can be called upon in any
program as per requirement.
However, if you don't find a suitable library function to serve your purpose,
you can define one.
6. Defining a Function in C
In C, it is necessary to provide the forward declaration of the prototype of any
function. The prototype of a library function is present in the corresponding
header file.
For a user-defined function, its prototype is present in the current program.
The definition of a function and its prototype declaration should match.
After all the statements in a function are executed, the flow of the program
returns to the calling environment. The function may return some data along
with the flow control.
7. Function Declaration & Definition
• Declaration tells the compiler about the function's name, return type, and parameters.
• Definition provides the actual body of the function.
• Declaration: int add(int, int);
• Definition: int add(int a, int b) { return a + b; }
• A function declaration tells the compiler about a function's name, return type, and
parameters.
• A function definition provides the actual body of the function.
• The C standard library provides numerous built-in functions that your program can call.
• For example, strcat() to concatenate two strings, strcpy() to copy one memory location to
another location, and many more functions.
• A function declaration is required when you define a function in one source file and you call
that function in another file. In such cases, you should declare the function at the top of the
file calling the function.
8. Parts in a Function
The general form of a function definition in C programming language is as
follows −
return_type function_name(parameter list)
{
body of the function
}
9. Parts in a Function
A function definition in C programming consists of a function header and a function body. Here are all the parts
of a function −
Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you
pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is,
a function may contain no parameters.
Function Body − The function body contains a collection of statements that defines what the function
does.
A function in C should have a return type. The type of the variable returned by the function must be the return
type of the function. In the above figure, the add() function returns an int type.
10. Example: User-defined Function in C
In this program, we have used a user-defined function called max(). This function takes two parameters num1
and num2 and returns the maximum value between the two −
#include <stdio.h>
/* function returning the max between two numbers */
int max(int num1, int num2){
/* local variable declaration */
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
11. Example: User-defined Function in C
int main(){
printf("Comparing two numbers using max() function: n");
printf("Which of the two, 75 or 57, is greater than the other? n");
printf("The answer is: %d", max(75, 57));
return 0;
}
Output:
When you runt this code, it will produce the following output −
Comparing two numbers using max() function:
Which of the two, 75 or 57, is greater than the other?
The answer is: 75
12. Calling Functions & Returning
Values
• Functions can be called from main or other functions.
• The value returned can be stored or used directly.
• Example: int result = add(10, 20);
• void functions do not return a value.
13. Calling Functions & Returning
Values
• While creating a C function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task.
• To call a function properly, you need to comply with the declaration of the function prototype. If the
function is defined to receive a set of arguments, the same number and type of arguments must be
passed.
• When a function is defined with arguments, the arguments in front of the function name are called formal
arguments. When a function is called, the arguments passed to it are the actual arguments.
• When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the main program.
14. The main() Function in C
A C program is a collection of one or more functions, but one of the functions must be named as main(),
which is the entry point of the execution of the program.
From inside the main() function, other functions are called. The main() function can call a library function
such as printf(), whose prototype is fetched from the header file (stdio.h) or any other user-defined function
present in the code.
In C, the order of definition of the program is not material. In a program, wherever there is main(), it is the
entry point irrespective of whether it is the first function or not.
The main() function in C is an entry point of any program. The program execution starts with the main()
function. It is designed to perform the main processing of the program and clean up any resources that were
allocated by the program. In a C code, there may be any number of functions, but it must have a main()
function. Irrespective of its place in the code, it is the first function to be executed.
Note: In C, any function can call any other function, any number of times. A function can call itself too. Such
a self-calling function is called a recursive function..
15. The main() Function in C
The program's execution starts from the main() function as it is an entry point of the program, it starts
executing the statements written inside it. Other functions within the source program are defined to
perform certain task. The main function can call any of these functions. When main calls another function, it
passes execution control to the function, optionally passing the requisite number and type of arguments, so
that execution begins at the first statement in the called function. The called function returns control to
main when a return statement is executed or when the end of the function is reached. Note that return
statement is implicitly present as the last statement when its return type is int.
A program usually stops executing when it returns from or reaches the end of main, although it can
terminate at other points in the program for various reasons. For example, you may want to force the
termination of your program when some error condition is detected. To do so, you can use the exit function.
16. The main() Function in C
A C program must have a main() function.
The main is not a C keyword.
It is classified as a user-defined function because its body is not pre−decided, it depends on the processing
logic of the program.
By convention, int is the return type of main(). The last statement in the function body of main() returns 0, to
indicate that the function has been successfully executed. Any non−zero return value indicates failure.
Some old C compilers let you define main() function with void return type.
However, this is considered to be non−standard and is not recommended.
As compared to other functions, the main() function:
Can't be declared as inline.
Can't be declared as static.
Can't have its address taken.
Can't be called from your program.
17. Function Arguments
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
18. Call by Value vs Call by Reference
While calling a function, there are two ways in which arguments can be passed to a function −
1) Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
2) Call by reference
This method copies the address of an argument into the formal parameter. Inside the function, the address is
used to access the actual argument used in the call. This means that changes made to the parameter affect the
argument.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter
the arguments used to call the function.
19. Call by Value vs Call by Reference
• Call by value: Copy of actual parameter is passed.
• Changes do not affect the original variable.
• Call by reference: Address is passed using pointers.
• Changes affect the original variable.
20. Call by Value
You must know the terminologies to understand how the call by value method works −
• Formal arguments − A function needs certain data to perform its desired process.
When a function is defined, it is assumed that the data values will be provided in
the form of parameter or argument list inside the parenthesis in front of the
function name. These arguments are the variables of a certain data type.
• Actual arguments − When a certain function is to be called, it should be provided
with the required number of values of the same type and in the same sequence as
used in its definition.
21. Call by Value
Take a look at the following snippet −
type function_name(type var1, type var2, ...)
Here, the argument variables are called the formal arguments. Inside the functions
scope, these variables act as its local variables.
Consider the following function −
int add(int x, int y){
int z = x + y;
return z;
}
The arguments x and y in this function definition are the formal arguments.
22. Call by Value
Example: Call by Value in C
If the add() function is called, as shown in the code below, then the variables inside the parenthesis (a and b) are the actual
arguments. They are passed to the function.
Take a look at the following example −
#include <stdio.h>
int add(int x, int y){
int z = x + y;
return z;
}
int main(){
int a = 10, b = 20;
int c = add(a, b);
printf("Addition: %d", c);
}
When you run this code, it will produce the following output −
Addition: 30
23. Call by Value
The Call by Value method implies that the values of the actual arguments are copied
in the formal argument variables. Hence, "x" takes the value of "a" and "b" is
assigned to "y". The local variable "z" inside the add() function stores the addition
value. In the main() function, the value returned by the add() function is assigned to
"c", which is printed.
Note that a variable in C language is a named location in the memory. Hence,
variables are created in the memory and each variable is assigned a random
memory address by the compiler.
Call by Value is the default function calling mechanism in C. It eliminates a functions
potential side effects, making your software simpler to maintain and easy to
understand. It is best suited for a function expected to do a certain computation on
the argument received and return the result.
24. Call by Value (Example)
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main(){
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a: %dn", a);
printf("Before swap, value of b: %dn", b);
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a: %dn", a);
printf("After swap, value of b: %dn", b);
return 0;
}
25. Call by Value (Example)
void swap(int x, int y){
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Output
When you run this code, it will produce the following output −
Before swap, value of a: 100
Before swap, value of b: 200
After swap, value of a: 100
After swap, value of b: 200
26. Call by Value (Example)
It shows that there are no changes in the values, although they had been changed inside the function.
Since the values are copied in different local variables of another function, any manipulation doesnt have
any effect on the actual argument variables in the calling function.
However, the Call by Value method is less efficient when we need to pass large objects such as an array or a
file to another function. Also, in some cases, we may need the actual arguments to be manipulated by
another function. In such cases, the Call by Value mechanism is not useful.
27. Recursion
• A function that calls itself is called a recursive function.
• Used to solve problems that can be broken down into sub-problems.
• Example: Factorial function.
• Must include base case to stop recursion.
• Recursion is the process by which a function calls itself. C language allows
writing of such functions which call itself to solve complicated problems by
breaking them down into simple and easy problems. These functions are
known as recursive functions.
28. Why Recursion is Used in C?
Recursion is used to perform complex tasks such as tree and graph structure
traversals. Popular recursive programming solutions include factorial, binary
search, tree traversal, tower of Hanoi, eight queens problem in chess, etc.
A recursive program becomes concise, it is not easily comprehendible. Even
if the size of the code may reduce, it needs more resources of the processor,
as it involves multiple IO calls to the function.
29. Factorial using Recursion
#include <stdio.h>
#include <math.h>
/* function declaration */
int factorial(int i){
if(i <= 1){
return 1;
}
return i * factorial(i - 1);
}
int main(){
int a = 5;
int f = factorial(a);
printf("a: %d n", a);
printf("Factorial of a: %d", f);
return 0;
}
Output
Run the code and check
its output −
a: 5
Factorial of a: 120
30. Fibonacci using Recursion
#include <stdio.h>
int fibonacci(int i){
if(i == 0){
return 0;
}
if(i == 1){
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main(){
int i;
for (i = 0; i < 10; i++){
printf("%dtn", fibonacci(i));
}
return 0;
}
Output
−
0
1
1
2
3
5
8
13
21
34
31. Recursion
A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in
terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive
approach provides a very concise solution to seemingly complex problems.
Syntax:
This is how a general recursive function looks like −
void recursive_function(){
recursion(); // function calls itself
}
int main(){
recursive_function();
}
While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it
will go into an infinite loop.
32. Storage Classes
C storage classes define the scope (visibility) and lifetime of variables and/or
functions within a C Program. They precede the type that they modify.
We have four different storage classes in a C program −
• auto: Default storage class for local variables.
• static: Retains value between function calls.
• extern: Refers to a global variable defined elsewhere.
• register: Stores variable in CPU register for faster access.
33. The auto Storage Classes
The auto is a default storage class for all variables that are declared inside a function or a
block. The keyword "auto", which is optional, can be used to define local variables.
The scope and lifetime of auto variables are within the same block in which they are declared.
Example of auto Storage Class
The following code statements demonstrate the declaration of an automatic (auto) variable −
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be
used within functions, i.e., local variables.
34. The register Storage Classes
The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator applied to it (as it
does not have a memory location).
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the variable
will be stored in a register. It means that it MIGHT be stored in a register depending on
hardware and implementation restrictions.
Example of register Storage Class
The following code statement demonstrates the declaration of a register variable −
{
register int miles;
}
35. The static Storage Classes
The static storage class instructs the compiler to keep a local variable in
existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope. Therefore,
making local variables static allows them to maintain their values between
function calls.
The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it is
declared.
In C programming, when static is used on a global variable, it causes only
one copy of that member to be shared by all the objects of its class.
36. The static Storage Classes
Example of static Storage Class
The following example demonstrates the use of a static storage class in a C program −
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main(){
while(count--) {
func();
}
return 0;
}
/* function definition */
void func(void) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %dn", i, count);
}
Output
When the above code is compiled
and executed, it produces the
following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
37. The extern Storage Classes
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized however, it points the
variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used
in other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another
file.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
Example of extern Storage Class
The example of an extern storage class may contain two or more files. Here is an example
demonstrating the use of an extern storage class in C language −
38. The extern Storage Classes
First File: main.c
#include <stdio.h>
int count;
extern void write_extern();
main(){
count = 5;
write_extern();
}
39. The extern Storage Classes
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("Count is %dn", count);
}
Here, extern is being used to declare count in the second file, whereas it has its definition in the first file (main.c). Now, compile these two
files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it will produce the following output −
Count is 5
40. Exercises
1) Write a function to calculate factorial of a number.
2) Create a recursive function to compute Fibonacci sequence.
3) Write a program using static variable in a function.
4) Demonstrate extern keyword with two functions.