0% found this document useful (0 votes)
15 views

PSC 2020 Lecture Notes Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

PSC 2020 Lecture Notes Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT - III

UNIT-3:
Arrays: Declaration, accessing array elements, Storing values, Operations on arrays, Multi-
dimensional arrays.
Functions: Introduction, Us i n g Functions, Function declaration, Function definition and Function
call, Parameter passing, passing arrays to functions, Recursion, Storage classes.
Learning Outcomes: The students will be able to
• Writing Structured programs using Functions (L5).
• Apply arrays concepts on real time applications (L6).

ARRAY:

Array is a data structure which can store fixed-size sequential collection of elements of the same
type.

Purpose of Array:
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.

The lowest indexis always zero which corresponds to the first element/location and the highest
index(maximum size -1) refers to the last element/location.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
Data type arrayName[arraySize];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance of
type double, use this statement:
double balance[10];
Now balance is avariable array which is sufficient to hold upto 10 double numbers.

Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5]={1000.0,2.0,3.4,7.0,50.0};

The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ].

Following is an example to assign a single element of the array:


balance[4]=50.0;

The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as
the index of their first element which is also called base index and last index of an array will be total
size of the array minus 1. Following is the pictorial representation of the same array we discussed above:

Examples of array initialization:

Inputting Values using a for Loop

• Once we know the length of an array, we can input values using a for loop:
array name : scores[9], arrayLength = 9;

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


{
scanf(“%d”, &scores[j]);
}//end for

Assigning Values to Individual Elements

• We can assign any value that reduces to an array’s data type:

scores[5] = 42;
scores[3] = 5 + 13;
scores[8] = x + y;
scores[0] = pow(7, 2);

“Copying” Arrays

• We cannot directly copy one array to another, even if they have the same length and share the
same data type.
• Instead, we can use a for loop to copy values:
for(m = 0; m < 25; m++)
{
array2[m] = array1[m];
}//end for

Swapping Array Elements

To swap (or exchange) values, we must use a temporary variable. A common novice’s
mistake is to try to assign elements to one another:
/*The following is a logic error*/
numbers[3] = numbers[1];
numbers[1] = numbers[3];

/*A correct approach …*/


temp = numbers[3];
numbers[3] = numbers[1];
numbers[1] = temp;

Printing Array Elements

• To print an array’s contents, we would use a for loop:


for(k = 0; k < 9; k++)
{
printf(“%d”, scores[k];
}//end for

TWO DIMENSIONAL ARRAY


Declaring Two Dimensional Arrays
To declare a 2D array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
Data type arrayName[RowSize][colsize];
This is called a two-dimensional array. The RowSize, colsize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element 2 D array
called balance of type int, use this statement:
int balance[2][5]; or int balance[5][2];
Now balance is a variable array which is sufficient to hold upto 10 int numbers.

Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
int balance[2][5]={10,1,2,3,4,50,6,7,80,99};

The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ].

Following is an example to assign a single element of the array:


balance[1][2]=22; /* to assign a value for the second row, third column */
Inputting Values using a for Loop

• Once we know the length of an array, we can input values using a for loop:
array name : matrix[3][3], arrayLength = 9;

For(i=0;i<3;i++)
for (j = 0; j <3; j++)
{
scanf(“%d”, &matrix[i][j]);
}//end for

“Copying” Arrays

• We cannot directly copy one array to another, even if they have the same length and share the
same data type.
• Instead, we can use a for loop to copy values:
• for(i=0;i<3;i++)
• for(j = 0; j < 3; j++)
{
array2[i][j] = array1[i][j];
}//end for

POINTER TO THE ARRAY

Programming language C internally converts an array as pointer. So, whenever array name is
specified in a printf statement as shown below:

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

It will be interpreted as

printf(“%d”,*(a+i));

Likewise, whenever an array name is specified in a scanf statement as shown below:

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

It will be interpreted as

scanf(“%d”,a+i);

Note: Just referring the name of the array gives the starting address of the array, * followed by name
of the array gives the value at that address.

Multidimensional Arrays:
Arrays with more than two dimension are called multidimensional arrays. Although
humans cannot easily visualize objects with more than three dimensions, representing
multidimensional arrays present no problem to Computers.
FUNCTIONS

Function: Defined as self contained block of code to perform a task.


Functions can be categorized to system-defined functions and user-defined functions.

System defined functions: These are functions that are supported along with the programming
language. The block of instructions of these functions and the task to be performed is predefined. For
e.g. clrscr(), printf(), scanf(), pow(), sqrt() etc.

User defined functions: These are functions that are not supported along with the programming
language. The block of instructions of these functions and the task to be performed is defined by the
programmer.

The following are the advantages of functions:


 Reusability of code i.e. block of code defined can be used when required.
 Facilitates Modular Programming i.e. breaking the complex problem into small manageable
sub-problems called as modules and also makes the process of debugging easier.
 Reduces the length of the program.

Important Terminologies:
Function call is the reference made in the calling function by specifying the name of the
function along with arguments if any exists and should be terminated with semicolon.
Calling function is the function in which we write function call statements.
Called function is the definition of function call

for e.g.

main() /* calling function */


{
clrscr(); /* function call */
}

Defining User defined functions:


To understand user-defined functions one should understand the following elements:
 Function definition
 Function declaration
 Function call
Function Definition: The function definition consists of two parts namely
1. Function header
2. Function body
The general format of the function definition is shown below:

Return type function-name(arguments) Function header


Argument declaration;
{ Function Body
Local variable declaration;
Executable statement1;
Executable statement 2;
Return statement;
}

Function Header:
The function header comprises of three parts namely
1. Return type
2. Function name
3. arguments

Return type: Specifies the type of data (primitive/user-defined) that the function will
return.
Function Name: Takes a valid name to identify the function and this name should
follow the rules for naming a user defined identifier.
Arguments: the values/variables that we receive from function call
Function body:
The function body comprises of the following parts enclosed in flower
Braces:
1. Local variable declaration
2. Executable statements
3. Return statement
Local variable declaration: Variables that are needed in that function are declared
for its type.
Executable Statements: These are statements that are needed in the function to
assign a value or to read a value or to print the value or to perform some
computations.
Return statement: Every function body ends with return statement. This statement is
used to return a value to the calling function. If the function does not return any value
then the return statement is written as
Return; or return 0;
If the function returns any value then the return statement is written as
Return value; or return expression;
The function definition can be done either above the main function or after the main function.
Example of function definition:
float mul(x,y)
float x,y;
{
float result;
result=x*y;
return result;
}
In the above example in the function header the return type is float and the name of the function
In the function body, result is a variable that is needed in that function and is declared locally
for its type. Result=x*y is the executable statement and the return statement returns the value available
in the variable result.

Function Declaration or prototype declaration: Declaring a function also called as function


prototyping is used to inform the compiler about the specification of the function that will be defined
and the syntax for invoking the function call.
The general format of function declaration is given below:
Return type functionname(arguments);
Where arguments specify the type of data (primitive/user-defined) and each of these arguments should
be separated with comma.
The function declaration is done above the main function.
Example of function declaration:
float mul(float,float);
In the above example the return type is float and the name of the function is mul and the
arguments that should be passed to the function definition through function call should be of type float.

Function call: The function definition is invoked by referring the function name along with arguments
if any exists. The arguments in the function call, if exists will take data or variables declared for its
type matching to the function declaration and definition.
The arguments in the function are called as actual arguments.
The function call should be made always within another function.
The general format for function call which returns value is given below:

Variable=functionname(arguments);
Or
printf(“format string”,functionname(arguments));

Where arguments may or may not exist.


The general format for function call which does not return value is given below:

Functionname(arguments);

Where arguments may or may not exist.

Example of function call which returns values:


main()
{
float y;
y=mul(23.4,12.5); /* function call */
printf(“product of two numbers is %f\n”,y);
}

Example of function call which does not return value:

main()
{
mul(); /* function call */
}

/* complete program showing the usage of function declaration, function call and definition */

#include <stdio.h>

float mul(float,float); /* function declaration */

main()
{
float y;
y=mul(23.4,12.5); /* function call */
printf(“product of two numbers is %f\n”,y);
}

/* function definition */
float mul(x,y)
float x,y; /* argument declaration */
{
float result; /* local variable declaration */
result=x*y; /* executable statement */
return result; /* returns the computed value in result to the calling function */
}

Functions Arguments:
Arguments and parameters refer to the variables or expressions passed from the function.
Each and every argument is separated with comma.

Actual Arguments are arguments passed from function call.


Formal Arguments are arguments received in called function.

Actual Argument names and Formal Argument names can be same or different.
Actual Argument names are recognized only in that function.
Formal Argument names are recognized only in the definition of the function.
Example:
Sample(x1,y1)
Main() Int x1,y1;
{ {
intx,y; Formal Arguments
Actual Arguments
Sample(x,y);
} }

Call by Value Call by reference


Passing values/variables from function call. Passing address of the variable(s) from
function call.
Example: Example:
main() main()
{ {
int a,b; int a,b;
clrscr(); clrscr();
printf(“Enter the values of a and b:\n”); printf(“Enter the values of a and b:\n”);
scanf(“%d %d”,&a,&b); scanf(“%d %d”,&a,&b);

/* function call with arguments and no /* function call with arguments and no
return value */ return value */
swap(a,b); swap(&a,&b);

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


} }

/* function definition with arguments and no /* function definition with arguments and
return value */ no return value */

void swap(a1, b1) void swap(a1, b1)


int a1,b1; int *a1,*b1;
{ {
int temp; int *temp;
temp=a1; *temp=*a1;
a1=b1; *a1=*b1;
b1=temp; *b1=*temp;
return 0; }
}

Categories of Functions (Based on the arguments and return type)

Functions fall into four categories as listed below:

1. Function with Arguments and with return value.


2. Function with Arguments and no return value.
3. Function with no arguments and with return value.
4. Function with no arguments and no return value.
Below we will see the comparative study of each of these categories of functions:
Function with Function with arguments Function with no arguments Function with no
Arguments and with and no return value and with return value arguments and no
return value return value

Description: Description: Description: Description:


Function call: Function call: Function call: Function call:
 Function call is made  Function call is made by  Function call is made by  Function call is
by passing arguments passing arguments passing no arguments made by passing no
 The function call is  The function call is assigned arguments
assigned to a variable  Function call is not to a variable that matches to  Function call is not
that matches to the assigned to any variable the return type of the assigned to any
return type of the or not used in printf function definition or used variable or not used
function definition or function. in the printf function with in printf function.
used in the printf format specifier matching to
function with format the return type of the
specifier matching to function definition.
the return type of the
Function Definition:
function definition. Function Definition:
Function Definition: Function Definition:  The function
 The function definition will definition will not
 The number of  The number of not receive any arguments.
arguments in the receive any
arguments in the  The return value should arguments.
function definition function definition
match with the return type  The return
should match with the should match with the
of the function definition. statement will not
number of arguments number of arguments
passed from the return any value.
passed from the Below shows an example of
function call. function call.
 The return statement how the programming Below shows an
 The return value
should match with the will not return any instruction changes for this example of how the
return type of the value. category of function. programming
function definition. instruction changes for
Below shows an example of this category of
Below shows an example how the programming #include <stdio.h> function.
of how the programming instruction changes for this
instruction changes for this category of function. /* function declaration*/
category of function. int printvalue(void);

#include <stdio.h> main()


{
/* function declaration*/ #include <stdio.h> #include <stdio.h>
int value;
int printvalue(int);
clrscr();
/* function declaration*/ /* function
/* function call */
main() void printvalue(int); declaration*/
value=printvalue();
{ void printvalue(void);
printf(“%d”,value);
main()
int value; }
{ main()
clrscr();
/* function call */ clrscr(); /* function definition */ {
value=printvalue(10); /* function call */ int printvalue(void) clrscr();
printf(“%d”,value); printvalue(10); { /* function call */
} } int a; printvalue();
a=10; }
/* function definition */ return a;
int printvalue(a) }
int a; /* function definition */
{ void printvalue(a) /* function definition */
return a; int a; void printvalue(void)
} { {
printf(“%d”,a); int a;
return 0; a=10;
} printf(“%d”,a);
return 0;
}

The Return Statement:


It has two important uses.
 First, it causes an immediate exit from the function. That is, it causes program execution
to return to the calling code.
 Second, it can be used to return a value.
Returning from a Function
Functions rely on the return statement to stop execution either because a value must be
returned or to make a function's code simpler and more efficient.
Returning Values
All functions, except those of type void, return a value. This value is specified by the return
Statement.
Returning Pointers:

To return a pointer, a function must be declared as having a pointer return type

Storage Class Specifiers:


The "storage class" of a variable determines whether the item has a "global" or "local" lifetime.
C calls these two lifetimes "static" and "automatic." An item with a global lifetime exists and
has a value throughout the execution of the program. All functions have global lifetimes.

Automatic variables, or variables with local lifetimes, are allocated new storage each time
execution control passes to the block in which they are defined. When execution returns, the
variables no longer have meaningful values.
Storage specifiers are:
 auto
 register
 static
 extern
S. Storage Storage Initial / default Scope Life
No. Specifier place value
1 auto CPU Garbage value local Within the function only.
Memory
2 extern CPU Zero Global Till the end of the main program.
memory Variable definition might be
anywhere in the C program
3 static CPU Zero local Retains the value of the variable
memory between different function calls.
4 register Register Garbage value local Within the function
memory

Important Questions:

1. How an array is declared and initialized? Discuss.


2. Write a program in C to sort n elements.
3. Write a program in C to search for an element in the list.
4. Write a program in C to find the biggest among n elements.
5. Write a program in C to compute matrix multiplication.
6. Define a function. List the benefits of the function.
7. Explain the parameter passing techniques with examples.
8. Briefly discuss about the categories of functions bases on arguments and return
type.
9. Define Recursion. Write a program in c to find the factorial of a number using
recursion.
10. Define Storage Class. Briefly discuss the storage classes supported in C.

Assignment Questions.

1. Define Storage Class. Briefly discuss the storage classes supported in C.


2. Define an array. How one dimensional arrays are declared and initialized

You might also like