UNIT2 Functions Objectives To understand the software engineering
UNIT-2: Functions Objectives • To understand the software engineering principles of Structured programming and modularity (top-down development) • To understand the function declaration, function call, and function definition • To understand inter- function communication through parameters • To understand the four basic function designs • To understand how function communicate through parameters • To understand Standard functions • To understand the differences between global and local scope 1
Derived data types • Limited number of problems can be solved by using primary data types • Derived data types are needed to solve complex problems. • Complex data types are derived from primary data types • Derived data types available in C language are given below: 2
Designing Structured Programs • Simple programs studied so far can be solved and understood without too much effort. • Large programs need to be reduced into elementary parts for better understanding. • The principles of top-down design and structured programming dictate that a program should have a main module and its related modules. • Each module can be further divided in to sub modules. • Breaking a complex problem into smaller parts is known as factoring. 3
Hierarchy of modularization • Module 1, 2, 3 are sub modules of main module • Module 1 a, 1 b, 1 c are sub modules of module 1 • Module 2 a is sub module of module 2 • Module 3 a, 3 b are sub modules of module 3 4
Modularization Example: PRINCIPAL (main module) CULTURAL ( module 1) SINGING (module 1 a) DANCE (module 1 b) SPORTS (module 2) CRICKET (module 2 a) ACADEMIC (module 3) VOLLEY BALL (module 2 b) TECH QUIZ (module 3 a) PRESENTATION (module 3 b) 5
Modular Programming - Manageable Huge Book of 3000 pages Same book published in several volumes. Easily manageable
Functions in C • Top-down design is implemented by using Functions in C • A Program in C is made up of one or more functions, one and only one of which must be named as main. • The execution of the program always starts and ends with main, but it can call other functions to do specific task. • main ( ) is called by the OS and control returns to the OS after completion of main function. 7
Structure Chart for a C Program 8
Functions in C • 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 • A function receives zero or more pieces of data, operate on them and return at most one piece of data 9
Advantages of Functions (1 of 2) • Problems can be factored in to understandable and manageable steps(easy to code and debug). • Functions can be developed by different people and can be combined together as one application. • 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. 10
Advantages of Functions (2 of 2) Work Allotment Application Development 11
Function Definition (1 of 4) • A function is always associated with following three steps • Function definition • Function declaration • Function call • Function definition contains the code for a function • Function definition is made up two parts • Function Header • Function body (Compound statement within opening and closing braces) 12
Function Definition (2 of 4) Function Header • A function header consist of 3 parts return type function name formal parameter list A semicolon is not used at end of function definition header • Function Body • • The function body contains local declarations and function statements in between braces. Local declarations specify the variables needed by the function. The function statement terminated by a return statement If the function return type is void, a return statement is optional. 13
Function Definition (3 of 4) Parameters • Formal parameters are variables that are declared in the header of the function definition • Actual parameters are used in the calling statement or sometimes they may be an expression • Formal and actual parameters must match exactly in type, order, and number. Their names, however, no need to match. 14
Function Definition (4 of 4) Parameters Formal and actual parameters must match exactly in type, order, and number. Their names, however, need not match. double average(int x, int y); void main() actual parameters { double sum 1; sum 1=average(10, 20); // calling function x, y formal } parameters turbo C program examples 2 & 3, also show error simulation Execute 15
Function Declaration (1 of 2) • Function declaration consists only of a function header (no code) • Function declaration header consists of three parts: the return type, the function name and formal parameters • Function declarations are terminated with a semicolon • Declarations are placed in global declaration section before the main function • Function declaration is also known as function prototype 16
Function Declaration (2 of 2) The general form of a function Prototype or Declaration 17
Function Call (1 of 4) • Function call is a postfix expression • The operand in a function call is the function name; the operator is the parentheses set (…), which contains actual parameters. • Actual parameters identify the values that are to be sent to called function and must match the formal parameters in type and order • Multiple actual parameters are separated by comma • Function call transfers the control to the function definition (called function) • After execution of the function, it returns the result to the calling function • Function having a return type void can be used only as a stand-alone statement 18
Function Call (2 of 4) General form Actual parameters return type function-name(name 1, name 2, name 3, ………. , namen); Return type of function Each parameter is separated by comma and function call ends with semicolon 19
Function Call (3 of 4) turbo c example 1 also show error simulation 20
Function Call (4 of 4) Examples of Function Calls 21
How Functions Work? main() Function call User defined function 22
Sample Program with function 23
Sample Program with function 24
Sample Program with function turbo c example 2 also show error simulation 25
User Defined Functions • Functions must be both declared and defined. • Function declaration gives the whole picture of the function. • Function declaration must be placed before the function call. • Function declaration consists of: • name of the function, • return type, • type and order of parameters • Function definition contains the code that needs to complete the task 26
Declaring, Calling and Defining Functions 27
Basic Function designs (1 of 5) • Basic function design is based on their return value and parameter list • There are four basic designs 1. Void Functions without Parameter. • Function with no arguments and no return value. 2. Void Functions with Parameter. • Functions with arguments and no return values. 3. Non Void Functions without Parameters • Functions with no argument and return values. 4. Non Void Functions with Parameters • Functions with argument and return values. 28
Basic Function designs (2 of 5) 1. Void Functions without Parameters • Void functions without parameters does not receive any parameters and also does not return any value. • This can be used only as a statement because a Void function does not return a value • This cannot be used in an expression Example : result=greeting(); turbo c example 4 also show error simulation //error 29
Basic Function designs (3 of 5) 2. Void Functions with Parameter • • The function that receives parameter but does not return any value This function takes arguments(parameter list) It can be used only as statement It cannot be used in an expression Example: result=greeting(); //error Void Function with Parameters C program example 5. c 30
Basic Function designs (4 of 5) 3. Non Void Functions without Parameters • The function returns a value but does not receive parameters • It cannot be used as statement • It can be used in an expression Example: result=greeting(); //correct Non-void Function without Parameters c program example 6. c 31
Basic Function designs (5 of 5) 4. Non Void Function with Parameters • The function receives parameters and return values • It cannot be used as a statement • It can be used in an expression Example : result=greeting(); //correct Calling a Function That Returns a Value c program example 7. c 32
Assignment Write a C program to implement GCD of 2 numbers by using 4 types of user defined functions 33
Inter-Function Communication (1 of 5) • The calling and called functions need to communicate to exchange data. • The data flow between the calling and called functions can be divided into three strategies: 1. a downward flow, 2. an upward flow, and 3. a bi-directional flow. • A downward flow from calling function to called function • An upward flow from called function to calling function • A bi-directional flow in both directions 34
Inter-Function Communication (2 of 5) Data Flow Strategies 35
Inter-Function Communication (3 of 5) Downward flow • Calling function sends data to called function (one way communication) • Copy of data items are passed from calling function to called function • Called function may change the values passed, but the original values in the calling function remains unchanged • Use call by value mechanism to implement downward flow • Rules: a. Use values in function call to pass the data b. Use appropriate data types in function parameter list to receive data values c. Use parameter identifiers in the called function to access the local copies of the data 36
Inter-Function Communication (4 of 5) Upward flow • Called function sends data back to the calling function (one way communication) • Data items are returned to the calling function from the called function • Calling function may use the values passed from called function • Original values of called function remains unchanged • Use call by reference or return mechanism to implement upward communication • Rules: a. Use &variable name in function call to pass a reference to the variable b. Use types * in the function parameter list to receive the variable’s address c. Use *parameter name in the function to reference the original variable 37
Inter-Function Communication (5 of 5) Bi-directional flow • Calling function sends data down to called function • Called function sends data up to calling function during or at the end of the process. • Use call by reference or return mechanism to implement bi-directional communication • Rules: a. Use &variable name in function call to pass a reference to the variable b. Use types * in the function parameter list to receive the variable’s address c. Use *parameter name in the function to reference the original variable 38
Inter-Function Communication ‘C’ implementation • Most programming languages have three strategies for Inter-function communication: Pass by value, pass by reference and return • C Language uses two mechanisms for Inter function communication: 1. Pass by values 2. return 39
Inter-Function Communication Downward Communication in C • Pass-by-Value is a perfect solution for communication in downward direction • Two data items are passed from main to the down function. • Called function does not return any data item 40
Inter-Function Communication An example for Downward Communication turbo c example 8. c also show error simulation 41
Inter-Function Communication Upward Communication • Return statement provides a mechanism for the return of data items in upward direction flow • This mechanism allows only one data item to be returned to the calling function. • Called function needs to access variables in the calling function for passing multiple data items. But C does not allow direct reference to a variable in the calling function. • The solution to this problem is as follows. • Calling function pass the address of a variable: Ex: upfun (&x, &y) • Called function declares a pointer variable to receive the address: Ex: void upfun (int * ax, int * ay). • Called function can then put the data in the address of the variable given by the calling function. 42
Inter-Function Communication Upward Communication in C 43
Inter-Function Communication An example for Upward Communication turbo c example 9. c also show error simulation 44
Inter-Function Communication Bi-directional Communication • Strategy used for upward direction can be applied for communication in both directions with a little difference. • Use indirect reference in both sides of the assignment statement • The variable in the called function is first accessed for retrieving the address variable in the right hand side • Access the same parameter again to store a value in the left hand side 45
Inter-Function Communication An example for Bi-directional Communication turbo c example 10. c also show error simulation 46
Inter-Function Communication An Exchange Function turbo c example 11. c also show error simulation 47
Inter-Function Communication An example for Bi-directional Communication Calculate Quotient and Remainder C program example 16. c 48
Standard Functions (1 of 15) • A Function whose definitions have been written and are available, which can be used in a program. • Declare the standard function that is to be used in the function declaration. • Function declaration for these functions are grouped together and collected in several header files • Instead of using function declarations, standard functions can be included in the header files at top portion of the program • Ex: printf(), scanf() 49
Standard Functions (2 of 15 ) Library Functions and the Linker 50
Standard Functions (3 of 15 ) Math functions • • Many important library functions are available for mathematical calculations • Integer functions can be found in stdlib. h Most of these function declarations are in math header file (math. h) or standard library header file (stdlib. h ) Absolute value functions • • Absolute value function returns absolute value of a number Absolute value is the positive rendering of the value regardless of its sign In this function, there are 3 integer and 3 real functions Three integer functions are abs, labs and llabs int abs (int long int labs(long int llabs(long int number); //stdlib. h 51
Standard Functions (4 of 15 ) Absolute value functions • Three real functions are fabs(), fabsf() and fabsl() double float long double fabs(double number); //math. h fabsf(float number) //math. h fabsl(long double number); //math. h Example abs(3)=3 abs(-3)=3 fabs(-3. 4)=3. 4 fabs(1. 1)=1. 1 abs(-1. 9)=1 C example program 12. c 52
Standard Functions (5 of 15) Ceiling Functions • A ceiling is the smallest integral value greater than or equal to a number • If all numbers are considered as a continuous range from minus infinity to plus infinity, this function moves the number right to an integral value • Syntax double ceil(double number); //math. h float ceilf(float number); //math. h long double ceill(long double number); //math. h • Example ceil(-1. 9) =-1. 0 ceil(1. 9) =2. 0 ceil(1. 1) =2. 0 ceil(-1. 1) =-1. 0 Note: ceilf() and ceill() are not supported in the current version c example program 13. c 53
Standard Functions (6 of 15) Floor Functions • A floor is the largest integral value that is less than or equal to a number • If all numbers are considered as a continuous range from minus infinity to plus infinity, this function moves the number left to an integral value • • Syntax double floor(double number); //math. h float floorf(float number); //math. h long double floorl(long double number); //math. h Example floor(-1. 9) =-2. 0 floor(1. 1) =1. 0 floor(1. 9) floor(-1. 1) =1. 0 =-2. 0 Note: floorf() and floorl() are not supported in the current version c example program 14. c 54
Standard Functions (7 of 15) Truncate Functions • A Truncate functions return the integral in the direction of zero • This functions same as floor function for positive numbers and the same as ceiling for negative numbers • • Syntax double trunc(double number); //math. h float truncf(float number); //math. h long double truncl(long double number); //math. h Example trunc(-1. 1) =-1. 0 trunc(1. 9) =1. 0 trunc(2. 1)=2. 0 trunc(-1. 1) =-1. 0 Note: trunc() function not supported in the current version 55
Standard Functions (8 of 15) Round function • Round function returns nearest integer value • Syntax: • double round(double float roundf(float long double roundl(long double number); long int lround(double long int lroundf(float long int lroundl(long double number); long int llround(double number); long int llroundf(float number) long int llroundl(long double Examples: round(-1. 1)=-1. 0 round(1. 9)=2. 0 round(-1. 5)=-2. 0 round(1. 5)=2. 0 number); number) //math. h //math. h number); //math. h 56
Standard Functions (9 of 15 ) Power function • The power(x, y) function returns the value of the x raised to the power of y i. e. , x y • Syntax: double pow(double n 1, double n 2) //math. h float powf(float n 1, float n 2) //math. h long double powlf(long double n 1, lobg double n 2)//math. h • Example: pow(3. 0, 4. 0)=81. 0 pow(3. 4, 2. 3)=16. 687893 57
Standard Functions (10 of 15) Sqrt function Sqrt () returns non-negative square root of a number. Error occurs if the number is negative Syntax: double sqrt(double number); //math. h float sqrtf(float number) //math. h long double sqrtlf(long double number); //math. h Examples: sqrt(25)=5. 0 sqrt(256)=16. 0 58
Standard Functions (11 of 15 ) Random numbers • A random number is a number selected from a set in which all members have same probability of being selected • Random numbers are useful in many areas of computer science • Applications are testing and gaming Random number Generation: • Most languages provides functions to generate random numbers • Each time a function is called, it generates another number • To generate next number, the function uses its previous number Random number generation methods 1. Seed provided by the user 2. we can use default seed provided by system 59
Standard Functions (12 of 15 ) Random Number Generation 60
Standard Functions (13 of 15 ) Generating a Random Number Series 61
Standard Functions (14 of 15) Random numbers in C • Two Random functions are provided in ‘C’ to build a random number series seed random (srand) random (rand) • These function declarations are available in stdlib. h Seed Random Number function(srand) • This function creates the starting seed from a number series Syntax void srand(unsigned int seed); • To generate same series in each run we can provide a constant seed, preferably prime number such as 997 Ex: srand(997); • To generate a different series in each run , we use time of day as seed as time will change every second , for this we need time. h Ex: srand(time(NULL)); C program example 15. c example 17. c 62
Standard Functions (15 of 15) Random number function • The random number function - rand() returns pseudo random integer between 0 and RAND_MAX • • • RAND_MAX is defined in standard library as largest number that rand() can generate Each call generates next number in a random number series The random number function declaration is int rand(void); • • C specifies the range between 0 to 32767 • Two common ranges are When we need a random number in a different range we must map the standard range to specified range real number series 0. 0 to 1. 0 integer series 0 to 25 or 11 to 20 • Generalized formula: rand()%range + minimum range=(maximum-minimum)+1 63
Object Storage Attributes • Each and every variable is stored in computer memory. • Every variable and function in C has two attributes: 1. datatype (Eg: int, float, char, etc. . ) 2. Storage Class • Storage Class specifies the scope, extent and linkage. 64
SCOPE (1 of 4) • Scope determines the region of the program in which a defined object is visible. • Scope pertains to any object that can be declared, such as a variable or a function declaration. • An object can have three levels of scope 1. Block scope 2. Function scope 3. File scope 65
Scope (2 of 4) Block Scope • Variables defined within a block have a local scope. They are visible in that block only. Outside the block they are not visible. Eg: • { //outer block starts {//inner block starts }//inner block ends • } //outer block ends • Variables are in scope from their point of declaration until the end of the block. Block scope is also referred as local scope. • Variables that are declared in a block are known as local variables. Demo C Program Ex No. 18 and also show error simulation. 66
Scope (3 of 4) Function Scope • Variables defined within a function (including main) are local to this function and no other function has direct access to them. • Eg: int add(int a, int b) //add() is a function { //function scope starts }//function scope ends Demo C Program Ex No. 19 and also show error simulation. 67
Scope (4 of 4) File Scope • File scope includes the entire source file for a program, including any files that are part of it. • An object with file scope has visibility through the whole source file in which it is declared. • Objects within block scope are excluded from file scope unless specifically declared to have file scope; in other words, by default, block scope hides objects from file scope. • An object with file scope sometimes referred to as a global object and the variables declared inside this scope are referred to as Global Variables. Demo C Program Ex No. 20 and also show error simulation. 68
Extent • Defines the duration for which the computer allocates memory for the variable. • It is also known as storage duration. • Extents are of two types: 1. Automatic Extent: object is created each time when it is declared and it is destroyed each time when the block is exited. 2. Static Extent : object is created when the program is loaded for execution and it is destroyed when the execution stops. 69
Linkage A large application program may be broken into several modules, with each module potentially written by a different programmer. Each module is a separate source file with its own objects. We can define two types of linkages: -internal -external Internal Linkage: An object with an internal linkage is declared and visible in one module. Other modules cannot refer to this object. External Linkage: An object with an external linkage is declared in one module but is visible in all other modules with a special keyword, extern. 70
Storage Class Specifiers � There are four storage classes 1. Automatic (auto variable) 2. Register (register variable) 3. Static (static variable) 4. External (extern variable) 71
Automatic Variables (1 of 2) • The default and the most commonly used storage class is automatic. • Memory for automatic variables is allocated when a block or function is created. They are defined and are “local” to the block. • When the block is exited, the system releases the memory that was allocated to the automatic variables, and their values are lost. • These variables are also referred as local variables. 72
Automatic Variables (2 of 2) • Characteristics: • Scope: block • Extent: automatic • Linkage: internal • Declaration: auto type variable_name; • Initialization: An auto variable can be initialized where it is defined or left uninitialized. When auto variables are not initialized, its value is a garbage value. Demo C Program Ex No. 21 and also show error simulation. 73
Register Variables (1 of 2) • Register variables specify to the compiler that the variables should be stored in highspeed memory registers if possible. This is done for efficiency. • If no register space is free, variables become auto instead. • Keep register variables in small local blocks which are reallocated quickly. • The address of a register variable is unavailable to the user. The user program can’t use both the address operator and the indirection operator (pointer) with a register. 74
Register Variables (2 of 2) • Characteristics: • Scope: block • Extent: automatic/register • Linkage: internal • Declaration: register type variable name; • Initialization: A register variable can be initialized where it is defined or left uninitialized. Demo C Program Ex No. 22 and also show error simulation. 75
Static Variables (1 of 3) • The value of static variables persists until the end of the program. • It is declared using the keyword static : static int x; static float y; • By default, Static variables are initialized with zero. • The static specifier has two different usages depending on its scope. 1. static variable with block scope 2. static variable with file scope. 76
Static Variables (2 of 3) Static variable with block scope • When a static variable is declared in a block scope, static defines the extent of the variable • Static variables with Block Scope are also known as Static Local Variables Scope: Block Extent: Static Linkage: Internal • Declaration: static type variable_name • Initialization: • A static variable name can be initialized where it is defined, or it can be left uninitialized. If it is initialized, it is initialized only once. If not initialized, its value will be initialized to zero Demo C Program Ex No. 23 and also show error simulation. 77
Static Variable (3 of 3) Static variable with file scope • When the static specifier is used with a variable that has a file scope (global scope) and its linkage is internal. Scope: Extent: File Static Linkage: Internal Declaration: Static type variable name; Demo C Program Ex No. 24 and also show error simulation. 78
External Variables (1 of 2) • Extern is used for global variables that are shared across code in several files. • External variables are used with separate compilations. • Large projects are decomposed in to many source files. • Decomposed source files are compiled separately and linked together to form a unit. • Storage is permanently assigned to Global variables (defined outside functions) and all functions of the storage class extern. 79
External Variables (2 of 2) • Characteristics: • Scope: file • Extent: static • Linkage: external • Declaration: extern type variable_name; Demo C Program Ex No. 25 80
Summary of Storage Classes Class Scope Extent Linkage Keyword auto block automatic internal auto or none register block automatic internal register static(extent) block static internal static(linkage) file static internal static extern file static internal extern or none 81
Type Qualifiers (1 of 4) • The Type qualifiers are modifiers that are applied to data types. • The type qualifier adds three special attributes to data types: const, volatile, and restrict. Type Qualifiers const volatile restrict 82
Type Qualifiers (2 of 4) Constants Uses keyword const. A read only object. Must be initialized when it is declared. Cannot be changed later. Pointers can also be defined as constant. Eg: const float PI = 3. 1422 PI = 3. 14; //cannot be modified 83
Type Qualifiers (3 of 4) Volatile • Volatile type qualifier specifies to the computer that an object value may be changed by entities other than the currently running program. • Volatile type qualifier also provides the information to the compiler that the object can be shared between the currently running program and other facilities outside the program • Declaration: volatile type variable name; 84
Type Qualifiers (4 of 4) Restricted • Used only with pointers, indicates that the pointer is only the initial way to access the de-referenced data. • The restrict type qualifier is an indication to the compiler that, if the memory addressed by the restrict-qualified pointer is modified, no other pointer will access that same memory. • Declaration: • restrict type variable_name; 85
Recursion • There are two approaches to write repetitive algorithms: one approach uses loops and the other one uses recursion • Recursion is a repetitive process, in which a function call itself. • Recursive functions are useful in evaluating certain types of mathematical functions. • Recursion is also a useful way of creating and accessing dynamic data structures such as linked lists or binary trees. 86
Designing recursive function • Recursive functions have two steps: • each call either solves one part of the problem • it reduces the size of the problem • Every recursive function must have a base case. The statement that solves the problem is known as the base case. • The rest of the function is known as the general case. • The recursion will be done until the problem converges to the simplest case. • This simplest case will be solved by the function which will then return a value. • Each recursive call reduces the size of the problem 87
Rules for designing recursive function • First, determine the base case • Then, determine the general case • Finally, combine the base case and general case into a function. 88
Example: Factorial of a given number Iterative Definition • Factorial(n)= 1 n*(n-1)*(n-2)… 3*2*1 if n=0 if n>0 Recursive Definition Base Case Factorial(n) = 1 n*Fcatorial(n-1) if n=0 if n>0 General Case 89
Recursive representation of Factorial(3) (1 of 2) 90
Recursive representation of Factorial(3) (2 of 2) factorial(0) = 1; factorial(n) = n*factorial(n 1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) =3*2 =6 91
Recursive representation of Factorial(4) (1 of 11) Executes factorial(4) 92
Recursive representation of Factorial(4) (2 of 11) Executes factorial(3) 93
Recursive representation of Factorial(4) (3 of 11) Recursive representation of Factorial(4) Executes factorial(2) 94
Recursive representation of Factorial(4) (4 of 11) Executes factorial(1) 95
Recursive representation of Factorial(4) (5 of 11) Executes factorial(0) 96
Recursive representation of Factorial(4) (6 of 11) returns 1 97
Recursive representation of Factorial(4) (7 of 11) returns factorial(0) 98
Recursive representation of Factorial(4) (8 of 11) returns factorial(1) 99
Recursive representation of Factorial(4) (9 of 11) returns factorial(2) 100
Recursive representation of Factorial(4) (10 of 11) returns factorial(3) 101
Recursive representation of Factorial(4) (11 of 11) returns factorial(4) 102
Differences between Iteration and Recursion ITERATION RECURSION Iteration explicitly uses repetition structure. Recursion achieves repetition by calling the same function repeatedly. Iteration is terminated when the loop condition fails Recursion is terminated when base case is satisfied. May have infinite loop if the loop condition never fails Recursion is infinite if there is no base case or if base case never reaches. Iterative functions execute much faster and occupy less memory space. Recursive functions are slow and takes a lot of memory space compared to iterative functions Demo C Program Ex No. 26 & 27 103
Preprocessor commands • The C compiler is made of two functional parts: a preprocessor and a translator. The preprocessor is a program which processes the source code before it passes through the compiler. The translator converts C statements into machine code(object module). 104
Preprocessor commands • The preprocessor is a collection of special statements called commands or preprocessor directives. Each directive is examined by the preprocessor before the source program passes through the compiler. • Statements beginning with # are considered preprocessor directives. • Preprocessor directives indicate certain things to be done to the program code prior to compilation. • It includes certain other files when compiling, replace some code with other code. • Preprocessor commands can be placed anywhere in the program. 105
Major tasks of a Preprocessor There are three major tasks of a preprocessor directive • File inclusion (inclusion of other files) • Macro definition (Definition of symbolic constants and macros) • Conditional compilation of program code/Conditional execution of preprocessor directives 106
File Inclusion (1 of 3) • The first job of a preprocessor is file inclusion - the copying of one or more files into programs. • The files are usually header files consisting declarations of predefined functions and external files containing functions and data declarations. • General form is, #include filename • It has two different forms 1. #include <filename> 2. #include “filename” 107
File Inclusion (2 of 3) #include <filename> • It is used to direct the preprocessor to include header files from the system library. • In this format , the name of the header file is enclosed in pointed brackets. • Searches standard library only for inclusion of a file. example #include<stdio. h> • In the above example , the preprocessor directive statements searches for content of entire code of the header file stdio. h in the standard library , if it finds there includes the contents of the entire code at the place where the statement is in the source program before the source program passes through the compiler. Note : here we can’t include user files because it searches for files in the standard library. 108
File Inclusion (3 of 3) #include “filename” • It is used to direct the preprocessor to look for the files in the current working directory and the standard library. • This searches current working directory, then it will search in the standard library. • In this format, the name of the file is enclosed in double quotes. Example #include “header. h” note : We can also include file that is not present in the current directory by specifying the complete path of the file like #include “e: muc. c” Example Program No. 28 & 29 109
Macro (1 of 4) • A macro definition command associates a name with a sequence of tokens. The name is called the macro name and the tokens are referred to as the macro body. • The following syntax is used to define a macro: #define macro_name(<arg_list>) macro_body Example: #define CIRCLE_AREA( x ) ( PI * ( x ) ) Example Program No: 30 110
Macro (2 of 4) • • Macro must be coded in a single line. We can use backslash() immediately followed by a new line to code the macro in multiple lines. #define PREND printf(“Normal end of programn”); • • Macro performs text substitution – no data type checking. Whenever there is a macro call, the preprocessor replaces the call with the macro body. Example for macro definition : #define ANS 0 …. num = ANS After preprocessing the result would be num==0 //we needed num=0 111
Macro (3 of 4) Applications • The simplest application of macro is to define a constant. #define SIZE 10 • The body of the macro definition can be any constant value including integer, real, character or string. Character constants can be enclosed in single quotes and string constants in double quotes. 112
Macros (4 of 4) Predefined Macros Command Meaning _ _DATE_ _ Provides a string constant in the form “mm dd yyyy” containing the date of translation. _ _ FILE _ _ Provides a string constant containing the name of the source file. _ _TIME_ _ Provides a string constant in the form “hh: mm: ss” containing the time of the translation. _ _LINE_ _ Provides an integer constant containing the current statement number in the source file. _ _STDC_ _ Provides as integer constant with value 1 if and only if the compiler confirms with ISO implementation. Example Program No: 31 113
Conditional Compilation (1 of 2) Conditional Compilation allows us to control the compilation process by including or excluding statements. Two-Way Commands Example Program No: 32 114
Conditional compilation (2 of 2) Multi-Way Commands Example Program No: 33 115
Conditional Compilation Commands Command Meaning #if expression When expression is true, the code that follows is included for compilation. #endif Terminates the conditional command. #else Specifies alternate code in two-way decision. #elif Specifies alternate code in multi-way decision. #ifdef name Tests for the macro definition. #ifndef name Tests whether macro is not defined. 116
Other Commands • Line Command The line command used in two formats, that can set the line number and the filename for a program. #line 100 “My. Program. c” • Error Command The error command is of the form #error message Used to print the message detected by the preprocessor. • Pragma Command The pragma command causes the compiler to perform implementation and other defined actions. #pragma tokens Example Program No: 34, 35, 36 117
Introduction to Arrays • An array is one of the derived data types. • Arrays are useful to process large amounts of data • For example, suppose we have a temperature reading for each day of the year and need to manipulate their values several times within a program • With simple variables, • We would need to declare 365 variables. • We would not be able to loop over these variables • The above problem can be solved by using an array: Temp [365] • The elements in an array share the same name and are distinguished from one another by their numbers or subscripts: 0, 1, 2…. . Size-1 • An array must be declared before it can be used. • Array declaration and definition provides information to the compiler - the name of the array, type of array and the size. 118
Characteristics of an Array • An array represents a group of related data. • An array has two distinct characteristics: An array is ordered: data is grouped sequentially: element 0, element 1, … n-1 An array is homogenous: every value within the array must share the same data type. In other words, an int array can only hold integers, but not other data types. 119
How to Create an Array • Before we create an array, we need to decide on two properties: Element type: what kind of data will the array hold? int, double, char? Remember, we can only choose one type. Array size: how many elements will the array contain? 120
Types of Arrays • Arrays can be classified based on how the data items will be arranged. • Arrays are broadly classified into three categories. 1. One dimensional arrays 2. Two dimensional arrays 3. Multi dimensional arrays 1121
One Dimensional Arrays • One dimensional array is a linear list consisting of related and similar data items. • In memory, all the data items are stored in contiguous memory locations. Declaring a one dimensional array • To declare ordinary variables, we use the following notation: int number; • To declare an array, the following syntax can be used: Syntax: type arrayname[size]; For example: int number[5]; • Creates an array of 5 integer elements. 122
Operations on one Dimensional Array (1 of 5) 1. Initializing • There are four options to initialize one dimensional arrays. Option A: Basic Initialization • If the values of all the data elements are known, the values must be specified within the braces. int temp [5] = {75, 79, 82, 70, 68}; Memory Layout temp[0] temp[1] temp[2] temp[3] temp [4] 75 79 82 70 68 1000 1002 1004 1006 1008 123
Memory Representation of an Integer Array 124
Operations on one Dimensional Array (2 of 5) Option B: Initialization without size int temp [] = {75, 79, 82, 70, 68}; • The compiler allocates memory for an array of 5 elements. The array temp is initialized as shown below: temp[0] temp[1] temp[2] 75 1000 79 1002 temp[3] temp[4] 82 70 1004 1006 68 1008 Address Option. C: Partial Array Initialization int temp [5] = {75, 79, 82}; // All values are not specified temp[0]temp[1] temp[2]temp[3]temp[4] 75 1000 • • 79 1002 82 0 1004 1006 0 1008 Address Values for first three elements have been specified The elements for which values are not specified, are initialized to zero’s. 125
Operations on one Dimensional Array (3 of 5) Option D: Initialization to all zero’s • If values of data elements are not known well in advance, then all elements can be initialized to zero’s. For example: int temp [5] = {0}; temp[0] temp[1] temp[2] temp[3] temp [4] 0 1000 0 1002 0 1004 0 0 1006 1008 Address 126
Operations on one Dimensional Array (4 of 5) 2. Inputting values • Another way to fill the array is to read the values from the keyboard or a file. • This could be done by using a loop. Ex: for(i=0; i<9; i++) scanf(“%d”, &scores[i]); 3. Accessing elements of an array • Index is used to access individual elements of an array. Ex: scores[0]; 4. Printing/Output values • Another common application is printing the contents of an array. • This can be easily done by using a loop. Ex. for(i=0; i<9; i++) printf(“%d”, scores[i]); 127
Operations on one Dimensional Array (5 of 5) 5. Assigning values to an array • Suppose we have an array temperature, the readings of the temperature for the year is represented in the below example. • The subscripts would be 0, 1, …, 364. Temperature array 75 79 82 70 68 65 58 63 67 61 temperature[4] • We can loop through the elements of an array by varying the subscript. To set all the elements of any array to 0: for(i=0; i<365; i++) temperature[i] = 0; • We cant use assignment statement directly with arrays. • if a[], b[] are two arrays then the assignment a=b is invalid Example 37 shows 1 D array declaration & accessing 128
Inter-function Communication • To process arrays in a large program, arrays are required to be passed to functions. • Arrays can be passed to functions in two ways: • Passing Individual Elements • Individual elements can be passed to a function either by passing the data values or by passing the addresses • Passing the whole Array • By using this, an Array name can be passed to the called function 129
Inter-function Communication Passing Array Elements 130
Inter-function Definition Passing the Address of an Array Element 131
Inter-function Definition Passing the Whole Array 132
Two Dimensional Array • An array of arrays is called multi-dimensional array. • A multidimensional array can have two dimensions, three dimensions, four dimensions, etc. • A Multi-dimensional array which has only two dimensions is called as a two dimensional array. • Two-dimensional array can be regarded as a table with rows and columns: Example: 'J' 'o' 'h' 'n' is a 3 4 array: 3 rows, 4 columns 'M' 'a' 'r' 'y' 'J' 'o' 'h' 'n' 'I' 'v' 'a' 'n' 'M' 'a' 'r' 'y' • This is a two dimensional array having 3 rows and 4 columns 133
Two Dimensional Array DECLARATION Syntax: • Type array. Name [rows][cols]; Example • char names[3][4]; In the above declaration • Char (element. Type) specifies type of element in each slot • Names (array. Name) specifies name of the array • [3] (rows) specifies number of rows • [4] (cols) specifies number of columns 134
Two Dimensional Array Initialization • A two dimensional array can be initialized at the time of declaration: char names [3][4] = { {‘J’, 'o', 'h', 'n'}, {‘M’, 'a', 'r', 'y'}, {‘I’, 'v', 'a', 'n'} }; • An integer array can be initialized to all zeros by using the following statement: int nums[3][4] = {0}; • The declaration of a two dimensional array should have the column size so that , the elements can be in the form of rows and columns. • To access an element of a 2 D array, requires both the row and the column. 2 Dexmpl 38 , 2 Dexmp 39. c demonstrate 2 d array declaration and initialization through turbo c. 135
Applications of Arrays 1. Matrix Operations Addition, multiplication, trace, transpose…etc 2. Sorting: One of the most common applications in computer science is sorting—the process through which data is arranged according to their values. • Sorting techniques • Selection Sort • Bubble Sort • Insertion Sort • Merge Sort • etc 136
Multi Dimensional Array • C allows arrays of multiple dimensions. • The general form of a multidimensional array is type array. Name[s 1][s 2][s 3]…. [sm]; • For example int a[10][3][2]; • It is represented as “an array of ten arrays of three rows of two columns” 137
Multi Dimensional Array 3 -D Array example. Example 40. c will demonstrate 3 D array…. 138
Representation of a Multi Dimensional Array A Three-dimensional Array (3 x 5 x 4) 139
- Slides: 139