C Notes Unit 3 & 4
C Notes Unit 3 & 4
Or
It is a set of rules that define how a particular problem can be solved in a finite sequence of
steps.
1. Input: The algorithms reads the data by accepting the input of given problem.
2. Process: The algorithm does the required computation.
3. Output: The algorithms produce output.
4. Definiteness: Each instruction to represent with clear & unambiguous.
5. Finiteness: The algorithm terminates; that is it terminates after finite number of steps.
6. Correctness: The produced output by the algorithm is correct.
EXAMPLE
Consider the given algorithm to find the largest of three numbers x, y and z.
FLOWCHART
A flow chart is a graphical or pictorial representation that uses symbols to show the
operations and decision to be followed by a computer in solving a problem. Each step in
the process is represented by a different symbol and contains a start description of the
process.
The following symbols that are commonly used in flowcharts they are,
1. OVAL/TERMINATOR: Ovals indicates both the start and end of the process.
2. PROCESS: A Rectangular flow shape indicates the activity in the process.
3. DECISION: Diamonds indicates the decision point, such as yes/no or on/off or
go/not go.
4. CIRCLE/CONNECTOR: A circle indicates the particular step is connected to another
page or part of the flowchart.
5. INPUT/OUTPUT: A Parrellogram indicates data input or output (I/O) for a process.
6. DOCUMENT: A document is used to indicate a document or report.
7. FLOW LINE/ARROW/CONNECTOR: An Arrow indicates to show the direction
that the process flows.
8. PREDEFINED PROCESS: A predefined process is used to indicate a subroutine or
interrupt program.
Predefined
Process
The given table represents symbol, symbol name and function of flowchart.
Start/end
1 Oval/Terminator Start/end
N D
3 Diamond/Decision Indicating a Decision
Point
Y
ADVANTAGES OF FLOWCHART
LIMITATIONS OF FLOWCHART
1. COMPLEX LOGIC: The program logic is very complicated; in this manner drawing
flowchart is difficult
2. ALTERATIONS AND MODIFICATIONS: Alteration and modifications cannot be
made and hence flowchart is very complex process
EXAMPLE 1
Write an algorithm to determine a student‟s final grade and indicate whether he is pass
or fail. The final grade is calculated as the average of four marks.
ALGORITHM
else
Print “PASS”
end if
Step 5 : Stop
ARRAYS
An array is a group of elements (data items) that have common characteristics (Ex:
Numeric data, Character data etc.,) and share a common name. The elements of an array are
differentiated from one another by their positions within an array.
Each array element (i.e., each individual data item) is referred as specifying the array name
followed by its subscript enclosed in square brackets. The subscript indicates the position of
the particular element with respect to the rest of the element. The subscript must be a non
negative number.
For example, in the n element array, x, the array elements are x [1], x [2], x [3], x
[4]….x[n] and 1,2,3…n are the subscripts x[i] refers to the ith element in a list of n elements.
Depending on the number of subscripts used, arrays are classified into one-dimensional
arrys, two-dimensional arrays and so on.
Definition of Array
An array is defined to be a group of logically related data items of similar type stored in
contiguous memory location is called array.
TYPES OF ARRAYS:
1. ONE DIMENSIONAL ARRAY
2. MULTIDIMENSIONAL ARRAY
TWO DIMENSIONAL ARRAY
THREE DIMENSIONAL ARRAY
Arrays whose elements are specified by a single subscript are called one-dimensional or
single dimensional array. It is used to stored a list of values, all of which share a common names
and disguisable by subscripts values.
DECLARATION OF ONE DIMENSIONAL ARRAYS
SYNTAX
EXAMPLE
int list[50]; (integer array)
char a[10; (character array)
The integer array declaration int list[50] creates an array of 50 memory locations, each of
which is of integer type with the first element being 0 and the last being 49.
LIST
0 1 2 3 49
…………………..
An individual element in an array can be referred to by means of the subscript, the number in
brackets following the array name. A subscript is the number that specifies the elements
position in an array. In the C language, subscript begins with zero. Thus the valid subscript
value can from 0 to n-1, if n is the dimension of array. The subscript value used to access an
array element could a binary expression etc.Thus,list[2] is not the second element of the array
list but the third.
Properties of an array
An array can be initialized when declared by specifying the values of some or all of its
elements. Array can be initialized at the time of declaration when their initial values are known
in advance. The values to initialize an array must be constants never variables or function calls.
The array can be initialized as follows:
int array[5]={4,6,5,7,2};
when an float x[6]={0,0.25,-0.50,0,0}; integer array is declared as int
array[5]={4,6,5,7,2}; the compiler will reserve ten contiguous bytes in hold the five integer
elements as shown in the diagram.
4 6 5 7 2
array[0] array[1] array[2] array[3] array[4]
The array size need not be specified explicitly. When initial values are included as a part of
an array declaration. With a numerical array, the array size will automatically be set equal to the
number initial values included within the declaration.
int digits[]={1,2,3,4,5,6}
float x[]={0,0.25,0,-0.5}
Thus, digits will be a six-element integer array, and x will be a four-element floating-point
array. The individual elements will be assigned the following values. The example given below,
digits[0]=1;digits[1]=2;digit[2]=3;
digits[3]=4;digits[4]=5;digits[5]=6;
int xyz[10]={78,23,67,56,87,76}
in the above array initialization, although the array size is 10,values where defined only for the
first six elements. If fewer then all numbers have values specified, then the rest will have
undefined values.
Write a program to get five person ages to calculate average of person age.
TWO DIMENSIONAL ARRAYS
Arrays whose elements are specified by two subscripts are referred as two-dimensional
arrays or double dimensional arrays. A two dimensional arrays of size m rows by n columns are
declared as follows:
type array-name[m][n];
A two dimensional array two dimension of type int, 3
rows and 4 columns is declared as follows:
EXAMPLE
int twodim[3][4];
Arrays can be stored in the memory in two orders.
Row major order and column major order.Multi-dimensioanl arrays are stored in memory using
the row major order. Organization of the array named twodim with 3 rows and 4 columns in the
row major order is shown here:
For example, twodim [1][3] will access the elements in two number 1(the second row) and
in a column number (fourth) of the array. In array notation, twodim [1] represents a row and
twodim [1][3] represents a column within that row. When initializing a two dimensional array at
the time of array declaration, the elements will be assigned by rows, that are the elements of the
first row will be assigned, then the elements of the second and so on.
NOTE
1. If there are too few values within a pair of braces the reaming elements of that row will be
assigned zero.
2. If the number of values in each inner pair of braces exceeds the defined row size, it will result
a compilation error.
INITIALIZING TWO DIMENSIONAL ARRAYS
Like single-dimensional array, a two dimensional array can also be initialized. Arrays can be
initialized by the following ways,
Similar to single dimensional arrays, a two dimensional array can also be initialized
with one or more values during its declaration.
The data type array-name[row size][col size]={list of values}; datatype
specifies the
type of elements that will be stored in the array. The array name is the name used to identify the
array. The rules for naming array names are same as identifiers .Note that an array should not
have the same name as an ordinary variable in the same block or a function.
For Example
int marks[4][2];
marks[4][2]={82,44},
{92,65},
{73,64},
{65,100}.
The first subscript ranges from 0 to 3 and the second subscript ranges from 0 to 1.In the first case,
the first inner pair of braces are assigned to the array elements in the first row, the value of second
inner pair of braces are assigned to the array elements in the row and so on.
int marks{82,44,92,65,73,64,65,100};
marks[0][0]=82 marks[0][1]=44
marks[1][0]=92 marks[1][1]=65
marks[2][0]=73 marks[2][1]=64
marks[3][1]=65 marks[3][2]=100
float amount[2][3]={70.50,90.74,50.75,75.10}
In the example, the size o the array is 6(2*3) and the values 1,2,3,4,5,6 are assigned to
the variable amount[0][0],amount[0][1]…..amount[2][1],amount[3][1] respectively.
An array can be initialized by using for loop, a while loop or do-while loop. The given
example illustrates the use of initializing an array using for loops.
int i,j,mark[5][5]
for(i=0;i<0;i++)
scanf(“%d”,&mark[i][j]);
In the example, the for loop initializes all the program elements of the array to zero.Similary,
array elements of the index to zero.Similary, array can also be initialized while loop and do-
while loops.
Row size and column size should be integer consists or convertible into integer values. Total number
of locations allocated will be equal to row size* column size.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][4],i ,j;
clrscr();
printf(“Enter the elements of matrix a of order 3*4 \n”);
for(i=0;i<3;i++)
for(j=4;j<4;j++)
scanf(“%d”,&a[i][j]);
printf(“Matrix a \n”);
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
printf(“%4d”,a[i][j]);
printf(“\n”);
}
getch(); }
USER DEFINED FUNCTIONS
In the previous units, we used two types of functions such as printf() and scanf().These
functions have already been written, compiled and placed in libraries are called library
functions.
In this unit, we will study about user define function in which user has chosen the
function name, return data type and arguments (numbers and type), are called user-defined
functions.
1. Library functions
2. User-defined functions
printf() and scanf() are called the library functions. We already user other library functions
such as sqrt(),cos(),sin(),tan(),strcmp(),strcat() etc.This is greatest features in C in the sense
that there is no conceptual difference between the user-defined functions and library functions.
For example, we can write a series of function to process matrices (such as square of given
number, finding cos value, finding sine value, etc).These are user-defined functions they are
written by user. After user, they can be compiled into libraries and distributed. To the users of
the library, these functions will act as library functions. That is these functions are predefined
and precompiled; the users need not worry about the functions work internally.
In C, some time we need certain types of operation or calculations is repeated again and
again in the program. In this situation, we use user-defined functions. This saves both the time
and space.
FUNCTIONS
Modular Programming
They are three elements that are related to user defined functions are:
1. Function definition
2. Function call
3. Function declaration
The function definition is an independent program module that is specially written to implement the
requirements of the function. In order to use this function we need to invoke it at a required place in
the program. This is known as the function call. The program (or a function) that calls the function is
referred to as the calling program or calling function. The calling program should declare any
function (like declaration of a variable).This is known as function declaration or function prototype.
Function Definition
1. Function name
2. Function type
3. List of parameters
4. Local variable declaration
5. Function statements
6. A return statement
All the six elements are grouped into two parts, namely,
Function header
Function body
Function Header
The function header consists of three parts: The function type (also known as return type, the
function name and the formal parameters list. Note that a semicolon is not used at the end of the
function header.
Function Body
The function body contains the declarations and statements necessary for performing the
required task. The body enclosed in braces, contains three parts, and is given below:
And represents type1 par1, ..., typen par n external values needed by the
function. The list of parameters can be empty. All
declarations and statements that are valid in the main program can be used in the Function
definition, where they make up the function body.
Example,
int add(int x,int y)
{
int temp;
temp=x+y;
return temp;
}
The return statement forces the function to return immediately, possibly before reaching
the end of the function body.
Function Call
A function can be called by simply using the function name followed by a list of actual
parameters (or arguments), if any, enclosed in parentheses.
SYNTAX
function-name (arguments);
The arguments are values with types
corresponding to the function parameters.
EXAMPLE
main()
{
int a,b,sum;
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
sum=add(a,b);
printf(“Sum is %d”,sum);
return 0;
}
Function Declaration
Like variables all function in a C program must be declared, before they are invoked. A
function declaration (also known as function prototype) consists of four parts.
DEFINITION OF FUNCTIONS
1. Argument declaration
2. Body of the function
The first part of the function specification consists of type specification of the value
returned by the function followed by the function name, a set of arguments (may or may not be
present) separated by commas and enclosed in parenthesis. If the function definition does not
include any arguments, an empty pair of parenthesis must follow the function name.
SYNTAX
Most functions have list of parameters and a return value that provides means for
communication between functions. The arguments in the function reference, which defines the data
items that are actually transferred, are referred as actual arguments or actual parameters. All
variables declared in function definitions are local variables. Their scope is visible known only in the
function in which they are defined. Functions arguments are als0 local variables.
EXAMPLE
Write a program for sum of two numbers and return the sum to the main function.
#include<stdio.h>
int add(int x,int y); // function Declaration
void main()
{
int sum,a,b;
printf(“\n Enter two number to be summed:”);
scanf(“%d %d”,&a,&b);
sum=add(a,b); //function Call
printf(“\n The sum of %d and %d is %d”,a,b,sum);
}
int add(int x,int y)
{
int temp;
temp=x+y;
return temp;}
Sample program output:
The integer values are transferred via the arguments x and y,and their sum is returned to the
calling portion of the program via the return statement.
Parameters are the data values that are passed from calling function to called function.
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are specified in calling function. The formal parameters are
the parameters that are declared at called function. When a function gets executed, the copy of actual
parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling function to called
function and they are as follows...
Call by Value
Call by Reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called function. The changes made on the formal
parameters does not effect the values of actual parameters. That means, after the execution control comes
back to the calling function, the actual parameter values remains same. For example consider the following
program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
OUTPUT
Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual parameters is
copied to formal parameters. This address is used to access the memory locations of the actual parameters
in called function. In this method of parameter passing, the formal parameters must be pointer variables.
That means in call by reference parameter passing method, the address of the actual parameters is passed to
the called function and is recieved by the formal parameters (pointers). Whenever we use these formal
parameters in called function, they directly access the memory locations of actual parameters. So the
changes made on the formal parameters effects the values of actual parameters. For example consider
the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
Output:
In the above example program, the addresses of variables num1 and num2 are copied to pointer
variables a and b. The changes made on the pointer variables a and b in called function effects the values of
actual parameters num1 and num2 in calling function.
1.While calling a function, we pass values of 1.While calling a function, instead of passing the
variables to it. Such functions are known as “Call values of variables, we pass address of
By Values”. variables(location of variables) to the function known
as “Call By References.
2.In this method, the value of each variable in 2.In this method, the address of actual variables in the
calling function is copied into corresponding calling function are copied into the dummy variables
dummy variables in the called function have no 3.With this method, using addresses we would have an
effect on the values of actual variables in the calling access to the actual variables and hence we would be
return 0; return 0;
} }
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);
} }
Output: Output:
Thus actual values of a and b remain unchanged even Thus actual values of a and b get changed after
4.In call by values we cannot alter the values of actual 4.In call by reference we can alter the values of
Here, are some fundamental differences between Local and Global variables.
Lifetime It is created when the function starts It is created before the program's global
execution and lost when the functions execution starts and lost when the program
terminate. terminates.
Data sharing Data sharing is not possible as data of the Data sharing is possible as multiple
local variable can be accessed by only one functions can access the same global
function. variable.
Parameters Parameters passing is required for local Parameters passing is not necessary for a
variables to access the value in other global variable as it is visible throughout
function the program
Modification of When the value of the local variable is When the value of the global variable is
variable value modified in one function, the changes are modified in one function changes are
not visible in another function. visible in the rest of the program.
Accessed by Local variables can be accessed with the You can access global variables by any
help of statements, inside a function in statement in the program.
which they are declared.
1. By default all local variables are automatic 1.Static Variables are declared inside a function by
variables. Keyword auto can be used to using keyword static.
declare an automatic variable.
For example: auto int a; For example: static int a;
2. They don’t retain their value from one 3. Static variable retain their value even after
function call to next. We need to initialize the execution of the function in which it is
automatic variables otherwise these declared. The value of static variable is not
variables may contain garbage value. destroyed when the function terminates.
We need not to initialize static variable, by
default they are initialize to zero in case of
numeric variable and null in case of
character variable.