Functions allow programmers to organize code into reusable blocks. There are three main types of functions: library functions, user-defined functions, and main(). Functions can return values and take parameters. Parameters can be passed by value, reference using an alias, or reference using pointers. Passing by value copies the values, while passing by reference or pointer passes the actual arguments so any changes made in the function also change the original variables. Well-defined functions promote code reuse and modular programming.
This document discusses C++ functions. It begins by defining what a function is and describing standard and user-defined functions. It then covers the structure of C++ functions including the function signature, parameters, return values, and body. Examples are provided of defining, declaring, calling and overloading functions. The document also discusses scope of variables, passing data between functions, and inline functions.
1. A function is a block of code that performs a specific task. Functions allow programmers to split a large program into smaller sub-tasks and call them multiple times.
2. There are two main types of functions - library functions provided by the standard library, and user-defined functions created by the programmer.
3. Functions make programs easier to write, read, update and debug by splitting them into smaller, well-defined tasks.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
Function overloading in C++ allows defining multiple functions with the same name as long as they have different parameters. This enables functions to perform different tasks based on the types of arguments passed. An example demonstrates defining multiple area() functions, one taking a radius and the other taking length and breadth. Inline functions in C++ avoid function call overhead by expanding the function code at the call site instead of jumping to another location. Demonstrated with an inline mul() and div() example.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
This document discusses C++ functions. It begins by defining what a function is and describing standard and user-defined functions. It then covers the structure of C++ functions including the function signature, parameters, return values, and body. Examples are provided of defining, declaring, calling and overloading functions. The document also discusses scope of variables, passing data between functions, and inline functions.
1. A function is a block of code that performs a specific task. Functions allow programmers to split a large program into smaller sub-tasks and call them multiple times.
2. There are two main types of functions - library functions provided by the standard library, and user-defined functions created by the programmer.
3. Functions make programs easier to write, read, update and debug by splitting them into smaller, well-defined tasks.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
A large program can be divided into smaller subprograms or functions. Functions make a program easier to write, read, update and debug by dividing it into self-contained tasks. Functions allow code to be reused and are called by the main program. Functions may accept arguments from the main program and return values to the main program. This allows two-way communication between functions and the main program.
The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform a specific task. Functions make a program modular and easier to debug. There are four main types of functions: functions with no arguments and no return value, functions with no arguments but a return value, functions with arguments but no return value, and functions with both arguments and a return value. Functions are called by their name and can pass data between the calling and called functions using arguments.
This document discusses C++ functions. It defines standard functions that come with C++ and user-defined functions. It explains the structure of a C++ function including the function header and body. It discusses declaring function signatures separately from implementations. Parameters and scopes are also covered. Examples are provided of standard math and character functions as well as user-defined functions. Header files for organizing function declarations and implementation files are demonstrated.
The document discusses call by value and call by reference in functions. Call by value passes the actual value of an argument to the formal parameter, so any changes made to the formal parameter do not affect the actual argument. Call by reference passes the address of the actual argument, so changes to the formal parameter do directly modify the actual argument. An example program demonstrates call by value, where changing the formal parameter does not change the original variable.
The document discusses functions and recursion in C programming. It provides examples of different types of functions like void, float, int functions. It demonstrates simple functions with no parameters, functions that return values, and functions with parameters. It also explains recursion with examples of calculating factorials and Fibonacci series recursively. Finally, it discusses other function related concepts like function prototypes, scope of variables, and pre-defined math functions in C.
Functions in C can be divided into smaller subprograms to make programs more modular and easier to read, debug, and update. Functions allow code to be reused by calling the function multiple times. There are four main types of functions: functions with no arguments and no return value, functions with no arguments but a return value, functions with arguments but no return value, and functions with both arguments and a return value. Functions are defined with a return type, name, and list of parameters, and allow for modularization and passing of data between the calling function and called function.
C++ functions require prototypes that specify the return type and parameters. Function overloading allows multiple functions to have the same name but different signatures. Default arguments allow functions to be called without providing trailing arguments. Inline functions expand the function body at the call site for small functions to reduce overhead compared to regular function calls.
The document discusses C programming functions. It provides examples of defining, calling, and using functions to calculate factorials, Fibonacci sequences, HCF and LCM recursively and iteratively. Functions allow breaking programs into smaller, reusable blocks of code. They take in parameters, can return values, and have local scope. Function prototypes declare their interface so they can be called from other code locations.
Functions allow code to be reused by defining formulas that can be called from different parts of a program. Functions take in inputs, perform operations, and return outputs. They are defined outside of the main body with a function prototype, and can be called multiple times from within main or other functions. This document demonstrates how to define a FindMax function that takes in two numbers, compares them, and returns the maximum number. It shows function prototypes, defining the function outside of main, and calling the function from within main to find the maximum of two user-input numbers.
This document discusses parameters in C++. There are two types of parameters: formal parameters defined in a function and actual parameters passed during a function call. C++ supports two ways of passing parameters: call by value where the formal parameter is a copy of the actual value, and call by reference where the formal parameter is an alias to the actual parameter. Call by reference allows a function to modify the original value. While it is more efficient for large data types, it can be ambiguous whether a parameter is intended for input or output.
The document discusses functions in C programming and structured programming. It explains that a C program consists of user-defined functions that each solve smaller subproblems obtained through top-down design. Functions are defined with a return type, parameter list, and body. Functions can call other functions. Arguments are passed by value, so changes to parameters do not affect the original variables. The document provides examples of function prototypes, definitions, and calls.
hey this is Rupendra choudhary..!! i shared my "c" lang ppt..!!! u just goto that ppt if u r in deep with "c" ..!!! i create after i hv played a much with "c"..(sorry bt ppt is slightly disturbd may be due to unsupportable msppt2010 by slideshare)...find me on rupendrachoudhary1990@gmail.com or https://rupendrachoudhary.wordpress.com
The document discusses passing objects as arguments to functions in C++. It can be done in two ways - by value using a copy of the object or by reference passing the address. The sample program demonstrates passing two height objects to a sum function that adds their feet and inches values. The function receives the objects by value, performs the calculation, and outputs the total height.
The document discusses functions in C++. It defines a function as a self-contained program that performs a specific task. Functions help break large programs into smaller, modular pieces. The key parts of a function include the prototype, definition, arguments, return statement, and calling a function. Functions make programs easier to understand, maintain and debug.
The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().
The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().
A function is a block of code that performs a specific task. It takes input, processes it, and returns output. There are two types of functions: library functions provided by the C language, and user-defined functions created by the programmer. Functions allow programmers to divide a large program into smaller, separate, and reusable parts of code. Functions make code more organized and modular.
This document discusses functions in C programming. It defines what a function is and explains why we use functions. There are two types of functions - predefined and user-defined. User-defined functions have elements like function declaration, definition, and call. Functions can pass parameters by value or reference. The document also discusses recursion, library functions, and provides examples of calculating sine series using functions.
The document discusses functions in C programming. It defines what a function is and explains that functions can be used to break a large program into smaller modular pieces of code that can be reused. The key points covered include: defining functions with return types, parameters, and bodies; declaring functions; calling functions by passing arguments; and passing arguments by value vs reference. Examples are provided to demonstrate creating, calling, and passing arguments to functions. Recursion is also discussed as a special case where a function calls itself.
The document discusses C functions. Some key points:
1. Functions allow breaking code into reusable chunks that perform specific tasks. The main() function is required in every C program.
2. Functions are declared with a return type, name, and parameters. Definitions include the function body.
3. Standard library functions like strcat() and memcpy() are pre-defined for common tasks.
4. Functions are called by name and pass arguments by value or reference. Parameters allow customizing a function's behavior.
5. Recursion allows a function to call itself, enabling solutions to problems like factorials and Fibonacci sequences.
The document discusses functions in C programming. It defines functions as blocks of code that perform a specific task and can be called multiple times. There are two types of functions: user-defined functions created by the programmer, and pre-defined functions that are part of standard libraries. Functions have three aspects - declaration, definition, and call. They can return a value or not, and take arguments or not. Examples are given of different function types. Recursion and string handling functions are also explained.
The document discusses C functions, including their definition, types, uses, and implementation. It notes that C functions allow large programs to be broken down into smaller, reusable blocks of code. There are two types of functions - library functions and user-defined functions. Functions are declared with a return type, name, and parameters. They are defined with a body of code between curly braces. Functions can be called within a program and allow code to be executed modularly and reused. Parameters can be passed by value or by reference. Functions can return values or not, and may or may not accept parameters. Overall, functions are a fundamental building block of C that improve code organization, reusability, and maintenance.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
Functions are blocks of code that perform tasks in C programs. A function takes input, processes it, and returns a value. Functions must be declared with prototypes before use. Function definitions specify the return type, name, arguments, and body. Arguments are passed by value by default, but can be passed by reference using pointers. Recursion is when a function calls itself. External and static variables define scopes beyond the local function block.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers function components like parameters and arguments. It explains passing parameters by value and reference. It also discusses different types of functions like built-in functions, user-defined functions, and functions with default arguments. Additionally, it covers concepts like scope of variables, return statement, recursion, and automatic vs static variables. The document is intended to teach the fundamentals of functions as building blocks of C++ programs.
The document provides an overview of functions in C++. It discusses the basic concepts of functions including declaring, defining, and calling functions. It covers different types of functions such as built-in functions, user-defined functions, and functions that return values. The key components of a function like the prototype, definition, parameters, arguments, and return statement are explained. It also describes different ways of passing parameters to functions, including call by value and call by reference. Functions allow breaking down programs into smaller, reusable components, making the code more readable, maintainable and reducing errors.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
The document presents information about functions in the C programming language. It discusses what a C function is, the different types of C functions including library functions and user-defined functions. It provides examples of how to declare, define, call and pass arguments to C functions. Key points covered include how functions allow dividing a large program into smaller subprograms, the ability to call functions multiple times, and how functions improve readability, debugging and reusability of code. An example program demonstrates a simple C function that calculates the square of a number.
The document discusses user-defined functions in C. It defines a user-defined function as a programmed routine with parameters set by the user. It covers the parts of a function including prototypes, calls, and definitions. It discusses passing parameters by value and reference. It also discusses local and global variables, recursion, and the advantages of user-defined functions in C.
Databases store large amounts of data permanently on disk. Only a small portion of data is loaded into memory at a time for processing. Data is stored on disk in files containing records of related data values. Records can have fixed or variable lengths. Files are organized using different methods like heap, sequential, indexed, and hashed to allow for efficient data retrieval, storage, and access. Indexed files use a separate index file to locate records in the data file faster. Hashed files determine record locations using a hashing algorithm and hash function to map records to disk blocks.
The document discusses transaction processing and related concepts. It introduces transactions as units of work that must be completely processed or not processed at all. It covers transaction control language commands like START TRANSACTION, COMMIT, and ROLLBACK. It discusses the ACID properties of atomicity, consistency, isolation, and durability that transactions should satisfy. It defines schedules as the order of transaction operations and describes serial, non-serial, and conflict schedules. It also discusses concurrency control issues that can arise from conflicting schedules like lost updates.
1. The document defines key concepts in conceptual data modeling including entities, attributes, relationships, and extended entity relationship (EER) modeling.
2. Entities can be strong or weak. Attributes can be single-valued or multi-valued, stored or derived. Relationships can be one-to-one, one-to-many, many-to-one, or many-to-many.
3. EER modeling allows for generalization and specialization of entities through supertypes/subtypes to model common and unique attributes more accurately.
Normalization is a process of organizing data to reduce redundancy and improve data integrity. It involves decomposing relations with anomalies into smaller, well-structured relations by identifying functional dependencies and applying normal forms. The normal forms are first normal form (1NF), second normal form (2NF), third normal form (3NF) and Boyce-Codd normal form (BCNF). Each normal form adds additional rules to reduce redundancy through a multi-step process of identifying dependencies and extracting subsets of data into new relations.
This document contains interview questions and answers related to C++. It discusses concepts like constructors, copy constructors, virtual destructors, and the differences between constructor and assignment operator. Key points are that constructors initialize objects while assignment operators assign values to existing objects, virtual destructors allow calling the proper destructor at runtime, and constructors cannot be virtual but destructors can.
An Oracle database consists of physical files on disk that store data and logical memory structures that manage the files. The database is made up of data files that contain tables and indexes, control files that track the physical components, and redo log files that record changes. The instance in memory associates with one database and manages access through background processes. The database is divided into logical storage units called tablespaces that map to the physical data files. Common tablespaces include SYSTEM, SYSAUX, undo and temporary tablespaces.
11. using regular expressions with oracle databaseAmrit Kaur
The Oracle database provides a set of SQL functions to search and manipulate strings using regular expressions. These functions include REGEXP_COUNT, REGEXP_LIKE, REGEXP_SUBSTR, REGEXP_INSTR, and REGEXP_REPLACE. Regular expressions use metacharacters like period, plus, star, and pipe to specify patterns to match. Metacharacters have special meanings like wildcard, repeating, or range of characters. The regular expression functions take a source string and pattern to perform matching and extraction.
This document discusses time zones and functions related to timestamps and time zones in databases. It explains that time is measured in 24 time zones based on Greenwich Mean Time. It provides examples of functions like CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP that return date and time values based on the user or database time zone. It also demonstrates functions like TO_TIMESTAMP, EXTRACT, and operations like adding intervals to timestamps to change them to different time zones or adjust relative dates.
Indexes are data structures that enable fast searching of data in database tables. There are different types of indexes including B-tree, bitmap, and function-based indexes. Indexes can be unique or non-unique. Index-organized tables store data in an index structure based on the primary key, while heap-organized tables store data separately from indexes and access rows using row IDs. Proper use of indexes can improve query performance.
A transaction is a logical unit of work that contains one or more SQL statements. It must be committed or rolled back as a whole to comply with the ACID properties of atomicity, consistency, isolation, and durability. Transactions begin with the first SQL statement and end with a COMMIT or ROLLBACK. The COMMIT makes all changes permanent while ROLLBACK undoes any changes made in the transaction. SAVEPOINT can be used to roll back portions of a transaction.
Exceptions in PL/SQL refer to unwanted events that terminate scripts unexpectedly. There are predefined exceptions for common errors that provide more user-friendly error messages instead of system codes. User-defined exceptions handle violations of business rules. The EXCEPTION block catches both predefined and user-defined exceptions, and specific exception types can be handled with the WHEN clause to execute exception handling code.
Triggers are stored program units that are implicitly executed when DDL or DML statements are used on associated tables. They define procedures to enforce business rules, prevent invalid transactions, and provide information on user events. Triggers can be row or statement level and fire before, after, or instead of insert, update, or delete operations. They are comprised of a trigger event, optional restriction, and action to execute.
Stored procedures and functions are named PL/SQL blocks that are stored in a database. They improve performance by reducing network traffic and allowing shared memory usage. Stored procedures are created using the CREATE PROCEDURE statement and can accept parameters using modes like IN, OUT, and IN OUT. Stored functions are similar but return a value. Packages group related database objects like procedures, functions, types and provide modularity and information hiding.
PL/SQL is a block-structured language used for accessing and manipulating Oracle databases. A PL/SQL block contains three parts: a declarative section, executable section, and exception-handling section. PL/SQL supports both scalar and composite datatypes. Control structures include conditional statements like IF-THEN-ELSE and CASE, and iterative statements like LOOP, WHILE, and FOR. Database interaction is done through SQL statements and cursors, which allow processing of multiple rows returned from a query.
This document discusses how to manage tables in a database including creating, modifying, and dropping tables. The key points are:
1. A table stores data in rows and columns and is created using the CREATE TABLE statement.
2. Tables can be modified using the ALTER TABLE statement to add, modify, or drop columns and constraints.
3. Integrity constraints like primary keys, foreign keys, checks and defaults are applied to tables to maintain data integrity.
4. External tables allow querying data stored outside the database in flat files and are created using the CREATE TABLE statement with the ORGANIZATION EXTERNAL clause.
The document discusses different ways to manipulate data in tables, including inserting, updating, and deleting rows. It explains that the INSERT statement is used to add rows to a table. The UPDATE statement updates existing rows by changing column values. Rows can be deleted using the DELETE statement with an optional WHERE clause to target specific rows, or the TRUNCATE statement to delete all rows at once. Subqueries can also be used with these statements to insert, update, or delete rows based on the results of a subquery. Guidelines are provided for each operation to ensure data integrity is maintained.
The document provides an overview of SQL concepts for retrieving and manipulating data using SQL statements like SELECT, JOIN, GROUP BY, and subqueries. It discusses the key clauses and operations for projection, selection, aggregation, sorting, joining tables, grouping data, and using subqueries. Some important points covered include using SELECT to retrieve specific attributes or calculate column values, filtering rows with WHERE, sorting with ORDER BY, aggregation functions, inner/outer/cross joins, and applying grouping and aggregation at different levels with ROLLUP and CUBE.
This document discusses inheritance in C++. It defines inheritance and the key terminology used. It describes the different types of inheritance including single, hierarchical, multilevel, multiple and hybrid inheritance. Examples of code are provided for each type. Issues that can arise with multiple inheritance like ambiguities are also covered. In summary, the document provides an overview of inheritance in C++ through definitions, explanations and code examples of the various inheritance techniques.
This document discusses C++ as an object-oriented language. It describes key concepts like classes, objects, data members, member functions, access specifiers (public, private, protected), constructors, and destructors. Classes allow the combination of data and related functions that represent real-world objects. Constructors initialize objects, while destructors handle cleanup when objects are destroyed. Access specifiers determine visibility and access to class members from within and outside the class.
1. AmritKaur Functions in C++
1
Chapter 5: Functions
A function is a named, independent section of C++ code that performs a specific task and
optionally returns a value to the calling program.
A function is a part of program called by another part of a program. In a program, there are
many calling function (caller) and called functions (callee).
5.1 Function Definition
Function Definition is the actual function body, which contains the code that will be
executed. Function definition must not end with semicolon. A function can be
defined as follows
Syntax:
returntype functionname (parameter(s))
{
//function body
}
Example 1: function definition to find average of 5 nos
float average(int a, int b,int c, int d, int e )
{
float avg;
avg=(a+b+c+d+e)/5.0f;
return (avg)
}
Here floatspecifiesreturntype; average is name of function; int a, int b, int c, int d , int e are
parameters
Example 2: function definition and function call
#include<iostream.h>
void func()
{
cout<<” IN FUNCTION func()”<<endl;
}
void main()
{
cout<<”IN FUNCTION main()”<<endl;
func();//call to a function
cout<<” BACK IN main() FUNCTION”<<endl;
}
2. AmritKaur Functions in C++
2
5.2 Function Prototype
A function must be defined before using it. That is, if the function definition does not
precedes the function call, the function need to declare. The process of declaring
function is known as function prototyping.
In other words, if programmer wants to define a function after using it they have to
declare the function at the top just after pre-processor directives. It includes
returntype , function name and paramterlist followed by semicolon.
Syntax: returntype functionname (paramtere(s));
Example 3 : float average(int a, int b,int c, int d, int e ) ;
5.3. Types of Function
In C++, the function are classified into types
Library Functions:
Library functions are pre defined and pre compiled functions present in a library file
and found in include directory with extension .h
Example 4:
a. sqrt(), pow() are available in header file math.h
b. strlen(), strcpy() are present in string.h
User defined function
It is small independent program designed by user for performing the specific
operations.
5.4 Elements of User defined Function
Return Types
Functions can return a value to the caller. When a called function sends the data
back to calling program it is known as return type. If the function doesn’t return a
value use void. Otherwise it can return one value by using the return keyword. The
value to be returned must match with the value of return type.
3. AmritKaur Functions in C++
3
Function Name
It is name of the function that is used while calling. It can be any valid identifier.
Parameters or Arguments
Passing a values during function call takes place through arguments. The argument(s)
or parameter(s) of a function is/are the data the function must receive when called
from another function. When a calling function sends the data to a called function,
data is known as parameters or arguments. Types of Arguments
Actual Parameters / Arguments : Arguments listed in function calling statement.
These are the values passed to function to compute.
Formal Parameters / Arguments : The arguments used in the function
declaration. They receive the values supplied by calling program.
Default Parameters / Arguments : When a default value is assigned to formal
arguments it is known as default arguments. Useful in case when argument is
not passed in call statement
Example 5: Program to find average of 5 nos
#include<iostream.h>
#include<conio.h>
float average (int a, int b, int c, int d, int e) // formal parameters
{
float avg;
avg=(a+b+c+d+e)/5.0;
return avg;
}
void main()
{ int a,b,c,d,e;
cout<<"Enter Five Numbers";
cin>>a>>b>>c>>d>>e;
float result=average(a,b,c,d,e); // actual parameters
cout<<"Avergare of "<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" = "<<result;
}
5.5 Invoking Function
In C++, function can be invoked or called in one of the following ways
a. Call By Value
4. AmritKaur Functions in C++
4
b. Call By Reference
5.5.1 Call By Value
In Call by Value, the value of a parameter(s) is passed.
When parameters are passed by value, the called function creates the new variables
of same type and copies the argument values into it.
In call by value, the value of actual (original) parameter remain unchanged.
Example: Program to swap (interchange) two numbers using call by value.
#include<iostream.h>
#include<conio.h>
void swap(int p, int q) // p and q are formal arguments
{ // p is the copy of a and q is copy of b
int temp;
cout<<"nValue of p and q...... BEFORE swapping";
cout<<"np="<<p<<" t q="<<q;
temp=p;
p=q;
q=temp;
cout<<"nValue of p and q...... AFTER swapping";
cout<<"np="<<p<<" t q="<<q;
}
void main()
{
int a,b;
clrscr();
cout<<"n Enter value of a:";
cin>>a;
cout<<"n Enter value of b:";
cin>>b;
cout<<"nValue of a and b IN main ()";
cout<<"na="<<a<<" t b="<<b;
//call to swap function - call by value
swap(a,b);//a and b are actual parameter, their value is passed
cout<<"nValue of a and b IN main () after swap";
cout<<"na="<<a<<" t b="<<b;
}
5 10
A B
0x12 0x70
5 10
A B
0x12 0x70
5. AmritKaur Functions in C++
5
5.5.2 Call By Reference using an Alias
A reference provides an alias (alternate names) for the variable.
In call be reference using alias, a reference of the parameter in the calling program is
passed.
While passing, call by reference, the value of actual (original) variable changes
because there is only one copy of data is maintained with two different names.
Example: Program to swap (interchange) two numbers using call by reference using
alias.
#include<iostream.h>
#include<conio.h>
void swap(int &p, int &q)// p and q are formal arguments
{ // ampersand indicates p is alias of a
// and q is alias of b
int temp;
cout<<"nValue of p and q...... BEFORE swapping";
cout<<"np="<<p<<" t q="<<q;
temp=p;
p=q;
q=temp;
cout<<"nValue of p and q...... AFTER swapping";
cout<<"np="<<p<<" t q="<<q;
}
void main()
{
int a,b;
clrscr();
cout<<"n Enter value of a:";
cin>>a;
6. AmritKaur Functions in C++
6
cout<<"n Enter value of b:";
cin>>b;
cout<<"nValue of a and b IN main ()";
cout<<"na="<<a<<" t b="<<b;
//call to swap function - call by reference using alias
swap(a,b);//a and b are actual parameter, their value is passed
cout<<"nValue of a and b IN main () after swap";
cout<<"na="<<a<<" t b="<<b;
}
5.5.3 Call By Reference using an Pointers
In call be reference using pointers, an address of actual (original) parameter is
passed to the calling program.
While passing, call by reference, the value of actual (original) variable changes
because there is only one copy of data is maintained.
Example: Program to swap (interchange) two numbers using call by reference using
pointers.
#include<iostream.h>
#include<conio.h>
void swap(int *p, int *q)// p and q are formal arguments
{ // p contain address of a
// q contain address of b
int temp;
cout<<"nValue of p and q...... BEFORE swapping";
cout<<"np="<<*p<<" t q="<<*q;
temp=*p;
*p=*q;
*q=temp;
cout<<"nValue of p and q...... AFTER swapping";
cout<<"np="<<*p<<" t q="<<*q;
}
void main()
{
int a,b;
Afterswap() functionexecuted
10 5
P Q
A B
7. AmritKaur Functions in C++
7
clrscr();
cout<<"n Enter value of a:";
cin>>a;
cout<<"n Enter value of b:";
cin>>b;
cout<<"nValue of a and b IN main ()";
cout<<"na="<<a<<" t b="<<b;
//call to swap function - call by reference using pointer
swap(&a,&b);//a and b are actual parameter, their address is passed
cout<<"nValue of a and b IN main () after swap";
cout<<"na="<<a<<" t b="<<b;
}
5 10
A B
0x12 0x70
0x12 0x70
P Q
0x40
00
0x90
Afterswap() functionexecuted