Bpopc Module 03
Bpopc Module 03
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.
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
Output:
Enter number:
4
Square root=2.00000
Output:
Enter number:
27
cube root=3.00000
clrscr(),getch(),getchar(),getche(),gets(),putchar(),pu
2 Console I/O Library <conio.h>
tch(),puts()
1. Function Declaration
• EveryfunctioninCprogramshouldbedeclaredbeforetheyareused.
• Functiondeclarationgivescompilerinformationabout
→ function name
→ type of arguments to be passed and
→ return type
Syntax:
or
Example:
int add(int a, int b);
2. Function Call
Syntax:
function_name(argument(1),.. . .,argument(n));
Example:
add(a,b);
3. Function Definition
Syntax:
Example:
int add(int a, int b)
{
int sum; // local variable
declaration sum=a+b; // statement
return sum; // return expression
}
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
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.
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.
#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);
}
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.
#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);
}
Output:
a=20
b=10
Output:
Enter a and b : 2 3
sum=5
}
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
Output: Enter
a and b 2 3
sum=5
#include <stdio.h>
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;
}
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.
fact(n)= 1 if n==0
n*fact(n-1)
otherwise
#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
#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
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
#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));
}
LAB PROGRAMS
#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”);
}
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);
}
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
#include <stdio.h>
int c; //global variable
void main()
{
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
#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:
Examples:
Array of 5 integers:
Array of 5 characters:
• 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
CLASSIFICATION/TYPES OF ARRAYS:
data_typearray_name[array_size];
example:
int a[5];
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.
• Assigning or providing the required values to a variable before processing is called initialization.
Syntax:
data_type array_name[array_size]={v1,v2,...,vn};
example:
int a[5]={10,20,30,40,50};
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};
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};
10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]
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};
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)
• The elements 10,20,30,40 and 50 can be inserted into array at positions 0,1,2,3,4,5, as shown below.
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]);
}
#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
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]);
}
}
• 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
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.
Example:
int a[4][3]={
{11,22},
{33,44},
{55,66},
{77,88}
};
• 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:
#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];
}
}
#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
Output:
aggregate marks= 70
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