Вы находитесь на странице: 1из 35

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Functions
Top Down Design
When we consider larger programs, it is not possible to understand all aspects of such programs without reducing them to smaller parts. The planning for large programs is as follows Understand the problems as a whole Break it into simpler, understandable parts. Solve individual parts and combine them.

Each part of a program is termed as module. The process of sub-dividing a problem into manageable parts is called top-down design. In top-down design, a program is divided into a main module and its related modules. Each module in turn is divided into sub modules until the resulting modules are intrinsic; that is until they are implicitly understood without further division. This process is known as factoring. Top-down design is usually done using a visual representation of the modules known as a structure chart. The structure chart shows the relation between each module and its sub-modules. The structure chart is read top-down, left-right. The reading starts from main module followed by reading of sub-modules of main from left to right. The main module is called calling module because it has sub modules. The sub modules are known as called modules. Communication between modules in a structure chart is allowed only through a calling module. No communication takes place directly between modules that do not have a calling-called relationship. The technique used to pass data to a function is known as parameter passing. The parameters are contained in a list that is a definition of data passed to the function by the caller.

Functions in C
In C, idea of top-down is done using functions. A C program is made of one or more functions, one and only one of which be called main. The execution of the program always starts with main, but it can call other functions to do some part of job. Definiton : A function is an independent module that will be called to do a specific task. Advantages of functions: 1. Problem can be factored into understandable and manageable parts.

2. Provides a way to reuse code that is required in more than one place in a program.
3. Used to protect data. Local data in function is available only to function when it is executing. When the function is not running, the data are not accessible. 4. Improve the code efficiency and saves programming effort. Functions mainly classified into two categories. They are as follows 1. Library Functions (System defined functions)
I YEAR B.TECH MECH

Page 1

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

2. User Defined Functions Library functions are prewritten and precompiled by the compiler vendor and come along with the compiler software as the library of functions. Ex. printf(), scanf(), clrscr() etc The functions defined by the user are termed as user defined functions. There are three steps involved in creating and using a user defined functions. They are Function Declaration Function Definition Function Call

Function Declaration Function declarations consists only of a function header, they contain no code. The header consists of three parts: the return type, the function name and the formal parameters list. The function definition is terminated with a semi-colon. The return type and parameter list are required entries. If the program has no return type, we write void as function return type. Function name is user defined name just like any other C variable name. If there are no parameters to a function, we can code void in parenthesis. If a function have multiple parameters, we separate each type-identifier with commas. The C standard does not require identifier names in a function declarations formal parameters. Syntax : Example : return_type function-name(formal_parameters_list); (or) int sum(int, int);

int sum(int a, int b); arguments of integer data types.

Here sum is function name and the function returns integer value. The functions take two Example : void sum(void) Here sum is function name and the function dont return any value. The functions have no parameters. So void is coded in parentheses. The function declarations are placed in the global declaration section before main. Grouping all the function declarations at the beginning of the program makes them available whenever they are needed. Function declarations also provide an excellent quick reference for functions used in the program, making them excellent documentation. Function Definition In function definition, we write the actual lines of code required to accomplish the task assigned to the function. It is made up of two parts: the function header and the function body. The function header consists of return type, function name and formal parameter list. A semi colon is not used at the end of the function header. The return type specifies the data type of the value being returned by the function. If the program has no return type, we write void as function return type.

I YEAR B.TECH MECH

Page 2

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Function name is user defined name just like any other C variable name. All rules of variables are applicable for function name. The function name in function declaration statement and function definition header need not to be same but the return type must be same. The formal parameter list defines and declares the variables that will contain the data received by the function. The parameter list is always required. If the function has no parameters that is, if it does not receive any data from the calling function, then void is coded in parentheses. The function body is a compound statement i.e. it must have opening and closing braces. It contains the local declarations and function statements. After function statements, a return statement can be coded. If a function return type is void, it can be written without return statement. Syntax : return-type function-name(formal-parameter-list) { // Local Declarations //Lines of code; }

Example:

int sum(int x, int y) { int z; z = x+y; return z; } In the above example, sum is the function accepting two parameters int x, int y named as x, y of integer data type. The function sum performs addition of two number and return the result value with help of statement return z. As the function returns an integer value the data-type of function is given as int. Function Call Function call is a statement we use in your programs to invoke the services of the function. A function call is a postfix expression. The operand in a function call is the function name; the operator is the parentheses, which contain actual parameters. The actual parameters identify the values that are to be sent to the called function. They match the functions formal parameters in type and order in the parameter list. If there are multiple actual arguments, they are separated by commas. Syntax : Example function-name(actual-parameters-list); sum(10,20); Here we are calling the function named sum by passing two values 10 & 20 Note : There are many different ways to call a function. Return Statement A function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass any number of values to the called function, the called function can return only a single value per call, at the most. A return statement terminates a function. When there is no return statement at the end of function, the system inserts one with a void return value.

I YEAR B.TECH MECH

Page 3

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Syntax : Example :

return expression. return 1; return z; return (a+b); // 1 is a value // z is a variable // (a+b) is an expression

Working of Function Example: void sum(int , int ); int a,b; void main() { int num1, num2; -----; sum(num1,num2); -----; } void sum(int x,int y) { ------; } (Function Declaration) (Global Variable Declartion) (Local Variable Declaration) (Function Call) (Function Definition)

Calling Function : A function which makes call to another function is termed as calling function. In the above example, main() is defined as calling function. i.e. it makes a call to function named sum(). Called Function : A called function receives control from a calling function. When the called function completes it task, it returns control o the calling function. It may or may not return a value to the caller. In the above example, sum() is defined as called function. This function is being called from main() function. Actual Parameters : The actual parameters are the expressions in the calling statement. In the example num1,num2 are actual parameters. Formal Parameters : The variables that are declared in the header of the function definition are called formal parameters. In the example x, y are called formal parameters. Note : Formal and actual parameters must match exactly in type, order and he number. Their names, however do not need to match. Local Variables : The local variables are defined inside a function and used without having any role in the communication between functions. The variable defined is local to that function or block only. Other functions can not access these variables. In the above example num1, num2 are local variables to the function main(), x,y are local variables to the function sum(). Global Variables : The global variables are defined outside the main() function and used for communication between functions. The global variables can be used by multiple functions in the program. In the above example a,b are global variables. Basic Function Designs

I YEAR B.TECH MECH

Page 4

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Functions are classified based on their return values and their parameter lists. Functions either return a value or they dont. Functions that dont return a value are known as void functions. Functions may have parameters or they dont. Combining return types and parameter lists results in following four basic designs. 1. void Functions without Parameters 2. void Functions with Parameters 3. Non-void Functions without Parameters 4. Non-void Functions with Parameters 1. void Functions without Parameters Neither the data is passed through the calling function nor the data is sent back from the called function. There is no data transfer between calling and the called functions. The function is only executed and nothing is obtained. /*Program to add sum of two numbers using functions */ #include<stdio.h> void sum(); void main() { clrscr(); sum(); getch(); } void sum(void) { int a,b,c; printf("Enter two numbers :"); scanf("%d%d",&a,&b); c=a+b; printf("Sum = %d",c); } Output Enter two numbers : 20 30 Sum = 50 2. void Function with Parameters Parameters are passed through the calling function. The called function operates in the values. But no result is sent back. Such functions are partly dependent on calling function. The result obtained is utilized by the called function and there is no gain to main(). /* Program to calculate sum to two numbers */ #include<stdio.h> void sum(int,int); void main() { int a,b,result; clrscr(); printf("Enter two numbers :"); scanf("%d%d",&a,&b); sum(a,b); getch(); } void sum(int x, int y) {
I YEAR B.TECH MECH

Page 5

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

} Output Enter two numbers : 12 13 Sum = 25

int z; z=x+y; printf("Sum = %d",z);

3. Non-void Functions without Parameters No parameters are passed from the calling function, but the called function returns the values. The called function is independent. It reads values from the keyboard or generates from initialization and returns the value. Here both calling and called functions are partly communicated with each other. /* Program to calculate sum of two numbers */ #include<stdio.h> int sum(); void main() { int result; clrscr(); result = sum(); printf("Sum = %d",result); getch(); } int sum(void) { int a,b,c; printf("Enter two numbers :"); scanf("%d%d",&a,&b); c=a+b; return c; } Output Enter two numbers : 20 32 Sum = 52 4. Non-void Functions with Parameters The data is being sent from calling function to called function in terms of parameters. The called function does the operations based on the data received and returns back the result to the calling function. Here the communication between calling and called function is fully utilized. /*Program to calculate sum of two numbers */ #include<stdio.h> int sum(int,int); void main() { int a,b,result; clrscr(); printf("Enter two numbers :"); scanf("%d%d",&a,&b); result = sum(a,b); printf("Sum = %d",result); Page 6

I YEAR B.TECH MECH

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

getch(); } int sum(int x, int y) { int z; z=x+y; return z; } Output Enter two numbers : 12 13 Sum = 25

Inter Function Communication


Although calling and called functions are two different entities, they need to communicate to exchange data. The data flow is classified into three strategies. They are 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 unchanged. C language uses pass-by-value mechanism to implement this communication. A variable is declared and defined in the called function for each value to be received from the calling function. The calling function sends a copy of each value to the called function; no data flows upward. /* Program to demonstrate pass by value mechanism (or) downward communication */ void downFun(int,int); void main() { int a=10,b=20; clrscr(); printf("Before Function : a = %d, b = %d",a,b); fun(a,b); printf("\nAfter Function : a = %d, b = %d",a,b); } void downFun(int x, int y) { printf("\nIn function before operation: x = %d, y = %d",x,y); x = x * 10; y = y * 10; printf("\nIn function after operation: x = %d, y = %d ",x,y); } Output: Before Function : a= 10, b = 20 In function before operation : x = 10, y = 20 In function after operation : x = 100, y = 200 After Function : a = 10 , b = 20 Rules
I YEAR B.TECH MECH

Page 7

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Use values in the function call to pass data. Use appropriate data types in the function parameter list to receive the data values. Use the parameter identifiers in the called function to access the local copies of the data.

Upward Flow Upward communication occurs when the called function sends data back to the called function with our receiving any data from it. A good example is when the called function reads data from keyboard that needs to be passed back to the called function. C provides only one upward direction flow, i.e. return statement. While it works well, only one data item can be returned. The only way that a called function can pass multiple data items up to the calling function is to access variables in the calling function and deposit there. This is done by calling function by passing address of variable to the called function. Given the variables address, the called function can then put the data in the calling function. The calling function needs to declare a data variable to receive the data. The called function needs to declare a variable to store the address that it receives from the calling function. In C, a variable can store data of different type. But here the called function needs a special variable which stores the address of variable. It is called as pointer variable. To pass address of a variable, we use address operator(&). To receive the address of variable we use asterisk(*) after the type. Asterick(*) is known as indirection operator. The mechanism used for this communication is pass-by-reference mechanism. /* Program to demonstrate the usage of upward communication*/ void upFun(int*,int*); void main() { int a,b; clrscr(); fun(&a,&b); printf("\nAfter Function : a = %d, b = %d",a,b); } void upFun(int *x, int *y) { *x = 28; *y = 38; printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y); } Output: In function after operation : *x = 28, *y = 38 After Function : a = 28 , b = 38 Rules

Use &variableName in the function call to pass a reference to the variable. Use type* in the function parameter list to receive the variables address. Use *parameterName in the function to reference the original variable.

I YEAR B.TECH MECH

Page 8

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Bi-directional Flow Bi-directional communication occurs when the calling function sends data down to the called function. During or at the end of its processing, the called function then sends data up to the calling function. For example, the calling function may send data to the called function, which it manipulates and sends up the calling function. The strategy used for upward direction can be augmented to allow the communications in both directions. The only difference is that the indirect reference must be used in both sides of the assignment statement. The variable in the called function first is accessed for retrieving using address variable in the right hand side. The same parameter is accessed again to sore a vale in the left-hand side. The mechanism used for this communication is pass-by-reference. /* Program to demonstrate the usage of birectional communication*/ void biFun(int*,int*); void main() { int a=10,b=20; clrscr(); printf("Before Function : a = %d, b = %d",a,b); biFun(&a,&b); printf("\nAfter Function : a = %d, b = %d",a,b); } void biFun(int *x, int *y) { printf("\nIn function before operation: *x = %d, *y = %d",*x,*y); *x = *x * 5; *y = *y * 5; printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y); } Output: Before Function : a= 10, b = 20 In function before operation : *x = 50, *y = 100 In function after operation : *x = 50, *y = 100 After Function : a = 50 , b = 100 /* Program to exchange two numbers using functions*/ void xChange(int*,int*); void main() { int a,b; clrscr(); printf("Enter two numbers :); scanf(%d%d,&a,&b); printf(\nBefore Function : a = %d, b= %d,a,b); xChange(&a,&b); printf("\nAfter Function : a = %d, b = %d",a,b); } void xChange(int *x, int *y) { int temp; printf("\nIn function before operation: *x = %d, *y = %d",*x,*y); temp = *x; *x = *y; *y = temp; printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y); } Output:

I YEAR B.TECH MECH

Page 9

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Enter two numbers : 44 55 Before Function : a = 44, b = 55 In function before operation : *x = 44, *y = 55 In function after operation : *x = 55, *y = 44 After Function : a = 55 , b = 44

Recursion Function
Two approaches are used to write repetitive algorithms. One approach uses loops, the other uses recursion. Recursion is a repetitive process in which a function calls itself. Some older languages like COBOL do not support recursion. A repetitive function is defined recursively whenever the function appears within the definition itself. All recursive functions have two elements : each call either solves one part of the problem or it reduces the size of the problem. The statement that solves the problem is known as base case. Every recursive function must have a base case. The rest of function is known as the general case. Rules for designing a Recursive Function

First, determine the base case. Then, determine the general case. Finally combine the base case and general case into a function

Limitations of Recursive Functions Recursion solutions involve extensive overhead because they use function calls. Each time we make a call, it uses some of memory allocation. If the recursion is deep, that is, if the program has a large number of recursive calls, then we may run out of memory. Examples 1. Factorial of a number The factorial function can be defined recursively. Factorial (n) = 1 n * factorial (n-1) int fact(int); void main() { int num,res; clrscr(); printf("Enter a number :"); scanf("%d",&num); res = fact(num); printf("Factorial = %d",res); } int fact(int n) { int f=1; if(n==0) return 1;
I YEAR B.TECH MECH

if n=0 if n>0

1./*Program to find factorial of a number using recursion function */

Page 10

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

} Output: Enter a number : 5 Factorial = 120

else { f = n * fact(n-1); return f; }

In this example, the base case is return 1 statement. The general case is return f i.e. n* fact(n-1) statement. In this problem, once the base case has been reached, the solution begins. The program has found one part of the answer and can return that part to the next more general statement. As, the program solves each general case, the program can solve the next higher general statements until it finally solves the most general case, the original problem. 2. Fibonacci Series The Fibonacci series for few numbers is as follows 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 The function of Fibonacci series is Given : Fibonacci0 = 0 Fibonacci1 = 1 Then : Fibonacci n = Fibonacci n-1 + Fibonacci n-2 /*Program to print Fibonacci series using recursion function */ int fib(int); void main() { int n,i; clrscr(); printf("Enter a number :"); scanf("%d",&n); for(i=0; i<=n; i++) printf(%d, fib(i)); } int fib(int num) { if(num==0 || num==1) return num; else return (fib(num-1)+ fib(num-2)); } Output: Enter a number : 8 Fibonacci Series : 0 1 1 2 3 5 8 13 21 3. Towers of Hanoi According to legend, the monks in a remote monastery knew how to predict when the world would end. They had a set of three diamond needles. Stacked on the first diamond needle were 64 gold disks of decreasing size. The monks moved one disk to another needle each hour, subject to the following rules a) Only one disk could be moved at a time

I YEAR B.TECH MECH

Page 11

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

b) A larger disk must never b stacked above a smaller one. c) One and only one auxiliary needle could be used for the intermediate storage of disks. Generalized solution for problem is 1) Move n-1 disks from source to auxiliary needle. 2) Move one disk from source to destination needle. 3) Move n-1 disks from auxiliary to destination needle. (General Case) (Base Case) (General Case)

Our solution requires four parameters : the number of disks to be moved, the source needle, the destination needle, and the auxiliary needle. Using the above pseudo code, three moves are 1) Call Towers(n-1, source, auxiliary, destination) 2) Move one disk from source to destination 3) Call Towers(n-1, auxiliary, destination, source) /* Program to implement Towers of Hanoi using Recursion function*/ void towers(int, char, char, char); void main() { int num; clrscr(); printf(Enter number of disks :); scanf(%d,&num); towers(num, A,C,B); } void towers(int n, char src, char dest, char aux) { if(n==1) printf(Move from %c to %c\n,src,dest); else { towers(n-1, src, aux, dest); printf(Move from %c to %c\n,src,dest); towers(n-1, aux, dest, src); } } Output Enter number of disks : 3 Move from A to C Move from A to B Move from C to B Move from A to C Move from B to A Move from B to C Move from A to C

Standard Library Functions


C provides a rich collection of standard functions whose definition have been written and are ready to be used in our programs. To include functions, we must include their function declarations. The function declarations for these functions are grouped together and collected in several header files. Instead of adding individual function declarations of each function, we simply include the headers at the top of our file. Math Functions

I YEAR B.TECH MECH

Page 12

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Many important library functions are available for mathematical calculations. Most of the function declarations for these functions are in either math header file (math.h) or functions are found in stdlib.h. 1) Absolute Value functions An absolute value is the positive rendering of the value regardless of its sign. There are three integer functions and three real functions.The integer functions are abs, labs, llabs. The real functions are fabs, fabsf, fabsl. Examples are abs(6) fabs(-3.4) returns 6 returns 3.4 standard library (stdlib.h). In general, the integer

Function Prototype int abs(int number); long labs (long number); long long llabs(long long number); double fabs(double number); float fabsf(float number); long double fabsl(long double number); 2) Ceiling Function

Library stdlib.h stdlib.h stdlib.h math.h math.h math.h

A ceiling is the smallest integral value greater than or equal to a number. Although the ceiling functions determine an integral value, the return type is defined as a real value that corresponds to the argument. Examples ceil(-1.9) ceil(1.1) returns 1.0 returns 2.0 Function Prototype float ceilf(float number); double ceil(double number); long double ceill(long double number); 3) Floor Functions A floor is the largest integral value that is equal to or less than a number. Examples floor(-1.1) returns floor(1.9) returns -2.0 1.0 Library math.h math.h math.h Library math.h math.h math.h

Function Prototype float floorf(float number); double floor(double number); long double floorl(long double number); 4) Truncate Functions

I YEAR B.TECH MECH

Page 13

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

The truncate functions returns the integral in the direction of 0. They are the same as floor function for positive numbers and the same as ceiling function for negative numbers. Examples trunc (-1.1)returns -1.0 trunc (1.9) returns 1.0 Function Prototype float truncf(float number); double trunc(double number); long double truncl(long double number); 5) Round Functions The round functions return the nearest integral value. Examples round (-1.1)returns -1.0 round (1.9) returns 2.0 round(-1.5) returns -2.0 Function Prototype float roundf(float number); double round(double number); long double roundl(long double number); long int lround(double number); long int lroundf(float number); long int lroundl(long double number); long long int llround(double number); long long int llroundf( float number); long long int llroundl(long double number); 6) Power Function The power function returns the value of the x raised to the power y i.e. x y. An error occurs if he base is negative and the exponent is not an integer, or if the base is zero and the exponent in not positive. Examples pow(3.0, 4.0) pow(3.4, 2.3) returns 81.0 returns 16.68893 Library math.h math.h math.h Library math.h math.h math.h stdlib.h stdlib.h stdlib.h stdlib.h stdlib.h stdlib.h Library math.h math.h math.h

Function Prototype float powf(float n1, float n2); double pow(double n1, double n2); long double powl(long double n1, long double n2); 7) Square Root Function

The square root functions return the non-negative square root of a number. An error occurs if the number is negative. Examples sqrt(25) returns 5.0 Function Prototype float sqrtf(float
I YEAR B.TECH MECH

number); Page 14

Library math.h
N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

double sqrt(double number); long double sqrtl(long double number); Random Numbers

math.h math.h

A random number is a number selected from a set in which all members have the same probability of being selected. Random numbers are useful in many areas of Computer Science. Two examples are application testing and gaming. C provides tow functions to build random number series. They are seed random (srand) and random (rand) functions. These functions are found in stdlib.h 1)Seed Random Number Function The seed random function creates the starting seed for a number series. The function declaration is void srand(unsigned int seed); Examples 1) srand(997) Generates the same number series in each run, we can either omit srand or we can provide a constant seed random, preferably a prime number such as 997. 2) srand(time(NULL)) Generates the different series in each run, we use the time of day as seed. C call fo the time which requires the time.h library. 2) Random Number Function The random number function returns a pseudorandom integer between 0 and RAND_MAX, which is defined in the standard library as the largest number that rand can generate. Each call generates the next number in a random number series. The function declaration is int Example rand(void); rand();

/* Program to generate random numbers in range 10-20 */ #include<stdio.h> #include<stdlib.h> #include<time.h> void main() { int range; srand(time(NULL)); range = (20 10) + 1; printf(Random Numbers :%d\t, rand() % range + 10); printf(%d\t, rand() % range + 10); printf(%d, rand() % range + 10); } Output Random Numbers : 10 11 16

-o0o-

I YEAR B.TECH MECH

Page 15

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Storage Classes
Scope
Scope determines the region of the program in which a defined object is visible that is, the part of the program in which we can use the objects name. Scope pertains to any object that can be declared, such as variable or a function declaration. Scope is a source program concept. It has no direct bearing on run-time program. Statements enclosed in the set of braces are called a block. A function body is enclosed in set of braces, thus a body is also a block. An objects scope extends from its declaration until the end of its block. A variable is in scope if it is visible to the statement being examined. Variables are in scope from their point of declaration until the end of block. Global Scope The scope of object defined in the global area of program is termed as global scope i.e. the objects scope is up to end of the program. Global scope variables are visible every where in the program. Local Scope Variables defined within a block have local scope. They exist only from the point of their declaration until the end of the block (usually a function) in which they are declared. Outside the block they are invisible.

Object Storage Attributes


Storage class specifiers control three attributes of an objects storage. They are scope, extent and linkage. Scope Scope defines the visibility of an object; it defines where an object can be referenced. In C, an object can have four levels of scope. They are block, file, function and function-prototype. When scope of object is block, it is visible only in the block in which it is defined. When scope of object is file, it is visible through the entire source file. When the scope of object is function, it is visible in that function body in which it is declared. Extent The extent of an object defines the duration for which the computer allocates memory for it. The extent of an object is also known as storage function. In C, an object can be automatic, static extent or dynamic extent. An object with an automatic scope is created each time its declaration is encountered and is destroyed each time its block is exited. An object with a static extent is created when the program is loaded for execution and destroyed when execution stops. An object with dynamic extent is created by the program through the malloc and its related library functions. Linkage
I YEAR B.TECH MECH

Page 16

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

A large application broken into modules, with each module potentially written by programmer in separate source file with its own objects. Different modules ma be related when the program is link edited. In C, linkage can be of two types: internal and external. An object with an internal linkage is declared and visible in one module. Other modules refer to this object. An object with an external linkage is declared in one module but is visible in all other modules that declare it with a special keyword extern.

Storage Classes
Based on the object storage specifiers, C classifies four storage classes. They are auto, register, static and extern storage classes. Auto Variables A variable with an auto specification has the following characteristics Scope = Block Extent = Automatic Linkage = Internal By defining a variable as auto storage class, it is stored in the memory. The default value of the variable will be garbage value. To define a variable as auto storage class, the keyword auto is used. Syntax : Example : auto data_type auto int a; variable_name;

Note : The keyword auto is not mandatory because the default storage class in C is auto. /*Program to illustrate use of automatic storage class*/ void divert(); void main() { int i=0; clrscr(); divert(); printf("%d\n",i); divert(); printf("%d\n",i); getch(); } void divert() { int i=0; i=i+2; printf("%d\n",i); } Output 2 0 2 0 Register Variable

I YEAR B.TECH MECH

Page 17

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

A variable with a register specification has the following characteristics Scope = Block Extent = Automatic Linkage = Internal By defining a variable as register storage class, it is stored in the CPU register. The time required to access a CPU register is significantly less than the time required to access a memory location. The default value of the variable will be garbage value. To define a variable as register storage class, the keyword auto is used. Syntax : Example : register data_type register int a; variable_name;

/* Program to illustrate the usage of register variable */ void main() { register int i; clrscr(); for(i=1; i<=5; i++) printf("%3d",i); } Output 1 2 3 4 5 Static Variables A variable with a static specification has the following characteristics Scope = Block (or) File Extent = Static Linkage = Internal When a variable is declared as static, it is stored in memory. The default value of the variable will be zero. A static variable can be initialized only once, it cannot be reinitialized. To define a variable as static storage class, the keyword static is used. Syntax : Example : static data_type static int a; variable_name;

/*Program to illustrate the usage of static variables */ void divert(); void main() { clrscr(); divert(); printf("In main()"); divert(); getch(); } void divert() { static int i; i = i+2; printf("\nThe static value in function = %d",i); }
I YEAR B.TECH MECH

Page 18

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Output The static value in function = 2 In main() The static value in function = 4

Extern Variables A variable with a extern specification has the following characteristics Scope = File Extent = Static Linkage = Internal When a variable is declared as extern, it is stored in the memory. The default value is initialized to zero. An extern variable is also called as global variable. To define a variable as extern storage class, the keyword extern is used. Syntax : Example : extern data_type extern int a; variable_name;

/*Program to show the working of external variable */ extern int v=10; void divert(); void main() { clrscr(); printf("In main() : %d",v); divert(); getch(); } void divert() { v=v+3; printf("In divert() : %d",v); } Output : In main() : 10 In divert() :13

Type Qualifiers
C provides three type qualifiers const, volatile and restrict. Const, volatile can be applied to any variables, but restrict qualifiers may only applied to pointer. Const Variable A variable value can be made unchanged during program execution by declaring the variable as constant. The keyword const is placed before the declaration. For a const pointer, place the keyword between * and identifier. Ex : const int a; int * const x; In the above example, the pointer to x is constant. The value that x points can be changed, but the value of x cannot be changed. Here a is a constant and its value cannot be changed.

I YEAR B.TECH MECH

Page 19

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Volatile Variable Variables that can be changed at any time by external programs or the same program are called volatile variables. The keyword volatile is placed before declaration. To make a variable value changeable by the current program and unchangeable by other programs, declare the variable, declare it as volatile and constant. Ex : volatile int x; int * volatile z;

The variable x and pointer variable z can be changed by any program at any time. volatile const int y; The variable y can be changed by current program but not by external program. Restrict Variable The restrict type qualifier may only be applied to a pointer. A pointer declaration that uses this type qualifier establishes a special association between the pointer and the object it accesses, making the pointer and expressions based on that pointer, the only ways to directly or indirectly access the vale of that object. The restrict type qualifier is an indication to the compiler that, if the memory addressed by the restrict qualified pointer is modified, no other pointer will access that same memory. Ex : int * restrict z;

-o0o-

I YEAR B.TECH MECH

Page 20

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Preprocessor Directives
Preprocessing is one of the step involved in the process of compilation of C program. The preprocessor is a program that processes the source program before it is passed on the compiler. The source code is given to preprocessor that includes some directive definitions and then passes it to the compiler. One of the most important features of C language is to offer preprocessing commands. The preprocessor commands are always initialized at the beginning of the program. It begins with a symbol (#) hash. It can be placed anywhere quite often it is declared at the beginning before the main() function or any particular function. The #define directive This directive is used to define macro templates. The macro templates generally declared with capital letters for quick identification. One can define macros with small letters. Syntax : #define Example : #define identifier MAX 50 <substitute text>

In the above example, during preprocessing the preprocessor replaces every occurrence of MAX with 50. The macro templates and its expansions must be separated by blank space. It is not necessary to provide space between # and define. It is optional to programmer. The macro definition can be terminated with semi-colon and it is optional. /*Program to demonstrate #define directive*/ #define cls clrscr() #define display printf #define greater > #define MAX 50 #define square(a) a*a void main() { int a=5; cls; if(a greater MAX) display(%d is greater,a); else display(%d is greater,MAX); display(\nSquare = %d,square(10)); } Output 50 is greater Square = 100 The #undef directive

I YEAR B.TECH MECH

Page 21

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

A macro defined with #define directives can be undefined with #undef directive. It is useful when we do not want to allow the use of macros in any portion of the program. Syntax : #undef Example : #undef Stringizing Operators In this operation macro argument is converted to the string. The sign # carries the operation. It is placed before the argument. /*Program to carry out stingizing operation*/ #define say(m) printf(#m) void main() { clrscr(); say(Hello); } Output : Hello In the above program, after conversion the statement say(Hello) is treated as printf(Hello). It is not essential to enclose the text in quotation marks in the stringizing operator. The #include directive The #include directive loads specified file in the current program. The macros and functions of loaded file can be called in the current program. The included is file is also compiled with the current program. Syntax : Examples : #include <filename> #include<stdio.h> #include string.h Conditional Compilation directives The most frequently used conditional compilation directives are #ifdef, #else, #endif, #ifndef etc. These directives allow the programmer to include the portion o the codes based on the conditions. The compiler compiles selected portion of the source code based on conditions. Syntax : #ifdef #else Statements; #endif The #ifdef preprocessor tests whether the identifier has defined substitute text or not. If the identifier is defined then #if block is compiled and executed. The compiler ignores #else block even if errors are intentionally made. Error messages will not be displayed. The #ifndef preprocessor works exactly opposite to the #ifdef. The #ifndef preprocessor tests whether the identifier has defined substitute text or not, if the identifier is defined then #else block is compiled and executed. <identifier> Statements; (or) #include filename identifier MAX

I YEAR B.TECH MECH

Page 22

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

/*Program to demonstrate use of conditional compilation directives*/ #define MAX 50 void main() { clrscr(); #ifdef MAX printf(Max = %d,MAX); #else printf(MAX is not defined); #endif } Output Max = 50 The #error directive The #error is used to display user defined message during compilation of program. The syntax is as follows #error The #line directive The syntax of line directive is as follows #line <constant> <identifier> It causes the compiler to imagine the number of the next source line as given by <constant> and <identifier> gives the current input file. If <identifier> is absent, then current file name remains unchanged. Example : #line 15 sample.c <error message>

Predefined Macros in ANSI and Turbo C


1) ANSI C predefined Macros The list of pre-defined macros according to ANSI standard are as follows Predefined Macros _DATE_ _TIME_ _LINE_ _FILE_ _STDC_ Function Displays system data in string format Displays system time in string format Displays line number as integer Displays current file name in string format In ANSI C the value returned will be non-zero

There are five pre-defined macros and are always visible to the programmer for use. They can not be undefined. Every macro name is defined with two underscores as prefix and suffix. The macros are useful for finding system information such as date, time, file name and line number. 2) Turbo C predefined Macros The pre-defined macros in Turbo C are listed in the table. Predefined Macros _TURBOC_ _PASCAL_ _CDECL_ Function Displays current turboc version. 1 if Calling convention pascal options chosen, other wise undefined 1 if Calling convention .C option is chosen,

other wise undefined. _MSDOS_ The integer constant 1. By setting option of code generation in option menu one can test next two macros.
I YEAR B.TECH MECH

Page 23

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

3) Memory Model Macros The following six macros are defined based on the memory models chosen by the user. There are six memory models and only one is defined which is currently in use and remaining all are undefined.

Predefined Macros _TINY_ _SMALL_ _MEDIUM_ _COMPACT_ _LARGE_ _HUGE_ Standard I/O Predefined Streams in stdio.h The predefined streams automatically opens when the program is started. The following table describes their macro expansion defined in stdio.h header file. Macros stdin stdout stderr stdaux stdprn The Predefined Macro in ctype.h The header file ctype.h contains a set of macros that checks character. The following table describes all the macros. These macros take an argument of integer type and return an integer. Macros isalpha(d) isupper(d) islower(d) isdigit(d) isalnum(d) isxdigit(d) isspace(d) ispunct(d) isprint(d) isgraph(d) iscntrl(d) isascii(d) Returns true(!0) value if d is a letter d is a capital letter d is a small letter d is a digit d is a letter or digit d is a hexadecimal digit d is a space d is a punctuation symbol d is a printable character d is printable, but not be a space d is a control character d is an ASCII code Definition Standard Input Device Standard Output Device Standard error Output Device Standard Auxiliary Device Standard Printer

-o0o-

Arrays

I YEAR B.TECH MECH

Page 24

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Array is a collection of similar data types in which each element is unique one and located in separate memory locations. Declaration of Array data-type array-variable[size]; Ex : int a[10]; char ch[10]; float avg[10]; The first example tells to the compiler that a is an integer type of array and can store 5 integers. The compiler reserves 2 bytes of memory for each integer array element. Total space of 10 bytes are allocated to variable a Array Initialization The array initialization is done is given below int a[5] = {12, 14, 16, 17, 18}; Here 5 elements are stored in an array a. The array elements are stored sequentially in separate locations. Reading of array elements begins from 0. Array elements are called by array names followed by the element numbers. The 5 elements are referred as Subscripted variable a[0] refers to the first element of array a, 12 i.e. a[0]=12 Subscripted variable a[1] refers to the first element of array a, 14 i.e. a[1]=14 Subscripted variable a[2] refers to the first element of array a, 16 i.e. a[2]=16 Subscripted variable a[3] refers to the first element of array a, 17 i.e. a[3]=17 Subscripted variable a[4] refers to the first element of array a ,18 i.e. a[4]=18 If the array size is declared as 5. The elements are stored from index 0 to 4. i.e. If a[5] has been declared, then values are stored from a[0] to a[4]. The integer enclosed in brackets is the array subscript, and its value must be in the range from zero to one less than the number of memory cells in the array. Sample Programs 1. /*Program to read an array of 10 numbers and print them */ void main() { int a[10],i; clrscr(); printf("Enter 10 values :"); for(i=0; i<10; i++) scanf("%d",&a[i]); printf("Given Values :"); for(i=0; i<10; i++) printf("%3d",a[i]); } Output Enter 10 values ; 21 22 23 24 25 26 27 28 29 30 Given Values : 21 22 23 24 25 26 27 28 29 30 2./* Program to calculate the sum and average of six subject marks using arrays */
I YEAR B.TECH MECH

Page 25

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

void main() { int a[10],i,sum=0; float avg; clrscr(); printf("Enter 6 subject marks :"); for(i=0; i<6; i++) { scanf("%d",&a[i]); sum = sum + a[i]; } printf("Sum = %d",sum); avg= sum/6; printf("\nAvg = %f",avg); } Output Enter 6 subject marks : 50 55 60 65 70 75 Sum = 375 Avg = 62.000000 3./* Program to calculate maximum and minimum of given numbers */ void main() { int a[100],n,max=0,min,i; clrscr(); printf("Enter total numbers :"); scanf("%d",&n); printf("Enter %d numbers :",n); for(i=0; i<n; i++) { scanf("%d",&a[i]); } for(i=0; i<n; i++) { if(max<a[i]) max = a[i]; } printf("Maximum Number = %d",max); min=a[0]; for(i=0; i<n; i++) { if(min>a[i]) min = a[i]; } printf("\nMinimum Number = %d",min); } Output Enter total numbers : 5 Enter 5 numbers : 16 32 03 15 12 Maximum Number = 32 Minimum Number = 36

Inter Function Communication


To process arrays in a large program, we have to be able to pas them to functions. We can pass arrays in two ways: pass individual elements or pass the whole array. Passing Individual Elements Page 26

I YEAR B.TECH MECH

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

We can pass individual elements by either passing their data values or by passing their addresses. a) Passing Data Values We can pass data values, that is individual array elements, just like we pass any data value. As long as the array element type matches the function parameter type, it can be passed. Example: void main() { int arr[10]; ---; fun(arr[3]); ---; } void fun(int x) { Statements; } In the above example, only one element is passed by using the indexed expression arr[3]. Since the value of this expression is integer, it matches the formal parameter type in the function. b) Passing Addresses We can use two-way communication by passing the address. We can pass the address of an individual element in an array just like we can pass the address of any variable. Example : void main() { int arr[10]; ----; fun(&arr[3]); -----; } void fun(int* x) { Statements; } To pass address of array element, we prefix the address operator to the elements indexed reference. Passing an address of an array element requires two changes in the called function. First, it must declare that it is receiving an address. Second, it must use the indirection operator (*) to refer to the elements value. Passing the Whole Array In C, the name of an array is a primary expression whose value is the address of the first element in the array. Since indexed references are simply calculated addresses, all we need to refer to any of the elements in the array is the address of the array. Because the name of the array is in fact its address, passing the array name, as opposed to a single element, allows the called function to refer to the array back in the calling function. Fixed length Arrays To pass the whole array, we simply use the array name of the actual parameter. In the called function, we declare that the corresponding formal parameter is an array. We do not need to specify the number of elements in fixed-length array.

I YEAR B.TECH MECH

Page 27

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Example :

void main() { int arr[10]; ----; fun(arr); -----; } void fun(int x[]) { Statements; }

The function declaration for an array can declare the array in two ways 1. First, it can use an array declaration with an empty set of brackets in the parameter list. 2. Second, it can specify that the array parameter as a pointer Variable-length arrays When the called function receives a variable-length array, we must declare and define it as variable length. In a function declaration, we declare an array as variable using an asterisk for the array size or by using a variable for the array size. In function definition, we must use the variable name, and following standard syntax rules, it must be defined before the array. Example : void main() { int arr[size],size; ----; fun(arr); -----; } void fun(int x[*]) { Statements; }

Passing an Array as a Constant When a function receives an array and doesnt change it, the array should be received as a constant array. This prevents the function from accidentally changing the array. To declare an array as a constant, we prefix its type with the type qualifier const. Example : double average(const int arr[], int size); Rules to pass whole array to a function 1. The function must be called passing only the name of the array. 2. In the function definition, the formal parameter must be an array type, either fixed or variable. 3. The size of fixed-length array does not need to be specified. 4. The size of variable-length array in the function prototype must be asterisk or a variable. 5. The size of variable-length array in the function definition must be a variable that is in the functions scope, as a previously specified variable parameter.

I YEAR B.TECH MECH

Page 28

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

/*Program to calculate sum of array elements by passing entire array to function */ int sum(int[],int); void main() { int num,i,a[20],res=0; printf("Enter a number :"); scanf("%d",&num); printf("Enter %d elements :",num); for(i=0; i<num; i++) scanf("%d",&a[i]); res = sum(a,num); printf("Sum = %d",res); getch(); } int sum(int b[10],int n) { int res=0,i; for(i=0; i<n; i++) { res = res+b[i]; } return res; } Output Enter a number : 5 Enter 5 numbers : 1 2 3 4 5 Sum = 15

Array Applications
Two applications of arrays are : 1. Graphical Representations 2. Random Number Permutations Graphical Representation Two common statistical applications that use arrays are frequency distribution and histograms. A frequency array shows the number of elements with an identical value found in a series of numbers. For example, suppose we have taken a sample of 100 values between 0 and 19. We want to know how many of the values are 0, how many are 1, how many are 2 and so forth up through 19. A histogram is a pictorial representation of frequency array. Instead of printing the values of elements to show the frequency of each number, we print a histogram in the form of a bar chart. Random Number Permutations A random number permutation is a set of random numbers in which no numbers are repeated. For example, given a random number permutation of 10 numbers, the values from 0 to 9 would all be included with no duplicates.

Two dimensional Arrays


Two- dimensional array can be thought as a rectangular display of elements with rows and columns. The two dimensional array is a collection of number of one- dimensional arrays, which are placed one after another.

I YEAR B.TECH MECH

Page 29

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Declaration: int a[3][2]; Here 3 indicates the no. of rows and 2 indicates columns Initialization: int a[3][2] = { 21, 22, 23, 24, 25, 26}; The values are stored in the following pattern Row0 Row1 Row2 The values are represented as a[0][0] = 21; a[1][0] = 23; a[2][0] = 25; Example : a[0][1] = 22; a[1][0] = 24; a[2][1] = 26; Col0 21 23 25 Col1 22 24 26

The total number of elements in two dimensional array is product of no. of rows and no. of columns. int a [3][2] ; stores 3x2=6 values conceptually stored in matrix form.

/* Program to read elements of two-dimensional array and print them in matrix format*/ void main() { int a[3][2],i,j; clrscr(); printf("Enter elements of 3x2 matrix :"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Given Elements are :\n"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { printf("%3d",a[i][j]); } printf("\n"); } } Output Enter elements of 3x2 matrix : 1 5 2 6 3 7 Given elements 1 5 2 6 3 7

I YEAR B.TECH MECH

Page 30

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

/* Program to perform addition and subtraction of two matrices*/ void main() { int a[3][2],b[3][2],c[3][2],d[3][2],i,j; clrscr(); printf("Enter elements of 3x2 matrix A:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Enter elements of 3x2 matrix B:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&b[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<2; j++) { c[i][j] = a[i][j] + b[i][j]; d[i][j] = a[i][j] - b[i][j]; } } printf("Resultant Sum Matrix :\n"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { printf("%3d",c[i][j]); } printf("\n"); } printf("Resultant Diff. Matrix :\n"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { printf("%3d",d[i][j]); } printf("\n"); } } Output Enter elements of 3x2 matrix A : 1 2 3 4 5 6 Enter elements of 3x2 matrix B : 7 8 9 0 1 2 Resultant Sum Matrix : 8 10 12 4 6 7 Resultant Diff. Matrix ; -6 -6 -6 4
I YEAR B.TECH MECH

Page 31

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

/* Program to perform multiplication of two matrices*/ void main() { int a[3][2],b[2][3],c[3][3],i,j,k; clrscr(); printf("Enter elements of 3x2 matrix A:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Enter elements of 2x3 matrix B:"); for(i=0; i<2; i++) { for(j=0; j<3; j++) { scanf("%d",&b[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<3; j++) { c[i][j]=0; for(k=0; k<2; k++) { c[i][j] =c[i][j] + (a[i][k] * b[k][j]); } } } printf("Resultant Product Matrix :\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%3d",c[i][j]); } printf("\n"); }

Output Enter elements of 3x2 matrix A : 1 2 3 4 5 6 Enter elements of 2x3 matrix B : 1 2 3 4 5 6 Resultant Product Matrix : 9 12 15 19 26 33 29 40 51 /* Program to check whether given matrix is symmetric or not*/ void main() { int a[3][3],b[3][3],i,j,count=0;
I YEAR B.TECH MECH

Page 32

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

clrscr(); printf("Enter elements of 3x3 matrix :"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { scanf("%d",&a[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<3; j++) { b[i][j]=a[j][i]; } } printf("Transpose of matrix :\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%3d",b[i][j]); } printf("\n"); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { if(a[i][j] == b[i][j]) count++; } } if(count == 9) printf("Symmetric Matrix"); else printf("Non Symmetric Matrix"); } Output Enter elements of 3x3 matrix : 1 2 3 2 3 4 3 4 5 Transpose of matrix : 1 2 3 2 3 4 3 4 5 Symmetric Matrix Passing a two-dimensional Array With two-dimensional arrays, we have three choices for passing parts of the array to a function. They are a) Passing individual elements b) Passing a row of an array c) Passing whole array Passing a row of an Array

I YEAR B.TECH MECH

Page 33

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

Passing a row of an array means we pass a whole row by indexing the array name with only the row number. When we pass the row, therefore, the function receives a one-dimensional aray. Example : void main() { int arr[3][2]; ----; fun(arr[1]); } void fun(int x[]) { Statements; } Passing whole array When we pass a two-dimensional array to a function, we use the array name as the actual parameter just as we did with one-dimensional arrays. The formal parameter in the called function header, must indicate that the array has two dimensions, To pass two dimensional arrays to functions

1. The function must be called by passing only the array name.


2. In the function definition, the formal parameter is a two-dimensional array, with the size of second dimension required for a fixed-length array. 3. In the function definition for a variable length array, the size of all dimensions must be specified. Example : void main() { int arr[3][2]; ----; fun(arr); } void fun(int x[][2]) { Statements; }

Multidimensional Arrays
Multidimensional arrays have three, four or more dimensions. The first dimension is called plane, which consists of rows and columns. Arrays of four or more dimensions can be created and used, but difficult to draw. Three-dimensional array can be defined as array of two-dimensional arrays. In other words, it is an array of arrays of array. Declaration: int a[2][3][4]; Here2 indicates a plane consisting of 3 rows and 4 columns Initialization int a[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11}

}, {
I YEAR B.TECH MECH

Page 34

N.Vamshi Krishna

Computer Programming and Data Structures Technology

Unit III

Vignana Bharathi Institute of

} };

{12,13,14,15}, {16,17,18,19}, {20,22,23,24}

I YEAR B.TECH MECH

Page 35

N.Vamshi Krishna

Вам также может понравиться