B.com CA I Yr C-Language Notes

31
Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language UNIT-II Functions & Arrays Syllabus: Functions in C, Global and local variables, Parameter Passing, Standard Functions in Header files, Recursion Arrays in C, One dimensional Arrays and Multi dimensional Arrays, Arrays as Function arguments, Sorting, Searching and Merging. Important Questions 1Q: Define the process of Developing a Function? 2Q: Explain various categories of Functions? 3Q: Explain various types of functions? 4Q: Differentiate the Global & Local Variables? 5Q: Explain various standard functions in Header files? 6Q: Explain One Dimensional arrays with an Example? 7Q: Explain two Dimensional Arrays with an Example? 8Q: Explain the concept of Sorting of array elements with an Example? 9Q: Explain Function Recursion with an Example? Prepared By: Raju.K 1

description

Kakatiya University B.Com I Yr C language Unit-II

Transcript of B.com CA I Yr C-Language Notes

Page 1: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

UNIT-IIFunctions & Arrays

Syllabus:

Functions in C, Global and local variables, Parameter Passing, Standard Functions in Header

files, Recursion

Arrays in C, One dimensional Arrays and Multi dimensional Arrays, Arrays as Function

arguments, Sorting, Searching and Merging.

Important Questions

1Q: Define the process of Developing a Function?

2Q: Explain various categories of Functions?

3Q: Explain various types of functions?

4Q: Differentiate the Global & Local Variables?

5Q: Explain various standard functions in Header files?

6Q: Explain One Dimensional arrays with an Example?

7Q: Explain two Dimensional Arrays with an Example?

8Q: Explain the concept of Sorting of array elements with an Example?

9Q: Explain Function Recursion with an Example?

Prepared By: Raju.K 1

Page 2: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Function: A Function is a self contained block of instructions that can be used to execute a set of

instructions or to perform a specific operation.

In the C Language mainly the functions are classified in to two types. They are 1. System

Defined Functions and 2. User Defined Functions

System Defined Functions: A System defined function is a function that is already developed by

the Developer of C and Stored in the library of C. All the System defined functions can be used

directly in a program simply by calling them in the program.

Ex: printf( ), scanf( ), clrscr( ), getch() etc…

User Defined Functions: The Functions that are defined and implemented by the users are called

as User defined functions.

Ex: add( ), sub( ), main( ) etc…

Working with User Defined Functions:

In order to implement the User Defined functions we have to follow some steps. They are as follows

Step 1: Function Declaration: Each and every function that we are going to implement must be

known to the controller so that the controller can identifies the function. Basically a function

declaration will provides the following information to the controller

1. Return Type of the Function: That means which type of value we are going to return to the calling function. The return type may be one of (void, char, int, float and double).

2. Name of the Function: The function name that we can use to identify the function in the program

3. Arguments list: The list of arguments that the function can receive from the calling function

Syntax: <return_type> <function_name>( arguments list…);

Example: void add(int a,int b); , int fact(int x);

Prepared By: Raju.K 2

1Q: Define the process of Developing a Function?

Page 3: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Step 2: Function Definition: In this step we have to define the actual task of the function by

specifying the code of the function. The function definition can be done by using the following

syntax.

<return_type> <function_name>(arguments list…)

{

Local variables….;

………………….

Code of the function

…………………..

…………………..

}

Example: void add(int a,int b)

{

int c;

c=a+b;

printf(“The sum=%d\n”,c);

}

Step3: Function Call: In order to execute a user defined function it must be called by the main( ),

so that only the user defined function can be executed successfully.

Syntax: <function_name>(values…);

Example: add(8, 3);

Program: Write a Function to perform addition of two numbers?

void add(int a,int b);

void add(int a,int b)

{

int c;

c=a+b;

printf(“The sum=%d\n”,c);

}

Prepared By: Raju.K 3

Page 4: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

main( )

{

clrscr();

printf(“Function demonstration\n”);

add(8,3);

printf(“Function executed Successfully”);

getch();

}

Output:Function Demonstration

The sum=11

Function executed Successfully

Explanation:1. The program execution will starts from the main( )

2. Next the clrscr( ) is executed and the Output screen will be cleared

3. the nete statement add(8,3) is executed, when this is executed the controller will transfers

from main( ) to add( ) and carries the values 8 and 3 from main( ) to add( ). The values will

be stored in to a and b respectively

4. The complete code of add( 0 is executed at the end it returns back to main( ) from add( )

5. Finally the “Function is executed successfully will be printed on the output screen

Prepared By: Raju.K 4

Page 5: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

By depending on the way of communication among the functions the functions are classified

in to four types. They are as follows

a) Functions without arguments and return type

b) Functions with arguments but no return type

c) functions with no arguments but with return type

d) functions with arguments and return type

a) Functions without arguments and return type: In this category the functions does not

carries any values from the calling function to called function and at the same time not

returns any values from the called function to calling function

Example: A Program to demonstrate the functions without arguments and without return type

Output:

Prepared By: Raju.K 5

2Q: Explain various categories of Functions?

Page 6: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

b) Functions with arguments but no return type: In this category of functions we can

pass the values from the calling function to called function but we are not going to return

any value from the called function to calling function.

Example: Program to demonstrate functions with arguments but no return type

Output:

Prepared By: Raju.K 6

Page 7: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

c) Functions with no arguments but with return type: In this category of functions we

are not going to pass any value from the calling function to the called function but we

return the values from called function to calling function

Example:

Output:

Prepared By: Raju.K 7

Page 8: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

d) Functions with arguments and return type: In this category we are going to pass the

values from the calling function to called function as well as we return the values from

the called function to calling function.

Output:

Prepared By: Raju.K 8

Page 9: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Various Types of Functions:By depending on the type of the variables that we are using in the function call statement as

well as in the function definition the functions are classified in to two types

1. Function call by value

2. Function call by Address

Actual Parameters: The values that are passed from the calling function to the called function are

known as the actual parameters

Ex: add(5,8); where 5 and 8 are the actual parameters

Formal Parameters: The variables which are used in the function definition are known as formal

parameters.

Ex: void add(int a,int b) where a and b are the formal parameters

Note: The actual parameters in the calling function will be copied in to the formal parameters of the

called function

Function call by Value: In this type of functions the actual parameters are the values/variables and

the formal parameters also the variables. All the previous example

programs that are considered in the previous section are the examples to

function call by value only

Function call by Address: In this type of the functions the actual parameters are the address

variables where as the formal parameters are the pointer variables

The address of a variable can be find by using the “&” operator before the variable name

and the pointer variables can be represented by using the “*” operator before the variable name.

Prepared By: Raju.K 9

3Q: Explain various types of functions?

Page 10: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Example: A Program to demonstrate the function call by Address

Output:

Prepared By: Raju.K 10

Page 11: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Differences between Local & Global Variables

Local Variables Global Variables

1. The variables which are defined with in a function are called as local variables to the function

1. The variables which are defined out side of all the functions are called as the global variables

2. The local variables can be accessed with in function only

2. The global variables can be accessed by all the functions in a program

3. The local variables are limited to that function only in which they have defined

3. The global variables don’t have any limitations

4. they will be created automatically when the function is called and destroyed when they loss scope from memory

4. The global variables will be created once and can be accessed through out the program

5. The declaration and accessing of local variables is same as to global but the difference is only scope of the variable

5. These variables are also similar to local but scope of these variables is wide range of its access

Example:#include<stdio.h>int a,b,c;main(){ a=10; b=20; c=a+b; printf(“The sum=%d\n”,c);}

Example:#include<stdio.h>main(){ int a,b,c; a=10; b=20; c=a+b; printf(“The sum=%d\n”,c);}

Prepared By: Raju.K 11

4Q: Differentiate the Global & Local Variables?

Page 12: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Standard Functions: The C Language is came with so many number of built in library functions to

perform complex operations. These functions are developed by the developers and stored in the

Library of C. Such functions are called as System Defined functions

Functions in stdio.h:1. printf( ): This function is used to print amessage on the output screen

Syntax: printf(“format specifiers”,variables list);

Example: printf(“The sum of the given numbers=%d”,x);

2. scanf( ): this function is used to read the values and store them in to the variables

Syntax: scanf(“Format Spefiers”,&var1,&var2,…);

Example: scanf(“%d%d”,&x,&y);

3. gets( ): this function is used to read a string from the standard input device

Syntax: gets(var);

Example: gets(str1);

4. fputc( ): this function is used to write a character in to the file

Syntax: fputc(<file pointer>,variable);

Example: fputc(fp,ch);

5. fgetc( ): This function is used to read the values from a file

Syntax: <char_variable>=fgetc(<file_pointer>);

Example: ch=fgetc(fp);

Functions in conio.h:1. clrscr( ): this function is used to clear the output screen

Syntax & Example: clrscr( );

2. getch( ): This function is used to read a character but does not echoes

Syntax & Example: getch( );

Prepared By: Raju.K 12

Standard Functions

stdio.h conio.h math.h string.h

5Q: Explain various standard functions in Header files?

Page 13: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

3. putch( ): this function is used to print a character on the output screen

Syntax: putch(<char>);

Example: putch(ch);

Function in math.h:1. exp( ): this function is used to calculate the exponential(ex) value

Syntax: exp(number);

Example:exp(5);

2. pow( ): this function is used to calculate the value when a number a is raised to b (ab)

Syntax: pow(a,b);

Example: pow(2,6);

3. sqrt( ): Used to calculate the square root value of a number

Syntax: sqrt(number);

Example: sqrt(25);

4. log( ): Used to calculate the logarithmic value of a number

Syntax: log(number);

Example: log(58);

Functions in String.h:1. strcpy( ): This function is used to copy a string to another string

Syntax: strcpy(str1,str2); Here str2 will be copied in to str1

Example: strcpy(name,”Raju”);

2. strlen( ): This function is used to calculate the length of the string

Syntax: strlen(string);

Example: strlen(“Gaayathri”);

3. strcmp( ): This function is used to compare the given two string whether they are equal or

not

Syntax: strcmp(str1,str2);

Example: strcmp(“WELCOME”,”welcome”);

4. strcat( ): This function is used to concatenate the given two strings in to a single string

Syntax: strcat(str1,str2);

Example: strcat(“Sri”,”Gaayathri”);

5. strrev( ): this function is used to reverse the given string

Syntax: strrev(str1);

Example: strrev(“WELCOME”);

Prepared By: Raju.K 13

Page 14: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Array: An array can be defined as a collection of similar data items. When there is a need to store

large number of similar values the normal variables concept can not be applied due to their

implementation drawbacks. To avoid this we can use arrays. By using array we can store large

number of data values in a single variable name.

In the C Language the arrays are classified in to two types. They are 1. One dimensional

arrays 2. Two dimensional or Multi dimensional arrays.

One Dimensional Arrays: The array which consists only one dimension or only one direction is

known as one dimensional arrays. The one dimensional arrays use an index or a subscript to identify

the elements of the array. The one dimensional arrays can be represented graphically as follows.

As shown in the above diagram the one dimensional arrays can be represented. Where X is

the array name and 0,1,2,… are the index of the elements. A particular element in the array can be

identified by using the array name along with its index.

Ex: the element in the fifth position can be identified as “X[4]”.

As shown in the above diagram the array index will always starts from “0” and ends at “n-1”.

Where n is the array size.

Working with arrays:Step1: Array Declaration

Before implementing an array it should be declared in the variable declaration section of the

program along with the size of the array. The array can be declared by using the following syntax

Syntax: <data_type> <variable>[size];

Example: int X[10]; or char name[20] etc…

Prepared By: Raju.K 14

6Q: Explain One Dimensional arrays with an Example?

X[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

Page 15: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Step2: InitializationAfter declaration of an array it should be initialized, that means we have to assign the values

in to the array elements. The array initialization can be done in two different ways

a. At the time of declaration: Whenever we are declaring the array we can initialize the

array as follows.

Ex: int X[5]={6,3,8,2,5}; and these elements can be stored as follows

6 3 8 2 5

b. By using the scanf( ) function: The scanf( ) function is used to read the values from the

standard input device while executing the program. The following program demonstrates

how to initialize the array by using scanf( ) at runtime.

Ex: for(i=0;i<n;i++)

{

Scanf(“%d”,&X[i]);

}

Step 3: Accessing the array elements:

The process of using the array elements for our purpose is accessing. The accessing of array

elements will depends on the requirements of the program. The following program will

demonstrates how to calculate the sum of array elements.

Prepared By: Raju.K 15

X

[0] [1] [2] [3] [4]

Page 16: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Two Dimensional Arrays: The array which consists two dimensions or two indices is called as two

dimensional array. Unlike the one dimensional array, the two dimensional array consists more than

one rows and more than one columns. The two dimensional arrays can be declared as follows

Syntax: <data_type> <variable>[size1][size2];

Example: int M[3][4];

Where Size1 represents the number of rows and size2 represents the number of columns.

The two dimensional arrays can be represented in the memory as follows

M[0][0] M[0][1] M[0][2] M[0][3]

M[1][0] M[1][1] M[1][2] M[1][3]

M[2][0] M[2][1] M[2][2] M[2][3]

Note: If the array is declared as M[x][y], then the maximum number of elements that we can store

in the array are “x*y”.

The two dimensional arrays mostly can be used to perform the matrix operations. Let us

consider the following example that demonstrates the addition of two 2X2 Matrices

Program:main(){ int A[2][2],B[2][2],C[2][2],i,j; clrscr(); printf("Enter A Matrix elements:\n"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&A[i][j]);

printf("Enter B Matrix Elements:\n"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&B[i][j]);

for(i=0;i<2;i++) for(j=0;j<2;j++) C[i][j]=A[i][j]+B[i][j];

Prepared By: Raju.K 16

7Q: Explain two Dimensional Arrays with an Example?

Page 17: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

printf("The A Matrix is:\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%5d",A[i][j]); }printf("\n"); }

printf("The B Matrix is:\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%5d",B[i][j]); } printf("\n"); }

printf("The C Matrix is:\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%5d",C[i][j]); } printf("\n"); } getch();}

Output:

Prepared By: Raju.K 17

Page 18: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Sorting: Sorting is a process of arranging the array elements either in ascending order or in

descending order. Generally the array elements may not be presented in an order, instead they may

be in a zigzag order. In order to arrange the array elements in an order there are so many algorithms

are proposed. The general procedure of sorting array elements can be done as follows

Procedure:Iteration 1: First we select X[0] element and we compare X[0] with all the remaining elements

in the array. If any element is found less than or equals to X[0] then we interchange those two

elements. This process can be done until we reach the end of the array

Iteration 2: In the second iteration we select X[1] element and we compare it with the next

elements in the array and we swap the values if anyone is less than or equals to X[1].

…………………………Iteration I: similarly in the iteration I we select X[I] element and we compare it with the

remaining elements in the array

…………Iteration n-1: For the n-1 iteration we compare the X[n-1] element with remaining elements in

the array, finally the nth element will be in order automatically.

Example:Let us consider the following array that we need to sort. Sorting can be done by using the

swapping process. To swap the numbers we take a temporary variable

int X[5]={7,3,9,2,4};

Iteration1:

Step1:

Step2:

Step3:

Step4:

Final Array after Iteration1 is:

Prepared By: Raju.K 18

7 3 9 2 4

7 3 9 2 4

3 7 9 2 4

3 7 9 2 4

2 7 9 3 4

2 7 9 3 4

8Q: Explain the concept of Sorting of array elements with an Example?

X[1]X[0] X[2] X[3] X[4]

Page 19: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Iteration2: Step1:

Step2: Step3:

Final Array is:

Iteration3:

Step1:

Step2:

Final Array is:

Example Program:main(){ int X[5]={7,3,9,2,4},i,j,temp; clrscr(); for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(X[i]>=X[j]) {

temp=X[i];X[i]=X[j];X[j]=temp;

} } } printf("The array elements in ascending order are:"); for(i=0;i<5;i++) { printf("%4d",X[i]); } getch();}

Prepared By: Raju.K 19

2 7 9 3 4

2 7 9 3 42 3 9 7 4

2 3 9 7 4

2 3 9 7 4

2 3 7 9 4

2 3 4 7 9

Page 20: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Function Recursion:1. Generally the user defined functions can be executed by calling them from another function

which is called by main( )2. If a function is called by itself, such function call leads to recursion in the functions. So that

Function recursion can be defined as “A Function call by itself”.3. When a function is needed to execute continuously in such moment we can use the function

recursion concept

Example: Let us consider the following program that demonstrates the function recursion

int fact(int f);

main()

{

int n,fv;

clrscr();

printf("Enter any number:");

scanf("%d",&n);

fv=fact(n);

printf("The factorial value=%d\n",fv);

getch();

}

int fact(int f)

{

int x=1;

if(f==0)

return x;

else

x=f*fact(f-1);

return x;

}

Prepared By: Raju.K 20

9Q: Explain Function Recursion with an Example?

Page 21: B.com CA I Yr C-Language Notes

Sri Gaayathri Colleges Unit-II B.Com CA-I Yr. C-Language

Explanation:

The above function can be executed as follows

1. First main( ) is executed and a value can be read and supplied to fact( ) function

2. The fact function will copies the value in to a variable “f”.

3. If the “f” value is 0 then it returns 1 else it calculates x=f*fact(f-1)

4. If the statement x=x*fact(x-1) is calculated it executes as follows

5. Let us consider a number 5 is passed to fact( )

X=f*fact(f-1)

=5*fact(5-1)

=5*4*fact(4-1)

=5*4*3*fact(3-1)

=5*4*3*2*fact(2-1)

=5*4*3*2*1*fact(1-1)

=5*4*3*2*1*1 (since fact(0)=1)

=120 This can be returned to main( ) and printed as output.

Prepared By: Raju.K 21