Chapter 4 Function and Structure Function What is

  • Slides: 44
Download presentation
 Chapter 4 Function and Structure

Chapter 4 Function and Structure

Function What is a Function? A function is a named, independent or selfcontained block

Function What is a Function? A function is a named, independent or selfcontained block of statements that performs a specific, well defined task and may return a value to the calling program.

 • A function is named : - Each function is identified by a

• A function is named : - Each function is identified by a unique name and is called using this name. • A function is independent : - It can perform the task on its own. It can contain its own variables and constants to be used only within the function. • It perform a specific task : - A function is given a discrete job to perform as a part of the overall program. The task has to be well defined. • It can return a value to the calling program : The function can perform executions and optionally return information to the calling program.

 Advantages of functions 1. Modular or structured programming can be done. 2. By

Advantages of functions 1. Modular or structured programming can be done. 2. By following top-down approach, the main function can be kept very small and all the tasks can be designed to various functions. 3. Debugging becomes easier. 4. It is easier to understand the program logic. 5. A repetitive task can be put into a function that can be called whenever required. This reduces the size of the program. 6. A function call other functions. It may even call itself. This technique is called recursion is very useful in solving complex problem.

 Types of Functions • Library functions These are pre written, compiled and placed

Types of Functions • Library functions These are pre written, compiled and placed in libraries. They come along with the compiler. e. g. printf(), scanf()(present in stdio. h) clrscr(), getch() (present in conio. h) • User defined functions These are written by the user and the user has the freedom to choose the name, argument and return data type of the function.

 • Function Declaration The function declaration is called the function prototype and is

• Function Declaration The function declaration is called the function prototype and is always end with a semicolon. Syntax : - return_datatype function_name(datatype arg 1, datatype arg 2, -----); It provides following information to the compiler. 1. The name of the function. 2. The return data type. 3. The number and type of the arguments.

 • Function definition syntax: return_datatype function_name(argument list) { local variable declaration; executable statements;

• Function definition syntax: return_datatype function_name(argument list) { local variable declaration; executable statements; …………. return( expression); }

 • Function Calling Syntax : Function_name();

• Function Calling Syntax : Function_name();

Types of function : There are three categories of the function : 1. Function

Types of function : There are three categories of the function : 1. Function with no arguments and no return value. These are commonly used to display messages. 1. Function with arguments and no return value. 3. Function with arguments and returning a value Such a function accepts information and also returns back a value to the calling program.

 • Function with no arguments and no return value : #include<stdio. h> void

• Function with no arguments and no return value : #include<stdio. h> void mul(); // function declaration void main() { mul(); // function call getch(); Input } void mul() // function defination Let j=5, k=4 Output { int j, k, ans; Multiplication is 20 printf(“n Enter 2 nos”); scanf(“%d%d”, &j, &k); ans= j * k; printf(“n Multiplication is %d”, ans); }

 Function with arguments and no return value : #include<stdio. h> #include<conio. h> void

Function with arguments and no return value : #include<stdio. h> #include<conio. h> void mul(int l, int m); void main() { int j, k; Input clrscr(); printf(“n Enter 2 nos”); Let j=5, k=4 scanf("%d %d", &j, &k); Output mul(j, k); Multiplication is 20 getch(); } void mul(int l, int m) { int ans; ans = l * m; printf(“Multiplication is %d", ans); }

 • Function with arguments and with return value : #include<stdio. h> #include<conio. h>

• Function with arguments and with return value : #include<stdio. h> #include<conio. h> int mul(int, int); void main() { int j, k, m; clrscr(); printf(“n Enter 2 nos”); scanf("%d %d", &j, &k); m=mul(j, k); printf(“Multiplication is getch(); } int mul(int l, int m) { int ans; ans = l * m; return(ans); Input %d", m); Let j=5, k=4 Output Multiplication is 20

 • Passing arguments to a function 1. Call by value : This method

• Passing arguments to a function 1. Call by value : This method copies the value of actual parameter into the formal parameter. Changes made to the formal parameters have no effect on the actual parameter. 2. Call by reference : In this method the called function has access to actual parameter by using addresses and pointers. This allows the function to directly access the original variables and modify their values.

 • Recursion : Recursion is a process where a function calls itself. Two

• Recursion : Recursion is a process where a function calls itself. Two important conditions should be satisfied by any recursive function. 1. Each time the function is called recursively it must be closer to the solution. 2. There must be some terminating condition, which will stop recursion. The most common example is to calculate factorial of a number.

Ex: Write the program to find the factorial of the given no. using the

Ex: Write the program to find the factorial of the given no. using the recursion : int factorial(int no) { #include<stdio. h> int fact; int factorial(int no); if(no==1) void main() return(1); { int no, ans; else printf(“n. Enter the number"); fact=no*factorial(n scanf("%d", &no); ans=factorial(no); o-1); return(fact); printf(“n Factorial of } %d is%d”, no, ans); Enter the getch(); number 5 } Factorial of 5 is 120

no=3 i. e. 6 to main From main 3 * factorial(2) return 3*2 no=2

no=3 i. e. 6 to main From main 3 * factorial(2) return 3*2 no=2 2 * factorial(1) return 2*1 no=1 No further calls return 1 i. e. 3! = 3* factorial(2) = 3* 2 * factorial(1) = 3 * 2 *1 = 6

Example – 1 : Swapping using call by value #include<stdio. h> #include<conio. h> void

Example – 1 : Swapping using call by value #include<stdio. h> #include<conio. h> void swap(int a, int b); { void main() int temp; { temp = a; int a, b; a = b; printf("Enter the b = temp; value of a and b "); printf(“After scanf("%d%d", &a, swapping : a = %d b &b); =%d", a, b); swap(a, b); } Output: Enter the value of a getch(); and b 12 67 After swapping a= 67 } b =12

a no #include<stdio. h> #include<conio. h> int fact (int n); void main() { int

a no #include<stdio. h> #include<conio. h> int fact (int n); void main() { int n, f; printf("Enter a number : "); scanf("%d", &n); f = fact(n); printf("The factorial of the number is %d", f); getch(); } int fact(int n) { int i, f=1; for(i=1; i<=n; i++) f =f*i; return(f); } Output: Enter a number : 5 The factorial of the number is 120

Structure Definition : Number of data items of same or different data types grouped

Structure Definition : Number of data items of same or different data types grouped together is called a structure. Purpose : To store multiple values of multiple data types in a single variable. Syntax: struct book_name { char title ; char author; int pages ; float prices; }; struct book_name book 1, book 2, book 3;

 Second method to defining structure is : struct book_name { char title ;

Second method to defining structure is : struct book_name { char title ; char author; int pages ; float prices; } book 1, book 2, book 3; You can defined structure globally as well as locally.

//program for declaring of structure #include<stdio. h> #include<conio. h> void main() { int i,

//program for declaring of structure #include<stdio. h> #include<conio. h> void main() { int i, j; struct stud { int rno; char nm[50]; char add[50]; char ct[50]; int ph; }s;

 printf("Give Roll No: "); scanf("%d", &s. rno); printf("Give Name: "); scanf("%s", s. nm);

printf("Give Roll No: "); scanf("%d", &s. rno); printf("Give Name: "); scanf("%s", s. nm); printf("Give Address: "); scanf("%s", s. add); printf("Give City: "); scanf("%s", s. ct); printf("Give Phone No: "); scanf("%d", &s. ph); printf("Roll No: %dn", s. rno); printf("Name: %sn", s. nm); printf("Address: %sn", s. add); printf("City: %sn", s. ct); printf("Phone No: %dn", s. ph); getch(); } OUTPUT Give Roll NO: 12 Give Name: Disha Give Address: Chinchwaad Give City: Pune Give Phone no: 985641237

 Initialization of structure variable : First method to initialise structure : void main()

Initialization of structure variable : First method to initialise structure : void main() { struct st_record { int weight; float height; }; struct st_record stud 1 = {60, 80. 5}; struct st_record stud 2 = {53, 170}; }

Second method to initialise structure : struct st_record { int weight; float height; }

Second method to initialise structure : struct st_record { int weight; float height; } stud 1={60, 80. 5}; you also initialise stud 2 globally by separating comma void main() { struct st_record stud 2 = {60, 80. 5}; }

 Arrays of structure : #include<stdio. h> #include<conio. h> #define l 3 void main()

Arrays of structure : #include<stdio. h> #include<conio. h> #define l 3 void main() { int i, j; struct stud { int rno; char nm[50]; char add[50]; char ct[50]; int ph; }s[l];

clrscr(); for(i=0; i<l; i++) { printf("Give Roll No: "); scanf("%d", &s[i]. rno); printf("Give Name:

clrscr(); for(i=0; i<l; i++) { printf("Give Roll No: "); scanf("%d", &s[i]. rno); printf("Give Name: "); scanf("%s", s[i]. nm); printf("Give Address: "); scanf("%s", s[i]. add); printf("Give City: "); scanf("%s", s[i]. ct); printf("Give Phone No: "); scanf("%d", &s[i]. ph); }

for(i=0; i<l; i++) { printf("Roll No: %dn", s[i]. rno); printf("Name: %sn", s[i]. nm); printf("Address:

for(i=0; i<l; i++) { printf("Roll No: %dn", s[i]. rno); printf("Name: %sn", s[i]. nm); printf("Address: %sn", s[i]. add); printf("City: %sn", s[i]. ct); printf("Phone No: %dn", s[i]. ph); } getch(); }

 Structure within structure : Structure within a structure means nesting of structures. Ex:

Structure within structure : Structure within a structure means nesting of structures. Ex: the following structure defined to store information about the salary of employees. struct salary { char name[20] ; char department[20]; int basic_pay; int houserent_allowance; int city_allowance ; int medical_allowance; }

 • Now we can group all the items related to allowance together and

• Now we can group all the items related to allowance together and declare them under a structure. struct salary { char name[20] ; char department[20]; int basic_pay; struct pay { int houserent_allowance; int city_allowance ; int medical_allowance; } allowance ; }employee;

 • The members contained in the inner structure can be referred as :

• The members contained in the inner structure can be referred as : employee. allowance. dearness employee. allowance. house_rent employee. allowance. city The direct access is not allowed. ex: employee. allowance (actual member is missing) employee. house_rent (inner structure variable is missing)

An inner structure can have more than one variable name. Ex: struct salary {

An inner structure can have more than one variable name. Ex: struct salary { char name[20]; char department[10]; struct pay { int city_allowance; int houserent_allowance; int medicle_allowance; } allowance, arears; } * We can also declare inner structure separately.

struct pay { int city_allowance; int houserent_allowance; int medicle_allowance; }; struct salary { char

struct pay { int city_allowance; int houserent_allowance; int medicle_allowance; }; struct salary { char name[20]; char department[10]; struct pay allowance; struct pay arrears; }; struct salary employee;

Command Line Arguments Command line arguments is a parameter supplied to a program when

Command Line Arguments Command line arguments is a parameter supplied to a program when the program is invoked. To pass the arguments to a program (main function) on command line is called command line arguments. Execution of the c program is starting from the main function also contains arguments like another normal function. main function can take two arguments : argc and argv variable argc counts the number of arguments on the command line including program name. argv represents an array of character pointers that point to the command line arguments. The size of this array will be equal to the value of argc.

 • Ex: if we want to execute a program to swap the contents

• Ex: if we want to execute a program to swap the contents of 2 variables then we have to pass arguments as c: tcbin> swap. c 10 20 Where swap. c is a filename where program execution code is stored. so, argc ----> 3 arguments argv[0] ------> swap. c argv[1] ------> 10 argv[2] ------> 20 To access the command line arguments, we must declare main function and its parameters. main(int argc, char *argv[ ]) { …………… }

//Swapping using command line arguments #include<stdio. h> #include<conio. h> void main(int argc , char

//Swapping using command line arguments #include<stdio. h> #include<conio. h> void main(int argc , char *argv[]) { int a, b, t; if (argc!=3) { printf(“n Invalid arguments”); exit(0); } a=atoi(argv[1]); b=atoi(argv[2]); t=a; a=b; b=t; printf(“n After swapping a=%d, b=%d”, a, b); }

STORAGE CLASSES The scope and lifetime of variables in function : The scope of

STORAGE CLASSES The scope and lifetime of variables in function : The scope of variable can be defined as the part of the program to which the variable is visible(accessible) or valid. Extent is the time during which memory is associated with the variable. Storage class refers to the manner in which memory is allocated to the variable by the compiler. Storage class determines the scope and lifetime of a variable.

In C there are four types of storage classes : 1. auto 2. static

In C there are four types of storage classes : 1. auto 2. static 3. extern 4. register 1. Automatic Storage Class : This is the default storage class of variables that are declared within a function. To declare the variable of this class keyword auto is used. syntax: auto data type variable; e. g. auto int i;

 • Automatic variables are referred as a local variable or internal variable. #include<stdio.

• Automatic variables are referred as a local variable or internal variable. #include<stdio. h> void main() { auto int i=10; Output { 20 auto int i=20; 10 printf(“%dn”, i); }

2. Extern Storage class: Variables belonging to this class are also called as global

2. Extern Storage class: Variables belonging to this class are also called as global variables or external variables. If the function uses an external variable, it is good programming practice to declare it again within the function using the extern keyword. syntax : extern data type var; e. g extern int a; By default variable is initialized to zero.

#include<stdio. h> int n=5; void display(); void main() { extern int n; printf(“n%d”, n);

#include<stdio. h> int n=5; void display(); void main() { extern int n; printf(“n%d”, n); display(); } void display() { extern int n; printf(“n %d”, n); } Output 5 5

3. Static Storage Class: A variable belonging this class retains its value between function

3. Static Storage Class: A variable belonging this class retains its value between function calls. To declare the variable of this class keyword static is used. Static variables are initialized only once during the execution of the program. Syntax : static data type var; e. g. static int x; By default variable is initialized to zero.

#include<stdio. h> void increment(); void main() { int n; for(n=1; n<=3; n++) Output increment();

#include<stdio. h> void increment(); void main() { int n; for(n=1; n<=3; n++) Output increment(); lcount =1 scount=1 } lcount =1 scount=2 void increment() lcount =1 scount=3 { int lcount=0; static int scount=0; lcount++; scount++; printf(“n lcount =%d scount=%d”, lcount, scount); }

4. Register Storage Class : To declare the variable of this class keyword register

4. Register Storage Class : To declare the variable of this class keyword register is used. The register keyword is used to tell the compiler to store the variable in a CPU register rather than in main memory. Thus, if a particular variable is kept in the CPU register, CPU can access it faster. So the execution becomes faster. syntax : register data type var; e. g register int i; register char ch; If the variable is not initialized, then it is initialized to garbage value.