Docsity

C functions pointers, Essays (university) of C programming

Toggle sidebar
bg1
P a g e | 1
Raghu Engineering College(A) Dept of CSE C Programming Unit - 5
UNIT V
Objective: Modular programming and recursive solution formulation, Understanding
pointers and Dynamic memory allocation
FUNCTIONS- MODULAR PROGRAMMING: functions, basics, parameter passing, storage
classes extern, auto, register, static, scope rules, block structure, user defined functions,
standard library functions, recursive functions, Recursive solutions for fibonacci series,
towers of Hanoi, header files, C Preprocessor, example c programs, Passing 1-D arrays, 2-D
arrays to functions.
POINTERS: Pointers- concepts, initialization of pointer variables, pointers and function
arguments, passing by address- dangling memory, address arithmetic, character pointers and
functions, pointers to pointers, pointers and multi-dimensional arrays, dynamic memory
management functions, command line arguments
Function definition
A Function is a self-contained block of statement that performs a specific task
when called. A function is also called as sub program or procedure or subroutine.
๏ƒ˜ Every function is given a name.
๏ƒ˜ The name of the function is used to invoke (call) the function.
๏ƒ˜ A function may also take parameters (arguments). If a function takes parameters,
parameters are to be passed within parentheses at the time of invoking function.
๏ƒ˜ A function theoretically also returns a value, but you can ignore the return value of the
function in C language.
๏ƒ˜ Function name must follow the same rules of formation as other variables in C.
๏ƒ˜ The argument list contains valid variable names separated by commas.
C is a function-oriented language. Every C Program can be thought of as a
collection of these functions. Function is a set of instructions to carry out a particular task.
Function after its execution returns a single value.
Many operations in C language are done through functions. For example, we have used
printf() function to display values, scanf() function to read values from keyboard, strlen()
function to get the length of the string etc.
Types of functions:
Generally, the functions are classified into two types:
1. Standard functions
2. User-defined functions.
Standard/Library functions
The Standard functions are also called library functions or built-in functions.
A function which is made available to programmer by compiler is called as standard or pre-
defined function. Every C compiler provides good number of functions. All that a programmer
has to do is use them straight away. For example, if you have to find length of a string, use
strlen() without having to write the required code.
All standard functions, such as sqrt(), abs(), log(), sin() etc. are provided in the library of
function. But, most of the applications need other functions than those available in the
software, those are known as user-defined functions.
User-defined functions
User-defined function is a function that is defined by user. That means, the code for the
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a

Partial preview of the text

Download C functions pointers and more Essays (university) C programming in PDF only on Docsity!

P a g e | 1

Raghu Engineering College(A) Dept of CSE C Programming Unit - 5

UNIT V

Objective: Modular programming and recursive solution formulation, Understanding pointers and Dynamic memory allocation

FUNCTIONS- MODULAR PROGRAMMING: functions, basics, parameter passing, storage classes extern, auto, register, static, scope rules, block structure, user defined functions, standard library functions, recursive functions, Recursive solutions for fibonacci series, towers of Hanoi, header files, C Preprocessor, example c programs, Passing 1-D arrays, 2-D arrays to functions. POINTERS: Pointers- concepts, initialization of pointer variables, pointers and function arguments, passing by address- dangling memory, address arithmetic, character pointers and functions, pointers to pointers, pointers and multi-dimensional arrays, dynamic memory management functions, command line arguments

Function definition A Function is a self-contained block of statement that performs a specific task when called. A function is also called as sub program or procedure or subroutine. ๏ƒ˜ Every function is given a name. ๏ƒ˜ The name of the function is used to invoke (call) the function. ๏ƒ˜ A function may also take parameters ( arguments ). If a function takes parameters, parameters are to be passed within parentheses at the time of invoking function. ๏ƒ˜ A function theoretically also returns a value, but you can ignore the return value of the function in C language. ๏ƒ˜ Function name must follow the same rules of formation as other variables in C. ๏ƒ˜ The argument list contains valid variable names separated by commas.

C is a function-oriented language. Every C Program can be thought of as a collection of these functions. Function is a set of instructions to carry out a particular task. Function after its execution returns a single value.

Many operations in C language are done through functions. For example, we have used printf() function to display values, scanf() function to read values from keyboard, strlen() function to get the length of the string etc.

Types of functions: Generally, the functions are classified into two types:

  1. Standard functions
  2. User-defined functions.

Standard/Library functions The Standard functions are also called library functions or built-in functions. A function which is made available to programmer by compiler is called as standard or pre- defined function. Every C compiler provides good number of functions. All that a programmer has to do is use them straight away. For example, if you have to find length of a string, use strlen() without having to write the required code. All standard functions, such as sqrt(), abs(), log(), sin() etc. are provided in the library of function. But, most of the applications need other functions than those available in the software, those are known as user-defined functions.

User-defined functions User-defined function is a function that is defined by user. That means, the code for the

P a g e | 2

Raghu Engineering College(A) Dept of CSE C Programming Unit - 5

function is written by user (programmer). User-defined functions are similar to standard functions in the way you call. The only difference is instead of C language providing the function, programmer creates the function. If a program is divided into functional parts th main() function is an example of user-defined function. Every program must have a main function to indicate where the program has to begin its execution. an each part may be independently coded and later combined into single unit.

Advantages of functions Several advantages of dividing the program into functions include:

  1. Modularity
  2. Reduction in code redundancy
  3. Enabling code reuse
  4. Better readability

User-defined functions are used mainly for two purposes:

๏ƒ˜ To avoid repetition of code ๏‚ท In programming you often come across the need to execute the same code in different places in the program. ๏‚ท For example, if you have to print an array at the beginning of the program and at the end of the program. Then you need to write the code to display the array twice. ๏‚ท If you create a function to display the array, then you have to call the function once at the beginning of the program. That means, the source code need not be written for multiple times. It is written only for once and called for multiple times. ๏ƒ˜ To break large program into smaller units ๏‚ท It is never a good idea to have a single large code block. ๏‚ท If you write entire C program as one block, the entire blocks ends up in main() function. It becomes very difficult to understand and manage. ๏‚ท If you can break a large code block into multiple smaller blocks, called functions, then it is much easier to manage the program. In the following example, instead of taking input, processing and displaying output in main() function, if you can divide it into three separate functions, it will be much easier to understand and manage.

P a g e | 4

Raghu Engineering College(A) Dept of CSE C Programming Unit - 5

in any part of the program text or within a library

Example: void welcome( ) {

Function header

printf(โ€œhello world\nโ€; function body }

Function Call A function call has the following syntax:

(); Example: sum(a,b);

Passing Parameters: A parameter or argument is a value passed to function so that function can use that value while performing task. A function may take none, one or more parameters depending upon the need. Example: line(); /function that pass no parameters/ line(20); /function that pass one parameter/ getaverage(10,20); /function that pass more than one parameter/

The parameters are two types:

  1. Actual parameters or original parameters.
  2. Formal parameters or duplicate parameters.

Actual Parameter: It is the value that is passed to function while calling the function. When a function call is made, only a copy of the values of actual arguments is passed into the called function. For example; 10 and 20 values that we passed to line() and getaverage() function in the above are actual parameters. Formal Parameter: Variable that is used to receive actual parameter is called formal parameter. The actual and formal arguments should match in the number, type and order, the values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first argument.

Example: getaverage(int a, int b); Here a and b are formal parameters.

Note: ๏‚ท Actual parameterโ€“ This is the argument which is used in function call. ๏‚ท Formal parameterโ€“ This is the argument which is used in function definition.

P a g e | 5

Raghu Engineering College(A) Dept of CSE C Programming Unit - 5

Returning Value: Normally after performing the task functions return a value. The return value may be of any type. But a function can return only one value. To return a value from the function, we have to first specify what type of value the function returns and then we have to use return statement in the code of the function to return the value. When return type is not explicitly mentioned it defaults to int. If a function doesn't return any value then specify return type as void. A function returns the value to the location from where it has been called.

Types of functions A function depending on whether arguments are present or not and whether a value is returned or not may belong to one of the following categories: Functions can be divided into 4 categories:

  1. A function with no arguments and no return value
  2. A function with no arguments and a return value
  3. A function with an argument or arguments and returning no value
  4. A function with arguments and returning a values 1. A function with no arguments and no return value When a function has no argument, it does not receive any data from calling function. When it does not return a value, the calling function does not receive any data from called function. In effect, there is no data transfer between calling function & called function.

Example-1: #include<stdio.h> void welcome(); //function prototype declaration int main() // calling function { welcome(); //function call return 0; } void welcome() //called function { printf("Hi students..!"); function body }

OUTPUT Hi students..!

Example-2: #include<stdio.h> int main() { printf("Addition of 2 numbers:\n"); sum(); return 0; } sum() {

P a g e | 7

Raghu Engineering College(A) Dept of CSE C Programming Unit - 5

s=a+b+c; return s/3.0; }

3. A function with an argument(s) and returning no value When a function has argument(s), it does receive data from calling function. When it does not return a value, the calling function receives does not data from called function. In effect, there is data transfer between calling function & called function. ๏ƒ˜ A function has argument(s). ๏ƒ˜ A calling function can pass values to function called, but calling function not receives any value. ๏ƒ˜ Data is transferred from calling function to the called function but no data is transferred from the called function to the calling function. ๏ƒ˜ Generally Output is printed in the Called function. Example #include<stdio.h> void add(int x, int y); int main() { add(30,15); add(63,49); add(952,321); return 0; } void add(int a, int b) { int result; result = a+b; printf("Sum of %d and %d is %d\n",a,b,result); } OUTPUT Sum of 30 and 15 is 45 Sum of 63 and 49 is 112 Sum of 952 and 321 is 1273 4. A function with arguments and returning a values ๏ƒ˜ Argument are passed by calling function to the called function ๏ƒ˜ Called function return value to the calling function ๏ƒ˜ Data returned by the function can be used later in our program for further calculation ๏ƒ˜ Mostly used in programming because it can two way communication Example #include <stdio.h> int add(int x, int y); int main() { int z; z=add(952,321); printf("Result %d\n", add(30,55)); printf("Result %d\n", z); return 0; }

Unit โ€“ V C Programming int add(int a, int b) { int result; result = a + b; return (result); } OUTPUT Result = 85 Result = 1273

Nesting of functions (Calling Function within Function) One of the main reasons of using various functions in your program is to isolate assignments; this allows you to divide the jobs among different entities so that if something is going wrong, you might easily know where the problem is. Functions trust each other, so much that one function does not have to know HOW the other function performs its assignment. One function simply needs to know what the other function does, and what that other function needs. Once a function has been defined, other functions can use the result of its assignment. Imagine you define two functions A and B.

Example: Program to call function inside a function. int main() { processinput(); return 0; } processinput() { int a,b,sum; printf("Enter 2 numbers: "); scanf("%d %d",&a,&b); sum = process(a,b); displayresult(a,b,sum); } process(int a,int b) { return a+b; } displayresult(int x,int y,int s) { printf("Sum of 2 numbers %d and %d is %d",x,y,s);} Storage classes From C compilerโ€™s point of view, a variable name identifies some physical location within the computer where the value of the variable is stored. There are basically two kinds

Unit โ€“ V C Programming auto int i=3;

printf ( "\n%d ", i ) ; } printf ( "%d ", i ) ; } printf ( "%d", i ) ; return 0; } OUTPUT 3 2 1

Example โ€“ 2: #include<stdio.h> int i=10,x=20; int main() { auto int i=20; printf(โ€œthe I value is %dโ€,i); printf(โ€œ\n x value is dโ€,x); return 0; }

Register variables These variables are stored in one of the machineโ€™s register and are declared using keyword register. Example register int count; ๏ƒ˜ Since register access are much faster than a memory access keeping frequently accessed variables in the register lead to faster execution of program. ๏ƒ˜ Use register storage class for only those variables that are being used very often in a program (loop counters).

Properties of external variable are as under:

Storage CPU registers Initial value Garbage value Scope Local to the block in which the variable is defined. Life Till the control remains within the block in which the variable is defined

Example โ€“ 1: #include<stdio.h> int main( ) { register int i ; for ( i = 1 ; i <= 10 ; i++ ) printf ( โ€œ%d ", i ) ; return 0; }

OUTPUT 1 2 3 4 5 6 7 8 9 10

Unit โ€“ V C Programming

Static variables The value of static variables persists until the end of the program. It is declared using the static keyword. Example static int x; ๏ƒ˜ Static variables are initialized only once, when the program is compiled. ๏ƒ˜ Use static storage class only if you want the value of a variable to persist between different function calls. ๏ƒ˜ Two kinds of variables are allowed to be specified as static variables: static variables and local variables. The local variables are also referred to as internal variables while the global variables are also known as external variables. The default value of static variables is zero. Properties of static variable are as under:

Storage Memory/ RAM Initial value Zero Scope Local to the block in which the variable is defined Life Value of the variable persists between different function calls

Example โ€“ 1: #include<stdio.h> void increment(); int main( ) { increment(); increment(); increment(); return 0; } void increment() { static int i ; printf ( "%d\n", i ) ; i = i + 1 ; } OUTPUT: 0 1 2

Example โ€“ 2: #include<stdio.h> int main() { printf(โ€œ\n first class\t โ€); show(); printf(โ€œ\n second class \tโ€); show(): printf(โ€œthird class \tโ€); show(); return 0; } show()

Unit โ€“ V C Programming printf("\nOn decrementing:%d ",i); }

OUTPUT Initial value is 0 On incrementing: 1 On incrementing: 2 On decrementing: 1 On decrementing: 0

Example -1: <file.c> #include<stdio.h> #include<file2.c> int i=10; int main() { int i=20; printf(โ€œ %dโ€,i); incre(); return 0; } incre() { printf(โ€œ\n%dโ€,i); }

// <file2.c> extern int i=10; main() { printf(โ€œ\n %dโ€,i); incr(); } incr() { printf(โ€œ\n %dโ€,++i); }

Scope rules: ๏ƒ˜ The scope relatives to the accessibility, the period of existence, and the boundary of usage of variables declared in a statement block or function. ๏ƒ˜ If any variables declared inside the block, that variables scope is in the block only. ๏ƒ˜ If any variables declared in the main(), that variable scope is within the main and their sub blocks only. ๏ƒ˜ If any variable declared outside the main(). As global, that variable can accessed entire program means, main() and their sub program.

Block structure: Block structure means it is the blocks of executable statements, constructed with curly braces({}). The block of statements enclosed with open curly brace and closed curly brace. The scope rules in the block of C code, lying with in curly braces({}), basically specifies the accessibility duration of existence and boundary of usage of the variable.

Unit โ€“ V C Programming Example-1: // program: for scope rules and block structure. #include<stdio.h> int main() { int x=3; printf(โ€œ\n x value in outer block %dโ€,x); { int x=45; printf(โ€œ\n x value in inner block %dโ€,x); } printf(โ€œ\n again x value in outer block %dโ€,x); return 0; }

OUTPUT

x value in outer block 3 x value in inner block 45 again x value in outer block 3

Recursion A recursion function is one that calls itself directly or indirectly to solve a smaller version of its task until a final call which does not require a self-call. (or) A function that calls itself repetitively is known as a recursive function. And, this technique is known as recursion. The function calls itself repetitively until certain condition is satisfied. The recursive function has following types of statements:

  1. A statement or condition to determine if the function is calling itself again.
  2. A function call which should have argument.
  3. Conditional statement(if-else)
  4. A return statement. Need of recursion
  5. decomposition into smaller problems of same type
  6. recursive calls must reduce problem size
  7. a recursive function would call itself indefinitely
  8. recursion is like a top-down approach

Example: // C Program that calculates factorial of a given number using recursion #include <stdio.h> long int factorial(int); int main() { int x; long int f; prinf(โ€œEnter a number:โ€); scanf(โ€œ%dโ€,&x); f=factorial(x); printf("Factorial of %d is %ld\n",x,f); return 0; }

long int factorial(int n)

P a g e | 16

Raghu Engineering College(A) Dept. of CSE C Programming Unit - 5

The towers of Hanoi: The towers of Hanoi problem is a classic case study in recursion, it involves moving a specified number if disks from one tower to another using a third as an auxiliary tower. Specification move n disks from peg A to peg C, using peg B as needed. ๏ƒ˜ Only one disk may be moved at a time. ๏ƒ˜ This disk must be the top disk on a peg. ๏ƒ˜ A larger disk can never b placed on top of a smaller disk.

The problem is not to focus on the first step, but on the hardest step i.e, moving the bottom disk to peg C. ๏ƒ˜ move disk3 from peg A to peg C ๏ƒ˜ move disk2 from pg A to peg B ๏ƒ˜ move disk3 from peg C to peg B ๏ƒ˜ moving disk1 from peg A to peg C ๏ƒ˜ moving disk3 from peg B to peg A ๏ƒ˜ moving disk2 from peg B to peg C ๏ƒ˜ moving disk3 from peg A to peg C

Parameter passing mechanism There are two ways that a C function can be called from a program. They are,

  1. Call by value
  2. Call by reference

Call by Value (or Pass by Value) In call by value method, the value of the variable is passed to the function as parameter. The value of the actual parameter cannot be modified by formal parameter. Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to the formal parameter. If data is passed by value, the data is copied from the variable used in calling function to a variable used by the called function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. When we call a function then we will just pass the variables or the arguments and we doesnโ€™t pass the address of variables , so that the function will never effects on the values or on the variables. So Call by value is that the values those are passed to the functions will never

P a g e | 17

Raghu Engineering College(A) Dept. of CSE C Programming Unit - 5

effect the actual values those are Stored into the variables.

Example #include<stdio.h> void swap(int , int ); int main() { int a = 22, b = 44; printf("\nValues before swap \n a = %d and b = %d", a, b); swap(a,b); printf(" \nValues after swap \n a = %d and b = %d", a, b); return 0; } void swap(int x, int y) { int temp; temp = x; x = y; y = temp;

} OUTPUT Values before swap a =22 and b = 44 Values after swap a =22 and b = 44

Call by reference (or Call by address / Pass by address) In call by reference method, the address of the variable is passed to the function as parameter. The value of the actual parameter can be modified by formal parameter. Same memory is used for both actual and formal parameters since only address is used by both parameters.

Example #include<stdio.h> void swap(int *, int *); int main() { int a = 22, b = 44; printf("\nValues before swap \n a = %d and b = %d", a, b); swap(&a,&b); printf(" \nValues after swap \n a = %d and b = %d", a, b); return 0; } void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } OUTPUT Values before swap a =22 and b = 44 Values after swap a =44 and b = 22

P a g e | 19

Raghu Engineering College(A) Dept. of CSE C Programming Unit - 5

return 0; } printarray(int ar[5]) { int i; for(i=0;i<5;i++) printf("%d\n",i[ar]); }

Example 2: //Program to find largest from the given array #define SIZE 50 int big(int [], int); int main() { int a[SIZE], n, i, b; printf("\nEnter size of array: "); scanf("%d", &n); printf("\nEnter elements:\n"); for (i=0; i<n; i++) scanf("%d", &a[i]); b = big(a, n); printf("\nLargest number: %d", b); return 0; } int big(int a[], int n) { int b, i; b = a[0]; for(i=0; i<n; i++) { if (a[i] > b) b = a[i]; } return b; }

Passing 2-D array to functions: Example: #include<stdio.h> int main() { int a[2][2],i,j,s; clrscr(); printf(โ€œenter array elements \nโ€); for(i=0;i<2;i++) { for(j=0;j<2;j++) {

P a g e | 20

Raghu Engineering College(A) Dept. of CSE C Programming Unit - 5

scanf(โ€œ%dโ€,&a[i][j]); } } s=sum(a); printf(โ€œsum is %d\nโ€,s); return 0; } sum(int b[2][2]) { int i,j,s; for(i=0;i<2;i++) { for(j=0;j<2;j++) { s=s+b[i][j]; } } return s; }

Example: // Program to find Diagonal elements of given matrix #define ROW 10 #define COL 10 int trace(int [][], int, int); int main() { int a[ROW][COL], row, col, i, j, sum; printf("\nEnter no. of rows and columns of a matrix: "); scanf("%d %d", &row, &col); printf("\nEnter elements:\n"); for (i=0; i<row; i++) { for (j=0; j<col; j++) { scanf("%d", &a[i][j]); } } printf("\nMatrix is:\n\n"); for (i=0; i<row; i++) { for (j=0; j<col; j++) { printf("\t%d", a[i][j]); } printf("\n"); } sum = trace(a, row, col); printf("\nSum: %d", sum);