0% found this document useful (0 votes)
17 views31 pages

Unit 2

module 2 contains Arrays,Functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views31 pages

Unit 2

module 2 contains Arrays,Functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

For example:-

int arr[5]={1,2,3,4,5,6,7,8};//error

we cannot copy all the elements of an array to another array by simply assigning it
to the other array like, by initializing or declaring as

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

int b[5];

b=a;//not valid

(note:-here we will have to copy all the elements of array one by one, using for
loop.)

Single dimensional arrays and functions

/*program to pass array elements to a function*/

#include<stdio.h>

void main()

int arr[10],i;

printf(“enter the array elements\n”);

for(i=0;i<10;i++)

scanf(“%d”,&arr[i]);

check(arr[i]);

51 *Under revision
void check(int num)

if(num%2=0)

printf(”%d is even \n”,num);

else

printf(”%d is odd \n”,num);

Lecture Note: 12

Two dimensional arrays

Two dimensional array is known as matrix. The array declaration in both the array
i.e.in single dimensional array single subscript is used and in two dimensional
array two subscripts are is used.

Its syntax is

Data-type array name[row][column];

Or we can say 2-d array is a collection of 1-D array placed one below the other.

52 *Under revision
Total no. of elements in 2-D array is calculated as row*column

Example:-

int a[2][3];

Total no of elements=row*column is 2*3 =6

It means the matrix consist of 2 rows and 3 columns

For example:-

20 2 7

8 3 15

Positions of 2-D array elements in an array are as below

00 01 02

10 11 12

a [0][0] a [0][0] a [0][0] a [0][0] a [0][0] a [0][0]

20 2 7 8 3 15

2000 2002 2004 2006 2008

Accessing 2-d array /processing 2-d arrays

For processing 2-d array, we use two nested for loops. The outer for loop
corresponds to the row and the inner for loop corresponds to the column.

For example

int a[4][5];

for reading value:-

53 *Under revision
for(i=0;i<4;i++)

for(j=0;j<5;j++)

scanf(“%d”,&a[i][j]);

For displaying value:-

for(i=0;i<4;i++)

for(j=0;j<5;j++)

printf(“%d”,a[i][j]);

Initialization of 2-d array:

2-D array can be initialized in a way similar to that of 1-D array. for example:-

int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};

These values are assigned to the elements row wise, so the values of
elements after this initialization are

Mat[0][0]=11, Mat[1][0]=14, Mat[2][0]=17 Mat[3][0]=20

Mat[0][1]=12, Mat[1][1]=15, Mat[2][1]=18 Mat[3][1]=21

Mat[0][2]=13, Mat[1][2]=16, Mat[2][2]=19 Mat[3][2]=22

54 *Under revision
While initializing we can group the elements row wise using inner braces.

for example:-

int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};

And while initializing , it is necessary to mention the 2nd dimension where 1st
dimension is optional.

int mat[][3];

int mat[2][3];

int mat[][];

int mat[2][]; invalid

If we initialize an array as

int mat[4][3]={{11},{12,13},{14,15,16},{17}};

Then the compiler will assume its all rest value as 0,which are not defined.

Mat[0][0]=11, Mat[1][0]=12, Mat[2][0]=14, Mat[3][0]=17

Mat[0][1]=0, Mat[1][1]=13, Mat[2][1]=15 Mat[3][1]=0

Mat[0][2]=0, Mat[1][2]=0, Mat[2][2]=16, Mat[3][2]=0

In memory map whether it is 1-D or 2-D, elements are stored in one


contiguous manner.

We can also give the size of the 2-D array by using symbolic constant

Such as

#define ROW 2;

55 *Under revision
#define COLUMN 3;

int mat[ROW][COLUMN];

String

Array of character is called a string. It is always terminated by the NULL


character. String is a one dimensional array of character.

We can initialize the string as

char name[]={‘j’,’o’,’h’,’n’,’\o’};

Here each character occupies 1 byte of memory and last character is always NULL
character. Where ’\o’ and 0 (zero) are not same, where ASCII value of ‘\o’ is 0
and ASCII value of 0 is 48. Array elements of character array are also stored in
contiguous memory allocation.

From the above we can represent as;

J o h N ‘\o’

The terminating NULL is important because it is only the way that the
function that work with string can know, where string end.

String can also be initialized as;

char name[]=”John”;

Here the NULL character is not necessary and the compiler will assume it
automatically.

String constant (string literal)

56 *Under revision
A string constant is a set of character that enclosed within the double quotes
and is also called a literal. Whenever a string constant is written anywhere in a
program it is stored somewhere in a memory as an array of characters terminated
by a NULL character (‘\o’).

Example – “m”

“Tajmahal”

“My age is %d and height is %f\n”

The string constant itself becomes a pointer to the first character in array.

Example-char crr[20]=”Taj mahal”;

1000 1001 1002 1003 1004 1005 1006 1007 100 1009
T a j M A H a l \o

It is called base address.

Lecture Note: 13

String library function

There are several string library functions used to manipulate string and the
prototypes for these functions are in header file “string.h”. Several string functions
are

strlen()

This function return the length of the string. i.e. the number of characters in the
string excluding the terminating NULL character.

It accepts a single argument which is pointer to the first character of the string.

57 *Under revision
For example-

strlen(“suresh”);

It return the value 6.

In array version to calculate legnth:-

int str(char str[])

int i=0;

while(str[i]!=’\o’)

i++;

return i;

Example:-

#include<stdio.h>

#include<string.h>

void main()

char str[50];

print(”Enter a string:”);
58 *Under revision
gets(str);

printf(“Length of the string is %d\n”,strlen(str));

Output:

Enter a string: C in Depth

Length of the string is 8

strcmp()

This function is used to compare two strings. If the two string match, strcmp()
return a value 0 otherwise it return a non-zero value. It compare the strings
character by character and the comparison stops when the end of the string is
reached or the corresponding characters in the two string are not same.

strcmp(s1,s2)

return a value:

<0 when s1<s2

=0 when s1=s2

>0 when s1>s2

The exact value returned in case of dissimilar strings is not defined. We only know
that if s1<s2 then a negative value will be returned and if s1>s2 then a positive
value will be returned.

For example:

59 *Under revision
/*String comparison…………………….*/

#include<stdio.h>

#include<string.h>

void main()

char str1[10],str2[10];

printf(“Enter two strings:”);

gets(str1);

gets(str2);

if(strcmp(str1,str2)==0)

printf(“String are same\n”);

else

printf(“String are not same\n”);

strcpy()

60 *Under revision
This function is used to copying one string to another string. The function
strcpy(str1,str2) copies str2 to str1 including the NULL character. Here str2 is the
source string and str1 is the destination string.

The old content of the destination string str1 are lost. The function returns a pointer
to destination string str1.

Example:-

#include<stdio.h>

#include<string.h>

void main()

char str1[10],str2[10];

printf(“Enter a string:”);

scanf(“%s”,str2);

strcpy(str1,str2);

printf(“First string:%s\t\tSecond string:%s\n”,str1,str2);

strcpy(str,”Delhi”);

strcpy(str2,”Bangalore”);

printf(“First string :%s\t\tSecond string:%s”,str1,str2);

strcat()

61 *Under revision
This function is used to append a copy of a string at the end of the other string. If
the first string is “”Purva” and second string is “Belmont” then after using this
function the string becomes “PusvaBelmont”. The NULL character from str1 is
moved and str2 is added at the end of str1. The 2nd string str2 remains unaffected.
A pointer to the first string str1 is returned by the function.

Example:-

#include<stdio.h>

#include<string.h>

void main()

char str1[20],str[20];

printf(“Enter two strings:”);

gets(str1);

gets(str2);

strcat(str1,str2);

printf(“First string:%s\t second string:%s\n”,str1,str2);

strcat(str1,”-one”);

printf(“Now first string is %s\n”,str1);

Output

Enter two strings: data

Base

62 *Under revision
First string: database second string: database

` Now first string is: database-one

Lecture Note: 14

FUNCTION

A function is a self contained block of codes or sub programs with a set of


statements that perform some specific task or coherent task when it is called.

It is something like to hiring a person to do some specific task like, every six
months servicing a bike and hand over to it.

Any ‘C’ program contain at least one function i.e main().

There are basically two types of function those are

1. Library function

2. User defined function

The user defined functions defined by the user according to its requirement

System defined function can’t be modified, it can only read and can be used.
These function are supplied with every C compiler

Source of these library function are pre complied and only object code get used by
the user by linking to the code by linker

Here in system defined function description:

Function definition : predefined, precompiled, stored in the library

63 *Under revision
Function declaration : In header file with or function prototype.

Function call : By the programmer

User defined function

Syntax:-

Return type name of function (type 1 arg 1, type2 arg2, type3 arg3)

Return type function name argument list of the above syntax

So when user gets his own function three thing he has to know, these are.

Function declaration

Function definition

Function call

These three things are represented like

int function(int, int, int); /*function declaration*/

main() /* calling function*/

function(arg1,arg2,arg3);

int function(type 1 arg 1,type2 arg2,type3, arg3) /*function definition/*

Local variable declaration;

Statement;

Return value;

64 *Under revision
Function declaration:-
Function declaration is also known as function prototype. It inform the compiler
about three thing, those are name of the function, number and type of argument
received by the function and the type of value returned by the function.

While declaring the name of the argument is optional and the function prototype
always terminated by the semicolon.

Function definition:-

Function definition consists of the whole description and code of the function.

It tells about what function is doing what are its inputs and what are its out put

It consists of two parts function header and function body

Syntax:-

return type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/

Local variable declaration;

Statement 1;

Statement 2;

Return value

The return type denotes the type of the value that function will return and it is
optional and if it is omitted, it is assumed to be int by default. The body of the
function is the compound statements or block which consists of local variable
declaration statement and optional return statement.

65 *Under revision
The local variable declared inside a function is local to that function only. It can’t
be used anywhere in the program and its existence is only within this function.

The arguments of the function definition are known as formal arguments.

Function Call

When the function get called by the calling function then that is called, function
call. The compiler execute these functions when the semicolon is followed by the
function name.

Example:-

function(arg1,arg2,arg3);

The argument that are used inside the function call are called actual argument

Ex:-

int S=sum(a, b); //actual arguments

Actual argument

The arguments which are mentioned or used inside the function call is knows as
actual argument and these are the original values and copy of these are actually
sent to the called function

It can be written as constant, expression or any function call like

Function (x);

Function (20, 30);

Function (a*b, c*d);

Function(2,3,sum(a, b));

Formal Arguments

The arguments which are mentioned in function definition are called formal
arguments or dummy arguments.

66 *Under revision
These arguments are used to just hold the copied of the values that are sent by the
calling function through the function call.

These arguments are like other local variables which are created when the function
call starts and destroyed when the function ends.

The basic difference between the formal argument and the actual argument are

1) The formal argument are declared inside the parenthesis where as the
local variable declared at the beginning of the function block.

2). The formal argument are automatically initialized when the copy of actual
arguments are passed while other local variable are assigned values through the
statements.

Order number and type of actual arguments in the function call should be match
with the order number and type of the formal arguments.

Return type

It is used to return value to the calling function. It can be used in two way as

return

Or return(expression);

Ex:- return (a);

return (a*b);

return (a*b+c);

Here the 1st return statement used to terminate the function without returning any
value

Ex:- /*summation of two values*/

int sum (int a1, int a2);

main()

67 *Under revision
{

int a,b;

printf(“enter two no”);

scanf(“%d%d”,&a,&b);

int S=sum(a,b);

printf(“summation is = %d”,s);

int sum(intx1,int y1)

int z=x1+y1;

Return z;

Advantage of function

By using function large and difficult program can be divided in to sub programs
and solved. When we want to perform some task repeatedly or some code is to be
used more than once at different place in the program, then function avoids this
repeatition or rewritten over and over.

Due to reducing size, modular function it is easy to modify and test

Notes:-

C program is a collection of one or more function.

A function is get called when function is followed by the semicolon.

A function is defined when a function name followed by a pair of curly braces

68 *Under revision
Any function can be called by another function even main() can be called by other
function.

main()
{

function1()

function1()

Statement;

function2;

function 2()

So every function in a program must be called directly or indirectly by the main()


function. A function can be called any number of times.

A function can call itself again and again and this process is called recursion.

A function can be called from other function but a function can’t be defined in
another function

Lecture Note: 15
Category of Function based on argument and return type

i) Function with no argument & no return value

69 *Under revision
Function that have no argument and no return value is written as:-

void function(void);

main()

void function()

Statement;

Example:-

void me();

main()

me();

printf(“in main”);

void me()

printf(“come on”);

Output: come on

inn main

70 *Under revision
ii) Function with no argument but return value

Syntax:-

int fun(void);

main()

int r;

r=fun();

int fun()

reurn(exp);

Example:-

int sum();

main()

int b=sum();

printf(“entered %d\n, b”);

int sum()

int a,b,s;
71 *Under revision
s=a+b;

return s;

Here called function is independent and are initialized. The values aren’t passed by
the calling function .Here the calling function and called function are
communicated partly with each other.

Lecture Note: 16

iii ) function with argument but no return value

Here the function have argument so the calling function send data to the called
function but called function dose n’t return value.

Syntax:-

void fun (int,int);

main()

int (a,b);

void fun(int x, int y);

Statement;

72 *Under revision
Here the result obtained by the called function.

iv) function with argument and return value

Here the calling function has the argument to pass to the called function and the
called function returned value to the calling function.

Syntax:-

fun(int,int);

main()

int r=fun(a,b);

int fun(intx,inty)

return(exp);

Example:

main()

int fun(int);

int a,num;

printf(“enter value:\n”);

scanf(“%d”,&a)

73 *Under revision
int num=fun(a);

int fun(int x)

++x;

return x;

Call by value and call by reference

There are two way through which we can pass the arguments to the function such
as call by value and call by reference.

1. Call by value

In the call by value copy of the actual argument is passed to the formal argument
and the operation is done on formal argument.

When the function is called by ‘call by value’ method, it doesn’t affect content of
the actual argument.

Changes made to formal argument are local to block of called function so when the
control back to calling function the changes made is vanish.

Example:-

main()

int x,y;

change(int,int);

74 *Under revision
printf(“enter two values:\n”);

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

change(x ,y);

printf(“value of x=%d and y=%d\n”,x ,y);

change(int a,int b);

int k;

k=a;

a=b;

b=k;

Output: enter two values: 12

23

Value of x=12 and y=23

2. Call by reference

Instead of passing the value of variable, address or reference is passed and the
function operate on address of the variable rather than value.

Here formal argument is alter to the actual argument, it means formal arguments
calls the actual arguments.

Example:-

void main()

75 *Under revision
{

int a,b;

change(int *,int*);

printf(“enter two values:\n”);

scanf(“%d%d”,&a,&b);

change(&a,&b);

printf(“after changing two value of a=%d and b=%d\n:”a,b);

change(int *a, int *b)

int k;

k=*a;

*a=*b;

*b= k;

printf(“value in this function a=%d and b=%d\n”,*a,*b);

Output: enter two values: 12

32

Value in this function a=32 and b=12

After changing two value of a=32 and b=12

So here instead of passing value of the variable, directly passing address of the
variables. Formal argument directly access the value and swapping is possible even
after calling a function.

76 *Under revision
Lecture Note: 17

Local, Global and Static variable

Local variable:-

variables that are defined with in a body of function or block. The local
variables can be used only in that function or block in which they are declared.
Same variables may be used in different functions such as

function()

int a,b;

function 1();

function2 ()

int a=0;

b=20;

Global variable:-

77 *Under revision
the variables that are defined outside of the function is called global variable. All
functions in the program can access and modify global variables. Global variables
are automatically initialized at the time of initialization.

Example:

#include<stdio.h>

void function(void);

void function1(void);

void function2(void);

int a, b=20;

void main()

printf(“inside main a=%d,b=%d \n”,a,b);

function();

function1();

function2();

function()

Prinf(“inside function a=%d,b=%d\n”,a,b);

function 1()

78 *Under revision
prinf(“inside function a=%d,b=%d\n”,a,b);

function 2()

prinf(“inside function a=%d,b=%d\n”,a,);

Static variables: static variables are declared by writing the key word static.

-syntax:-

static data type variable name;

static int a;

-the static variables initialized only once and it retain between the function call. If
its variable is not initialized, then it is automatically initialized to zero.

Example:

void fun1(void);

void fun2(void);

void main()

fun1();

fun2();

void fun1()

79 *Under revision
int a=10, static int b=2;

printf(“a=%d, b=%d”,a,b);

a++;

b++;

Output:a= 10 b= 2
a=10 b= 3

Recursion

When function calls itself (inside function body) again and again then it is
called as recursive function. In recursion calling function and called function are
same. It is powerful technique of writing complicated algorithm in easiest way.
According to recursion problem is defined in term of itself. Here statement with in
body of the function calls the same function and same times it is called as circular
definition. In other words recursion is the process of defining something in form of
itself.

Syntax:

main ()

rec(); /*function call*/

rec();

rec();

Ex:- /*calculate factorial of a no.using recursion*/

int fact(int);

void main()

80 *Under revision
{

int num;

printf(“enter a number”);

scanf(“%d”,&num);

f=fact(num);

printf(“factorial is =%d\n”f);

fact (int num)

If (num==0||num==1)

return 1;

else

return(num*fact(num-1));

Lecture Note: 18

Monolithic Programming

The program which contains a single function for the large program is called
monolithic program. In monolithic program not divided the program, it is huge
long pieces of code that jump back and forth doing all the tasks like single thread
of execution, the program requires. Problem arise in monolithic program is that,
when the program size increases it leads inconvenience and difficult to maintain

81 *Under revision

You might also like