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

C Notes Unit 3 & 4

The document discusses algorithms and provides details about their properties, how to develop algorithms, and examples of algorithms. It also covers flowcharts, their symbols and benefits, array types including one-dimensional arrays, and how to declare and initialize one-dimensional arrays.

Uploaded by

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

C Notes Unit 3 & 4

The document discusses algorithms and provides details about their properties, how to develop algorithms, and examples of algorithms. It also covers flowcharts, their symbols and benefits, array types including one-dimensional arrays, and how to declare and initialize one-dimensional arrays.

Uploaded by

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

1ALGORITHM

An algorithm is a sequence of unambiguous instructions for solving a problem that is a


sequence of computational steps that transform them from input into the output.

Or

It is a set of rules that define how a particular problem can be solved in a finite sequence of
steps.

An algorithm has the following properties:

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.

How to Develop an Algorithm


The development of an algorithm (a plan) is a key step in solving a problem. Once we have an
algorithm, we can translate it into a computer program in some programming language. Our algorithm
development process consists of five major steps.

1. Understand the problem


2. Identify the output of the problem
3. Identify the inputs required by the problem to achieve the desired results
4. Design a logic that will produce the output
5. Test the given algorithm for a given set of input data
6. Repeat steps 1 to 5 till the algorithm produces the desired results.

EXAMPLE

Consider the given algorithm to find the largest of three numbers x, y and z.

Step 1: Start the program


Step 2: Read the value x, y and z
Step 3: To compare ((x>y) and (x>z)) then
print x
else if(y>z)
print y
else
print z
Step 4: Stop the program

FLOWCHART

DEFINITIONS OF FLOW CHART

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.

BENEFITS OF USING FLOWCHART

Correct process understanding


Provide tools for training
Identify problem areas and improvement opportunities
To describe the customer-supplier relationships

SYMBOLS USED IN FLOWCHART

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.

S.No SYMBOL SYMBOL NAME FUNCTION

Start/end
1 Oval/Terminator Start/end

2 Process Box/Process Activity in the Process

N D
3 Diamond/Decision Indicating a Decision
Point
Y

4 C Circle/Connector The Particular Step is


Connected to Another
Page

5 Data Triangle/Data Data Input/Output(I/O) for


a Process

6 Document Document Indicating a Document or


Report

7 Arrow/Connector Direction of Process Flow

8 Predefined Process Invoke a Subroutine or


Interrupt Program
The following flowchart shows the symbolic representation of flow diagram.
RULES FOR CREATING FLOWCHART

1. All boxes in the flowchart are connected with arrows


2. Flowchart symbols have an entry point on the top of the symbol only. The exit point for all
flowchart symbols is on the bottom except for decision making
3. Decision symbol have two exit points:
Yes/no or true/false or on/off
4. Flow chart will flow from top to bottom
5. Connectors are used to connect with following manners,
1. from one page to another page
2. from the bottom of the page to the top of the same page

ADVANTAGES OF FLOWCHART

1. COMMUNICATION: Flowchart is used for better way of communication in all


connections.
2. EFFECTIVE ANALYSIS: By using flowchart, problems are analyzed in better
manner.
3. PROPER DOCUMENTATION: Flowchart serves as good program documentation.
4. EFFICIENT CODING: The flowcharts act as a guideline during the system analysis
and development phase.
5. PROPER DEBUGGING: The flowchart helps in debugging process.
6. EFFICIENT PROGRAM MAINTENANCE: The maintenance of operating program
Is an easy way for drawing the 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

Step 1 : Start the program


Step 2 : Input m1,m2,m3,m4
Step 3 : Grade(m1+m2+m3+m4)/4
Step 4 : if(grade<50) then
Print “FAIL”

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

ONE DIMENSIONAL ARRAYS

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

A single dimensional array is declared as follows:

SYNTAX

where, type array-name[n];


array name- >is the name of an array of n elements of the type
specified. The size of an array must be an integer constant.

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

1. The type of an array is the data type of its elements.


2. The location of an array is the location of its first element.
3. The length of an array is the number of data elements in an array.

INITIALIZATION OF ONE-DIMENSIONAL ARRAYS

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;

An array may also be initialized as follows:

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.

EXAMPLE PROGRAM USING ONE DIMENSIONAL ARRAY

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:

Column 1 Column2 Column 3 Column 4


Row 1 [0][0] [0][1] [0][2] [0][3]
Row 2 [1][0] [1][1] [1][2] [1][3]
Row 3 [2][0] [2][1] [2][2] [2][3]
Elements in a two dimensional array can be accessed by means of a row and a column. The
row subscript generally is specified before the column subscript.

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.

Consider the following array declaration:


The result of int values[3][4]={1,2,3,4,5,6,7,8,9,10,11,12} this initial assignment is as
follows:

values[0][0]=1 values[0][1]=2 values[0][2]=3 values[0][3]=4


values[1][0]=5 values[1][1]=6 values[1][2]=7 values[1][3]=8
values[2][0]=9 values[2][1]=10 values[2][2]=11 values[2][3]=12

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,

Initializing an array during declaration


Initializing an array using loops
Initializing an array during declaration

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.

The array of mark can also be declared as,

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

Examples for initializing an array using declaration

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.

Initializing an array using loops

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.

Examples for initializing an array using a for loop,

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.

DECLARATION OF TWO-DIMENSIONAL ARRAYS

The syntax of declaring a two-dimensional array is as follows:

where, data-type variable-name[row-size][col-size];

data-type->refers to any valid c data-type.

variable-name->(A valid C identifier),refers to the name of the array


row-size->indicates the number of rows and column size indicates the number of
elements in each row

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.

EXAMPLE PROGRAM USING TWO-DIMENSIONAL ARRAYS

Write a program to accept and display a matrix.

#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.

In C functions can be classified into two categories,

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.

NEED FOR USER-DEFINED FUNCTIONS

As discussed earlier, main () is a specially recognized pre-defined function in C.In every


program we have to use main () function to indicate where the program has been executed.
While in any program, does not utilizing the main function, it has face to the number of
problems. In C, to write a program to become too large and complex and the result has been
debugging, testing, and maintaining becomes difficult. In this situation, if a program it‟s large,
program is divided into functional parts, then each part may be independently coded and
executed each part of program later combined into single unit. These subprograms called
function, this way to manipulate, the easier to understand, debug and test.

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

A function is a subprogram that can be defined by the user in his program.It is a


complete program in the sense that its structure is similar to main() function except that the
name main is replaced by the name of a function.
A function is a self-contained block of code that performs a particular task. Once a function has
been designed and packed, it can be treated as a ‘block box‟ that takes some data from the main
program. All that the program knows about a function is what goes in and what comes out.
Every C program can be designed using a collection of block boxes known as functions.

Modular Programming

Modular programming is a software design technique breaking a large program down


into a number of functions, each of which performs a specific, well-defined task. This separates
task is called modules. These modules are carefully integrated to become a software system that
satisfies the system requirements. It is basically a “divide-and-conquer” approach to program
solving.

Below diagram shows Flow of Control in multifunction program:


The use of functions in C has many advantages:

1. It facilitates top-down modular programming.


2. The length of a source program can be reduced by using functions at a appropriate
Places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs.

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

A function definition, also known as function implementation it include the following


elements.

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:

1. Local declarations that specify the variables needed by the function


2. Function statements that perform the task of the function
3. A return statement that returns the value evaluated by the function
SYNTAX
where,
return-type function-name(parameters)
return- { type ->type
of value Declarations; returned by
Statements;
function return value; or void if
none } function-
name-> unique name identifying function
parameters comma->separated list of types and names of parameters
value-> value returned upon termination (not needed if return-type void)

The list of parameters is a declaration on the form

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.

Function type (return type)


2. Function name
3. Parameter list
4. Terminating semicolon
SYNTAX
1.

return-type function-name(parameter types);

The function body is replaced by a semi-colon.

Parameters need not be named, it is sufficient to specify their types.

Example: declaring sum

int add(int x,int y);


Declaration is not necessary if the function definition precedes the first call.

DEFINITION OF FUNCTIONS

A function is defined as a self-contained program which is written for the purpose of


accomplishing some task.

A function definition consists of two parts. They are,

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

returntype functionname(argument list)


where {
declaration(s);
returntype- statement(s); >specifies the data type
return(expression);
value to be returned by the
}
function. The return type is
assumed to be of type int by default if it is not specified.
function name-> used to identify the function. The rules for naming a function are
Same as identifiers.
argument list->specified inside the parenthesis after the function name is optional.

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:

Enter two numbers to be summed: 15, 17 The


of 15 and 17 is 32
The above program consists of two functions,

The required main function


The programmer defined function sum, which sums the two values.
The function main reads in two integer values, and assigns them to a and b.Then, main calls sum,
transferring the integer values a and b receiving their sum. The sum is then displayed and the
program terminates.

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.

Parameter passing in functions


When a function gets executed in the program, the execution control is transferred from calling-function to
called function and executes function definition, and finally comes back to the calling function. When the
execution control is transferred from calling-function to called-function it may carry one or number of data
values. These data values are called as parameters.

Parameters are the data values that are passed from calling function to called function.

In C, there are two types of parameters and they are as follows...

 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 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function

printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);


getch() ;
}
void swap(int a, int b) // function definition
{
int temp ;
temp = a ;
a=b;
b = temp ;
}

OUTPUT

Before Swap num1=10,num2=20


After Swap num1=10,num2=20
In the above example program, the variables num1 and num2 are called actual parameters and the
variables a and b are called formal parameters. The value of num1 is copied into a and the value of num2 is
copied into b. The changes made on variables a and b does not effect the values of num1 and num2.

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 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // function definition
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

Output:

Before Swap num1=10,num2=20


After Swap num1=20,num2=10

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.

CALL BY VALUE CALL BY REFERENCE

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 of the called function. of the called function.

3.With this method, the changes made to the

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

function. able to manipulate them.

// C program to illustrate // C program to illustrate


// call by value // Call by Reference

#include <stdio.h> #include <stdio.h>

// Function Prototype // Function Prototype


void swapx(int x, int y); void swapx(int*, int*);

// Main function // Main function


int main() int main()
{ {
int a = 10, b = 20; int a = 10, b = 20;

// Pass by Values // Pass reference


swapx(a, b); swapx(&a, &b);

printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);

return 0; return 0;
} }

// Swap functions that swaps // Function to swap two variables


// two values // by references
void swapx(int x, int y) void swapx(int* x, int* y)
{ {
int t; int t;

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:

x=20 y=10 x=20 y=10


a=10 b=20 a=20 b=10

Thus actual values of a and b remain unchanged even Thus actual values of a and b get changed after

after exchanging the values of x and y. exchanging values of x and y.

4.In call by values we cannot alter the values of actual 4.In call by reference we can alter the values of

variables through function calls. variables through function calls.

Difference between Local and Global Variables

Here, are some fundamental differences between Local and Global variables.

Parameter Local Global

Scope It is declared inside a function. It is declared outside the function.

Value If it is not initialized, a garbage value is If it is not initialized zero is stored as


stored default.

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.

Difference bteween Automatic and Static Storage Class

Automatic Variable Static Variables

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.

You might also like