Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

Principles of Programming Using C

Course Code: BPOPS103


Module 3
Prof. Shilpa B V
TEXT BOOKS

1. E. Balaguruswamy, Programming in ANSI C, 7thEdition, Tata McGraw-Hill, 2017.


2. Fundamentals of Computers, V Rajaraman, 6thEdition, PHI, 2014
20-10-2023 Prof. Shilpa B V 1
• Arrays: • Functions:
• Declaration of arrays, • Introduction using functions,
• Accessing the elements of an • Function definition,
array and Storing values in • Function declaration,
arrays, • Function call,
• Operations on arrays, • Return Statement,
• Two dimensional arrays • Passing parameters to
• Operations on two- functions,
dimensional arrays, • Passing arrays to functions
• Passing Two-dimensional
arrays to functions
• Scope of variables

20-10-2023 Prof. Shilpa B V 2


20-10-2023 Prof. Shilpa B V 3
Arrays

• Array is the collection of similar data types and stored in contiguous


memory location.
• Each data item of an array is called an element.
• And each element is given a unique and separate memory location.
• Each of element of an array share the same variable name but each element
has a different index number known as subscript.
• arr[0], arr[1], …, arr[9]
• The subscript number or the index number of an array always starts with
zero.
• One dimensional array is known as vector and two dimensional arrays are
known as matrix.
20-10-2023 Prof. Shilpa B V 4
Declaration of Array
• Its syntax is : Data-type array-name [size];
• Example : int arr[100]; int mark[5]; int a[5]={10,20,30,100,5} ;
initilized
• The declaration of an array tells the compiler - the data type, name of the
array and size of the array.
• The size of the array is the number of elements that can be stored in an array
and it may be a integer constant or constant integer expression
• Example : int marks[5 ]; 5  integer constant
float percent[i+j ] ; i+j  constant integer expression, but i and j

should already have a value


20-10-2023 Prof. Shilpa B V 5
Contd….
• Array can be represented individually as :
int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
• Symbolic constant can also be used to specify the size of the array as:
#define SIZE 10;
int marks[SIZE];

20-10-2023 Prof. Shilpa B V 6


Initializing Array
• while initializing a single dimensional array, it is optional to specify the size
of array.
• If the size is omitted during initialization then the compiler assumes the
size of array equal to the number of initializers.
• For example:- int marks[ ]={99,78,50,45,67,89};
• If during the initialization of the number the initializers is less then size of
array, then all the remaining elements of array are assigned value zero .
• For example:- int marks[5]={99,78};
• Here the size of the array is 5 while there are only two initializers.
• so After this initialization, the value of the rest elements are automatically occupied
by zeros such as Marks[0]=99 , Marks[1]=78 , Marks[2]=0, Marks[3]=0, Marks[4]=0
• Again if an array is initialized like int array[100]={0};
• Then the all the element of the array
20-10-2023
will be initialized to zero.
Prof. Shilpa B V 7
Accessing and storing values in arrays
• As array data are many, looping control structures like while or for is used
to access and store the data into array elements
int arr[6];
for(i =0; i <= 5; i++)
scanf(“%d”, &arr[i]); store values to each element of array
printf(“%d “,arr[i]); for i = 0, 1, 2, 3, 4 ,5
arr[0], arr[1], arr[2], arr[3], arr[4] , arr[5]

20-10-2023 Prof. Shilpa B V 8


Operations on Array
• Any operator of C language can be used on individual array elements like -
arr[3] + arr[5]
a[i] – arr[j]
b[i] > a[i]
• But no operation can be performed on the whole array
arr3 = arr1 + arr2 ; invalid

20-10-2023 Prof. Shilpa B V 9


#include <stdio.h>
Program to int main()
input {
elements into int arr[20], i, n;
printf(“Enter the number of elements(size) of the array"); Input size
an array and
scanf(“%d”, &n); of array
also to print
printf("Input %d elements into the array :\n”, n);
the elements for(i=0; i<n; i++)
of the array {
***Note- scanf("%d", &arr[i]); input array elements
To input array }
elements, the printf("\nElements in array are: ");
size of the for(i=0; i<n; i++)
array -N has to {
printf("%d\n ", arr[i]); print array elements
be input first
}
return 0;
20-10-2023 Prof. Shilpa B V 10
}
#include <stdio.h>
int main()
{
int arr[20], i, n, sum=0;
• Program to printf(“Enter the number of elements(size) of the array");
add all the scanf(“%d”, &n);
elements of printf("Input %d elements into the array :\n”, n);
the array and for(i=0; i<n; i++)
display the {
sum scanf("%d", &arr[i]); //input array elements
}
for(i=0; i<n; i++)
{
sum += arr[i];// add each array element to sum
}
printf("\nSum of Elements of the array is: %d “, sum);
return 0;
20-10-2023 Prof. Shilpa B V 11
}
#include <stdio.h>
int main()
{
int arr[20], i, n, sum=0;
• Program to float mean;
find the printf(“Enter the number of elements(size) of the array");
average of n scanf(“%d”, &n);
printf("Input %d elements into the array :\n”, n);
numbers
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]); //input array elements
}
for(i=0; i<n; i++)
{
sum += arr[i];// add each array element to sum
}
mean = (float)sum / n ;
printf("\Average is: %f “, mean);
20-10-2023 return 0; Prof. Shilpa B V 12
• Program to search a key element in an array using linear search method
#include <stdio.h> for(i=0; i<n; i++)
int main() {
{ if (key == arr[i])
int arr[20], i, n, key, found=0; {
printf(“Enter the size of the array"); found = 1;
scanf(“%d”, &n); break;
printf("Input the array elements\n”); }
for(i=0; i<n; i++) }
{ if ( found == 1)
scanf("%d", &arr[i]); printf(“Key found”);
} else
printf(“Enter the key to search\n"); printf(“Key not found”);
scanf(“%d”, &key); // input key return 0;
20-10-2023 Prof. Shilpa B V} 13
• Program to search a key element in an array using binary search method
#include <stdio.h> while( first <= last)
if ( found == 1)
int main() {
printf(“Key found”);
{ mid = (first +last)/2;
else
int arr[20], i, n, key, found=0; if (key == arr[mid])
{ printf(“Key not found”);
int first, mid, last;
printf(“Enter the size of array"); found = 1;
return 0;
break;
scanf(“%d”, &n);
} }
printf("Input array elements\n”);
else if(key <= arr[mid])
for(i=0; i<n; i++)
{
{
last = mid-1;
scanf("%d", &arr[i]);
}
}
else
printf(“Enter the key to search\n"); {
scanf(“%d”, &key); // input key first = mid+1;
first = 0; }
last = n-1;
20-10-2023
}
Prof. Shilpa B V 14
• Program to sort elements in an array using bubble sort method
for( i = 0; i< n ; i++)
#include <stdio.h>
for( j = 0; j< (n-i-1); j++ )
void main()
{
{ if(a[j] > a[j+1])
int arr[20], i, n, j, temp; {
printf(“Enter the size of array"); temp = a[j];
scanf(“%d”, &n); a[j] = a[j+1];
printf("Input array elements\n”); a[j+1] = temp;
for(i=0; i<n; i++) }
}
{
printf(“Sorted array elements\n”);
scanf("%d", &arr[i]);
for(i=0; i<n; i++)
} {
printf("%d\n", arr[i]);
20-10-2023 Prof. Shilpa B V
} 15
Two Dimensional Arrays: 2-D
• Two dimensional array is known as matrix.
• The array declaration is done with two subscripts.
• Its syntax is :
Data-type array-name[row][column];
• Total no. of elements in 2-D array is calculated as row*column
• Example:- int a[2][3]; It means the matrix consists of 2 rows and 3 columns
Total no of elements=row*column - 2*3 =6
• For example:- 20 2 7
8 3 15
11 12 9
20-10-2023 Prof. Shilpa B V 16
2-D Arrays
Array data in memory
with address
Array data or Array data positions
Matrix data

24 15 34

26 134 194

67 23 345

20-10-2023 Prof. Shilpa B V 17


Operations on 2-D arrays
• For processing 2-d array, two nested for loops are used.
• The outer for loop corresponds to the row and the inner for loop
corresponds to the column.
• For example int a[4][5];
To display or output the value in matrix form:
To Read or input the value: for(i=0; i<4; i++)
for(i=0; i<4; i++) {
{ for(j=0; j<5; j++)
for(j=0; j<5; j++) {
{ printf(“%d\t”, a[i][j]);
scanf(“%d”, &a[i][j]); }
} printf(“\n”);
} 20-10-2023 } Prof. Shilpa B V 18
Initialization of 2-d array
• 2-D array can be initialized as follows.
• 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[0][1]=12, Mat[0][2]=13
• Mat[1][0]=14, Mat[1][1]=15, Mat[1][2]=16
• Mat[2][0]=17, Mat[2][1]=18, Mat[2][2]=19
• Mat[3][0]=20, Mat[3][1]=21, Mat[3][2]=22

20-10-2023 Prof. Shilpa B V 19


Initialization of 2-d array
• While initializing the elements can be grouped 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.
• Example : int mat[][3];
int mat[2][3];

• Whereas int mat[][];


int mat[2][]; are invalid

20-10-2023 Prof. Shilpa B V 20


Initialization of 2-d array
• If the array is initialized 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[0][1]=0, Mat[0][2]=0
• Mat[1][0]=12, Mat[1][1]=13, Mat[1][2]=0
• Mat[2][0]=14, Mat[2][1]=15, Mat[2][2]=16
• Mat[3][0]=17, Mat[3][1]=0, Mat[3][2]=0

20-10-2023 Prof. Shilpa B V 21


Program to find sum of elements of a matrix
# include<stdio.h> for(i=0; i<n; i++)
void main() {
{ for(j=0; j<m; j++)
int a[10][10], n,m, sum=0, i,j; {
printf(“enter row and col size\n”); sum = sum +a[i][j]);
scanf(“%d%d”,&n,&m); }
printf(“Enter elements of array\n”); }
for(i=0; i<n; i++) printf(“\nSum of elements of array = %d\n”,sum);
{ }
for(j=0; j<m; j++)
{
scanf(“%d”, &a[i][j]);
}
} 20-10-2023 Prof. Shilpa B V 22
# include<stdio.h>
void main()
{
int a[10][10], row,col, sum=0, i,j;
• The input and sum
printf(“enter row and col size\n”); calculation can be
scanf(“%d%d”,&row,&col); combined in one nested
printf(“Enter elements of array\n”); loop itself.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf(“%d”, &a[i][j]);
sum = sum + a[i][j];
}
}
printf(“\nSum of elements of array = %d\n”,sum);
20-10-2023 Prof. Shilpa B V 23
}
# include<stdio.h>
Addition of two matrices
void main( ) if((row1 == row2) && ( col1 == col2))
{ {
int a[10][10], row1,col1, b[10][10], row2,col2; for(i=0; i<row1; i++)
int s[10][10], i,j; for(j=0; j<col1; j++)
printf(“enter row and col size of matrix 1\n”); s[i][j] = a[i][j] + b[i][j];
scanf(“%d%d”,&row1,&col1); printf(“sum of two arrays is : \n);
printf(“enter row and col size of matrix 2\n”); for(i=0; i<row1; i++)
scanf(“%d%d”,&row2,&col2); {
printf(“Enter elements of matrix1\n”); for(j=0; j<col1; j++)

for(i=0; i<row1; i++) { printf(“%d\t”, s[i][j]); }


printf(“\n”);
for(j=0; j<col1; j++)
}
scanf(“%d”, &a[i][j]);
} // closing of if…
printf(“Enter elements of matrix2\n”);
else
for(i=0; i<row2; i++)
printf(“rows and columns do not match\n”);
for(j=0; j<col2; j++)
} // closing of main
20-10-2023
scanf(“%d”, &b[i][j]); Prof. Shilpa B V 24
if(col1 == row2)
Matrix multiplication {
# include<stdio.h> for(i=0; i<row1; i++)
void main( ) for(j=0; j<col2; j++)
{ {
int a[10][10], row1,col1, b[10][10], row2,col2; p[i][j] = 0;
int s[10][10], i,j,k;
for(k=0; k<row2; k++)
printf(“enter row and col size of matrix 1\n”);
p[i][j] = p[i][j] + (a[i][k] * b[k][j]);
scanf(“%d%d”,&row1,&col1);
}
printf(“enter row and col size of matrix 2\n”);
printf(“Product of two arrays is : \n);
scanf(“%d%d”,&row2,&col2);
// display p matrix
printf(“Enter elements of matrix1\n”);
// Input matrix 1 elements
} // closing of if…
printf(“Enter elements of matrix2\n”); else
// Input matrix 1 elements printf(“rows and columns do not match\n”);
} // closing of main
20-10-2023 Prof. Shilpa B V 25
• Write a program to perform matrix subtraction
• Write a program to find sum of principle diagonal matrix
• Write a program to check if given matrix is Unit matrix or not
• Write a program to transpose the matrix – row to column, column to row

20-10-2023 Prof. Shilpa B V 26


Functions
• A function is a block of codes or sub programs with a set of statements that
perform some specific task or coherent task when it is called by other
functions including main
• Any ‘C’ program contain at least one function i.e main().
• There are basically two types of functions:
1. Library function
2. User defined function
• The user defined functions defined by the user according to its
requirement.
• Library defined function can’t be modified, it can only read and can be used.
These function are supplied with every C compiler
20-10-2023 Prof. Shilpa B V 27
Functions
• Every Function has three parts
• Function Declaration
• Function Definition
• Function Call

20-10-2023 Prof. Shilpa B V 28


Library Functions User defined Functions

• Function definition : predefined, • Function definition : By the


precompiled, stored in the library programmer
• Function declaration : In header • Function declaration (prototype) :
file By the programmer
• Function call : By the • Function call : By the programmer
programmer

20-10-2023 Prof. Shilpa B V 29


Function declaration
• Function declaration is also known as function prototype.
• It informs the compiler about three things-
1.name of the function
2.number and type of arguments received by the function
3.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.

20-10-2023 Prof. Shilpa B V 30


Function Call
• When the function gets called by the calling function then that is - function
call.
• The arguments that are used inside the function call are called actual
arguments/ parameters and these are the original values and copy of
these are actually sent to the called function
• Example:-
result = add3num(n1,n2,n3); //actual arguments – n1,n2,n3

20-10-2023 Prof. Shilpa B V 31


Function definition
• Function definition consists of the code of the function - what function is doing what
are its inputs and what are its output
• Syntax:-
Return_value_Datatype function_name(datatype1 arg1, datatype2 arg2, …) /*function header*/
{
Local variable declaration;
Statement (s); /* function body */

return (value);
}
• The return_value_Datatype denotes the datatype of the value that function returns
• The arguments in the function definition are known as formal
arguments/parameters
• The body
20-10-2023of the function is the statements orBblock
Prof. Shilpa V which consists of local variable
32
User Defined Functions arguments list

• Example:
Return_type function_name(datatype 1 arg 1, datatype2 arg2, …)

int add3num(int a, int b, int c)


• Function declaration - int add3num(int, int, int); {
int sum;
• Function definition - complete function code sum = a+b+c;
return sum;
}

void main() /* calling function*/


• Function call - where the function is used {
int n1, n2, n3, result;
printf(“…”);
scanf(“…”);
result = add3num(n1,n2,n3);
printf(“…”);
20-10-2023 Prof. Shilpa B V } 33
Return Statement
• It is used to return a value to the calling function.
• Not more than one value can be returned through the return statement.
• It can be used as return value or return(expression);
• Ex:-
return;
return (a); or return a;
return (a*b+c/d);
return (add3num(a,b,c));
return a,b; invalid
• Here the 1st return statement is used to terminate the function without returning any
value
• We can use a function call statement in the return statement
20-10-2023 Prof. Shilpa B V 34
Parameters/Arguments
• Actual arguments
• The arguments which are mentioned or used inside the function call is knows as actual argument and
these are the original values
• It can be written as variable, constant, expression or any function call like
Functionname (x);
Functionname (x, 20, 30);
Functionname (a*b, 15, a, c*d);
Functionname(2, d, sum(a, b));

• Formal Arguments
• The arguments that are mentioned in function definition are called formal arguments or dummy
arguments , that just hold the copies of the actual parameter 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.
• Order number and type of actual arguments in the function call should be match with the order 35
# include<stdio.h>
int add3num(int, int, int); // Optional – Prototype – FUNCTION DELARACTION
void main( ) // Calling Function
{
int n1, n2, n3, result; Actual parameters n1, n2, n3
printf(“Enter 3 numbers”);
n1 = 20
scanf(“%d%d%d”, &n1, &n2, &n3);
result = add3num(n1,n2,n3); // FUNCTION CALL n2 = 25
printf(“Sum of 3 numbers = %d”, result);
n3 = 14
}

int add3num(int a, int b, int c) // FUNCTION DEFINITION – Called Function


{
a = 20
int sum;
sum = a+b+c; // formal parameters a,b,c b = 25
return sum;
c = 14
} 36
Advantages of function
• By using function large and difficult program can be divided in to sub programs
• and solved.
• When some task has to be performed repeatedly or some code is to be used more
than once at different place in the program, then function avoids this repetition
or rewritten over and over.
• Due to reducing size, modular function is easy to modify and test
• Identifying and Debugging errors is easier and faster
• 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
37
Types of Functions
• Functions are categorized based on the argument passing and return value
1. Passing parameter and return value
2. Passing parameter and No return value
3. No passing parameter and return value
4. No passing parameter and No return value
void main() void main() void main() void main()
{ { { {
int n1, n2, n3, result; int n1, n2, n3, result; …….. ……..
printf(“…”); printf(“…”); result = add3num( ); add3num();
scanf(“…”); scanf(“…”); …….. ……..
result = add3num(n1,n2,n3); add3num(n1,n2,n3); } }
printf(“…”); }
} int add3num( ) void add3num()
void add3num(int a, int b, int c) { {
int add3num(int a, int b, int c) { int a,b,c ,sum; int a,b,c ,sum;
{ int sum; printf(“…”); printf(“…”);
int sum; sum = a+b+c; scanf(“…”); scanf(“…”);
sum = a+b+c; printf(“…”); sum = a+b+c; sum = a+b+c;
return sum; return; return sum; printf(“…”);
} } } return ;
}

39
Passing parameters to functions
• There are two way through which we can pass the arguments/parameters
to the function
• call by value
• call by reference

20-10-2023 Prof. Shilpa B V 40


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 change the
value of the actual argument.
• Changes made to formal argument are local inside the called function, so
when the return statement is executed the formal parameters are deleted
or terminated in memory.
void main() /* calling function*/ a = 20 21
int add3num(int a, int b, int c)
{ n1 = 20 { b = 25 26
int n1, n2, n3, result;
int sum;
printf(“…”);
n2 = 25 sum = a+b+c;
scanf(“…”);
a++; b++; c++;
c = 14 15
result = add3num(n1,n2,n3);
n3 = 14 return sum;
printf(“…”); Sum = 59
}
} 20-10-2023 Prof. Shilpa B V 41
Call by Reference
• Instead of passing the value of variable, address/ reference is passed and
the function operates on the contents of that address.
• Any changes made to formal argument is reflected on the actual argument,
as both are referring to the same location.

void main() /* calling function*/


int add3num(int a, int b, int c)
{ n1, a = 20 21 {
int n1, n2, n3, result;
int sum; Sum = 59
printf(“…”);
n2, b = 25 26 sum = a+b+c;
scanf(“…”);
a++; b++; c++;
result = add3num(&n1,&n2,&n3);
n3, c = 14 15 return sum;
printf(“…”);
}
}
20-10-2023 Prof. Shilpa B V 42
Passing arrays to functions
• Array can be passed as an argument by call by reference, ie., the address of
the array is passed
• To pass an entire array to a function, only the name of the array is passed as
an argument.
• As the name of array represents the address, & is not required
• Example:
void main() /* calling function*/ int addnum(int n1, int arr1[ ])
{ {
int n, i, arr[10]; int sum=0;
printf(“…”); …
scanf(“…”); sum += arr1[i] ;
… return sum;
result = addnum(n, arr); }
printf(“…”);
20-10-2023
} Prof. Shilpa B V 43
Program to calculate the sum of array elements by passing
to a function
#include <stdio.h>
float calculateSum(float num[]); // FN declaration
int main()
{
float result, num[10]; float calculateSum(int n, float num[ ]) // FN definition
{
int i, n; float sum = 0.0;
… // code to read or input the size of array int i;
… // code to read or input the array elements for (i = 0; i < n; ++i)
{
result = calculateSum(n, num); // FN call sum += num[i];
printf("Result = %.2f", result); }
return 0; return sum;
}
}

20-10-2023 Prof. Shilpa B V 44


Passing 2D arrays to functions
• 2D Array can be passed as an argument by call by reference, ie., the address
of the array is passed
• To pass multidimensional arrays to a function, only the name of the array is
passed to the function - similar to one-dimensional arrays
• In the function definition, when passing two-dimensional arrays, it is not
mandatory to specify the number of rows, but, the number of columns
should always be specified.

20-10-2023 Prof. Shilpa B V 45


Program to calculate the sum of array elements by passing
#include}

to a function
#include <stdio.h> void displayNumbers(int num[ ][2])
void displayNumbers(int num[2][2]); {
// code
void main( ) }
{
int num[5][5], n, m, i; OR

printf("Enter number of rows and columns:\n");


void displayNumbers(int n, int m,int num[2][2])
scanf(“%d%d”,&n,&m); {
for (int i = 0; i < n; ++i) printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
{
{
for (int j = 0; j < m; ++j) for (int j = 0; j < 2; ++j)
scanf("%d", &num[i][j]); {
printf("%d\n", num[i][j]);
}
}
displayNumbers(n,m,num); }
} 20-10-2023 Prof. Shilpa B V
} 46
Scope of Variables • Variables can be either local or global

Global Scope Local Scope


• There is only one global scope, • A local scope is created whenever a
and it is created when the function is called.
program begins. • Any variables assigned in this
• When the program terminates, function exist within the local scope.
the global scope is destroyed, • When the function returns, the local
and all its variables are scope is destroyed, and these
variables are forgotten.
forgotten.
• The next time you call this function,
the local variables will be created
again with new value.
20-10-2023 Prof. Shilpa B V 47
Importance of scope
• Scopes matter for several reasons:
• Code in the global scope cannot use any local variables.
• A local scope can access global variables.
• Code in a function’s local scope cannot use variables in any other local scope.
• Same name for different variables can be used if they are in different scopes.
• That is, there can be a local variable named spam and a global variable also named
spam.

20-10-2023 Prof. Shilpa B V 48


Local and Global Scope
• Parameters and variables that are assigned in a called function are
said to exist in that function’s local scope.
• Variables that are assigned outside all functions are said to exist in
the global scope.
• A variable that exists in a local scope is called a local variable,
while a variable that exists in the global scope is called a global
variable.
• A variable must be either local or global; it cannot be both.

20-10-2023 Prof. Shilpa B V 49


#include <stdio.h> result = 0 59
int result=0;
void main() /* calling
function*/
{ a = 20
int a, b, c;
b = 25
printf(“…”);
scanf(“…”); c = 14
result = add3num(a,b,c);
printf(“…”);
}

void add3num(int a, int b, int c) a = 20 21


{
result = a+b+c; b = 25 26
a++; b++; c++; c = 14 15
return;
} 20-10-2023 Prof. Shilpa B V 50

You might also like