Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Function and Structure.

Similar presentations


Presentation on theme: "Chapter 4 Function and Structure."— Presentation transcript:

1 Chapter 4 Function and Structure

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

3 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.

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

5 void main() { //call to fun1() fun1(); //call to fun2() fun2(); } fun1() { fun3(); } fun3() { } fun2() { }

6 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.

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

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

9 Function Calling Syntax : Function_name();

10 Types of function : There are three categories of the function : Function with no arguments and no return value. These are commonly used to display messages. 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.

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

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

13 Output Multiplication is 20
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 %d",m); getch(); } int mul(int l,int m) int ans; ans = l * m; return(ans); Input Let j=5,k=4 Output Multiplication is 20

14 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.

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

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

17 i.e. 3! = 3* factorial(2) = 3* 2 * factorial(1) = 3 * 2 *1 = 6 no=3
From main i.e. 6 to 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

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

19 Example – 2 : Write a function to display factorial of 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

20 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 book1,book2,book3;

21 Second method to defining structure is :
struct book_name { char title ; char author; int pages ; float prices; } book1,book2,book3; You can defined structure globally as well as locally.

22 //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;

23 Give Address: Chinchwaad
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:%d\n",s.rno); printf("Name:%s\n",s.nm); printf("Address:%s\n",s.add); printf("City:%s\n",s.ct); printf("Phone No:%d\n",s.ph); getch(); } OUTPUT Give Roll NO:12 Give Name: Disha Give Address: Chinchwaad Give City:Pune Give Phone no:

24 Initialization of structure variable :
First method to initialise structure : void main() { struct st_record int weight; float height; }; struct st_record stud1 = {60,80.5}; struct st_record stud2 = {53,170}; }

25 Second method to initialise structure :
struct st_record { int weight; float height; } stud1={60,80.5}; you also initialise stud2 globally by separating comma void main() struct st_record stud2 = {60,80.5}; }

26 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];

27 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); }

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

29 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; }

30 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;

31 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)

32 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.

33 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;

34 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. 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.

35 Ex: if we want to execute a program to swap the contents of 2 variables then we have to pass arguments as c:\tc\bin> 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[ ]) { ……………. …………… }

36 //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);

37 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.

38 In C there are four types of storage classes :
auto static extern 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;

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

40 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.

41 #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

42 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.

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

44 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.


Download ppt "Chapter 4 Function and Structure."

Similar presentations


Ads by Google