Sunday, April 1, 2018









                  UNIT III



3.0 INTRODUCTION



There are six derived types in C: arrays, functions, pointer, structure, union and enumerated types. The function type is derived from its return type.
Figure: 3.0 Derived Types

3.1 DESIGNING STRUCTURED PROGRAMS



Whenever we are solving large programs first, we must understand the problem as a whole, then we must break it in to simpler, understandable parts. We call each of these parts of a program a module and the process of sub dividing a problem into manageable parts top-down design.



v The principles of top-don design and structured programming dictate that a program should be divided into a main module and its related modules.



v The division of modules proceeds until the module consists only of elementary process that is intrinsically understood and cannot be further subdivided. This process is known as factoring.



v Top-down design is usually done using a visual representation of the modules known as a structured chart.


Figure: 3.1 Structure Chart



3.2 FUNCTIONS IN C



A function is a self-contained block of code that carries out some specific and well-defined task.



C functions are classified into two categories



1.  Library Functions

2.  User Defined Functions



Library Functions



These are the built in functions available in standard library of C.The standard C library is collection various types of functions which perform some standard and predefined tasks.



Example: abs (a) function gives the absolute value of a, available in <math.h> header file



pow (x, y) function computes x power y. available in <math.h> header file



printf ()/scanf () performs I/O functions. Etc..,



User Defined Functions



These functions are written by the programmer to perform some specific tasks.



Example: main (), sum (), fact () etc.



The Major distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program.



3.3 USER-DEFINED FUNCTIONS



The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully.

A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program.



3.3.1 ADVANTAGES OF USER-DEFINED FUNCTIONS



  1. Modular Programming It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later.



  1. Reduction of source code The length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited.



  1. Easier Debugging It is easy to locate and isolate a faulty function for further investigation.



  1. Code Reusability a program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated.



  1. Function sharing Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program



3.3.2 THE GENERAL FORM OF A C FUNCTION




return_type function_name (argument declaration)

{

//local declarations



……

……

//statements

……



return (expression);

}



Figure: 3.2 General Form of A C Function


return-type



Specifies the type of value that a function returns using the return statement. It can be any valid data type. If no data type is specified the function is assumed to return an integer result.



function-name



Must follow same rules of variable names in C. No two functions have the same name in a C program.



argument declaration



Is a comma-separated list of variables that receive the values of the argument when function is called. If there are no argument declaration the bracket consists of keyword void.



A C function name is used three times in a program



1.  for function declaration

2.  in a function call



3.  for function definition.



3.3.3  FUNCTION DECLARATION (OR) PROTOTYPE



The ANSI C standard expands the concept of forward function declaration. This expanded declaration is called a function prototype.



A function prototype performs two special tasks.



  1. First it identifies the return type of the function so that the compile can generate the correct code for the return data.


  2. Second, it specifies the type and number of arguments used by the function.

The general form of the prototype is
Function Prototype:
Parameter names can be omitted

from the function prototype



return_type function_name (type1 name1, type2 name2,..., typen namen);



Return type and parameter types must be provided in the prototype


Semi-colon indicates that this is only the function prototype, and that its definition will be found elsewhere




Figure: 3.3 Function Prototype



Note: The prototype normally goes near the top of the program and must appear before any call is made to the function.


3.3.4 THE FUNCTION CALL



A function call is a postfix expression. The operand in a function is the function name. The operator is the parameter lists (…), which contain the actual parameters.



Example:



void main ()

{



sum (a, b);

}



When the compiler encounters the function call ,the control is transferred to the function sum().The functions is executed line by line and outputs the sum of the two numbers and returns to main when the last statement in the following has executed and conceptually, the function’s ending } is encountered.



3.3.5 FUNCTION DEFINITION


The function definition contains the code for a function. It is made up of two parts: The function header and the function body, the compound statement is must.



Parameter names are required



here – they’ll be used in the

Function header



function body









return_type function_name (type1 name1, type2 name2,…namen)


{
// local declarations
Body of the



...
function

No

// statements
appears in the

Semicol

...


definition

on

}












Figure: 3.4 Function Definition

v Function header consists of three parts: the return type, the function name, and the formal parameter list.

v function body contains local declarations and function statement.

v Variables can be declared inside function body.

v  Function can not be defined inside another function.

3.2.6 CATEGORY OF USER -DEFINEDFUNCTIONS

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:

Category 1: Functions with no arguments and no return values Category 2: Functions with no arguments and return values Category 3: Functions with arguments and no return values Category 4: Functions with arguments and return values

3.2.6.1  FUNCTIONS WITH NO ARGUMENTS AND NO RETURN VALUES

This type of function has no arguments, meaning that it does not receive any data from the calling function.Simillary this type of function will not return any value. Here the calling function does not receive any data from the called function. In effect, there is no data transfer between the calling function and the called function.
















Figure: 3.5 Functions with no arguments and no return values



Observe from the figure 3.5 that the function greeting () do not receive any values from the function main () and it does not return any value to the function main ().Observe the transfer of control between the functions indicated with arrows.



//C program to find sum of two numbers using functions with no arguments and no return values


#include<stdio.h> void sum ();



void main ()

{

clrscr ();

sum (); /*calling function */ getch ();



}

void sum ()

{

int x, y, z;



printf (“\n Enter the values of x and y: “); scanf (“%d%d”, &x, &y);

z=x+y;

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



}

3.2.6.2 FUNCTIONS WITH NO ARGUMENTS AND RETURN VALUES



There are two ways that a function terminates execution and returns to the caller.



1.     When the last statement in the function has executed and conceptually the function’s ending ‘}’ is encountered.



2.  Whenever it faces return statement.



THE RETURN STATEMENT



v The return statement is the mechanism for returning a value from the called function to its caller.



v The general form of the return statement is



return expression;



v The calling function is free to ignore the returned value. Further more, there need not be expression after the return.



v In any case if a function fails to return a value, its value is certain to be garbage.



v The return statement has two important uses



1. It causes an immediate exit of the control from the function. That is ,it causes program execution to return to the calling function.



2.  It returns the value present in the expression. example: return(x+y);



return (6*8); return (3); return;

Figure 3.6 Functions with no arguments and return values


In this category, there is no data transfer from the calling function to the called function. But, there is data transfer from called function to the calling function.



In the above example, observe from the figure 3.6 that the function getQuantity () do not receive any value from the function main ().But, it accepts data from the keyboard, and returns the value to the calling function.



// C program to find sum of two numbers using functions with no arguments and return values




#include<stdio.h> int sum ();



void main ()

{

int c; clrscr ();



c=sum (); /*calling function */ printf (“\n The sum = %d”, c);

getch ();



}

int sum ()

{

int x, y;



printf (“\n Enter the values of x and y: “); scanf (“%d%d”, &x, &y);

return x+y;

}

RETURNING VALUES FROM MAIN ()


When we use a return statement in main (), some program returns a termination code to the calling process (usually to the O.S).The return values must be an integer.


For many Operating Systems, a return value of ‘0’ indicates that the program terminated normally. All other values indicate that some error occurred. For this reason, it is good practice to use an explicit return statement.

3.2.6.3 FUNCTIONS WITH ARGUMENTS AND NO RETURN VALUES



In this category there is data transfer from the calling function to the called function using parameters. But, there is no data transfer from called function to the calling function.



Local Variables



variables that are defined within a function are called local variables.A local variable comes into existence when the function is entered and is destroyed upon exit.



Function arguments

The arguments that are supplied in to two categories


1.  actual arguments/parameters

2.  formal arguments/parameters

Actual arguments/parameters

Actual parameters are the expressions in the calling functions. These are the parameters present in the calling statement (function call).


formal arguments/parameters

formal parameters are the variables that are declared in the header of the function definition. These list defines and declares that will contain the data received by the function. These are the value parameters, copies of the values being passed are stored in the called functions memory area.



Note: Actual and Formal parameters must match exactly in type, order, and number. Their names however, do not need to match.

 Figure 3.7 Functions with arguments and no return values



 Observe from the figure 3.7 that the function printOne () receives one  value from the function main (), display the value copy of a.



 //C program to find sum of two numbers using functions with  arguments and no return values


 #include<stdio.h 
void sum (int ,int );  void main ()



 {

 int a, b;

 clrscr ();



 printf (“\n Enter the values of a and b: “); 
 scanf (“%d%d”, &a, &b);



 sum (a, b); /*calling function */  
getch ();



 }

 void sum (int x, int y)

 {

 int z;

 z=x+y;



 printf (“\n The Sum =%d”, z);



 }

Passing Parameters to Functions



There are two ways of passing parameters to the functions.



1.  call by value



2.  call by reference



call by value



When a function is called with actual parameters, the values of actual parameters are copied into the formal parameters. If the values of the formal parameters changes in the function, the values of the actual parameters are not changed. This way of passing parameters is called call by value (pass by value).



In the below example, the values of the arguments to swap () 10 and 20 are copied into the parameters x and y.Note that the values of x and y are swaped in the function. But, the values of actual parameters remain same before swap and after swap.




// C program illustrates call by value #include<stdio.h>



void swap (int , int ); void main ()



{

int a, b;

clrscr ();



printf (“\n Enter the values of a and b: “); scanf (“%d%d”, &a, &b);

swap (a, b);   /*calling function */

printf (“\nFrom main The Values of a and b a=%d, b=%d “, a, b); getch ();



}

void swap (int x, int y)

{

int temp; temp=x; x=y;

y=temp;

printf (“\n The Values of a and b after swapping a=%d, b =%d”, x, y);



}

OUTPUT

Enter the values of a and b: 10 20

Figure 3.5 Example Call by Value



The Values of a and b after swapping a=20, b=10 from main The values of a and b a=10, b=20

Note: In call by value any changes done on the formal parameter will not affect the actual parameters.



v call by reference will be discussed in UNIT IV.



3.2.6.4. FUNCTIONS WITH ARGUMENTS AND RETURN VALUES



In this category there is data transfer between the calling function and called function.






 
//C program to find sum of two numbers using functions with arguments and return values

#include<stdio.h> int sum (int ,int );

void main ()
{
int a, b;
clrscr ();

printf (“\n Enter the values of a and b: “); scanf (“%d%d”, &a, &b);

c=sum (a, b); /*calling function */ printf (“\n The Sum =%d”, c);
getch ();

}

int sum (int x, int y)
{
int z; return x+y;

}







Note: generally we are using functions with arguments and return values (category 4) in our applications. Why because the job of a function is to perform a well-defined task, it carrys inputs and sends result after executed. In real world the programming teams codes the modules (functions) according to the input (arguments) given by the team coordinators.








Figure 3.8 Functions with arguments and return values



Observe from the above figure 3.8 t the function sqrt receive one value from the function main (), finds the square of the number and sends the result back to the calling function.
//C program to find sum of two numbers using functions with arguments and return values

#include<stdio.h> int sum (int ,int );

void main ()
{
int a, b;
clrscr ();

printf (“\n Enter the values of a and b: “); scanf (“%d%d”, &a, &b);

c=sum (a, b); /*calling function */ printf (“\n The Sum =%d”, c);
getch ();

}

int sum (int x, int y)
{
int z; return x+y;

}


Note: generally we are using functions with arguments and return values (category 4) in our applications. Why because the job of a function is to perform a well-defined task, it carrys inputs and sends result after executed. In real world the programming teams codes the modules (functions) according to the input (arguments) given by the team coordinators.
3.3 STANDARD LIBRARY FUNCTIONS

C has a large set of built-in functions that perform various tasks. In order to use these functions their prototype declarations must be included in our program.

Figure 3.9 Library Functions and the Linker

The above figure shows how two of the C standard functions that we have used several times are brought into out program. The include statement causes the library header file for standard input and output(stdio.h) to be copied in to our program It contains the declaration for printf and scanf.Then,when the program is linked, the object code for these functions is combined with our code to build the complete program.

Some of the header files includes these functions are

<stdio.h> Standard I/O functions

<stdlib.h> Utility functions such as string coversion routines, memory allocation routines, etc..,

<string.h> String manipulation functions <math.h> Mathematical functions
<ctype.h> Character testing and conversion functions
3.4 NESTING OF FUNCTIONS

C permits nesting of functions, main can call function1, which calls function2, which calls function3 .., There is no limit as how deeply functions can be b=nested .

consider the following example:
#include<stdio.h> int read ();

int sum (int, in t); void main ()

{
int a, b;

printf (“%d”, sum ());

}
int sum (int x, int y)
{
x=read (); y=read ();

return x+y;
}
int read ()
{
int p;

printf (“\n Enter any value: “); Scanf (“%d”, &p);
return p;
}

In the above example ,when the main() function executes it finds the function call sum(), then the control is transferred from main() to the function sum(),here we are calling the function read(), then the control transferred to read() function,then the body of the function read() executes,the control transfered from read to sum() and once again the same is done for rading some other value. Then the addition is performed this value is carried from sum() to main().Observe the chain of control transfers between the nested functions.

3.5 RECURSION IN C

In C, functions can call themselves .A function is recursive if a statement of the function calls the function that contains it. This process is some times called circular definition.

Recursion is a repetive process, where the function calls itself.

Concept of recursive function:

v A recursive function is called to solve a problem

v The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer.

v However, if a more complex input is given, a recursive function will divide the problem into 2 pieces: a part that it knows how to solve and another part that it does not know how to solve. The part that it does not know how to solve resembles the original problem, but of a slightly simpler version.

v Therefore, the function calls itself to solve this simpler piece of problem that it does now know how to solve. This is what called the recursion step.

v The statement that solves problem is known as the base case. Every recursive function must have a base case. The rest of the function is known as the general case.

v The recursion step is done until the problem converges to become the simplest case.

v This simplest case will be solved by the function which will then return the answer to the previous copy of the function.

v The sequence of returns will then go all the way up until the original call of the function finally return the result.

Example: Recursive factorial function

Iteration definition

fact (n) =1                                                    if n=0
=n*(n-1)*(n-2)…….3*2*1  if n>0




Recursion definition



fact (n) =1      if n=0


=n*fact (n-1) if n>0









BASE CASE



GENERAL CASE

//C program to find the factorial using recursion



#include <stdio.h>


long factorial (long);
Output:

void main (void)

{
4! = 24

int i;



i=4;


printf (“%2d! = %1d\n”, i, factorial (i));


}


long factorial (long number)


{





if (number ==0) return 1;



else

return (number * factorial (number-1));



}



designing a recursive function:



In the above program, once the base condition has reached, the solution begins. The program has found one part of the answer and can return that part to the next more general statement. Thus, after calculating factorial (0) is 1, and then it returns 1.That leads to solve the next general case,



factorial (1) à 1*factorial (0) à 1*1 à 1



The program now returns the value of factorial (1) to next general case, factorial (2),



factorial (2) à 2*factorial (1) à 2*1 à 2



As the program solves each general case in turn, the program can solve the next higher general case, until it finally solves the most general case, the original problem.


The following are the rules for designing a recursive function:

1.  First, determine the base case.



2.  Then, determine the general case.

3.  Finally, combine the base case and general case in to a function.





Figure 3.10 factorial (4) recursively



Difference between Iteration and Recursion



Table 3.1 Difference between Iteration and Recursion

3.6 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 the C statements into machine code that in places in an object module.


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.



v Statements beginning with # are considered preprocessor directives.



v Preprocessor directives indicate certain things to be done to the program code prior to compilation.



v It includes certain other files when compiling, replace some code by other code.



v Only white space characters before directives on a line.



v Preprocessor commands can be placed anywhere in the program.



There are three major tasks of a preprocessor directive



1.   Inclusion of other files (file inclusion)



2.   Definition of symbolic constants and macros(macro definition)


Conditional compilation of program code/Conditional execution of preprocessor directives

Life Articles And News:

Life Articles And News: