Functions• A function is a section of a program that performs a specific task
• Solving a problem using different functions makes programming much simpler with fewer defects
Advantages of Functions (1 of 3):
• The functions can be developed by different people and can be combined together as one application
• Easy to code and debug
• Functions support reusability. That is, once a function is written it can be called from any other module without having to rewrite the same. This saves time in rewriting the same code
Classification of Functions
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other
user-defined function
Classification of Functions:
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other user-defined function
Elements of a Function
�� Function Declaration or Function Prototype :
− The function should be declared prior to its usage
�� Function Definition :
− Implementing the function or writing the task of the function
− Consists of
• Function Header
• Function Body
�� Function Invocation or Function call:
− To utilize a function’s service, the function have to be invoked (called)
Declaring Function Prototypes (1 of 2)
• A function prototype is the information to the compiler regarding the userdefined function name, the data type and the number of values to be passed to the function and the return data type from the function
• This is required because the user-defined function is written towards the end of the program and the ‘main’ does not have any information regarding these functions
• The function prototypes are generally written before ‘main’. A function prototype should end with a semicolon
Declaring Function Prototypes (2 of 2)
• Function Prototypes declare ONLY the signature of the function before actually defining the function
• Here signature includes function name, return type, list of parameter data types and optional names of formal parameters
• Syntax:Return_data_type FunctionName ( data_type arg1,
data_type arg2,...,data_type argn );
• Example:
int iValidate_Date(int iDay,int iMonth, int iYear);
Writing User-Defined Functions
• A function header and body looks like this:
Return-data-type function-name(data-type argument-1, data-type argument-2,….)
{
Local variable declarations;
/* Write the body of the function here */
Statement(s);
return (expression);
}
• The return data type can be any valid data type in C
• If a function does not return anything then the void is the return type
• A function header does not end with a semicolon
• The return statement is optional. It is required only when a value has to be returned
Writing User-Defined Functions
void fnDisplayPattern(unsigned int iCount)
{
unsigned int iLoopIndex;
for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {
printf(“*”);
}
/* return is optional */
return;
}
Writing User-Defined Functions
int fnAdd(int iNumber1, int iNumber2)
{
/* Return the result */Can also be written as return (iNumber1 + iNumber2);
}
/* Function to display “Infosys Technologies Ltd.” */
void fnCompanyNameDisplay()
{
printf(“Infosys Technologies Ltd.”);
}
Returning values
• The result of the function can be given back to the calling functions
• Return statement is used to return a value to the calling function
• Syntax:
return (expression) ;
• Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * i);
Calling User-Defined Functions
• A function is called by giving its name and passing the required arguments
• The constants can be sent as arguments to functions
/* Function is called here */
iResult = fnAdd(10, 15);
• The variables can also be sent as arguments to functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
• Calling a function which does not return any value
/* Calling a function */
fnDisplayPattern(15);
• Calling a function that do not take any arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Formal and Actual Parameters
• The variables declared in the function header are called as formal parameters
• The variables or constants that are passed in the function call are called as actual parameters
• The formal parameter names and actual parameters names can be the same or different
Example – Finding the sum of two numbers using functions ( No parameter passing and no return)
#include< stdio.h >
void fnSum();
int main( int argc, char **argv ) {
fnSum();
return 0;
}
void fnSum() {
int iNum1,iNum2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNum1,&iNum2);
iSum = iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions ( parameter passing )
#include< stdio.h >
void fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ) {
int iNumber1,iNumber2;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
fnSum(iNumber1,iNumber2);
return 0;
}
void fnSum(int iNum1,int iNum2){
int iSum;
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions (parameter passing and returning value)
#include< stdio.h >
int fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ){
int iNumber1,iNumber2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
iSum = fnSum(iNumber1,iNumber2);
printf("\nThe sum is %d\n",iSum);
return 0;
}
int fnSum(int iNum1,int iNum2){
int iTempSum;
iTempSum=iNum1 + iNum2;
return iTempSum;
}
File test.c:
int fnSum (int iNum1, int iNum2);
int main(int argc,char ** argv ){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fndiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c:
int fnSum (int iNumc1, int iNumc2) {
return(iNumc1+iNumc2);
}
The above program gives a compilation error because fndiff is not declared
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNumc1, int iNumc2){
return(iNumc1 + iNumc2);
}
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
#include <stdio.h>
int main(int argc, char ** argv){
int iTemp;
i_Temp=10;
}
int fnSum(int iNumc1, int iNumc2){
return (iNumc1+iNumc2);
}
Example Three
The above programs will give a linker error because there are multiple main functions
Example Four
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iNum1,iNum2;
int iResult;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fnDiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int icNum1,int icNum2) {
return(icNum1+icNum2);
}
The above program gives linker error as the definition of the fnDiif function is not available
Example Five
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1, int iNum2);
int main(int argc, char ** argv){
int iResult;
int iVar1,iVar2;
scanf(“%d%d”,&iVar1,&iVar2);
iResult = fnSum(iVar1,iVar2);
printf(“%d”, iResult);
iResult = fnDiff(iVar1,iVar2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNum1, int iNum2) {
return (iNum1 + iNum2);
}
int fnDiff (int iNumc1, int iNumc2){
return (iNumc1-iNumc2);
}
Program compiles and links successfully
Function Calls and Stack
• A stack is a Last In First Out (LIFO) arrangement of memory in which the item that is added last is the one to be removed first
• Items are added and removed only at one end called as top of the stack
• Inserting an item in to the stack is called as PUSH and removing an item from the stack is called as POP
Local Variables:
• The variables that are declared inside a function are called as local variables
• Their scope is only within the function in which they are declared
• These variables cannot be accessed outside the function
• Local variables exist only till the function terminates its execution
• The initial values of local variables are garbage values
#include <stdio.h>
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
int Number1, iNumber2;
printf("Enter the first number ");
scanf("%d",&iNumber1);
printf("Enter the second number ");
scanf("%d",&iNumber2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = iNumber1 + iNumber2; /* Find the sum */
printf("The sum is %d",iResult);
}
Global Variables:
• The variables that are declared outside all the functions (above ‘main’ ) are called as global variables
• These variables can be accessed by all the functions
• The global variables exist for the entire life-cycle of the program
• The global variables are by default initialized to zero
• Coding Standard:
– Each global variable should start with the alphabet ‘g’
– Example:
int giValue;
float gfSalary;
Global Variables
#include <stdio.h>
/* Global varaibles are declared here */
int giValue1, giValue2;
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
printf("Enter the first number ");
scanf("%d",&giValue1);
printf("Enter the second number ");
scanf("%d",&giValue2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = giValue1 + giValue2; /* Find the sum */
printf("\nThe sum is %d\n",iResult);
Disadvantages of Global Variables:
• Lifetime of global variables is throughout the program.
– Hence usage of global variables leads to wastage of memory
• Scope of the global variable is throughout the program.
– Hence more than one function can modify the value of the global variable. This makes debugging difficult.
What is the output of the following code snippet?
int giGlobal ;
int main(int argc, char **argv) {
int iLocal;
printf(“ Value of Local = %d \n, Value of Global = %d”, iLocal, giGlobal);
}
The output is:
Value of Local = <some garbage value>
Value of Global = 0
Program stack and heap
• During execution of a program, the storage of program and data is as follows:
– The executable code is stored into the code /Text segment
– The global variables are stored into data segment
– The heap memory is used for dynamic memory allocation
– The local variables are stored into the stack
• Heap: A section of memory within the user job area that provides a capabilityfor dynamic allocation.
Parameter Passing Techniques
• When a function is called and if the function accepts some parameters, then there are two ways by which the function can receive parameters
– Pass by value
– Pass by reference
Pass by Value
• When parameters are passed from the called function to a calling function, the value of the actual argument is copied onto the formal argument
• Since the actual parameters and formal parameters are stored in different memory locations, the changes in formal parameters do not alter the values of actual parameters
Pass by Value
#include<stdio.h>
void fnUpdateValues (int, int); /* function prototype */
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
fnUpdateValues(iValue1, iValue2); /* Call the function */
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return 0 to the operating system */
}
void fnUpdateValues(int iNumber1, int iNumber2)
{
iNumber1 = iNumber1 + 15; /* Update the values */
iNumber2 = iNumber2 - 10;
}
Pass By Reference
#include<stdio.h>
void fnUpdateValues(int *, int *); /* Function prototype */
int main(int argc, char **argv)
{
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return success code to the operating system */
}
void fnUpdateValues(int *piNumber1, int *piNumber2)
{
*piNumber1 = *piNumber1 + 15; /* Update the values */
*piNumber2 = *piNumber2 - 10;
}
Passing array elements to a function – Pass by value
• There are two ways to pass array elements to a function.
– Pass by Value
– Pass by Reference
/* Demo of Pass by Value */
void fnDisplay(int iMarks);
int main(int argc, char **argv) {
int iIndex;
int aiMarks[] = {55,65};
for(iIndex=0;iIndex<=1;iIndex++) {
fnDisplay( aiMarks[iIndex] );
}
return 0;
}
void fnDisplay ( int iMarks) {
printf( “%d” , iMarks);
}
Passing arrays to a function-Pass by reference
• Arrays are always passed by reference.
• While passing arrays to a function, base address of 0th element gets passed.
• Any changes made to the array by the called function are reflected back into the original array in calling function.
Ex: void fnFindSq (int []); /* Function prototype*/
int main(int argc, char **argv) {
int iIndex;
int aiNum[] = {5,6,10};
fnFindSq( aiNum , 3 ); /* Function Call */
return 0;
}
void fnFindSq ( int aiSqNum[], int iMax) {
int iCnt;
for(iCnt = 0; iCnt < iMax; iCnt++)
aiSqNum[iCnt] = aiSqNum[iCnt] * aiSqNum[iCnt];
}
Summary
• The section of a program that performs a specific task is called as a function
• Advantages of functions
– Reusability
– Modularity
– Easy to code and debug
– Reduced application development time
• To Identify the functions, identify the sub problems to be solved
• Function prototypes should be exactly same as the function header
• The variables declared in the function header are called as formal parameters
• The variables and the constants that are passed in the function call are called as actual parameters
• Scope of variables: The portion of the program where the variables can be accessed
– Local variables: The variables that are declared inside a function
– Global variables: The variables that are declared outside all the functions
• Parameter passing techniques
– Pass by value: The actual values are passed to the function
– Pass by reference: The address of the variables are passed to the function
• When arrays are passed as arguments to the function they are passed by reference
Recursive Functions
• When a function calls itself it is called as Recursion
• Many mathematical, searching and sorting algorithms, can be simply expressed in terms of a recursive definition
• A recursive definition has two parts:
Base condition : When a function will terminate
Recursive condition :The invocation of a recursive call to the function
• When the problem is solved through recursion the source code looks elegant
/* Finding the factorial of an integer using a
recursive function */
int fnFact(int iNumber); /* Function Prototype */
int main(int argc, char **argv) {
int iFactorial;
iFactorial=fnFact(4);
printf("The factorial is %d\n\n",iFactorial);
return 0;
}
int fnFact(int iNumber)
{
int iFact;
if (iNumber <= 1) {
return 1;
}
else {
iFact = iNumber * fnFact(iNumber - 1);
}
return iFact;
}
• Find the output of the following code snippet when the function is called as
fnReverse(5);
void fnReverse(int iValue)
{
if (iValue > 0) {
fnReverse(iValue-1);
}
printf("%d\t",iValue);
}
Output will be 0 1 2 3 4 5
• Find the output of the following code snippet when the function is called as
fnReverse();
int giValue = 5; /* Global Variable Declaration */
void fnReverse()
{
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}
Output: prints 0 six times
• Find the output of the following code snippet when the function is called as
fnReverse();
char gacString[] = "Test";
int giIndex = 0;
void fnReverse()
{
if (gacString[giIndex] != '\0') {
giIndex++;
fnReverse();
}
giIndex--;
if (giIndex >= 0)
{
printf("%c",gacString[giIndex]);
}
}
Output: Prints the string “tseT”
.............................................................................
Linked Lists • A linked list is a versatile data structure used to hold a collection of data
• A linked list essentially consists of nodes
• Each node comprises of data and a pointer (link) to the next node in the list
• The pointer in each node points to the next element in the linked list
• The last element in the linked list will point to NULL indicating the end of the linked list
• The linked list shown in below is a singly linked list
• This kind of linked list allows only uni-directional traversal from the first node to the last node in the list
• The first element of the linked list is called as the ‘head’ and the last element is called as ‘tail’
• The advantage of a linked list is that insertion and deletion is easier in contrast to an array where insertion and deletion requires the elements of the array to be moved down or moved up which require considerable amount of time
• Insertion of a new node in a linked list requires setting of two pointers
• The node, after which the new node has to be inserted, must be made to point to the new node
• The new node inserted must be set to point to the next node to complete the chain
• Deleting a node requires simply changing the pointer to point to the node next to the deleted node
• Linked list allows only sequential access. That is to search for the third node the traversal starts from the first node, then the second node and last the third node
• An array allows random access. That is any element can be accessed by supplying its index
Structures :
• Data used in real life is complex
• The primitive data types which are provided by all programming languages are not adequate enough to handle the complexities of real life data
• Examples:
Date: A date is a combination of day of month, month and year
Address: Address of a person can consist of name, plot number, street, city, pin (zip) code and state.
Account Details: Bank account information can contain the account number, customer ID and Balance
• A structure is a set of interrelated data
• A structure (also known as data structure or struct in short) in C, is a set of primitive data types which are related to business and are grouped together to form a new data type
• A structure is a mechanism provided by the language to create custom and complex data types
Declaring a Structure :
• In C, a structure can be declared using the ‘struct’ keyword
• The set of variables that form the structure must be declared with a valid name similar to declaring variables
• Each variable inside a structure can be of different data type
• Syntax:
struct tag-name
{
data-type member-1;
data-type member-2;
……
data-type member-n;
};
• A structure declaration ends with a semicolon
• Example:
Date is a simple data structure, but not available as a built-in data type in C
A date has three components:
– day of month (integer, Range: 1-31)
– month (integer, Range: 1-12)
– year (integer, four digits)
struct date {
short iDay;
short iMonth;
short iYear;
};
• Each variable declared inside a structure is known as a ‘member’ variable
• In the date structure, iDay, iMonth and iYear are member variables
• A structure is generally declared globally above function ‘main’
• The member variables cannot be initialized within a structure
• The structure is allocated memory only after declaring a variable of type Structure
Accessing Member Variables of a Structure
• Each member variable in a structure can be accessed individually
• Once a structure is declared, it can be used just like any primitive data type
• Inorder to access the structure members, a variable of structure should be created
• Example:
struct date sToday;
• To access individual members of the structure, the ‘.’ operator is used
• Example:
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
int main (int argc, char** argv) {
/* Declare two instances of date structure */
struct date sToday, sTomorrow;
/* Set 'day', 'month' and 'year' in instance sToday */
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
/* Set sTomorrow's values */
sTomorrow.iDay = 1;
sTomorrow.iMonth = 7;
sTomorrow.iYear = 2005;
/* Print the contents of structure */
printf ("Today's date is: %d-%d-%d\n", sToday.iDay, sToday.iMonth, sToday.iYear);
printf ("Tomorrow's date is: %d-%d-%d\n", sTomorrow.iDay, sTomorrow.iMonth, sTomorrow.iYear);
}
typedef Keyword :
• C allows one type of data to be renamed with a different name using the ‘typedef’ keyword (typedef is a short form of ‘define type’)
• A struct date had to be instantiated by using:
/* Create an instance of date structure */
struct date today;
• Alternately, typedef can be used to create the date structure
• It is a good practice while defining the structure and doing a typedef to keep the tag name same as the structure’s name with an underscore (‘_’) prefix
• Example:
/* Declare the structure date */
struct _date {
short iDay;
short iMonth;
short iYear;
};
/* Define the structure ‘_date’ as a new data type ‘date’ */
typedef struct _date date;
/* Create an instance of date structure */
date today;
Coding Standards and Best Practices for Structures
• Each structure should have a small header on the similar lines of a function header
/********************************************************************
* Structure: <structure name>
* Description: <brief description of its use
*
* Member Variables:
* <variable name> - <description of the variable>
* <variable name> - <description of the variable>
* ... ...
*********************************************************************/
• The name of the structure should all be in lowercase
• Examples: date, address, accountdetails
• The names of structure instance variables should have a prefix of ‘s’
Structures in Memory
• A structure instance occupies memory space
• The amount of memory occupied by a structure is the sum of sizes of all member variables
• The members of a structure are stored in contiguous locations
typedef struct _accountdetails {
int iAccountNumber;
char cAccountType;
char acCustomerName[10];
date sOpenDate;
double dBalance;
} accountdetails;
/* Declare an instance of accountdetails */
accountdetails sAccount;
Structure within a Structure (2 of 3)
sAccount.iAccountNumber = 702984;
sAccount.cAccountType = 'S';
sAccount.dBalance = 5000.0;
/* Populating the date sturucture within the accountdetails structure */
sAccount.sOpenDate.iDay = 1;
sAccount.sOpenDate.iMonth = 6;
sAccount.sOpenDate.iYear = 2005;
Structure within a Structure (3 of 3)
Accessing Member Variables using Pointer
• Example:
date psToday;
psToday->iDay = 30;
psToday->iMonth = 6;
psToday->iYear = 2005;
Passing Structures to Functions
• Like built in data types in C, structures can also be passed by value or by reference to functions
• When it is passed by value, the structure can be returned if the structure
members are updated
Passing Structures to Functions (2 of 3)
date fnInitialize(date sTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
sToday = fnInitializeDate(sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
date fnInitialize(date sTemp)
{
sTemp.iDay = 30;
sTemp.iMonth = 6;
sTemp.iYear = 2005;
return(sTemp);
}
• The above example is passing structure using pass by value
Passing Structures to Functions (3 of 3)
void fnInitialize(date *psTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
fnInitializeDate(&sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
void fnInitialize(date *psTemp)
{
psTemp->iDay = 30;
psTemp->iMonth = 6;
psTemp->iYear = 2005;
}
• The above example is passing structure using pass by reference
Reading Structure Members
int main (int argc, char** argv) {
date sToday;
printf(“Enter Today’s Date in format day month year”);
scanf(“%d %d %d”,&sToday.iDay, &sToday.iMonth, sToday.iYear);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
• Solving a problem using different functions makes programming much simpler with fewer defects
Advantages of Functions (1 of 3):
• The functions can be developed by different people and can be combined together as one application
• Easy to code and debug
• Functions support reusability. That is, once a function is written it can be called from any other module without having to rewrite the same. This saves time in rewriting the same code
Classification of Functions
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other
user-defined function
Classification of Functions:
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other user-defined function
Elements of a Function
�� Function Declaration or Function Prototype :
− The function should be declared prior to its usage
�� Function Definition :
− Implementing the function or writing the task of the function
− Consists of
• Function Header
• Function Body
�� Function Invocation or Function call:
− To utilize a function’s service, the function have to be invoked (called)
Declaring Function Prototypes (1 of 2)
• A function prototype is the information to the compiler regarding the userdefined function name, the data type and the number of values to be passed to the function and the return data type from the function
• This is required because the user-defined function is written towards the end of the program and the ‘main’ does not have any information regarding these functions
• The function prototypes are generally written before ‘main’. A function prototype should end with a semicolon
Declaring Function Prototypes (2 of 2)
• Function Prototypes declare ONLY the signature of the function before actually defining the function
• Here signature includes function name, return type, list of parameter data types and optional names of formal parameters
• Syntax:Return_data_type FunctionName ( data_type arg1,
data_type arg2,...,data_type argn );
• Example:
int iValidate_Date(int iDay,int iMonth, int iYear);
Writing User-Defined Functions
• A function header and body looks like this:
Return-data-type function-name(data-type argument-1, data-type argument-2,….)
{
Local variable declarations;
/* Write the body of the function here */
Statement(s);
return (expression);
}
• The return data type can be any valid data type in C
• If a function does not return anything then the void is the return type
• A function header does not end with a semicolon
• The return statement is optional. It is required only when a value has to be returned
Writing User-Defined Functions
void fnDisplayPattern(unsigned int iCount)
{
unsigned int iLoopIndex;
for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {
printf(“*”);
}
/* return is optional */
return;
}
Writing User-Defined Functions
int fnAdd(int iNumber1, int iNumber2)
{
/* Return the result */Can also be written as return (iNumber1 + iNumber2);
}
/* Function to display “Infosys Technologies Ltd.” */
void fnCompanyNameDisplay()
{
printf(“Infosys Technologies Ltd.”);
}
Returning values
• The result of the function can be given back to the calling functions
• Return statement is used to return a value to the calling function
• Syntax:
return (expression) ;
• Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * i);
Calling User-Defined Functions
• A function is called by giving its name and passing the required arguments
• The constants can be sent as arguments to functions
/* Function is called here */
iResult = fnAdd(10, 15);
• The variables can also be sent as arguments to functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
• Calling a function which does not return any value
/* Calling a function */
fnDisplayPattern(15);
• Calling a function that do not take any arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Formal and Actual Parameters
• The variables declared in the function header are called as formal parameters
• The variables or constants that are passed in the function call are called as actual parameters
• The formal parameter names and actual parameters names can be the same or different
Example – Finding the sum of two numbers using functions ( No parameter passing and no return)
#include< stdio.h >
void fnSum();
int main( int argc, char **argv ) {
fnSum();
return 0;
}
void fnSum() {
int iNum1,iNum2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNum1,&iNum2);
iSum = iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions ( parameter passing )
#include< stdio.h >
void fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ) {
int iNumber1,iNumber2;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
fnSum(iNumber1,iNumber2);
return 0;
}
void fnSum(int iNum1,int iNum2){
int iSum;
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions (parameter passing and returning value)
#include< stdio.h >
int fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ){
int iNumber1,iNumber2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
iSum = fnSum(iNumber1,iNumber2);
printf("\nThe sum is %d\n",iSum);
return 0;
}
int fnSum(int iNum1,int iNum2){
int iTempSum;
iTempSum=iNum1 + iNum2;
return iTempSum;
}
File test.c:
int fnSum (int iNum1, int iNum2);
int main(int argc,char ** argv ){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fndiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c:
int fnSum (int iNumc1, int iNumc2) {
return(iNumc1+iNumc2);
}
The above program gives a compilation error because fndiff is not declared
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNumc1, int iNumc2){
return(iNumc1 + iNumc2);
}
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
#include <stdio.h>
int main(int argc, char ** argv){
int iTemp;
i_Temp=10;
}
int fnSum(int iNumc1, int iNumc2){
return (iNumc1+iNumc2);
}
Example Three
The above programs will give a linker error because there are multiple main functions
Example Four
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iNum1,iNum2;
int iResult;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fnDiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int icNum1,int icNum2) {
return(icNum1+icNum2);
}
The above program gives linker error as the definition of the fnDiif function is not available
Example Five
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1, int iNum2);
int main(int argc, char ** argv){
int iResult;
int iVar1,iVar2;
scanf(“%d%d”,&iVar1,&iVar2);
iResult = fnSum(iVar1,iVar2);
printf(“%d”, iResult);
iResult = fnDiff(iVar1,iVar2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNum1, int iNum2) {
return (iNum1 + iNum2);
}
int fnDiff (int iNumc1, int iNumc2){
return (iNumc1-iNumc2);
}
Program compiles and links successfully
Function Calls and Stack
• A stack is a Last In First Out (LIFO) arrangement of memory in which the item that is added last is the one to be removed first
• Items are added and removed only at one end called as top of the stack
• Inserting an item in to the stack is called as PUSH and removing an item from the stack is called as POP
Local Variables:
• The variables that are declared inside a function are called as local variables
• Their scope is only within the function in which they are declared
• These variables cannot be accessed outside the function
• Local variables exist only till the function terminates its execution
• The initial values of local variables are garbage values
#include <stdio.h>
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
int Number1, iNumber2;
printf("Enter the first number ");
scanf("%d",&iNumber1);
printf("Enter the second number ");
scanf("%d",&iNumber2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = iNumber1 + iNumber2; /* Find the sum */
printf("The sum is %d",iResult);
}
Global Variables:
• The variables that are declared outside all the functions (above ‘main’ ) are called as global variables
• These variables can be accessed by all the functions
• The global variables exist for the entire life-cycle of the program
• The global variables are by default initialized to zero
• Coding Standard:
– Each global variable should start with the alphabet ‘g’
– Example:
int giValue;
float gfSalary;
Global Variables
#include <stdio.h>
/* Global varaibles are declared here */
int giValue1, giValue2;
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
printf("Enter the first number ");
scanf("%d",&giValue1);
printf("Enter the second number ");
scanf("%d",&giValue2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = giValue1 + giValue2; /* Find the sum */
printf("\nThe sum is %d\n",iResult);
Disadvantages of Global Variables:
• Lifetime of global variables is throughout the program.
– Hence usage of global variables leads to wastage of memory
• Scope of the global variable is throughout the program.
– Hence more than one function can modify the value of the global variable. This makes debugging difficult.
What is the output of the following code snippet?
int giGlobal ;
int main(int argc, char **argv) {
int iLocal;
printf(“ Value of Local = %d \n, Value of Global = %d”, iLocal, giGlobal);
}
The output is:
Value of Local = <some garbage value>
Value of Global = 0
Program stack and heap
• During execution of a program, the storage of program and data is as follows:
– The executable code is stored into the code /Text segment
– The global variables are stored into data segment
– The heap memory is used for dynamic memory allocation
– The local variables are stored into the stack
• Heap: A section of memory within the user job area that provides a capabilityfor dynamic allocation.
Parameter Passing Techniques
• When a function is called and if the function accepts some parameters, then there are two ways by which the function can receive parameters
– Pass by value
– Pass by reference
Pass by Value
• When parameters are passed from the called function to a calling function, the value of the actual argument is copied onto the formal argument
• Since the actual parameters and formal parameters are stored in different memory locations, the changes in formal parameters do not alter the values of actual parameters
Pass by Value
#include<stdio.h>
void fnUpdateValues (int, int); /* function prototype */
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
fnUpdateValues(iValue1, iValue2); /* Call the function */
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return 0 to the operating system */
}
void fnUpdateValues(int iNumber1, int iNumber2)
{
iNumber1 = iNumber1 + 15; /* Update the values */
iNumber2 = iNumber2 - 10;
}
Pass By Reference
#include<stdio.h>
void fnUpdateValues(int *, int *); /* Function prototype */
int main(int argc, char **argv)
{
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return success code to the operating system */
}
void fnUpdateValues(int *piNumber1, int *piNumber2)
{
*piNumber1 = *piNumber1 + 15; /* Update the values */
*piNumber2 = *piNumber2 - 10;
}
Passing array elements to a function – Pass by value
• There are two ways to pass array elements to a function.
– Pass by Value
– Pass by Reference
/* Demo of Pass by Value */
void fnDisplay(int iMarks);
int main(int argc, char **argv) {
int iIndex;
int aiMarks[] = {55,65};
for(iIndex=0;iIndex<=1;iIndex++) {
fnDisplay( aiMarks[iIndex] );
}
return 0;
}
void fnDisplay ( int iMarks) {
printf( “%d” , iMarks);
}
Passing arrays to a function-Pass by reference
• Arrays are always passed by reference.
• While passing arrays to a function, base address of 0th element gets passed.
• Any changes made to the array by the called function are reflected back into the original array in calling function.
Ex: void fnFindSq (int []); /* Function prototype*/
int main(int argc, char **argv) {
int iIndex;
int aiNum[] = {5,6,10};
fnFindSq( aiNum , 3 ); /* Function Call */
return 0;
}
void fnFindSq ( int aiSqNum[], int iMax) {
int iCnt;
for(iCnt = 0; iCnt < iMax; iCnt++)
aiSqNum[iCnt] = aiSqNum[iCnt] * aiSqNum[iCnt];
}
Summary
• The section of a program that performs a specific task is called as a function
• Advantages of functions
– Reusability
– Modularity
– Easy to code and debug
– Reduced application development time
• To Identify the functions, identify the sub problems to be solved
• Function prototypes should be exactly same as the function header
• The variables declared in the function header are called as formal parameters
• The variables and the constants that are passed in the function call are called as actual parameters
• Scope of variables: The portion of the program where the variables can be accessed
– Local variables: The variables that are declared inside a function
– Global variables: The variables that are declared outside all the functions
• Parameter passing techniques
– Pass by value: The actual values are passed to the function
– Pass by reference: The address of the variables are passed to the function
• When arrays are passed as arguments to the function they are passed by reference
Recursive Functions
• When a function calls itself it is called as Recursion
• Many mathematical, searching and sorting algorithms, can be simply expressed in terms of a recursive definition
• A recursive definition has two parts:
Base condition : When a function will terminate
Recursive condition :The invocation of a recursive call to the function
• When the problem is solved through recursion the source code looks elegant
/* Finding the factorial of an integer using a
recursive function */
int fnFact(int iNumber); /* Function Prototype */
int main(int argc, char **argv) {
int iFactorial;
iFactorial=fnFact(4);
printf("The factorial is %d\n\n",iFactorial);
return 0;
}
int fnFact(int iNumber)
{
int iFact;
if (iNumber <= 1) {
return 1;
}
else {
iFact = iNumber * fnFact(iNumber - 1);
}
return iFact;
}
• Find the output of the following code snippet when the function is called as
fnReverse(5);
void fnReverse(int iValue)
{
if (iValue > 0) {
fnReverse(iValue-1);
}
printf("%d\t",iValue);
}
Output will be 0 1 2 3 4 5
• Find the output of the following code snippet when the function is called as
fnReverse();
int giValue = 5; /* Global Variable Declaration */
void fnReverse()
{
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}
Output: prints 0 six times
• Find the output of the following code snippet when the function is called as
fnReverse();
char gacString[] = "Test";
int giIndex = 0;
void fnReverse()
{
if (gacString[giIndex] != '\0') {
giIndex++;
fnReverse();
}
giIndex--;
if (giIndex >= 0)
{
printf("%c",gacString[giIndex]);
}
}
Output: Prints the string “tseT”
.............................................................................
Linked Lists • A linked list is a versatile data structure used to hold a collection of data
• A linked list essentially consists of nodes
• Each node comprises of data and a pointer (link) to the next node in the list
• The pointer in each node points to the next element in the linked list
• The last element in the linked list will point to NULL indicating the end of the linked list
• The linked list shown in below is a singly linked list
• This kind of linked list allows only uni-directional traversal from the first node to the last node in the list
• The first element of the linked list is called as the ‘head’ and the last element is called as ‘tail’
• The advantage of a linked list is that insertion and deletion is easier in contrast to an array where insertion and deletion requires the elements of the array to be moved down or moved up which require considerable amount of time
• Insertion of a new node in a linked list requires setting of two pointers
• The node, after which the new node has to be inserted, must be made to point to the new node
• The new node inserted must be set to point to the next node to complete the chain
• Deleting a node requires simply changing the pointer to point to the node next to the deleted node
• Linked list allows only sequential access. That is to search for the third node the traversal starts from the first node, then the second node and last the third node
• An array allows random access. That is any element can be accessed by supplying its index
Structures :
• Data used in real life is complex
• The primitive data types which are provided by all programming languages are not adequate enough to handle the complexities of real life data
• Examples:
Date: A date is a combination of day of month, month and year
Address: Address of a person can consist of name, plot number, street, city, pin (zip) code and state.
Account Details: Bank account information can contain the account number, customer ID and Balance
• A structure is a set of interrelated data
• A structure (also known as data structure or struct in short) in C, is a set of primitive data types which are related to business and are grouped together to form a new data type
• A structure is a mechanism provided by the language to create custom and complex data types
Declaring a Structure :
• In C, a structure can be declared using the ‘struct’ keyword
• The set of variables that form the structure must be declared with a valid name similar to declaring variables
• Each variable inside a structure can be of different data type
• Syntax:
struct tag-name
{
data-type member-1;
data-type member-2;
……
data-type member-n;
};
• A structure declaration ends with a semicolon
• Example:
Date is a simple data structure, but not available as a built-in data type in C
A date has three components:
– day of month (integer, Range: 1-31)
– month (integer, Range: 1-12)
– year (integer, four digits)
struct date {
short iDay;
short iMonth;
short iYear;
};
• Each variable declared inside a structure is known as a ‘member’ variable
• In the date structure, iDay, iMonth and iYear are member variables
• A structure is generally declared globally above function ‘main’
• The member variables cannot be initialized within a structure
• The structure is allocated memory only after declaring a variable of type Structure
Accessing Member Variables of a Structure
• Each member variable in a structure can be accessed individually
• Once a structure is declared, it can be used just like any primitive data type
• Inorder to access the structure members, a variable of structure should be created
• Example:
struct date sToday;
• To access individual members of the structure, the ‘.’ operator is used
• Example:
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
int main (int argc, char** argv) {
/* Declare two instances of date structure */
struct date sToday, sTomorrow;
/* Set 'day', 'month' and 'year' in instance sToday */
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
/* Set sTomorrow's values */
sTomorrow.iDay = 1;
sTomorrow.iMonth = 7;
sTomorrow.iYear = 2005;
/* Print the contents of structure */
printf ("Today's date is: %d-%d-%d\n", sToday.iDay, sToday.iMonth, sToday.iYear);
printf ("Tomorrow's date is: %d-%d-%d\n", sTomorrow.iDay, sTomorrow.iMonth, sTomorrow.iYear);
}
typedef Keyword :
• C allows one type of data to be renamed with a different name using the ‘typedef’ keyword (typedef is a short form of ‘define type’)
• A struct date had to be instantiated by using:
/* Create an instance of date structure */
struct date today;
• Alternately, typedef can be used to create the date structure
• It is a good practice while defining the structure and doing a typedef to keep the tag name same as the structure’s name with an underscore (‘_’) prefix
• Example:
/* Declare the structure date */
struct _date {
short iDay;
short iMonth;
short iYear;
};
/* Define the structure ‘_date’ as a new data type ‘date’ */
typedef struct _date date;
/* Create an instance of date structure */
date today;
Coding Standards and Best Practices for Structures
• Each structure should have a small header on the similar lines of a function header
/********************************************************************
* Structure: <structure name>
* Description: <brief description of its use
*
* Member Variables:
* <variable name> - <description of the variable>
* <variable name> - <description of the variable>
* ... ...
*********************************************************************/
• The name of the structure should all be in lowercase
• Examples: date, address, accountdetails
• The names of structure instance variables should have a prefix of ‘s’
Structures in Memory
• A structure instance occupies memory space
• The amount of memory occupied by a structure is the sum of sizes of all member variables
• The members of a structure are stored in contiguous locations
typedef struct _accountdetails {
int iAccountNumber;
char cAccountType;
char acCustomerName[10];
date sOpenDate;
double dBalance;
} accountdetails;
/* Declare an instance of accountdetails */
accountdetails sAccount;
Structure within a Structure (2 of 3)
sAccount.iAccountNumber = 702984;
sAccount.cAccountType = 'S';
sAccount.dBalance = 5000.0;
/* Populating the date sturucture within the accountdetails structure */
sAccount.sOpenDate.iDay = 1;
sAccount.sOpenDate.iMonth = 6;
sAccount.sOpenDate.iYear = 2005;
Structure within a Structure (3 of 3)
Accessing Member Variables using Pointer
• Example:
date psToday;
psToday->iDay = 30;
psToday->iMonth = 6;
psToday->iYear = 2005;
Passing Structures to Functions
• Like built in data types in C, structures can also be passed by value or by reference to functions
• When it is passed by value, the structure can be returned if the structure
members are updated
Passing Structures to Functions (2 of 3)
date fnInitialize(date sTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
sToday = fnInitializeDate(sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
date fnInitialize(date sTemp)
{
sTemp.iDay = 30;
sTemp.iMonth = 6;
sTemp.iYear = 2005;
return(sTemp);
}
• The above example is passing structure using pass by value
Passing Structures to Functions (3 of 3)
void fnInitialize(date *psTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
fnInitializeDate(&sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
void fnInitialize(date *psTemp)
{
psTemp->iDay = 30;
psTemp->iMonth = 6;
psTemp->iYear = 2005;
}
• The above example is passing structure using pass by reference
Reading Structure Members
int main (int argc, char** argv) {
date sToday;
printf(“Enter Today’s Date in format day month year”);
scanf(“%d %d %d”,&sToday.iDay, &sToday.iMonth, sToday.iYear);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}