0% found this document useful (0 votes)
19 views38 pages

Bpopc Module 03

Uploaded by

Shobha Hiremath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views38 pages

Bpopc Module 03

Uploaded by

Shobha Hiremath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Notes on Principles of Programming Using C BPOPS203

MODULE 03
FUNCTIONS AND ARRAYS

FUNCTION IN C
• A function is a collection of statements that performs a specific task.
• Functions are very useful to read, write, debug and modify complex programs. A function can also be
referred as a method or a sub-routine or a procedure.
• One reason to use functions is that they break a program into small, manageable units. Each unit is
called module which performs a specific task.
• Another reason to use function is that they simplify programs.
• Every C program has at least one function main( ).Without main() function, there is technically no C
program.

• Advantages of a functions/Why Functions?


 It will help us to divide the large programs into small groups so that, we can understand
and debug the program quicker and better.
 Multiple persons can work on same program by assigning different functions to each of
them.
 Prevent us from writing same logic multiple times (duplicating).
 Helps us to call the same function over and over.

• Program to print a sentence using function is shown below.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

TYPES OF C FUNCTIONS
• There are 2 types of functions in C programming:
1. Library Functions/built-in functions/pre-defined functions
2. User defined functions

1. Library Function
• Libraryfunctionsarethein-builtfunctioninCcompiler.
• Functions which are defined in C library are called library functions or built-in functions.
• These functions are also called as pre-defined functions.
• Forexample:
→main() //The execution of every C program starts from this main() function
→printf() //printf() is used for displaying output inC
→scanf() //scanf() is used for reading/taking input inC

1. Program to find square root of a number using built-in function (sqrt)


#include<stdio.h>
#include<math.h>
void main()
{
int n;
float x;
printf(“enter number:\n”);
scanf(“%d”,&n);
x=sqrt(n);
printf(“square root=%f\n”,x);
}

Output:
Enter number:
4
Square root=2.00000

2. Program to find cube root of a number using built-in function (cbrt)


#include<stdio.h>
#include<math.h>
void main()
{
int n;
float x;
printf(“enter number:\n”);
scanf(“%d”,&n);
x=cbrt(n);
printf(“cube root=%f\n”,x);
}

Output:
Enter number:
27
cube root=3.00000

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

• C provides many built-in functions


 Standard I/O functions
 String Manipulation Functions
 Character manipulation Functions
 Mathematical Functions
 Memory Management Functions

S.No Libraries Functions Header Files

1 Standard I/O Library printf(), scanf() <stdio.h>

clrscr(),getch(),getchar(),getche(),gets(),putchar(),pu
2 Console I/O Library <conio.h>
tch(),puts()

3 Standard Library exit(0) <stdlib.h>

strlen(), strcpy(), strcmp(), strcat(), strrev(), strlwr(),


4 String Library <string.h>
strupr(), strchr()

5 Character library tolower(), toupper(), isalpha(), isascii() <ctype.h>

sqrt(), cbrt(), pow(), exp(), abs(), fabs(), sin(x), cos(x),


6 Math Library <math.h>
log(x), ceil(), floor()

7 Memory allocation malloc(), calloc(), realloc(), free() <malloc.h>

8 Time Library time(), clock() <time.h>

2. User Defined Function


• C allows programmer to define their own function according to their requirement. These types of
functions are known as user-definedfunctions.
• Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in
same program. Then, he can create two separate user-defined functions in that program:
→ one for finding factorial and
→ other for checking whether it is prime ornot
Example: add(), isprime(), factorial(),. etc

ADVANTAGES OF USER DEFINED FUNCTIONS


1) User defined functions helps to decompose the large program into small segments which makes
programmereasytounderstand,maintainanddebug.
2) If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling thatfunction.
3) Programmerworkingonlargeprojectcandividetheworkloadbymakingdifferentfunctions.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

FUNCTIONS AND PROGRAM STRUCTURE


• BasicstructureofCprogramwithfunctionisshownbelow
: #include<stdio.h>
void function_name(); //function declaration
void main()
{
...........
...........
function_name(); // function call or calling function
...........
...........
}

void function_name() //function definition


{
................
................
}
• Every C program begins from main() and program starts executing the codes inside main()function.
• When the control of program reaches to function_name() inside main() function, the control of
Program jumps to void function_name() and executes the codes inside it.
• When all the codes inside that user-defined function are executed, control of the program jumps to
the statement just after function_name() from where it is called.

Elements of Functions/user defined functions

1. Function Declaration

• EveryfunctioninCprogramshouldbedeclaredbeforetheyareused.
• Functiondeclarationgivescompilerinformationabout
→ function name
→ type of arguments to be passed and
→ return type
Syntax:

return_type function_name(type(1) argument(1),.....,type(n) argument(n));

or

return_type function_name(parameter list);

Example:
int add(int a, int b);

function name is add


return type can be int or void
arguments/parameters are a and b
(arguments/parameters are data values which are passed to functions)

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

2. Function Call

• Control of the program cannot be transferred to user-defined function unless it is called


invoked. It is also known as calling function.
• The function can be called by writing the name of the function and passing the appropriate
number of arguments.

Syntax:
function_name(argument(1),.. . .,argument(n));

Example:
add(a,b);

add is a function name.


a and b are arguments.

3. Function Definition

• Function definition contains programming codes to perform a specific task.


• The function body contains a collection of statements that define what the function does.

Syntax:

return_type function_name(type(1) argument(1),….,type(n) argument(n))


{

local variable declaration


statement(s) //body of function
return expression
}

Example:
int add(int a, int b)
{
int sum; // local variable
declaration sum=a+b; // statement
return sum; // return expression
}

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

TYPES OF FUNCTION ARGUMENTS/PARAMETERS


The arguments or parameters are classified as
• Actual parameters
• Formal parameters
ACTUAL AND FORMAL PARAMETERS/ARGUMENTS
Actual Parameters:
• Argument (or parameter) refers to data that is passed to function (function definition) while calling
function.
• Arguments listed in function calling statements are referred to as actual arguments. The variables
that are used when a function is invoked are called actual parameters.
• These actual values are passed to a function to compute a value or to perform a task.

Formal Parameters:
• The variables defined in the function header of function definition are called formal parameters.
• They are simply formal variables that accept or receive the values supplied by the calling function.
• The formal parameters are also called dummy parameters.
• Thenumberofactualandformalargumentsandtheirdatatypesshouldbesame.
Example: Program to add two integers/numbers using functions

#include<stdio.h>
int add(int a, int b);
int main()
{
int a,b,sum;
printf("Enter a and b \n");
scanf("%d%d",&a,&b);
sum=add(a,b); //actual arguments
printf("sum=%d\n", sum);
return 0;
}
int add(int a,intb)
//formal arguments
{
int sum;
sum=a+b;
return sum;
}

Output:
Enters two number to add
23
sum=5

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

Differences between Actual and Formal Parameters

Actual Parameters Formal Parameters

1. Actual Parameters are used in calling 1.Formal Parameters are used in the function
function when a function is invoked. header of a called function.
Example: Example:
sum=add(a,b); int add(int x, int y)
Here, a and b are actual parameters {
…..……
}
Here, x and y are called formal parameters
or dummy parameters.

2. Actual Parameters can be constants, 2. Formal Parameters should be only variables.


variables or expressions. Expressions and Constants are not allowed.
Example: Example:
sum=add(a+4,b); int add(int x, int y) //correct int
add(int x+y,int y) //error int
add(int x, 10) //error

3. Actual Parameters sends values to formal 3. Formal Parameters receive values from the
Parameters. actual parameters.
Example: Example:
Sum=add(4,5); int add(int x, int y)
{
………..
}
Here, x will have the value 4 and y will have
the value 5.

4. Addresses of actual parameters can be sent 4. If formal parameters contains addresses,


to formal parameters. they should be declared as pointers.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

PASSING PARAMETERS TO FUNCTIONS/ARGUMENT PASSING /PARAMETER PASSING


TECHNIQUES
There are three ways of passing parameters to the function:
1. Pass by value(call by value)
2. Pass by reference(call by reference)
3. Pass by address (call by address)

1. PASS BY VALUE ( CALL BY VALUE )


• In pass by value, the values of actual parameters are copied into formal parameters. Formal
parameters contain only the copy of actual parameters.
• Any changes made in the formal parameters does not effect/change the actual parameters.
• Pass by value is restricted to one-way transfer of information from calling function to called function.

Example:Program to exchange two numbers using call by value

#include<stdio.h>
void exchange(int x, int y);

void main()
{
int a,b;
a=10, b=20;
exchange(a,b); //a and b are actual parameters

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

void exchange(int x,int y) // x and y are formal parameters


{
int temp;
temp=x;
x=y;
y=temp;
}

Output:
a=10
b=20

• The function exchange() is called with actual parameters a and b whose values are 10 and 20.
• In the function header of function exchange() the formal parameters x and y receives the
values 10 and 20.
• In the function exchange(), the values of x and y are exchanged(swapped). x=20, y=10
• But, the values of actual parameters a and b in function main() have not been exchanged.
• The values of a=10 and b=20 remains same they are not changed even if formal parameters are
changed.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

2. PASS BY REFERENCE ( CALL BY REFERENCE )


• In pass by reference, the formal parameters are treated as aliases (alternate names) for actual
parameters. Any change in formal parameter will also effect the actual parameter.
• In this technique, if formal parameters changes then actual parameters are also changes.

Example: Program to exchange two numbers using call by reference

#include<stdio.h>
void exchange(int *x, int *y);

void main()
{
int a,b;
a=10, b=20;
exchange(&a,&b); //a and b are actual parameters

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

void exchange(int *x,int *y) // x and y are formal parameters


{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Output:
a=20
b=10

• The function exchange() is called by sending addresses of a and b.


• In the function header of function exchange(), the formal parameters x and y declared using
*operator holds the address of a and b.
• In the function exchange(), using *x and *ythe values of a and b can be accessed and they are
changed.
• The values of actual parameters are exchanged (a=20 and b=10). If there are any changes in the
formal parameter then actual parameters also changes.

3. PASS BY ADDRESS/CALL BY ADDRESS


• In pass by address, the addresses of actual parameters are copied into formal parameters.
• Using these addresses, the values of the actual parameters can be changed.
• This way of changing the actual parameters indirectly using the addresses of actual
parameters is called pass by reference.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

TYPES OFUSER DEFINED FUNCTIONS BASED ON PARAMETERS AND RETURN VALUES


OR
CLASSIFICATION/CATEGORIES OF FUNCTIONS BASED ON PARAMETERS AND RETURN VALUES
There are 4 types of Functions based on parameters and return values
1. Function with no parameters and no returnvalues
2. Functionwithnoparametersandreturnvalues
3. Function with parameters and no returnvalues
4. Function with parameters and returnvalue

1. Function with no parameters and no returnvalues/(void functions with no parameters).


No parameter is passed from calling function to the called functionand the called function does not
return any value to the calling function. There is no data transfer between the calling and called
function.

Example: Program to illustrate function with no parameters and no return value.


#include<stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a, b, sum;
printf("Enters a and b:\n ");
scanf("%d %d", &a, &b);
sum=a+b; printf("sum=
%d", sum);
}

Output:
Enter a and b : 2 3
sum=5

2. Function with no parameters and return values


In this category no parameter is passed from calling function to the called function, but function
returns a value. There is no data transfer from the calling function to the called function. But, there
is data transfer from called function to the calling function.

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


Notes on Principles of Programming Using C BPOPS203

Example: Program to illustrate function with no parameters and return value.


#include<stdio.h>
int add();
void main()
{
int sum;
sum=add();
printf("\n sum=%d", sum);

}
int add()
{
int a, b, sum;
printf(“enter a and b\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
return sum;
}

Output:
Enter a and b : 2 3
sum=5

3. Function with parameters and no returnvalues


Parameters are passed from calling function to the called function and called function does not return
a value. There is a data transfer from calling function to called function using parameters. But, there
is no data transfer from called function to the calling function.

Example: Program to illustrate function with parameters and no return values.


#include <stdio.h>
void add(int a, int b);
void main()
{
int a, b, sum;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);
add(a, b);
}
void add(int a, int b)
{
int sum;
sum= a+ b;
printf("\n sum=%d", sum);
}

Output: Enter
a and b 2 3
sum=5

By, Shanta K, Dept CSE, KLEIT, Hubballi-27


C Programming for Problem Solving 18CPS23

4. Function with parameters and returnvalues


In this category parameter is passed from calling function to the called function and function
returns a value. There is data transfer from the calling function to the called function. calling
function can receive a value from the called function.

Example: Program to illustrate function with parameters and return values.

#include <stdio.h>

int add(int a, int b);

int main()
{
int a, b, sum; printf("Enter
a and b:\n"); scanf("%d
%d", &a, &b); add(a, b);
printf("\n sum=%d", sum);
return 0;
}

int add(int a, int b)


{
int sum;
sum= a+ b;
return sum;
}

Output:

Enter a and b
23
sum=5
C Programming for Problem Solving 18CPS23

RECURSION
The process of solving a problem by reducing the given problem into smaller version of same problem is
called recursion.
• A function that calls itself is known as recursive function.

Example: Factorial of 5 using recursion


fact(5)=5*fact(4)
=5*4*fact(3)
=5*4*3*fact(2)
=5*4*3*2*fact(1)
=5*4*3*2*1*fact(0)
=5*4*3*2*1*1
=120
5!= 5*4!
n!=n*(n-1)!

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

1. Program to find factorial of a number using recursion


#include<stdio.h>
int factorial(int n);
void main()
{
int n,fact;
printf(“enter a number:\n”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“fact=%d\n”,fact);
}
int factorial(int n)
{
if( n==0)
return 1;
else
return (n*factorial(n-1));
}
C Programming for Problem Solving 18CPS23

Example: Sum of first 5 natural numbers


n=5
=add(5)
=5+ add(4)
=5+4+ add(3)
=5+4+3+ add(2)
=5+4+3+2+ add(1)
=5+4+3+2+1+ add(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Explanation:
• Here, add()functionisinvokedfromthesamefunction.
• If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous
argument it was calledwith.
• Suppose, n is 5 initially. Then, during next function calls, 4 ispassed to function and the value of
argument decreases by 1 in each recursivecall.
• When,n becomes equal to 0,the value of n is returned which is the sum numbers from 5 to 1.
• Observe the following for better visualization of recursion in this example:
• Every recursive function must be provided with a way to end the recursion. In this example when,n
is equal to 0, there is no recursive call and recursion ends.

2. Program to find sum of first n natural numbers using recursion.

#include <stdio.h>
int add(int n);
void main()
{
int num, sum;
printf("Enter a positive integer:");
scanf("%d",&num);
sum=add(num); printf("sum=
%d",sum);
}
int add(int n)
{
if(n==0)
return 0;
else
return n+add(n-1);
/*self call to function add()*/
}

Output:
Enter a positive integer: 5
15
C Programming for Problem Solving 18CPS23

3. Program to find factorial of number and value of nCr using recursion

#include<stdio.h>
int factorial(int n);
void main()
{
int n,x,y,z,ncr;
printf(“enter n and r:\n”);
scanf(“%d%d”,&n,&r);
x=factorial(n);
y=factorial(n-r);
z=factorial(r);
ncr=x/(y*z); printf(“ncr=
%d\n”,ncr);
}
printf(“fact=%d\n”,fact);
}
int factorial(int n)
{
if( n==0)
return 1;
else
return (n*factorial(n-1));
}

Output:
Enter n and r:
52
ncr=10

Example: Fibonacci Series using recursion

0, 1,1,2,3,5,8,13,21,……..

0 if n=0
fib(n)=1 if n=1
fib(n-1)+fib(n-2) if n>=2
C Programming for Problem Solving 18CPS23

4. Program to print Fibonacci series using recursion

#include<stdio.h>
int fibonacci(int n);
void main()
{
int i,n,x;
printf(“enter n:\n”);
scanf(“%d”,&n);
printf(“Fibonacci series:\n”);
for(i=0;i<n;i++)
{
x=fibonacci(i);
printf(“%d\n”,x);
}
}
int fibonacci(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return (fibonacci(n-1)+fibonacci(n-2));
}

5. Program to find GCD and LCM of two numbers using recursion


#include<stdio.h>
int gcd(int x, int y);
void main()
{
int x,y,z,lcm;
printf(“enter 2 numbers:\n”);
scanf(“%d%d”,&x,&y);
z=gcd(x,y); printf(“gcd=%d\
n”,z); lcm=(x*y)/z;
printf(“lcm=%d\n”,lcm);
}
int gcd(int x, int y)
{
int rem;
rem=x%y;
if(rem==0)
return y;
else
return (gcd(y,rem));
}
C Programming for Problem Solving 18CPS23

LAB PROGRAMS

1. Program to check a given number is prime or not using functions

#include<stdio.h> int
isprime(int num);
void main()
{
int num,result;
printf("Enter number\n");
scanf("%d”,&num);
result=isprime(num);
if(result==1)
printf(“It isprime number\n”);
else
printf(“not prime number\n”);
}

int isprime(int num)


{
int i;
if(num==0 || num==1)
return 0;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
return 0;
}
return 1;
}

2. Program to convert binary to decimal using recursion


#include<stdio.h>
int bintodec(long int binnum);

void main()
{
long int binnum,decnum;
printf(“enter binary number in the form of 0’s and 1’s\n”); scanf(“%ld”,&binnum);
decnum=bintodec(binnum);
printf(“decimal number=%ld\n”,decnum);
}

int bintodec(long int binnum)


{
if(!(binnum/10))
returnbinnum;
else
return (binnum%10+bintodec(binnum/10)*2);
}
C Programming for Problem Solving 18CPS23

STORAGE CLASSES
• Every variable in C program has two properties: type and storage classes.
• Type refers to the data type of variable whether it is character or integer or floating-point value etc.
• And storage class determine show long it stays in existence.
• There are 4 types of storageclasses:
1. automatic(orlocal)
2. external(orglobal)
3. static
4. register

1. AUTOMATIC /LOCAL VARIABLE


• Variablesdeclaredinsidethefunctionbodyareautomaticbydefault.
• These variables are also known as local variables as they are local to the function and doesn't have
meaning outside that function.
• Forexample:
int a,b;
or
auto int a,b;
• Since,variableinsideafunctionisautomaticbydefault,keywordautoarerarelyused.

2. EXTERNAL /GLOBAL VARIABLES


• External variable can be accessed by any function. They are also known as global variables.
• Variables declared outside every function are external/global variables.
• To solve this problem, keyword extern is used to indicate that, the variable specified is
global variable and declared in another file.

Example:Program to demonstrate working local and global variables.

#include <stdio.h>
int c; //global variable

void main()
{

auto int a, b; // a and b are local variables


printf("Enter a and b:\n");
scanf("%d %d", &a,&b);
c=a+b;
display();
}

void display()
{
printf("\n sum=%d", c);
}
Principles Of Programming In C BPOPS203 Notes On Module 03

3. REGISTER VARIABLES
• Register variables are similar to automatic variable and exists inside that particular function only.
• For example:
register int z;
where z is register variable
• If the compiler encounters register variable, it tries to store variable in microprocessor's
register rather than memory.
• Value stored in register are much faster to access than that of memory.
• In case of larger program, variables that are used in loops and function parameters are
declared register variables.
Example: Program to illustrate use of register variable.
#include<stdio.h>
void main()
{
int a,b;
register int z;
printf("Enter a and b \n");
scanf("%d %d", &a, &b);
z=a+b;
printf("\n sum=%d", z);
}

Output:
Enters two number to add
23
sum=5

4. STATIC VARIABLE
• The value of static variable persists until the end of the program.
• For example:
static int c;
where c is a static variable
Example:Program to demonstrate working of static variable.

#include<stdio.h>
void display(); void
main()
{
display();
display();
display();
display();
display();
}
void display()
{
static int i;
i=0;
i++;
printf(“%d\t”,i)
}
Principles Of Programming In C BPOPS203 Notes On Module 03

ARRAYS

BASIC CONCEPT OF ARRAYS


• Consider a situation, where we need to store 5 integer numbers.
• If we use simple variable and data type concepts, then we need 5 variables of int data type and
program will be something as follows:

#include<stdio.h
>void main()
{
int a,b,c,d,e;
a=10;
b=20;
c=30;
d=40;
e=50;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
printf("d=%d\n",d);
printf("e=%d\n",e);
}

Output:
a=10
b=20
c=30
d=40
e=50

 It was simple, because we had to store just 5 integer numbers. Now let's assume we have to store
5000integernumbers,so what is next? Are we going to use 5000 variables?
The main disadvantage of using above simple program are:
 Difficult to declare more number of variables.
 Difficult to read and write a program. It is difficult to print the data stored in more number of
variables.
 Very difficult to process large amount of data.
 Length of a program increases as the number of variable increases.
 Consumes too much time to write, modify and correct.
 It is not a good programming style.
• How to process large amount of data?
 All these disadvantages can overcome by using a very powerful data structure called Arrays
along with looping constructs.
Principles Of Programming In C BPOPS203 Notes On Module 03

ARRAY
• Array is a collection of elements of same data type.
• It is used to store, process and print large amount of data.
• The elements are stored sequentially one after the other in memory.
• It is also known as homogeneous collection of elements of same type.
• Array data type: data type of an array can be int, double, float and char
• Any element can be accessed by using
→ name of the array
→ position of element in the array

Representation of an array:

array[0] array[1] array[2] ………… array[n-1]

Examples:

 Array of 5 integers:

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


10 20 30 40 50

 Array of 5 floating point numbers:

b[0] b[1] b[2] b[3] b[4]


10.0 20.0 30.0 40.0 50.0

 Array of 5 characters:

c[0] c[1] c[2] c[3] c[4]


‘A’ ‘B’ ‘C’ ‘D’ ‘E’

How to access the elements of the array:

Consider the pictorial representation of an array of 5 integers.

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


10 20 30 40 50

• The array is identified by name a i.e, any element in the array can be accessed using the common
name.
• The element can be accessed using the subscript 0 ( also called index 0 ) along with name of array
• Index: An index is also called the subscript is the position of an element in the array.
• Using the index, we can access the elements.
Principles Of Programming In C BPOPS203 Notes On Module 03

Example to access the elements of an array:


• 0th element 10 can be accessed by specifying a[0]
• 1st element 20 can be accessed by specifying a[1]
• 2ndelement 30 can be accessed by specifying a[2]
• 3rd element 40 can be accessed by specifying a[3]
• 4thelement 50 can be accessed by specifying a[4]

Basic Properties of an array:


• The data items(called elements) stored in an array should be of the same data type.
• The data items are stored contiguously in memory (one after other).
• The subscript of first item is always zero.
• Each data item is accessed using the name of the array, but, with different subscripts.
• The index of the array is always an integer.
Example: a[1] // OK Index is an integer.
a[1.5] // Error Index has to be integer not floating point.
a[‘5’] // Ok Index is an integer. ‘5’ has an ASCII value which is integer.

CLASSIFICATION/TYPES OF ARRAYS:

Arrays are of 2types:


1) Single dimensionalarray(One Dimensional-1D array)
2) Multi-dimensionalarray (Two Dimensional-2D array)

1. Single dimensional array(1D array):


• Single dimensional array is the simplest type of array that contains only one row (linear list) for
storing the values of same type.
• Inmemory,all the elements are stored in continuous memory-location one after the other.

Declaration of Single Dimensional Array (1D array)

An array must be declared and defined before it is used.


syntax:

data_typearray_name[array_size];

where,data_type can be int,float or char


array_nameis name of the array
array_size indicates number of elements in the array

example:

int a[5];

Pictorial representation of an Array of 5 integers


Principles Of Programming In C BPOPS203 Notes On Module 03

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

Note that, the first element is numbered 0 and so on….


• Since sizeof(int) is 2 bytes. 2*5=10 bytes. 10 memory locations are reserved for an array of 5 integers.

example:

float b[5];

Since sizeof(float) is 4 bytes. 4*5=20 bytes. 20 memory locations are reserved for an array of 5
floating point numbers.

example:

char c[5];

Since sizeof(char) is 1 bytes. 1*5=5 bytes. 5 memory locations are reserved for an array of 5
characters.

STORING VALUES IN ARRAYS

• The values can be stored in array using following three methods:


1) Initialization
2) Assigning values
3) Input values from keyboard

1. Initialization of Single-Dimensional Array(1D array)

• Assigning or providing the required values to a variable before processing is called initialization.

Syntax:

data_type array_name[array_size]={v1,v2,...,vn};

where,v1, v2,…, vn are values

example:

int a[5]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

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


10 20 30 40 50

There are various ways of initializing arrays:


• Initializing all specified memory locations
Principles Of Programming In C BPOPS203 Notes On Module 03

• Partial array initialization


• Initialization without size
• Array initializing with a string

1. Initializing all specified memory locations:

Arrays can be initialized at the time of declaration when their initial values are known in advance.
During compilation 5 contiguous memory locations are reserved by the compiler for the variable a. The
size is 2 bytes then 10 memory locations will be allocated for variable a.
Example:

int a[5]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

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


10 20 30 40 50

2. Partial Array Initialization:

If the number of values to be initialized is less than the size of array, then the elements are initialized
in the order from 0th location. The remaining locations will be initialized to zero automatically.
Example:

int a[5]={10,20};

Pictorial representation of partial array:


Append 0’s

10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]

3. Initialization without size:

In this method even if the size is not specified the array size will be set to the total number of initial
values specified. Since the number of elements is 5 , totally 5*2=10 bytes are reserved.
Example:

int a[]={10,20,30,40,50};

The above code can be pictorially represented as shown below:

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


10 20 30 40 50

4. Array Initialization with a string:

Sequence of characters enclosed within a double quotes is a string. The string always ends with NULL
Principles Of Programming In C BPOPS203 Notes On Module 03

character ‘\0’.
Example:

char c[]=”COMPUTER”;

C 0 M P U T E R \0

Size of array is 9 bytes ( i.e String length+1 byte for null character)

2. Assigning values to array:


• How to assign values to array without initialization?
We can assign values to individual elements of the array using the assignment operator.

Declaration: Memory representation:

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


int a[5];

• The elements 10,20,30,40 and 50 can be inserted into array at positions 0,1,2,3,4,5, as shown below.

 After executing the instruction: The value 10 is stored in array a at position 0.

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


a[0]=10; 10

 After executing the instruction: The value 20 is stored in array a at position 1.

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


a[1]=20; 10 20

 After executing the instruction: The value 30 is stored in array a at position 2.

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


a[2]=30; 10 20 30

 After executing the instruction: The value 40 is stored in array a at position 3.


a[0] a[1] a[2] a[3] a[4]
a[3]=40; 10 20 30 40

 After executing the instruction: The value 50 is stored in array a at position 5.


a[0] a[1] a[2] a[3] a[4]
a[4]=50; 10 20 30 40 50
Principles Of Programming In C BPOPS203 Notes On Module 03

• Is it possible to assign one array to another?

 It is not possible to assign one array to other array.


Example:
int a[5]={10,20,30,40,50};
int b[5];
b=a; // Error Cannot assign one array to other array

 But we can copy all individual elements of one array a into other array b.

Example:
b[0]=a[0]; // b[0] is assigned the value of a[0]
b[1]=a[1]; // b[1] is assigned the value of a[1]
b[2]=a[2]; // b[2] is assigned the value of a[2]
b[3]=a[3]; // b[3] is assigned the value of a[3]
b[4]=a[4]; // b[4] is assigned the value of a[4]

b[i]=a[i];
i=0 to 4

 b[i]=a[i] can be executed for all values of i=0 to 4 using for loop.

Example:

for(i=0;i<=4;i++)
{
b[i]=a[i];
}

or

for(i=0;i<5;i++)
{
b[i]=a[i];
}

3. Reading/Writing ID Arrays:
• How to read the data from keyboard and how to display data items stored in the array?
We can easily read, write or process the array elements using loop constructs (for, while and do-while).
• We can read ‘n’ array elements from keyboard using scanf().
Example:

for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}

• Similarly to display ‘n’ elements stored in the array replace scanf() by printf() statement.
Example:
Principles Of Programming In C BPOPS203 Notes On Module 03

for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}

Example: Program to read and display one-dimensional array.

#include<stdio.h>
void main()
{
int i,n,a[10];
printf(“enter the size of array:\n”);
scanf(“%d”,&n);
printf(“enter the elements of array:\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]); //read array elements
}
printf(“array elements are:\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]); //display or print array elements
}
}

Output:
enter the size of array:
5
enter the elements of array:
10
20
30
40
50
The array elements are:
10 20 30 40 50
Principles Of Programming In C BPOPS203 Notes On Module 03

Applications of 1D arrays
• It is used for searching an element
• It is used for sorting elements
• It is used for storing elements of same type.

SEARCHING:
The process of identifying or finding a particular record or element is called searching.
2 Important Searching Techniques are:
• Linear Search
• Binary Search

Linear Search/Sequential Search


Linear Search or sequential search is a method for finding a target value within a list. It sequentially checks
each element of the list for the target value until a match is found or until all the elements have been
searched. This technique will search key items in linear order(sequential order) one after the other.

Example: Program tosearch a given element of array using Linear Search Technique.
#include<stdio.h>
void main()
{
int a[10],i,n,key,found=0;
printf(“enter the size of array\n”);
scanf(“%d”,&n);
printf(“enter the elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter key to be searched:\n”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf(“element is found at position:%d\n”,i+1);
found=1;
break;
}
}
if(found==0)
printf(“key not found\n”);
}

Binary Search
Principles Of Programming In C BPOPS203 Notes On Module 03

A binary search is a simple and very efficient searching technique which can be applied if the items to be
compared are either in ascending order or descending order. Therefore, the elements must be in the sorted
form. It compares the middle element if match occurs then the index of item is returned. If the key element is
greater than middle element then the element is searched on the right to the middle element. Otherwise, it is
searched to left of middle element. This process continues until search is successful.
Example: Introduce 1D Array manipulation and implement Binary search.
#include<stdio.h>
void main()
{
int a[10],key,low,high,mid,i,n,found=0;
printf("Enter size of array:\n");
scanf("%d",&n);
printf("Enter the elements in ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the key to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
found=1;
break;
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if (found==1)
printf("key is found in position: %d\n",mid+1);
else
printf(“key is not found\n”);
}
Output:
enter the size of array: 5
enter the elements in ascending order:
10 20 30 40 50
Enter the key to be searched:
50
Key is found at position: 5
SORTING:
Principles Of Programming In C BPOPS203 Notes On Module 03

The process of arranging the elements of array in ascending or descending order is called sorting.
2 techniques used for sorting are:
• Bubble Sort
• Selection Sort
Bubble Sort
It is a simplest sorting algorithm that works by repeatedly swapping the adjacent elements until the elements
are sorted.
Example: C program that reads N integer numbers and arrange them in ascending order using Bubble Sort.
#include<stdio.h>
void main()
{
int n, i, j, a[20], temp;
printf("Enter the size of array:\n");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted elements are:\n");
for(i=0;i<n;i++)
{
printf("%d\t", a[i]);
}
}

Output:
Enter size of array: 5
Enter the elements of array:
50 40 30 20 10
Sorted elements are:
10 20 30 40 50

Selection Sort
Principles Of Programming In C BPOPS203 Notes On Module 03

The Selection Sort algorithm is based on the idea of finding the minimum or maximum element in an unsorted
array and then putting it in its correct position in a sorted array. It repeats and picks up the smallest element
and put it into the right position. It repeats until all elements are in the right position.

Example: Program to sort the elements using Selection Sort Algorithm technique.

#include<stdio.h>
void main()
{
int n, i, j, a[20], temp, minimum;
printf("Enter the size of array:\n");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
minimum=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[minimum])
{
minimum=j;
}
}
temp=a[i];
a[i]=a[minimum];
a[minimum]=temp;
}
printf(“elements in sorted order:\n”);
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}

2. TWO DIMENSIONAL/MULTI DIMENSIONAL ARRAYS (2D arrays)


• Arrays with two or more dimensions are called 2D arrays/multi-dimensional arrays.
Principles Of Programming In C BPOPS203 Notes On Module 03

• A two-dimensional array is used when data items are arranged in row-wise and column wise in a tabular
fashion.
• To identify a particular item we have to specify two indices (also called subscripts): the first index
identifies the row number and the second index the column number of the item.

Declaration of 2D arrays:

Syntax:

data_type array_name[size1][size2];

where
data_type can be int,float,char etc.
array_name is the name of the array
size1: size of number of rows in table.
size2: size of number of columns in table.

Example:

int a[3][4];

It has 3 rows and 4 columns. This declaration informs the compiler to reserve 12 locations(3*4=12)
contiguously one after the other.

Initialization of 2D arrays:
Principles Of Programming In C BPOPS203 Notes On Module 03

Assigning required value to a variable before processing is initialization.

Syntax:

data_type array_name[size1][size2]={
{a1, a2, …..,an},
{b1, b2, …..,bn},
……………………
{z1, z2, …..,zn}
};
where
data_type can be int,float,etc.
array_name is the name of the array
size1: size of number of rows in table.
size2: size of number of columns in table.
a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so on.

There are various ways of initializing 2D arrays


• Initializing all specified memory locations
• Partial array initialization

1. Initializing all specified memory locations


Consider the initialization statement:
int a[4][3]={
{11,22,33},
{44,55,66},
{77,88,99},
{10,11,12}
};

a[0][0]=11, a[2][1]=88, a[3][2]=12 and so on…

2. Partial array initialization


If the number of values to be initialized are less than the size of the array then the elements are
initialized from left to right one after the other. The remaining locations are initialized to zero.
Principles Of Programming In C BPOPS203 Notes On Module 03

Example:

int a[4][3]={
{11,22},
{33,44},
{55,66},
{77,88}
};

Reading and Writing Two Dimensional Arrays


• In general, to read values, we can write:
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
• Similarly, to display elements stored in the matrix,we can write:
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ", a[i][j]);
}
}
Principles Of Programming In C BPOPS203 Notes On Module 03

• Example:
Program to read and write two-dimensional array.

#include<stdio.h>
void main()
{
int a[10][10], i, j;
printf(“ enter the order of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf("enter elements of matrix: \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]); // to read 2D array
}
}
printf("elements of the matrix are: \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", a[i][j]); // to print 2D array
}
printf(“\n”);
}
}

Output:

Enter the order of matrix:


22
Enter the elements of matrix
2 2
2 2
The matrix elements are:
2 2
2 2

By, Mrs. Shanta Kallur Dept. of CSE, KLEIT, Hubballi-27


Principles Of Programming In C BPOPS203 Notes On Module 03

Program to perform addition of two matrix using 2D array

#include<stdio.h>
void main()
{
int a[10][10], b[10][10], c[10][10], i, j;
printf(“ enter the order of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf("enter elements of matrix A: \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("enter elements of matrix B: \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}

printf(“ Resultant Matrix C is:\n”);


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", c[i][j]);
}
}
}

By, Mrs. Shanta Kallur Dept. of CSE, KLEIT, Hubballi-27


Principles Of Programming In C BPOPS203 Notes On Module 03

ARRAYS AND FUNCTIONS


• The arrays can be passed to functions using two methods:

1) Passing Individual Elements ofArray


• All array-elements can be passed as individual elements to a function like any other variable.
• The array-element is passed as a value parameter i.e. any change in the formal-parameter
will not affect the actual-parameter i.e.array-element.

Example:Program to illustrate passing individual elements of an array to a function.

#include<stdio.h>
void display(int a);

void main()
{
int c[3]={2,3,4};
display(c[2]);
}
void display(int a)
{
printf(“%d”,a);
}

Output:
4

2) Passing the Whole Array


• Here, the parameter passing is similar to pass by reference.
• In pass by reference,the formal parameters are treated as aliases for actual parameters.
• So,any changes in formal parameter imply there is a change in actual parameter.

Example:Program to find average of 6marks using pass by reference.


#include <stdio.h>
void average(int m[]);
void main()
{
int m[6]={60, 50, 70, 80, 40, 80,70};
average(m); // Only name of array is passed asargument
}
void average(int m[])
{
int i ,avg;
intavg, sum=0;
for(i=0;i<6;i++)
{
sum= sum+ m[i];
}
avg =(sum/6);
printf("aggregate marks= %d ", avg);
}

Output:
aggregate marks= 70

By, Mrs. Shanta Kallur Dept. of CSE, KLEIT, Hubballi-27


Principles Of Programming In C BPOPS203 Notes On Module 03

Question Bank
1. Define function. List application of function or advantages of functions
2. Write a C Program to swap two numbers using functions.
3. Explain general categories of functions
4. Explain different parameter passing techniques
5. List and explain various categories of user-defined functions.
6. Compare and contract actual and formal parameters
7. Write a c program to find factorial of N
8. Write a c program for calculating nCr using functions
9. Write a C Program for a sequential search
10. Write a C Program for binary search
11. What are the applications of 1-d array
12. List the applications of arrays
13. Write a C Program to sort n number of elements in an array using bubble sort
14. Write a C Program to print even and odd number in array of an n elements
15. Illustrate the declaration of 2-D array with suitable examples
16. Write a C Program to print transpose of the given matrix of order M x N
17. Write a C Program to print principle diagonal elements of given matric A of order P x Q
18. Write a C Program to add two matrix A and B . Print matrix A, matrix B and resultant matrix
19. Write a C Program to subtract two matrix A and B. Print matrix A, matrix B and resultant
matrix
20. Write a C Program to multiply two matrix A and B. Print matrix A matrix B and resultant
matrix

By, Mrs. Shanta Kallur Dept. of CSE, KLEIT, Hubballi-27

You might also like