COMPUTER PROGRAMMING (R13) Page 1 of 29

UNIT-II

Designing Structured Programs

Functions

Basics

User Defined Functions

Standard Functions

Inter function communication

Scope

Scope Rules

Storage classes-auto,register,static,extern

Type Qualifiers

Recursion

Example of Recursive functions

Preprocessor Commands

Arrays

Concepts

Using arrays in C

Interfunction Communication

Array Applications

Two Dimensional Arrays - Examples

Multi Dimensional Arrays – Examples

Designing Structured Programs

The programs that were discussed upto now are very simple. They solved problems that could be understood without too much effort. If the size of the problem to be solved is big then the complexity of problem increases and requires more no of instructions making the program big. Breaking a complex problem into smaller parts is a common practice. The big program is divided into smaller parts called as modules. Dividing the program into a main module and its related modules is called as top-down design. The above approach of solving the problems is called as designing top-down structured programs.

STRUCTURE CHART

The main module is known as calling module and the sub module is known as called module.

In C Language the above concept is implemented using Functions.

Functions

Basics-Introduction

In C, the idea of top-down design is done using functions. A C Program is made of one or more functions, one and only one of which must be named main. The execution of a program always starts and ends with main, but it can call other functions to do special tasks.

A function in C (including main) is an independent module that will be called to do a specific task. A called function receives control from the calling function. When the called function completes its task, it returns control to the calling function. It may or may not return a value to the caller. The function main is called by the operating system, main in turn calls other functions.

C Functions are of two types

They are:a) User-defined Functions

b)Library Functions

a)User-Defined Functions:

Users can create their own functions for performing any specific task of the program. These types of functions are called user-defined functions. Main() is an example of user-defined function. Every function must be both declared and defined. The function declaration, which needs to be done before the function call, gives the whole picture of the function that needs to be defined later. The function definition, which is traditionally coded after the function that makes the call, contains the code needed to complete the task.

Note : A function name is used three times : for declaration, in a call, and for definition

To create and use these functions, we should know about these three things

  1. Function Definition
  2. Function Declaration
  3. Function Call

For Example

// Function Declaration

Void greeting(void);

Int main(void)void greeting(void)

{{

//statements printf(“Hello World”);

greeting();// Function Callreturn;

return 0;}

}

Function Declaration :

A function definition, also known as function implementation shall include the following elements;

  1. Function name
  2. Function type
  3. List of parameters
  4. Local variable declarations
  5. Function statements and
  6. A return statement

All the six elements are grouped into two parts, namely,

Function header(function name, function type, list of parameters)

Function body(Local variable declarations, Function statements, a return statement)

A general format of a function definition to implement these two parts is given below:

function_typefunction_name(parameter list)

{

Local variable declarations;

Executable statement1;

Executable statement2;

……………

…………..

Return statement;

}

Function Header:

The function Header consists of the following three parts:

  1. Function Type
  2. Function Name
  3. List of parameters

Function Type:

The function type specifies the type of value(like float or double) that the function is expected to return to the program calling the function. If the return type is not explicitly specified, C will assume that it is an integer type. If the function is not returning anything, then we need to specify the return type as void. Void is one of the data type. The value returned is the output produced by the function.

Function Name:

The function name is any valid C identifier and therefore must follow the same rules of formation as other variable names in C. The name should be meaningful for the task performed by the function. However, care must be exercised to avoid duplicating library routine names or operating system commands.

List of Parameters:

The parameter list declares the variables that will receive the data sent by the calling program. They serve as input data to the function to carry out the specified task. The parameters are also called as arguments

Example: addition(int a, int b){ …. }

A function need not always receive values from the calling program. In such cases, functions have no formal parameters. To indicate the parameter list is empty, we use the keyword void between the parentheses as

Example: addition(void){ …. }

Some compilers may also accept this type of declaration.

Example:addition()

Function Body:

The function body contains the declarations and statements necessary for performing the required task. The body enclosed in braces, contains three parts, in the order given below:

  1. Local declarations that specify the variables needed by the function.
  2. Function statements that perform the task of the function
  3. A return statement that returns the task of the function.

*Note : we can omit return statement if there is no return value.

b)Library Functions(or) Standard Functions:

C has the facility to provide library functions for performing some operations. These functions are predefined and exists in the C library functions. For example sqrt() is a mathematical library function which is used to finding out the root of any number defined in math.h header file. The source code of the library functions is not given to the user. These functions are precompiled and the users gets only the object code. This object code is linked to the object code of your program by the linker. Different categories of library functions are grouped together in separate library files. When a library function in our program is called then the linker selects the code of that function from the library file and adds it to the program. Any function will have function definition, declarations and call.

Library Function:

  1. Function Definition – Predefined, precompiled
  2. Function Declaration– In header files(files with .h extension)
  3. Function Call_By the programmer.

The functions scanf() and printf() are input, output library function defined in stdio.h header file

To use a library function in our program we should know:

1)Name of the function and its purpose

2)Type and number of arguments it accepts

3)Type of the value it returns

4)Name of the header file to be included.

We use the an example of using a calculating a square root of a number.

1)Function name is sqrt for calculating square root of a number

2)It accepts integer as data type and one input parameter

3)It returns a integer value

4)It is included in the header file math.h

Example:Program used to print the square of a number.

#include<stdio.h>

#include<math.h>

Void main()

{

Int x;

X=sqrt(16);

Printf(“%d”,x);

}

In the above program there two library functions printf(),sqrt().

*Note : main() is not a library function.

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

  1. Functions with no arguments and no return values.
  2. Functions with arguments and no return values.
  3. Functions with arguments and one return value.
  4. Functions with no arguments but return a value.
  5. Functions that return multiple values.
  1. NO ARGUMENTS AND NO RETURN VALUES:

When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, 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.

No Input

No Output

2.ARGUMENTS BUT NO RETURN VALUES:

When a function has arguments, it does receive any data from the calling function. Similarly, but it does not return a value, the calling function does not receive any data from the called function. In effect, there is data transfer between the calling function to the called function, but not from the called function to the calling function.

Input a,b

No Output

The arguments in function2() of function1() are called as actual arguments i.e., a & b.

The arugments in function2() are called as formal arguments i.e., c & d.

3.ARGUMENTS WITH ONE RETURN VALUE:

When a function has arguments, it does receive any data from the calling function. Similarly, but it return a value, the calling function receive any data from the called function. In effect, there is data transfer between the calling function to the called function, and from the called function to the calling function.

Input a,b

Output sum

4.NO ARGUMENTS WITH RETURN VALUE:

When a function has no arguments, it does not receive any data from the calling function. Similarly, but it returns a value, the calling function receive any data from the called function. In effect, there is no data transfer between the calling function to the called function but data transfer exists from the called function to the calling function.

No Input

Output sum

5.FUNCTIONS THAT RETURNS MULTIPLE VALUES:

Upto now the calling function sends the data to the called functions through input parameters and receives data from the called function to the calling function through return statement. The limitation of a return statement is, it can return only one output.

In order to return multiple number of outputs i.e., data from called from function to calling function we use output parameters.

The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator (*).

Input a,b

Output s,d

Inter function Communication:

The Calling and called function are two separate entities, they need to communicate to exchange data. The data flow between the calling and called functions can be divided into three strategies

DOWNWARD FLOW UPWARD FLOW BI-DIRECTIONAL FLOW

Downward Flow:

In downward communication, the calling function sends data to the called function. No data flows in the opposite direction. In this strategy, copies of the data items are passed from the calling function to the called function. The called function may change the values passed, but the original values in the calling function remain untouched.

Example: call-by-value

#include<stdio.h>

void main()

{

int x=2,y=3,z=0;

add(x,y);

}

void add(int x,int y)

{int z;

z=x+y;

printf(“%d”,z);

}

Upward Flow:

Upward communication occurs when the called function sends data back to the called function without receiving any data from it.

Example: call-by-reference

#include<stdio.h>

void main()

{

int x=2,y=3,z=0;

modify(&x, &y);

printf((“%d%d”,x,y);

}

void modify(int *x,int *y)

{

*x=10;

*y=20;

}

Bi-directional Flow:

The strategy described for the upward direction can easily be augmented to allow the communication in both directions. The only difference is that the indirect reference must be used in both sides of the assignment variable.

#include<stdio.h>

void main()

{

int x=2,y=3,z=0;

modify(&x, &y);

printf((“%d%d”,x,y);

}

void modify(int *x,int *y)

{

*x=*x+10;

*y=*y+20;

}

SCOPE:

Scope determines the region of the program in which a defined object is visible – that part of the program in which we can use the object’s name. Scope pertains to any object that can be declared such as a variable or a function declaration.

#include<stdio.h>

void main()

{

int x=2,y=3,z=0;

add(x,y);

//main scope

if()

{

// if scope

}

}

void add(int x,int y) //global scope

{//

…………..

//Function’s scope

{

// Block scope

}

}

Variable declared in global scope are called as global variables

Variables declared in main function or sub-function are local variables to those respective functions

SCOPE RULES:

Scope Rules define the characteristics of the variables that are defined. It includes the following three characteristics of variables. They are

  1. Scope
  2. Visibility
  3. Life Time

Scope :The region of a program in which a variable is available for use.

Visibility: The program’s ability to access a variable from the memory.

Life Time: The Life time of a variable is the duration of time in which a variable exists in the memory during execution.

Rules of use:

1)The scope of a global variable is the entire program file

2)The scope of a local variable begins at point of declaration and ends at the end of the block or function in which it is declared.

3)The scope of a formal function argument is its own function.

4)The life time of an ‘auto’ variable declared in ‘main’ is the entire program execution time, although its scope is only the ‘main’ function.

5)The life of an ‘auto’ variable declared in a function ends when the function is exited.

6)A ‘static’ local variable, although its scope is limited to its function, its lifetime extends till the end of program execution.

7)All Variables have visibility in their scope, provided they are not declared again.

8)If a variable is redeclared within its scope again, it loses its visibility in the scope of the redeclared variable

STORAGE CLASSES: auto, register, static, extern

The concept of storage class modifiers is used for the purpose of efficient utilization of variables and economisation of variables. These are used to tell the compiler how the variable that follows should be stored.

The General declaration form is

Storage-specifier Data type variable name;

There are four storage class specifiers supported by C. They are

1)Auto

2)Register

3)Static

4)Extern

Auto: The variables generally declared in any function are called automatic variables. Even if the storage class is not specified they become auto by default.

For example : int a,b,c; is equal to auto int a,b,c;

The scope of these variables is that they are active only within the function in which they are declared. These are also called as ‘Local Variables’.

Ex Pgm: #include<stdio.h>

void main()

{

auto int x=2;

printf(“%d”,x);

}

Static: The variables that are declared and initialized in a function are normally initializing the variables for every function call and process further, but if we expect the function should initialize only once and process further then we go to the declaration of variable to be static.

Example:static int x;

The scope of these variables is within the function in which they are declared.

Ex pgm: : #include<stdio.h>

void main()

{

add();

add();

}

void add()

{ static int x=0;

X++;

Printf(“%d”,x);

}

Output: 1 2 3

Register: The variables generally declared in functions normally allocate the memory in the RAM type of memory. The variables declared using register allocate the memory in a ‘register’ type of memory. The speed of register type of memory is more than the speed of RAM type of memory. The declaration looks like this.

Example: register int a,b,c;

The scope of these variables is that they are active only within the functions in which they are declared.

Example Program: #include<stdio.h>

void main()

{

Register int x=2;

printf(“%d”,x);

}

Extern: The variables declared in a file are to be referenced by the variables in another files then such kind of variables can be accessed among the files by declaring the variable to be extern;

Example program:

First.csecond.h

#include<stdio.h>int m;

#include<second.h>void add()

Extern int m;{

void main()printf(“%d”, m);

{}

int m=2;

add();

}

TYPE QUALIFIERS:

Type Qualifiers are used to qualify types, modifying the properties of variables in certain ways.

Constant Type Qualifier: The keyword for the constant type qualifier is const. A constant variable is a read-only variable. A simple constant is show below

Example : const double pi = 3.14;

Volatile Type Qualifier: The volatile qualifier tells the computer that a variable may be changed by entities other than this program. Such as a variable declared for storing and updating date needs to be changed externally according to system’s time.

Example:volatile double seconds;

Restrict Type Qualifier:The restrict qualifier, which is used only with pointers, indicates that the pointer is only the initial way to access the dereferenced data. It provides more help to the compiler for optimization. Let us look at the following program segment

int * ptr;

int a=0;

ptr=&a;

*ptr +=4;

.....

*ptr +=5;

......

Here, the compiler cannot replace two statements *ptr +=4 and *ptr +=5 by one statement *ptr +=9 because it does not know if the variable a can be accessed directly or through other pointers. Now, let us look at the same program fragment using the restrict qualifier

restrict int * ptr;

int a=0;

ptr=&a;

*ptr +=4;

......

*ptr +=5;

.....

Here, the compiler can replace the two statments by one statement *ptr +=9, because it is sure that variable 'a' cannot be accessed through any other resources.