Anda di halaman 1dari 42

UNIT -III

FUNCTIONS
 A function is a self contained program segment that carries out a specific,
well defined task. A large problem has to be split in the smaller tasks, so that
it can be efficiently solved. This is where the functions are useful.

The functions are of two types:-

1) Library functions &


2) User defined functions.

1) Library Functions: - These functions can also be called as built in


function. The functions which can be accessed just by using
preprocessor directives without defining any logic are called library
functions.
E.g.:- printf( ), scanf( ), through #include<stdio.h>
sqrt( ), sin( ), cos( ), through #include<math.h>

2) User-Defined Functions:- The function for which the user has to


define the logic of the given function are called user-defined
Functions.

Structure Of A Function:-

Function_name(argument list)
E.g.:-
argument declaration; add(x,y)
{ int x,y;
Local variable declaration; {
Statement-1; int r;
Statement-2; r=x+y;
Statement-3; return(r);
Return(expression); }
}

1
Unit - 3 CMREC - CSE Department
The function name must follow the same rules of formation as other
variable names in c. The argument list contains valid variable separated with
comma‟s, with parenthesis ().These are called formal arguments, these
receive information from the arguments given in calling function thus
providing means of data communication from the calling function to called
function.

The variables that are useful with in the functions should be declared
internally within the called function. The list of statements (statement1,
statement2,……) in function are body of function. The return statement is
used to take the result given by function to calling function or empty to
calling function. The arguments given in calling function are called actual
arguments.

E.g.
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b);
c=add(a,b); /*calling function*/
printf(“%d”,c);
getch();
}
add(x,y) /*called function*/
int x,y; /* formal args declaration*/
{
int r;
r=x+y;
return(r);
}

A function is to be declared in the main() function, before it is defined. The


function declaration should be given with semicolon which indicates to
compiler that a function is being declared and logic is not followed.

A Function is called from the main programme by using its name, including
the parenthesis which follows the name.

2
Unit - 3 CMREC - CSE Department
NOTE:-

1) A semicolon is used at the end of the statement when a function is called


but not after the function definition
2) Parenthesis are compulsory after the function name, though arguments are
not there.
3) Functions are not returning and int type value, have to specify the type
value which will be returned ( FUNCTION PROTOTYPING)
4) Only one value can be returned by a function.
5) Every program should have at-least one function.

Categories of Functions: Depending on the presence of arguments and


return type, there are three categories of functions:-

1) No arguments, no return type


2) With arguments, no return type
3) With arguments, with return type

No Arguments, No Return Type:


When a function has no arguments, it does not receive any data from the
calling function. Similarity, when it does not return value, the calling
function receive any data from the called function.

No data
F1 ( ) F2 ( )
{ {
-- --
-- --
F2( ); }
} No data
In return

3
Unit - 3 CMREC - CSE Department
E.g.:-
main( )
{
square( );
getch( );
}
square( )
{
int a;
scanf( )
{
int a;
scanf(“%d”,&a);
printf(“%d”,a*a);
}

o/p:-2
4
Explanation: - Whenever the compiler reaches calling function, the control
immediately goes function definition to perform the logic. The calling
function accepts internal variable „a‟ through scanf( ), and calculates “a*a”
and prints the result. Here there is no data communication between calling
function and called function. So, no arguments no return type. The square
() function receives data from terminal directly the return; is optional in
function, when the function has nothing to return.

2) With Arguments, No Return Type: - The way of data communication


between calling function and called function are only arguments. Under
this category the functions receives arguments (data).From the calling
function, but returns nothing to it.

F1 ( ) Values of
F2 ( )
{ arguments {
-- --
-- --
-- --
F2(a); no data in }
}

4
Unit - 3 CMREC - CSE Department
E.g :-
main( )
{
int a;
scanf(“%d”,&a);
square(a);
getch();
}
square(b)
int b;
{
int c;
c=b*b;
printf(“%d”,c);
}

o/p:- 2
4

3) With Arguments, With Return Type :- Under this category, calling


function passes arguments to called functions, and the called function stores
a copy of information given in actually arguments and performs defined
logic on those and returns the result to the calling function again.

Values of
F1 ( ) arguments F2(b)
{ {
-- --
-- --
-- --
result of Return(e);
F2(a); }
}
function

5
Unit - 3 CMREC - CSE Department
E.g :-
main( )
{
int a,b;
scanf(“%d”,&a);
b=square(a);
printf(“%d”,b);
getch( );
}
square(x)
int x;
{
return(x*x);
}

o/p:- 2
4

Return Statement: The return statement is use to return from a function it


causes execution to return to the point of calling function of the function..
The general form of return is ,

Return;
or
Return (Expression);

 More than one return can be used in a function. How the function will
return when the first is encountered.

The return statement service 2 purposes:-


(a)It immediately transfers the control from the function back to the calling
function.
(b)Whatever is inside the parenthesis following the return is returned as a
value to the calling function.

6
Unit - 3 CMREC - CSE Department
Note: A function can return only single return type though it is having
several return statements

Function Prototype: Generally in function definition, the arguments are


declared in one line in new version (modern method). This new version is
called “function prototype”.
General form is
data type function name (type one a1, type a2, type a3,……)
{
--
--
--
}

E.g:

float div(int a,int b)


{
--
--
--
}

The functions generally returns integer but it you want the function to
return other than integer like float, double etc; then also you have to
prototype the function. Here the prototype is done in declaration.

E.g:
float div (float,float);
{
float a,b,c;
printf(“enter a, b”);
scanf(“%d%d”,&a,&b);
c=div (a,b);
printf(“%f”,c);
getch( );
}

7
Unit - 3 CMREC - CSE Department
Definition:-
float div(float x, float y)
{
return(x/y);
}

Void: - Void declares no value returned. Void is a prototype which


specifies, that the function has nothing to return.

E.g :-
main( )
{
print(“welcome”);
star( );
getch( );
}
star( )
{
printf(“*****”);
}

 Using Void:-
void main( )
{
void start( );
printf(“welcome”);
getch( );
}
void star( )
{
printf(“*****”);
}

The above program consists of star ( ) a user defined program but returned
nothing such functions can be declared that the qualifier “void”
This states that given function do not return values. We can also use void
for the functions not taking arguments, as
E.g. :- void star (Void) /* specifies no returned values*/
8
Unit - 3 CMREC - CSE Department
Parameter Passing :-

 Call by value:-

Sending variables to the function s called call by value. In call by


value, the actual parameters and formal parameters will be simply variable
names. When the function is called actual parameters are copied in to
formal parameters. The changes mode in to formal parameters in the
function, will not be reflected to actual parameters.

In fact, the formal parameters are created when the function is


started and destroy when the function is completed. The actual and formal
parameters names may (or) may not be same.

E.g.:-
void main( )
{
int x=3,y=4;
clrscr( );
printf(“\n before swapping are %d\t%d ”,x,y);
swap(x,y);
getch( );
}
swap(x,y)
int x,y;
{
int temp;
temp=x;
x=y;
y=temp;
printf(“after swapping are %d\t%d\n”x,y);
return;
}

9
Unit - 3 CMREC - CSE Department
The actual parameters are x and y. Here we are calling the function f() by
sending x and y variables. Hence it is call by value. In function f (),
actual parameter x is copied to formal parameter x, and actual parameter
y is copied to formal parameter y, then ( x=3 and y = 4 in f ( ) at first)

In function f() x and y are interchanged

x=4 and y= 3

The out put of printf in function f() is 43.when the function is exited
(completed), formal parameters are destroyed, then the control returns to the
main function. Actual parameters x and y still remains 3 & 4. Thus, charges
made of formal parameters are not reflected to actual parameters. It we want
to reflect them we have to call the function by call by reference using
pointers.

Call by Reference:-

Sending addresses to the function is known as call by reference i.e.,


sending address of variables, pointers, arrays etc. To a function is nothing
but call by reference.

In call by reference, the actual parameters are addresses and the


formal parameters are pointers.

In the function the data is accessed through pointers. We can make


the change to actual parameters from the unction, by using formal
parameters. Thus, in call by reference, changes can be made to actual
parameters from the function.

E.g.:-
main( )
{
int a,b;
printf(“enter the values of a,b”);
scanf(“%d%d”,&a,&b);
printf(“\n before swapping a=%d \t b=%d”,a,b);
swap(&a,&b);
10
Unit - 3 CMREC - CSE Department
printf(“\n after swapping a=%d\t b=%d”,a,b);
getch( );
}
swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
return(0);
}

Let us assume & a is 1000 & b is 2000. Here we are calling the function f1
by sending addresses hence it is known as call by reference, in the function
f1, x=&a=1000; y=&b=2000.Hence x & y contains address of x & y,
P1&P2 are called pointer variables.
a b
3 4

x=1000 y=2000

The actual parameters cannot be used in a function f1( ) and the formal
parameters cannot be used in function main. In f1( ) *x1&*x2 are inter
changed.
a b
4 3
4
x1=1000 y1=2000

When the function is excited, pointers are destroyed.


x y
4 3

Then the output of printf in main function is 4 3.

11
Unit - 3 CMREC - CSE Department
Storage Classes (Or) Scope of Variables (Or) Visible Class of
Variables:-
Every „C‟ variable has a characteristic called as storage class. The
storage class derives two characteristics of the variables.
--Life time (longetivity)
--Scope (visibility)
Life Time:- The life time of the variable is the length of time it returns a
particular value.

Scope:- The visibility of a variable defines which parts of a program will


be able to recognize it(the variable). A variable may be visible in a block a
function, a file, a group of files, or an entire program.
From the C compiler point of view, a variable name identifies
same physical location with in the memory, where the string of bits
representing the variables value is stored. They are basically two types of
locations in a computer where such a value may be kept.
(1)The memory
(2)One of the CPU registers

The variable storage class determines, whether the variable


should be stored in the memory or in a register. There are four storage
classes:
(1) Automatic(auto)
(2) External(extern)
(3) Static storage classes
(4) Register storage classes

Automatic storage classes:-


Automatic variables are declared in side a function.These is
created when a function is called and destroyed automatically when the
function is excited. Automatic variables are local to the function in which
they are declared.
We use keyword auto to declare automatic variables explicitly.
-One of the important features of the automatic variables is that their value
cannot be changed accidentally, by what happens in the some other
functions in the program.

12
Unit - 3 CMREC - CSE Department
-It assures that we may declare and use the same name variable in the
different function in the same program with out causing any confusion to the
compiler.
Storage - Memory
Default initial value- Garbage value
Scope - Local to the block in which the
variable is defined.
Life - Till the controls with in the block in
which it is defined.

E.g.:-main( )
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;
printf(“%d\n”,i);
}
printf(“%d\n”,i);
}
printf(“%d\n,i”);
}

o/p:-3
2
1

Extern Variables:-
Same variables are alive and active through the entire
program are known as external variables (or) global variables. External
variables are declared of all functions in the program. The global variables
can be accessed by any function in the program.

-Once a variable has been declared as global any function can use it and
change its value.
-Declaration external variable should be with “Extern” key word.

13
Unit - 3 CMREC - CSE Department
Storage --- Memory
Default initial Value --- zero
Scope --- Global
Life --- As long as the programs
Execution does not come
to an end.

E.g.:-
int i;
main( )
{
printf(“%d\n”,i);
incre( );
incre( );
decre( );
}
incre( )
{
i=i+1;
printf(“%d\n”,i);
}
i=i-1;
printf(“%d\n”,i);
}
o/p:-0
1
2
1

 Static variables:- A variable can be declared as static by using static


keyword. The value of static variables persists until the end of the program.
A static variable may be either an internal type or an external type,
depending on the place of the declaration internal static variables are those
which are declared in side a function. The scope of internal static variable
extends up to the end of the function. Therefore internal static variables are
existence, throughout the program.

A static variable is initialized only once, when the program is compiled; it is


never initiated again.
14
Unit - 3 CMREC - CSE Department
Storage - Memory

Default initial value - Zero


Scope - Local to the bloc in which it is
defined.

Life -Value of the variable persists


between different function calls.

E.g.:-
main( ) main( )
{ {
incre( ); int c;
incre( ); for (c=1;c<=3;c++)
incre( ); fun( );
} }
incre( ) fun( )
{ {
static int i=1; static int a=5;
printf(“%d\n”,i); a=a+3
i=i+1; printf(“%d\n”,a);
} }

o/p:-1 o/p:-a=8
2 a=11
3 a=14

Register variables:-

Computers have internal registers in their arithmetic logic unit


(ALU), which are used to temporarily store date that has to be occurred
separately. Operations can be performed upon the data stored in registers
more quickly than upon data stored in memory. Therefore if a variable is
used at many placed in a program it is better to declare its storage class as
register. Good examples of frequently used variables are loop canters.

15
Unit - 3 CMREC - CSE Department
Storage - CPU register
Default initial value - Garbage value
Scope - Local to the block in which it is defined
Life - Till the control remains within the block
In which it is defined.

E.g.:-main( )
{
register int i;
for(i=1;i<=10;i++)
printf(“%d”,i);
}

We cannot guarantee the given variable „I‟ will be stored in


register because they may be busy doing some other task. (The
microprocessor contains 14 registers). In that case the compiler transforms
it as automatic variable without any error or warning.

We cannot use register storage class for all types of variables.


Because the CPU registers in micro computers are usually 16 bit registers (2
bytes).

Ex: - register float q, Invalid because float need 4 bytes,


double need
Register double „a‟ 8 bytes.

Type qualifiers :-

TYPE QUALIFIERS

CONSTANT VOLATILE RESTRICT

16
Unit - 3 CMREC - CSE Department
 Constants:-
-The keyboard for the constant type qualifies is const.
-A constant object is a read only object
-A constant object must be initialized when it is declared because it cannot
be charged
later.

E.g.:-const double P1=3.1415926;


--
--
P1=3.142 invalid because p1 value is declared with const the value
cannot be changed

 Volatile:-

-It tells the computer that an object value may be charged by entities other
than
this program.

-As an example a „c‟ compiler may thinks that it is more efficient to remove
an object from print memory and put is in a register.

 In this case, we are telling compiler that this object may be referenced
or charged by other entity.
Volatile int x;
Volatile int x ptr;
The above example shows how an integer or a pointer to an integer can be
declared volatile.

Restrict:-
-The restrict qualifier which is used only with pointers, indicates that the
pointer is only initial way to access the deference data.
-It helps more help to the compiler for optimization.

Recursive function: - The function called by itself is called recursive


function and this process is after referred to as recursion.

Ex: - main ()
{
17
Unit - 3 CMREC - CSE Department
printf (“ welcome to CMREC \n”);
main( );
}
 There are two important conditions that must be satisfied by any
recursive procedure.

- Each time a procedure calls itself, it must be nearer to a solution


- There must be a decision criterion for stopping the computation

 Factorial of a given number by using recursion:-

#include<stdio.h>
#include < conio.h>
main( )
{
int n,x;
clrscr( );
printf(“enter the values of n”);
scanf(“%d”,&n);
r=fact(n);
printf(“%d”,r);
getch( );
}
fact(x)
int x;
{
int s;
if(n!=1)
{
s=*fact(x=1);
return(s);
}
else
return(1);
}

o/p:- enter the value of n:5


120

18
Unit - 3 CMREC - CSE Department
Calculating the GCD of given 2 numbers by using recursion.

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,r;
clrscr( );
printf(“enter the first number:”);
scanf(“%d”,&a);
printf(“enter the second number:”);
scanf(“%d”,&b);
printf(“gcd of %d and %d is:%d\n”,a,b,r);
getch( );
}
gcd(x,y)
int x,y;
{
if(y= =0)
return x;
else
return(gcd(y,x%y));
}

o/p:- enter the first number :18


enter the second number :45
GCD of 18 & 45 is : 9

Preprocessor Commands:-

„C‟ is a unique Language in many aspects. The other feature of „C‟


language is the preprocessor. The C pre processor provides several tools
that are unavailable in other
high level languages.
19
Unit - 3 CMREC - CSE Department
The preprocessor is a program that processes the source code before it
passes through the compiler. It operates under the control of what is known
as preprocessor command lines or directives.

The # define directive


Syntax if # define directive:
# define identifier < substitute text>
(or)
#define identifier (arg1 arg2-------argn)

Ex:- W.A.P to find the area of circle.

#include<stdio.h>
#include<conio.h>
#define P1 3.14
void main( )
{
float r,area;
clrscr( );
printf(“\n enter radius of circle in cms”);
scanf(“%f”,&r);
area=p1*r*r;
printf(“area of circle =%2f”,area);
getch( );
}

O/p:- Enter radius of circle in cms:7


Area if a circle = 153.86 cm2

UNDEFINING A MACRO

#undef directive-- Macro defined with # define directives can be undefined


with #undef directive.

syntax:-
Under identifier
20
Unit - 3 CMREC - CSE Department
Program to undefined a macro.

#include<stdio.h>
#include<conio.h>
#define wait getch( )
void main( )
{
int k;
#undef wait ( ) getch( );
clrscr( );
for(k=1;k<=5;k++)
printf(“%d\t”,k);
wait( );
}

 wait() defined in place of getch( );


In the program under directive undefines the same macro.
The compiler flags an error message undefined symbol, „wait‟ in function
main.

Token passing and stringizing operators:- In this operation macro


argument is converted to string.

#include<stdio.h>
#include<conio.h>
#define say(m) printf(#m)
void main( )
{
clrscr( );
say(Hello);
}

o/p:-Hello

21
Unit - 3 CMREC - CSE Department
Program after conversion the statement say(Hello) is treated as
printf(“Hello”). It
Is not essential be enclose the text in quotation marks in the strigizing
operator

Write a program to find the larger of two numbers using macro with
arguments.

#include<stdio.h>
#include<conio.h>
#define max(x,y) if(x>y)c=x; else c=y;
void main( )
{
int x=5,y=8,c;
clrscr( );
max(x,y);
printf(“\nlarger of 2 numbers=%d”,c);
}

o/p:- larger of 2 numbers =8

The # include directive:-

The # include directive loads a specified file in the current program.


The macro‟s and functions of loaded file can be called in the current
program. The macro‟s and functions of loaded file can be called in the
current program.

Include file is also compiled with current program.


#include<file name>
#include ”file name”

W.A.P to call the function defined in “udf.c” file.

#include<stdio.h>
#include<conio.h>
22
Unit - 3 CMREC - CSE Department
#include”udf.c”
void main( )
{
clrscr( );
display( );
}

o/p:- function called.

--Contents of udf.c file.


int display u( );
display( )
{
printf(“\n functioned called”);
return(0);
}

-- In the first program the “udf.c” is included. It is a user defined function


file .It is compiled before the main program is compiled. The o/p of the
program “functioned called” is displayed.

The # Error directive:-

The # error is used to display user defined message during compilation of


the function.

Syntax is:
#if!defined(identifier)
#error<error message”);
#end if.

#defined directive will work exactly opposite to


#!define directive.
Syntax is
#if defined(identifier)
{
}
#else
23
Unit - 3 CMREC - CSE Department
#error<error message>
#end if

# Line Directive:-
Syntax of line directive is # line<constant>[<identifier>]

--Inline Directive:-
It is important to known previously that the source code contains
assembly code.
#else
{
Stmt-3;
Stmt-4;
}

# End if

--The # indef works exactly opposite to #ifdef. ifdef processes tests


whether the identifier has defined substitute text or not.
--if the identifier is undefined then #else block is compiled and executed.
#define T8
void main( )
{
clrscr( );
#ifndef T
printf(“\n macro is not defined”);
#else
printf(“\n macro is defined”);
#end if
}
o/p:-Macro is defined.

CONDITIONAL COMPILATION: The most frequenty used


conditional compilation directives are #if, #else, #end if, etc.
Syntax of #ifdef directive is
#ifdef<identifier>

24
Unit - 3 CMREC - CSE Department
{
Stmt-1;
Stmt-2;
}
#else
{
Stmt-3;
Stmt-4;
}
#endif

--The #ifdef preprocessor tests whether the identifier has defined substitute
text or not.
--If the identifoier is defined then #ifblock is compiled and executed.
The compiler ignores #else block even if errors are intentionally made.
Error messages will not be displayed.

--If the identifier is not defined then #else block is compiled and executed.

program to use conditional compilation stmt as to whether the


identifier is defined or not.

#include<stdio.h>
#include<conio.h>
#defined line-1
void main( )
{
clrscr( );
#ifdef line
printf(“this line number 1”);
#else
printf(“this is line number 2”);
#end if
getch( );
}

o/p:-This is line number one.


25
Unit - 3 CMREC - CSE Department
The #indef directive:-
#indef<identifier>
{
Stmt-1;
Stmt-2;
}

<string.h> - String manipulation functions.


<time.h> - Time manipulation function.
<ctype.h> - Character testing and conversion functions.
<math.h> - Mathematical functions.
<stdio.h> - Standard I/O functions.
<stdli.h> - Utility functions such as string conversion routines, memory
allocation routines. Random number generator etc.
<conio.h> - Console i/p operation.

Directive Function
#define defines a macro substation.
#undef undefines a macro
#include specifies the files to be included.
#ifdef test for a macro definition.
#if test a compile time condition.

3 Categories:-
1) Macro substation directives.
2) File inclusion directives
3) Compiler control directives.

Functions are of two types:-


(1) Standard library function
(2) User-defined functions.

(1)Standard Library Functions:-


A function for which the program already written we have to
just call the function.
26
Unit - 3 CMREC - CSE Department
(1) Mathematical Library Functions:-
Mathematical functions such as cos, sqrt, log, etc are frequently
used in real-life problem. Most of „c‟ compiler support these basic functions.
To use any of these function in a program, we should include the statement.
#include<math.h>

In the beginning of the program the following lists gives some standard
mathematical functions.

Function Purpose
Abs( ) absolute value of given number.
Ceil( ) given value will be rounded up to
nearest integer
Cos( ) gives cosine value of given number.
Cosh( ) gives hyperbolic cosine of given
number.
Exp( ) raise e to power of even numbers.
Floor given number will be rounded down
to the nearest integer.
Fmod(d1,d2) provides the reminder of d1/d2.
Lod( ) natural logarithm of given numbers.
Pow( d1,d2) d1 raises to the power of d2.
Sign(d) sine of d
Sqrt(d) sqrt of d
Tan( ) tangent of given number.
A sin( ) arc sine of given number(means
sin-1)
A cos( ) arc cosine of given number.
A tan(d) arc tangent of d.

(2)Character –Handling function :-


The following functions all test a character to determine whether it
falls into a specific energy. They take as an argument a character
represented. These functions return Boolean integer values : 0 if the test
result is false,1 if the test result is true. These functions are contained in the
file “ctype.h” must be included in the program. The functions are given in
the following table.

Functions Test
is a num( ) is it alpha numeric.
27
Unit - 3 CMREC - CSE Department
is alpha( ) is it alphabetic.
iscntral( ) is it controlled character.
is digit( ) is it a digit.
islower( ) is it a lower case.
isupper( ) is it a upper case.
isprintf( ) is it printable character.
is space( ) is it a space.
toupper( ) converts the lower case argument to
upper case.
tolower( ) converts the upper case argument to
lower case.

.User-Defined Function:-
It is a function where user has to write . The user defined function
can be called from the other function. In „C‟ language, functions can be
return either a value (or) number.

ARRAYS

DEFINITION:-

An ARRAY is a set of homogeneous instructions (Elements)


Stored in to a single name. (or)

An ARRAY is a collection of elements of some type .The


elements of an array are referred by a common name and are
differentiate from one another by there position wit in an array.

28
Unit - 3 CMREC - CSE Department
It‟s mainly used to reducing the complexity of data in your program.
Three types of arrays:-
1) One or single dimensional array.
2) Two or double dimensional array.
3) Multi dimensional array.

Array Initialization / Declarations:-

Int a[5] = {1,2,3,4,5}


Here „5‟ elements are stored in array „a‟.

The array elements are stored sequentially in separate locations.

Reading of array elements begins from „0‟


A[o]-Refers to 1st element i.e; 1
A[1]-Refers to 2nd element i.e; 2
A[2]-Refers to 3rd element i.e; 3
A [3]-Refers to 4th element i.e; 4
A[4]-Refers to 5th element i.e; 5

1) One / Single Dimensional array:-

The general form of declaring a one dimensional array is


type array_ name[size];

*The of an integer array a[5] are stored in continues memory location.


*Assume that the starting memory location is 2000.
*Each integer elements requires 2 bytes.

It contains one column and multiple rows. Each row can be identify with
row id is
called index. It always starts with zero.
Syntax:-<datatype><var name>[<size>];
|
Subscript
E.g.:- int array[5]
In the above example array is that occupied 20 bytes (5*2) in that
each row with a 2 bytes like that it allocates 5 rows with one column.

Elements a[0] a[1] a[2] a[3] a[4]


29
Unit - 3 CMREC - CSE Department
Address 2000 2001 2002 2003 2004

DATATYPE MEMORY REQUIRMENT


Character 1byte
Integer 2bytes
Float 3bytes
Long 4bytes
Double 5bytes
Character arrays are called strings. There is a slight
difference between an integer array and a character array. In character array
NULL(%0) character is automatically added at the end, where as in integer
or other types of arrays no character is placed at the end.

Write a program to display character array with their address.


#include<stdio.h>
#include<conio.h>
void main( )
{
char name[10]={„A‟,‟R‟,‟R‟,‟A‟,‟Y‟};
int i=0;
clrscr( );
printf(“\n character memory location \n”);
while(name[i]!=0)
{
printf(“\n %c\t\t%u”,name[1],&name[i]);
i++;
}
getch();
}

OUTPUT:-
Character Memory Location
[A] 4054
[R] 4055
[R] 4056
[A] 4057
[Y] 4058

Write a program to print string in the reverse order.

30
Unit - 3 CMREC - CSE Department
Write program to display names of months in a year using single
dimensional array having length of 12.

Eg of single dimensional arrays :-


To find of the number of pass and fail students from the given
students marks.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[50],i,n,pass=0;
clrscr( );
printf(“enter the number of students:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“enter%d student marks=”,i+1);
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++);
if(a[i]>=35)
pass++;
printf(“number of passed students are:%d\n”,pass);
printf(“number of failed students are:%d\n”,n-pass);
getch();
}

 Write a program to find the percentage of marks from 1 to 7


subjects.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n,total=0;
int m[50];
float percentage;
printf(“enter number of subjects”);
scanf(“%d”,&n);
for(int i=0;i<n;i++)
31
Unit - 3 CMREC - CSE Department
{
printf(“enter marks of subject”);
scanf(“%d”,m[i]);
}
for(int i=0;i<n;i++)
{
printf(“%d”,m[i]);
total+=m[i];
}
printf(“%d”,total);
percentage=total/n;
printf(“%d”,percentage);
getch();
}

O/P:-

2) Two/Double Dimensional Array:-


Array can more then one dimension. Multidimensional
arrays make easier to represent multi objects, such as graph with rows
and column. A two dimensional array can thus be represented with two
pair of square brackets.
For Ex:- Elements of int x[3][3]
Column1 col2 col3
Row1 x[0] [0] x[0] [1] x[0] [2]
Row2 x[1] [0] x[1] [1] x[1] [2]
Row3 x[2] [0] x[2] [1] x[2] [2]
For example in the above table each row of a two dimensional array
can be thought of as a signal-dimensional array.

Write a program to display two dimensional array elements


together with their addresses.

#include<stdio.h>
#include<conio.h>
void main( )
32
Unit - 3 CMREC - CSE Department
{
int i,j;
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr( );
printf(“array elements and address\n\n”);
printf(“col-0 col-1 col-2\n”);
printf(“row0”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d[%5d]”,a[i][j],&a[i][j]);
}
printf(“\n row%d”,i+1);
}
printf(“\r”);
}

O/P:- Array elements and address


Col0 Col1 Col2
Row0 1[4052] 2[4054] 3[4056]
Row1 4[4058] 5[4060] 6[4062]
Row2 7[4064] 8[4066] 9[4068]

Write a program to display the elements of two dimensional arrays.

#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j;
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr( );
printf(“elements of an array\n\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%5d”,a[i][j]);
33
Unit - 3 CMREC - CSE Department
}
printf(“\n”);
}
}

O/P:-
Elements of an Array
123
456
789.

Write a program to perform multiplication of two matrices whose orders


are up to 10*10.

Write a program to display the names of the cities with their base
addresses.

Write a c program to find both the large and smallest number in a list
of integers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[20],i,n,largest,smallest;
clrscr( );
printf(“enter the size of array:”);
scanf(“%d”&n);
for(i=0;i<n;i++)
{
printf(“enter a[%d]=”,i);
scanf(“%d”,&a[i]);
}
smallest =a[0];
largest =a[0];
for(i=1;i<10;i++)
{
if(a[i]>largest)
largest=a[i];
if(a[i]<smallest)
34
Unit - 3 CMREC - CSE Department
smallest=a[i]
}
printf(“largest integer is:%d\n”,largest);
printf(“smallest integer is :%d\n”,smallest);
getch( );
}

Addition of two matrices:

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3],b[3][3],c[3][3];
int i,j,row,col;
clrscr( );
printf(“enter how many rows are there:”);
scanf(“%d”,&row);
printf( “enter how many columns are there:”);
scanf(“%d”,&col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf(“enter a[%d][%d]=”,i,j);
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf(“enter b[%d][%d]=”,i=1,j=1);
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j]+b[i][j];
35
Unit - 3 CMREC - CSE Department
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(“%2d”,a[i][j]);
printf(“\t\t”);
for(j=0;j<col;j++)
printf(“%2d”,b[i][j]);
printf(“\t\t”);
for(j=0;j<col;j++)
printf(“%2d”,c[i][j]);
printf(“\n”);
}
getch();
}

Write a c program to perform multiplication of two matrices.(using


2d-arrays).

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3],b[3][2],c[3][2],i,j,k;
clrscr( );
printf(“\n enter ,matrix a:\n”);
for(i=o;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“enter a[%d][%d]=”,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“\enter matrix b:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“enter b[%d][%d]=”,I,j);
scanf(“%d”,&b[i][j]);
36
Unit - 3 CMREC - CSE Department
}
}
for(i=0;i<3;i++);
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(“\n the resultant matrix c is \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“ \t%d ”,c[i][j]);
printf(“ \t%d ”,c[i][j]);
printf(“\n”);
}
getch( );
}

O/P:-

Ex: for two dimensional array:-

Write a program to read and display a simple 3*3 matrix

#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j,a[3][3];
clrscsr( );
printf(“ a[%d][%d]= ”,i,j);
scanf(“ %d ”,&a[i][j]);
}
printf(“ the elements 3*3 matrix are :\n ”);
for(i=0;i<3;i++)
{
37
Unit - 3 CMREC - CSE Department
printf(“\n\t\t”);
for(j=0;j<3;j++)
printf(“ %d\t ”,a[i][j]);
}
getch( );
}

Three /Multidimensional arrays:-

The c program allows array of two or multidimensional .


The syntax of multidimensional array is
Array name[S1][S2][S3]………[Sn].
It can be initialized as
Int mat[3][3][3]={{
{1, 2, 3}
{4,5,6}
{7,8,9}
};
{
{1,4,7}
{2,5,8}
{3,6,9}
};
{
{1,4,4}
{2,4,7}
{6,6,3}
};
}

*In a three dimensional array we can be thought of as an array of arrays.


*The outer array contains three elements
*The inner array size is two dimensional with size[3][3]

Write a program to explain the working of three dimensional array.

void main( )
38
Unit - 3 CMREC - CSE Department
{
int array_3d[3][3][3];
int a,b,c;
clrscr( );
for(a=0;a<3;a++)
for(b=0;b<3;b++)
for(c=0;c<3;c++)
array_3d[a][b][c]=a+b+c;
for(a=0;a<3;a++)
{
printf(“\n”);
for(b=0;b<3;b++)
{
for(c=0;c<3;c++)
printf(“%d”,array_3d[a][b][c]);
printf(“\n”);
}
}
}

O/P:-
012
123
234
123
234
345
234
345
456

The arrangement of array elements in two rows and column is only true-
since in memory there are no rows and columns. Hence even 2-d array are
arranged linearly in memory.
The arrangement is shown below.

S[0][0] S[0][1] S[1][0] S[1][1] S[2]8[0] S[2]8[1] S[3]8[0] S[3][1]


100 56 127 67 345 34 167 72

39
Unit - 3 CMREC - CSE Department
4002 4004 4006 4008 4010 4012 4014 4016

Multidimensional arrays:-
C allows of three or more dimensions. The exact limit is
determined by the compiler. The general form of multi dimensional array is

<datatype><array_name><[S1][S2]…………[S3]
Where Si is the size of ith dimensions.

The array contains 2*3(6 elements) and can be represented as


representation will be used as tmp[1][2].

Initialization Of Multidimensional Array:-


A multidimensional array can include

Column 0 1 2
R
O 0 1 2 3
W 1 4 5 6

Here number 6 is the stored in the elements of tmp designated


as column2 (both rows and columns are numbered from 0) to access this
element 6, the following the assignment of initial values.

During this initialization the elements of the first row


of the two dimensional will be assigned first, then the element so the second
row, and soon.
*Consider the following array definition:
int array [3][4]
*Three dimensional array can be initialized as follows:
int mat[3][3][3]={
{1, 2, 3}
{4, 5, 6}
{7, 8, 9}
};
{
{1, 4, 7}

40
Unit - 3 CMREC - CSE Department
{2, 5, 8}
{3, 6, 9}
};
{
{1, 4, 4}
{2, 4, 7}
{6, 6, 3}
};
}

Ex: For multidimensional array:-

Write a program to explain the working of 3-d array:

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3][3];
int a,b,c;
clrscr( );
for(a=0;a<3;a++)
for(b=0;b<3;b++)
for(c=0;c<3;c++)
a[a][b][c]=a+b+c;
for(a=0;a<3;a++)
{
printf(“\n”);
for(b=0;b<3;b++)
{
for(c=0;c<3;c++)
printf(“%3d”,a[a][b][c]);
printf(“\n”);
}
}
getch();
}

41
Unit - 3 CMREC - CSE Department
Passing Array Elements To Function:-

Array elements can be passed to a function by calling the


function:
1) By value i.e., by passing elements of array elements to the function.

2) By reference i.e., by passing addresses of array elements to the function.

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[5]={15,20,25,30,35};
int i;
for(i=0;i<5;i++)
write(i,a[i]);
getch();
}
write(int c,int n)
{
printf(“\t a a[%d]=%d\n”,c;n);
}

O/P: - a[0]=15
a[1]=20
a[2]=25
a[3]=30
a[4]=35

42
Unit - 3 CMREC - CSE Department

Anda mungkin juga menyukai