Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Functions
Furqan Aziz
Function
 A function groups a number of program statements into
a unit and gives it a name.
 This unit can then be invoked from other parts of the
program.
 Advantages of using functions
 Conceptual organization of a program.
 Reduced program size.
 Code reusability.
 Easy to maintain and debug.
Function C++
Simple Functions
#include <iostream>
using namespace std;
void starLine();
int main(){
starLine();
cout<<"NtN*10tN*100tN*1000n";
starLine();
for(int i=0; i<5; i++){
cout<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
starLine();
}
void starLine(){
for(int i=0; i<30; i++)
cout<<"*";
cout<<endl;
return;
}

Recommended for you

Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)

This presentation is about Polymorphism in c++ covering topic types of polymorphism,it's types and real life example of Polymorphism.

learningclassroomengineering
Functions in C++
Functions in C++Functions in C++
Functions in C++

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.

Functions in c language
Functions in c language Functions in c language
Functions in c language

what are functions in c importance of function in c uses of function in c syantax of function in c program of function in c

c languageprogramming
Sample output
How many functions are there in this program.
The Function Declaration
 Just as you can’t use a variable without first telling the compiler what
it is, you also can’t use a function without telling the compiler about it.
 There are two ways to do this.
 Declare the function before it is called, and defined it somewhere else.
 Declared and define it before it’s called.
 Syntax:
 void starline();
 The declaration tells the compiler that at some later point we plan to
present a function called starline.
 Function declarations are also called prototypes , since they provide
a model or blueprint for the function.
The Function Declaration
 A function can return a value of any basic type (like int,
float, char etc) or any user defined type (Class or
Structure).
 The keyword void specifies that the function has no
return value
 A function can accept any number/type of arguments
(also called parameters list).
 The empty parentheses indicate that it takes no
arguments.
Calling the Function
 The following statement will call the function starline().
 starline();
 This is all we need to call the function: the function name,
followed by parentheses.
 The syntax of the call is very similar to that of the
declaration, except that the return type is not used.
 The call is terminated by a semicolon.
 Executing the call statement causes the function to execute;
i.e.,
 control is transferred to the function,
 the statements in the function definition are executed,
 The control returns to the statement following the function call.

Recommended for you

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++

1. Arrays declared with a fixed size limit the program size, while dynamically allocated arrays using heap memory allow the size to be determined at runtime. 2. The heap segment is used for dynamic memory allocation using functions like malloc() and new to request memory from the operating system as needed. 3. Deallocation of dynamically allocated memory is required using free() and delete to avoid memory leaks and ensure memory is returned to the operating system.

Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++

This document discusses different conditional structures in C++ including if, if-else, switch and goto statements. It provides the syntax and examples of each. The if statement executes code if a condition is true, if-else adds an else block for when the condition is false. Switch allows choosing between multiple options. Goto directly transfers control to a labeled line of code.

C++ Function
C++ FunctionC++ Function
C++ Function

The document discusses C++ functions. It explains that functions allow code to be reused by grouping common operations into reusable blocks of code called functions. Functions have three parts: a prototype that declares the function, a definition that implements it, and calls that execute the function. Functions can take parameters as input and return a value. Grouping common code into well-named functions makes a program more organized and maintainable.

The Function Definition
 The function definition contains the actual code for the
function.
 The definition consists of a line called the declarator,
followed by the function body .
 The function body is composed of the statements that make
up the function, delimited by braces.
 The declarator must agree with the declaration: It must use
the same function name, have the same argument types in
the same order (if there are arguments), and have the same
return type.
 Notice that the declarator is not terminated by a semicolon.
Function C++
Function Components
Comparison with Library
Functions
 Library functions are inbuilt functions which are grouped together
and placed in common place called library.
 Each library function performs a specific task.
 We have already used some of the library functions, such as
 ch = getch();
 Where are the declaration and definition of this library function?
 The declaration is in the header file specified at the beginning of
the program.
 The definition (compiled into executable code) is in a library file
that’s linked automatically to your program when you build it.
 Note that the getch() function returns a character and its does not
accept any arguments.

Recommended for you

Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar

This document discusses the structure of a C++ program. It begins by defining software and the different types. It then discusses key concepts in C++ like classes, objects, functions, and headers. It provides examples of a class declaration with private and public sections, member functions, and a main function. It also discusses practical training resources available for learning C++ including e-learning websites, e-assignments, e-content, and mobile apps.

structure of c++ - r.d.sivakumar
Functions in C
Functions in CFunctions in C
Functions in C

This document discusses different types of functions in C programming. It defines library functions, user-defined functions, and the key elements of functions like prototypes, arguments, parameters, return values. It categorizes functions based on whether they have arguments and return values. The document also explains how functions are called, either by value where changes are not reflected back or by reference where the original values are changed.

kamal acharyacall by valuefunctions
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming

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.

function in ccomputer sciencecomputer engineerig
Eliminating the Declaration
 The second approach to inserting a function into a
program is to eliminate the function declaration and
place the function definition (the function itself) in the
listing before the first call to the function.
Eliminating the Declaration
#include <iostream>
using namespace std;
void starLine(){
for(int i=0; i<30; i++)
cout<<"*";
cout<<endl;
return;
}
int main(){
starLine();
cout<<"NtN*10tN*100tN*1000n";
starLine();
for(int i=0; i<5; i++){
cout<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
starLine();
}
Passing Arguments to
Functions
 An argument is a piece of data (an int value, for
example) passed from a program to the function.
 Arguments allow a function to operate with different
values, or even to do different things, depending on the
requirements of the program calling it.
Passing constants
#include <iostream>
using namespace std;
void starLine(char ch, int n);
int main(){
starLine('-',50);
cout<<'t';
starLine('=',30);
cout<<"tNtN*10tN*100tN*1000n";
cout<<"t";
starLine('=',30);
for(int i=0; i<5; i++){
cout<<"t"<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
cout<<'t';
starLine('=',30);
starLine('-',50);
cout<<endl;
}
void starLine(char ch, int n){
for(int i=0; i<n; i++)
cout<<ch;
cout<<endl;
return;
}

Recommended for you

virtual function
virtual functionvirtual function
virtual function

Virtual functions allow functions to be overridden in derived classes. The virtual keyword before a function in the base class specifies that the function can be overridden. When a virtual function is called using a base class pointer, the version from the most derived class will be executed due to late binding. This allows runtime polymorphism where the function call is resolved based on the actual object type rather than the pointer variable type.

virtual functionvennilabon secours
Inline function
Inline functionInline function
Inline function

The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++

Classes allow users to bundle data and functions together. A class defines data members and member functions. Data members store data within each object, while member functions implement behaviors. Classes support access specifiers like public and private to control access to members. Objects are instances of classes that allocate memory for data members. Member functions can access object data members and are called on objects using dot notation. Friend functions allow non-member functions to access private members of classes.

Sample output
 The function declaration looks like
 void starLine(char ch, int n);
 The items in the parentheses are the data types of the arguments
that will be sent to the function.
 These are called parameters.
 In a function call, specific values—constants in this case—are
inserted in the appropriate place in the parentheses. These are
called arguments:
 starLine(‘=‘, 30);
 The values supplied in the call must be of the types specified in
the declaration: the first argument must be of type char and the
second argument must be of type int.
 The types in the declaration and the definition must also agree.
Passing Variables
#include <iostream>
using namespace std;
void repchar(char, int);
int main()
{
char chin;
int nin;
cout << "Enter a character: ";
cin >> chin;
cout << "Enter number of times to repeat it: ";
cin >> nin;
repchar(chin, nin);
return 0;
}
void repchar(char ch, int n) //function declarator
{
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl;
}
Sample output

Recommended for you

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure

Introduction to control structure in C Programming Language include decision making (if statement, if..else statement, if...else if...else statement, nested if...else statement, switch...case statement), Loop(for loop, while loop, do while loop, nested loop) and using keyword(break, continue and goto)

Operators in C++
Operators in C++Operators in C++
Operators in C++

The document discusses the different types of operators in C++, including unary, binary, ternary, arithmetic, logical, comparison, assignment, bitwise, and special operators like scope resolution (::), endl, and setw. It provides examples of how each operator is used, such as increment/decrement for unary, addition/subtraction for binary, conditional operator ?: for ternary, and manipulating bits with bitwise operators. The document also explains how scope resolution allows accessing global variables from inner blocks and how endl and setw are used for formatting output displays.

Function C programming
Function C programmingFunction C programming
Function C programming

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.

Passing arguments to a
function
 There are two ways to pass arguments to a function.
 Passing by value
 Passing by reference
Passing by Value
 In passing by value, function creates a new variable for
each of the parameter.
 The parameters are initialized with the values of the
arguments.
 When the function finishes its execution, these
variables are deleted from the memory.
 If you change the value of a parameter, the original
value remains unchanged.
Function C++
Returning Values from
Functions
 When a function completes its execution, it can return a
single value to the calling program.
 Usually this return value consists of an answer to the
problem the function has solved.
 When a function returns a value, the data type of this
value must be specified.
 When a function returns a value, the value from the
variable in the called function is copied to the one
assigned to the function call into the variable in the
calling function.

Recommended for you

Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++

This document discusses exception handling in C++. It defines an exception as an event that occurs during program execution that disrupts normal flow, like divide by zero errors. Exception handling allows the program to maintain normal flow even after errors by catching and handling exceptions. It describes the key parts of exception handling as finding problems, throwing exceptions, catching exceptions, and handling exceptions. The document provides examples of using try, catch, and throw blocks to handle exceptions in C++ code.

oopc++exception handling
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class

This document discusses pure virtual functions and abstract classes. It provides an introduction and schedule, then covers rules for virtual functions, pure virtual functions, virtual base classes, virtual destructors, abstract classes, and limitations of virtual functions. It also discusses the difference between early binding and late binding.

cppbcasy bca
functions of C++
functions of C++functions of C++
functions of C++

The document contains information about Tarandeep Kaur, including her name, section, and roll number. It then lists and describes various topics related to functions in C++, including definition of functions, function calling, function prototypes, void functions, local vs global variables, function overloading, and recursion. Examples are provided to illustrate function calling, passing arguments, return values, and differences between call by value and call by reference.

Example
#include <iostream>
using namespace std;
float lbstokg(float); //declaration
int main()
{
float lbs, kgs;
cout << "nEnter your weight in pounds: ";
cin >> lbs;
kgs = lbstokg(lbs);
cout << "Your weight in kilograms is " << kgs << endl;
return 0;
}
float lbstokg(float pounds)
{
float kilograms = 0.453592 * pounds;
return kilograms;
}
Sample output
Function C++
Eliminating Unnecessary
Variables
#include <iostream>
using namespace std;
float lbstokg(float); //declaration
int main()
{
float lbs;
cout << “nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs);
cout << endl;
return 0;
}
float lbstokg(float pounds)
{
return 0.453592 * pounds;
}

Recommended for you

Functions
FunctionsFunctions
Functions

The document discusses functions in C++. It covers standard and user-defined functions, value-returning and void functions, formal and actual parameters, and how to define, declare, and call functions. It also discusses scope of identifiers, value vs reference parameters, function overloading, and functions with default parameters.

Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments

The document discusses different types of functions in C++ including: 1) Main functions are mandatory while other programs define additional functions. Functions are declared with a return type, name, and parameters. 2) Functions are defined with a syntax including the return type, name, parameters, and body. Functions can be called within other functions or the main function by passing values. 3) Inline functions have their code placed at the call site at compile time to avoid function call overhead. They are defined using the inline keyword before the return type for small, single line functions. 4) Functions can have default arguments which are values provided in the declaration that are used if not passed to the function. They must

argumentsinlinefunction
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)

View C++ notes of Friend function here. To get Detailed knowledge of Friend Function visit tutorialfocus.net where you can also download it.

tutorialfocus.netc++ tutorialfriend function
Pass by reference
 A reference provides an alias — i.e., a different name — for
a variable.
 One of the most important uses for references is in passing
arguments to functions.
 Passing arguments by reference uses a different
mechanism. Instead of a value being passed to the function,
a reference to the original variable, in the calling program, is
passed.
 An important advantage of passing by reference is that the
function can access the actual variables in the calling
program
Example
#include <iostream>
using namespace std;
int main()
{
void intfrac(float, float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << “nEnter a real number: “; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << “Integer part is “ << intpart //print them
<< “, fraction part is “ << fracpart << endl;
} while( number != 0.0 ); //exit loop on 0.0
return 0;
}
//--------------------------------------------------------------
void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long>(n); //convert to long,
intp = static_cast<float>(temp); //back to float
fracp = n - intp; //subtract integer part
}
Sample output
Function C++

Recommended for you

Function overloading
Function overloadingFunction overloading
Function overloading

Function overloading allows defining multiple functions with the same name but different parameters. It is used to improve consistency, readability, and compile-time binding. Functions are overloaded by defining multiple implementations that differ in the number and/or type of arguments passed. While enhancing usability, overloading can sometimes cause ambiguity.

Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++

This document provides an overview of functions in programming. Functions allow code to be reused by defining sub-parts of a program that can be called repeatedly. Functions are analogous to employees that perform specific tasks and can do so whenever needed. Functions take parameters as input, perform operations, and may return a value. The document provides examples of function syntax and practice problems for writing functions to perform mathematical operations and conversions.

Function class in c++
Function class in c++Function class in c++
Function class in c++

1. Inline functions are small functions whose code is inserted at the call site instead of generating a function call. This avoids overhead of function calls but increases code size. 2. Function overloading allows different functions to have the same name but different parameters. The compiler determines which version to call based on argument types. 3. C++ classes allow defining data types that bundle together data members and member functions that can access them. Classes support data hiding and inheritance.

Swapping of variables
#include <iostream>
using namespace std;
void swap_nums(int&, int&);
int main()
{
int n1=99, n2=11;
int n3=22, n4=77;
swap_nums(n1, n2);
swap_nums(n3, n4);
cout << "n1=" << n1 << endl; //print out all numbers
cout << "n2=" << n2 << endl;
cout << "n3=" << n3 << endl;
cout << "n4=" << n4 << endl;
return 0;
}
void swap_nums(int& numb1, int& numb2)
{
int temp = numb1; //swap them
numb1 = numb2;
numb2 = temp;
}
Sample output
Function Overloading
 An overloaded function appears to perform different
activities depending on the kind of data sent to it.
 Overloading is like the joke about the famous
scientist who insisted that the thermos bottle was
the greatest invention of all time. Why? “It’s a
miracle device,” he said. “It keeps hot things hot,
but cold things it keeps cold. How does it know?”
Overloaded Functions
 Two functions with same name but different
number/type of arguments are called overloaded
functions.
 Example (different type of arguments)
 int sum (int x, int y);
 float sum (float x, float y);
 Example (different number of arguments)
 double inchToMeter (int feet, double inches);
 double inchToMeter (double feet);

Recommended for you

C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA

The document discusses C++ functions. It defines what a function is and describes the different types of C++ functions including standard and user-defined functions. It explains the structure of C++ functions including the function header, signature, and body. It provides examples of defining, declaring, implementing and calling functions. It also discusses topics like function parameters, scope of variables, inline functions, and building libraries.

localfunction callsubprograms
C++ overloading
C++ overloadingC++ overloading
C++ overloading

This document discusses C++ function and operator overloading. Overloading occurs when the same name is used for functions or operators that have different signatures. Signatures are distinguished by parameter types and types are used to determine the best match. Overloading is resolved at compile-time based on arguments passed, while overriding is resolved at run-time based on object type. The document provides examples of overloading functions and operators and discusses issues like symmetry, precedence, and whether functions should be members or non-members.

Family Law Magazine
Family Law MagazineFamily Law Magazine
Family Law Magazine

This document summarizes an article from the Winter/Spring 2015 issue of Family Lawyer Magazine. The article discusses how to determine if a law firm's website is optimized for smartphones. It notes that smartphone use is increasing, with over half of all website visits now coming from smartphones. The article provides tips for law firms, including using responsive design so the website automatically adjusts to different screen sizes, keeping pages lightweight with minimal images and text, and testing the site on various devices. It emphasizes the importance of prioritizing mobility so prospective clients can easily access information from their smartphones.

family law magazine
Example
#include <iostream>
using namespace std;
void repchar(); //declarations
void repchar(char);
void repchar(char, int);
int main()
{
repchar();
repchar(‘=’);
repchar(‘+’, 30);
return 0;
}
void repchar()
{
for(int j=0; j<45; j++)
cout << ‘*’; // always prints asterisk
cout << endl;
}
void repchar(char ch)
{
for(int j=0; j<45; j++)
cout << ch;
cout << endl;
}
void repchar(char ch, int n)
{
for(int j=0; j<n; j++)
cout << ch;
cout << endl;
}
This program prints out three lines of characters. Here’s the output:
*********************************************
=============================================
++++++++++++++++++++++++++++++
Function C++
Recursion
 A function can call itself, and this is called recursion.
 when used correctly this technique can be surprisingly
powerful.
Example: Factorial
#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
int main()
{
int n; //number entered by user
unsigned long fact; //factorial
cout << "Enter an integer: ";
cin >> n;
fact = factfunc(n);
cout << "Factorial of " << n << " is " << fact << endl;
return 0;
}
unsigned long factfunc(unsigned long n)
{
if(n > 1)
return n * factfunc(n-1); //self call
else
return 1;
}

Recommended for you

Trabajotesismelinda
TrabajotesismelindaTrabajotesismelinda
Trabajotesismelinda

Este documento trata sobre el problema del alcoholismo en los adolescentes de la ciudad de Caracas. Explica que el consumo excesivo de alcohol entre los jóvenes se ha incrementado rápidamente en los últimos 5 años y representa un grave problema de salud pública, ya que causa deterioro en las nuevas generaciones. Argumenta que es importante que la familia, el Estado y los medios de comunicación trabajen juntos en campañas de prevención y concientización sobre los peligros del alcoholismo dirigidas a los adolescentes.

Comunicación estratégica de Aqualand
Comunicación estratégica de AqualandComunicación estratégica de Aqualand
Comunicación estratégica de Aqualand

Estrategia de comunicación y marketing de la empresa Aqualand (Aqualive), cuyo objetivo es la implementación de beneficios y el desestacionamiento.

estrategia en comunicaciónaqualand torremolinosaqualand
24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman

The document analyzes the wine industry in Bolivia and identifies bottlenecks preventing wine exports. It provides a history of wine production in Bolivia and discusses current grape varieties, regions of production, exports, quality standards, and the supply chain. Key bottlenecks identified include a lack of export experience and expertise, limited grape varieties and quality for exports, dependency on imports, and a lack of coordination between industry stakeholders. The document also evaluates market opportunities for Bolivian wines in countries like the UK, Netherlands, Germany, Denmark, Sweden, and Poland.

Inline Functions
 Functions save memory space because all the calls to the function
cause the same code to be executed; the function body need not
be duplicated in memory.
 When the compiler sees a function call, it normally generates a
jump to the function.
 At the end of the function it jumps back to the instruction following
the call.
 While this sequence of events may save memory space, it takes
some extra time.
 To save execution time in short functions, you may elect to put the
code in the function body directly inline with the code in the calling
program.
Function C++
Inline Functions
 To declare a function inline, you need to specify the
keyword inline.
 You should be aware that the inline keyword is actually
just a request to the compiler.
 Sometimes the compiler will ignore the request and
compile the function as a normal function. It might
decide the function is too long to be inline, for instance.
Example
#include <iostream>
using namespace std;
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
//--------------------------------------------------------------
int main()
{
float lbs;
cout << "nEnter your weight in pounds: ";
cin >> lbs;
cout << "Your weight in kilograms is " << lbstokg(lbs)
<< endl;
return 0;
}

Recommended for you

Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...

Vortrag von Dirk Röhrborn auf dem Forum eLearning & Knowledge Management auf der Cebit 2009 über Microsharing und wie dieser Ansatz die Kommunikation im Unternehmen verändert.

communotedokumentierenlernen
Mba college in bangalore - NIBE
Mba college in bangalore - NIBEMba college in bangalore - NIBE
Mba college in bangalore - NIBE

NIBE is among top mba colleges in bangalore , india . College offers different courses like mba , bca, bbm and bcom . Its vision is to give efficient professionals to the management sector

mba college in bangaloretop mba college in bangalore
Formations PAO & 3D
Formations PAO & 3DFormations PAO & 3D
Formations PAO & 3D

KIELA Consulting - Formation PAO 3D FX Livret formations consacrées aux outils du secteur Audiovisuel. www.kiela.fr

formationquarkafter effects
Default Arguments
 A function can be called without specifying all its
arguments.
 For this to work, the function declaration must provide
default values for those arguments that are not
specified.
 These are called default arguments.
Example
#include <iostream>
using namespace std;
void repchar(char='*', int=45); //declaration with
//default arguments
int main()
{
repchar(); //prints 45 asterisks
repchar('='); //prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
return 0;
}
//--------------------------------------------------------------
void repchar(char ch, int n) //defaults supplied
{ // if necessary
for(int j=0; j<n; j++) //loops n times
cout << ch; //prints ch
cout << endl;
}
Default Arguments
 Remember that missing arguments must be the trailing
arguments—those at the end of thr argument list.
 You can leave out the last three arguments, but you
can’t leave out the next-to-last and then put in the last.
Scope and Storage Class
 The scope of a variable determines which parts of the
program can access it, and its storage class determines how
long it stays in existence.
 Two different kinds of scope are important here: local and
file.
 Variables with local scope are visible only within a block.
 Variables with file scope are visible throughout a file.
 There are two storage classes: automatic and static.
 Variables with storage class automatic exist during the lifetime
of the function in which they’re defined.
 Variables with storage class static exist for the lifetime of the
program.
 A block is basically the code between an opening brace and
a closing brace. Thus a function body is a block.

Recommended for you

Visual cryptography1
Visual cryptography1Visual cryptography1
Visual cryptography1

This document provides an overview of visual cryptography, including its introduction, types, implementation methods, advantages, disadvantages, and applications. Visual cryptography allows visual information like pictures and text to be encrypted in a way that can be decrypted by the human visual system. It was pioneered in 1994 and works by splitting an image into shares such that stacking a sufficient number of shares reveals the original image. The document discusses various visual cryptography schemes and their properties.

ProCor audience survey results
ProCor audience survey resultsProCor audience survey results
ProCor audience survey results

ProCor conducted a survey of its subscribers to obtain feedback and determine how to better disseminate its cardiovascular health content globally. The survey received 97 responses. Most respondents were physicians or public health professionals doing work with a global focus, particularly in Africa. Respondents expressed interest in additional topics like lifestyle modification, diabetes, and strategies for primary prevention. They also showed interest in expanding delivery methods to include social media and smartphone applications. The conclusion was that ProCor's audience is receptive to growth, expansion into new topics, and alternative formats for content delivery.

Fb para empresas mod3 - ud2y3
Fb para empresas   mod3 - ud2y3Fb para empresas   mod3 - ud2y3
Fb para empresas mod3 - ud2y3

Este documento proporciona consejos y recomendaciones para administrar y optimizar una página de Facebook para empresas. Algunas de las sugerencias clave incluyen elegir un nombre y URL atractivos para la página, diseñar una portada llamativa, ordenar las publicaciones para maximizar el engagement, y publicar contenido valioso a un ritmo constante pero no excesivo para mantener a los fans comprometidos.

facebookcursoempresas
Local variables
 Variables defined within a function body are called local
variables. A variable scope is also called visibility.
 They have local scope, i.e., they can only be accessed
inside the block where they are defined.
 However, they are also sometimes called automatic
variables, because they have the automatic storage class.
 The time period between the creation and destruction of a
variable is called its lifetime.
 The lifetime of a local variable coincides with the time when
the function in which it is defined is executing.
Example
void somefunc()
{
int somevar; //local variables
float othervar;
somevar = 10; //OK
othervar = 11; //OK
nextvar = 12; //illegal: not visible in somefunc()
}
void otherfunc()
{
int nextvar; //local variable
somevar = 20; //illegal: not visible in otherfunc()
othervar = 21; //illegal: not visible in otherfunc()
nextvar = 22; //OK
}
Global Variables
 A global variable is visible to all the functions in a file.
 More precisely, it is visible to all those functions that follow
the variable’s definition in the listing.
 While local variables are defined within functions, global
variables are defined outside of any function.
 Usually you want global variables to be visible to all
functions, so you put their declarations at the beginning of
the listing.
 Global variables are also sometimes called external
variables, since they are defined external to any function.
Exmaple
#include <iostream>
using namespace std;
#include <conio.h> //for getch()
char ch = ‘a’; //global variable ch
void getachar(); //function declarations
void putachar();
int main()
{
while( ch != ‘r’ ) //main() accesses ch {
getachar();
putachar();
}
cout << endl;
return 0;
}
//--------------------------------------------------------------
void getachar() //getachar() accesses ch {
ch = getch();
}
//--------------------------------------------------------------
void putachar() //putachar() accesses ch {
cout << ch;
}

Recommended for you

Personal disciplina
Personal disciplinaPersonal disciplina
Personal disciplina

Este documento trata sobre la disciplina y los conflictos en el aula desde una perspectiva teórica y práctica. Primero, explora conceptos clave como la disciplina, la autoridad del docente y la socialización. Luego, analiza teorías educativas relevantes y propone un plan de trabajo centrado en el proyecto "Aula de convivencia" para mejorar la disciplina. Finalmente, incluye anexos sobre temas como la posmodernidad y tablas ilustrativas. El objetivo general es dar una visión general del tema y ofrecer e

Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1

The document discusses functions in C++. It defines a function as a block of code that performs a specific task. There are two types of functions: built-in functions provided by the language and user-defined functions created by the programmer. The components of a function include the function header, body, parameters, return type, local variables, and return statement. Functions can pass arguments either by value or by reference. The document provides examples of built-in and user-defined functions as well as examples demonstrating call by value and call by reference.

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function

Functions allow programmers to organize code into reusable blocks. A function performs a specific task and can accept input parameters and return an output. Functions make code more modular and easier to maintain. Functions are defined with a name, parameters, and body. They can be called from other parts of the code to execute their task. Parameters allow functions to accept input values, while return values allow functions to return output to the calling code. Functions can be called by passing arguments by value or reference. The document provides examples and explanations of different types of functions in C++ like inline functions, functions with default arguments, and global vs local variables.

Global Variables: Initialization
 If a global variable is initialized, it takes place when the
program is first loaded.
 If a global variable is not initialized explicitly by the
program, then it is initialized automatically to 0 when it
is created.
 This is unlike local variables, which are not initialized
and probably contain random or garbage values when
they are created
Lifetime and Visibility
 Global variables have storage class static, which
means they exist for the life of the program
 Memory space is set aside for them when the program
begins, and continues to exist until the program ends.
 You don’t need to use the keyword static when
declaring global variables; they are given this storage
class automatically.
 Global variables are visible in the file in which they are
defined, starting at the point where they are defined.
Static Local Variables
 A static local variable has the visibility of an automatic local
variable (that is, inside the function containing it).
 However, its lifetime is the same as that of a global variable,
except that it doesn’t come into existence until the first call to
the function containing it.
 Thereafter it remains in existence for the life of the program.
 Static local variables are used when it’s necessary for a
function to remember a value when it is not being executed;
that is, between calls to the function.
Example
#include <iostream>
using namespace std;
float getavg(float); //declaration
int main()
{
float data=1, avg;
while( data != 0 )
{
cout << “Enter a number: “;
cin >> data;
avg = getavg(data);
cout << “New average is “ << avg << endl;
}
return 0;
}
//--------------------------------------------------------------
float getavg(float newdata)
{
static float total = 0; //static variables are initialized
static int count = 0; // only once per program
count++; //increment count
total += newdata; //add new data to total
return total / count; //return the new average
}

Recommended for you

Function in c
Function in cFunction in c
Function in c

The document discusses functions in C programming. It defines what a function is, how functions are declared and defined, how to pass arguments to functions, and different ways to call functions. It provides examples of using functions to calculate factorials, Fibonacci series, find the highest common factor and lowest common multiple of two numbers, and sum the digits of a number recursively. Various ways of implementing functions using loops, recursion, and by passing arguments are demonstrated through code examples.

functioncexamples
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++

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

 
by LPU
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading

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.

Static variables
 Initialization: When static variables are initialized, as
total and count are in getavg() , the initialization takes
place only once—the first time their function is called.
They are not reinitialized on subsequent calls to the
function, as ordinary local variables are.
 Storage: local variables and function arguments are
stored on the stack, while global and static variables
are stored on the heap.
Storage types

More Related Content

What's hot

Control structure C++
Control structure C++Control structure C++
Control structure C++
Anil Kumar
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Sachin Sharma
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
amber chaudary
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
Sivakumar R D .
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
Sokngim Sa
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
Sachin Sharma
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
Amit Trivedi
 

What's hot (20)

Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in C
Function in CFunction in C
Function in C
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
virtual function
virtual functionvirtual function
virtual function
 
Inline function
Inline functionInline function
Inline function
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 

Viewers also liked

functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Functions
FunctionsFunctions
Functions
Online
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Function overloading
Function overloadingFunction overloading
Function overloading
Jnyanaranjan Dash
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
NUST Stuff
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
Kumar
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
sanya6900
 
Family Law Magazine
Family Law MagazineFamily Law Magazine
Family Law Magazine
Thomas Mastromatto NMLS #145824
 
Trabajotesismelinda
TrabajotesismelindaTrabajotesismelinda
Trabajotesismelinda
Brayan MiGuel
 
Comunicación estratégica de Aqualand
Comunicación estratégica de AqualandComunicación estratégica de Aqualand
Comunicación estratégica de Aqualand
kristinaah
 
24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman24 10-12 presentation vca marco tiggelman
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Communardo GmbH
 
Mba college in bangalore - NIBE
Mba college in bangalore - NIBEMba college in bangalore - NIBE
Mba college in bangalore - NIBE
NIBE ( National Institute Of Busiess Excellence )
 
Formations PAO & 3D
Formations PAO & 3DFormations PAO & 3D
Formations PAO & 3D
KIELA Consulting
 
Visual cryptography1
Visual cryptography1Visual cryptography1
Visual cryptography1
patisa
 
ProCor audience survey results
ProCor audience survey resultsProCor audience survey results
ProCor audience survey results
procor
 
Fb para empresas mod3 - ud2y3
Fb para empresas   mod3 - ud2y3Fb para empresas   mod3 - ud2y3
Fb para empresas mod3 - ud2y3
Comercial Agroalimentaria Bajo Aragón S.L.
 
Personal disciplina
Personal disciplinaPersonal disciplina
Personal disciplina
convertidor
 

Viewers also liked (20)

functions of C++
functions of C++functions of C++
functions of C++
 
Functions
FunctionsFunctions
Functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Family Law Magazine
Family Law MagazineFamily Law Magazine
Family Law Magazine
 
Trabajotesismelinda
TrabajotesismelindaTrabajotesismelinda
Trabajotesismelinda
 
Comunicación estratégica de Aqualand
Comunicación estratégica de AqualandComunicación estratégica de Aqualand
Comunicación estratégica de Aqualand
 
24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman
 
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
 
Mba college in bangalore - NIBE
Mba college in bangalore - NIBEMba college in bangalore - NIBE
Mba college in bangalore - NIBE
 
Formations PAO & 3D
Formations PAO & 3DFormations PAO & 3D
Formations PAO & 3D
 
Visual cryptography1
Visual cryptography1Visual cryptography1
Visual cryptography1
 
ProCor audience survey results
ProCor audience survey resultsProCor audience survey results
ProCor audience survey results
 
Fb para empresas mod3 - ud2y3
Fb para empresas   mod3 - ud2y3Fb para empresas   mod3 - ud2y3
Fb para empresas mod3 - ud2y3
 
Personal disciplina
Personal disciplinaPersonal disciplina
Personal disciplina
 

Similar to Function C++

Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh
 
Function in c
Function in cFunction in c
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
temkin abdlkader
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
Jari Abbas
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
Function
Function Function
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
SURBHI SAROHA
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
C function
C functionC function
C function
thirumalaikumar3
 
Functions
FunctionsFunctions
Functions
zeeshan841
 

Similar to Function C++ (20)

Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Function in c
Function in cFunction in c
Function in c
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Functions
FunctionsFunctions
Functions
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
functions
functionsfunctions
functions
 
Function
Function Function
Function
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
C function
C functionC function
C function
 
Functions
FunctionsFunctions
Functions
 

Recently uploaded

Conducting exciting academic research in Computer Science
Conducting exciting academic research in Computer ScienceConducting exciting academic research in Computer Science
Conducting exciting academic research in Computer Science
Abhik Roychoudhury
 
Front Desk Management in the Odoo 17 ERP
Front Desk  Management in the Odoo 17 ERPFront Desk  Management in the Odoo 17 ERP
Front Desk Management in the Odoo 17 ERP
Celine George
 
How to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 NotebookHow to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 Notebook
Celine George
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
Celine George
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
Elizabeth Walsh
 
Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?
Rakesh Jalan
 
Righteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdfRighteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdf
Zuzana Mészárosová
 
Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17
Celine George
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
Celine George
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
JackieSparrow3
 
Webinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional SkillsWebinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional Skills
EduSkills OECD
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Brajeswar Paul
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
HappieMontevirgenCas
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Liyana Rozaini
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
heathfieldcps1
 
How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17
Celine George
 
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
siemaillard
 
Principles of Roods Approach!!!!!!!.pptx
Principles of Roods Approach!!!!!!!.pptxPrinciples of Roods Approach!!!!!!!.pptx
Principles of Roods Approach!!!!!!!.pptx
ibtesaam huma
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Murugan Solaiyappan
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Astro Pathshala
 

Recently uploaded (20)

Conducting exciting academic research in Computer Science
Conducting exciting academic research in Computer ScienceConducting exciting academic research in Computer Science
Conducting exciting academic research in Computer Science
 
Front Desk Management in the Odoo 17 ERP
Front Desk  Management in the Odoo 17 ERPFront Desk  Management in the Odoo 17 ERP
Front Desk Management in the Odoo 17 ERP
 
How to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 NotebookHow to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 Notebook
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
 
Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?
 
Righteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdfRighteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdf
 
Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
 
Webinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional SkillsWebinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional Skills
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17
 
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
 
Principles of Roods Approach!!!!!!!.pptx
Principles of Roods Approach!!!!!!!.pptxPrinciples of Roods Approach!!!!!!!.pptx
Principles of Roods Approach!!!!!!!.pptx
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
 

Function C++

  • 2. Function  A function groups a number of program statements into a unit and gives it a name.  This unit can then be invoked from other parts of the program.  Advantages of using functions  Conceptual organization of a program.  Reduced program size.  Code reusability.  Easy to maintain and debug.
  • 4. Simple Functions #include <iostream> using namespace std; void starLine(); int main(){ starLine(); cout<<"NtN*10tN*100tN*1000n"; starLine(); for(int i=0; i<5; i++){ cout<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } starLine(); } void starLine(){ for(int i=0; i<30; i++) cout<<"*"; cout<<endl; return; }
  • 5. Sample output How many functions are there in this program.
  • 6. The Function Declaration  Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it.  There are two ways to do this.  Declare the function before it is called, and defined it somewhere else.  Declared and define it before it’s called.  Syntax:  void starline();  The declaration tells the compiler that at some later point we plan to present a function called starline.  Function declarations are also called prototypes , since they provide a model or blueprint for the function.
  • 7. The Function Declaration  A function can return a value of any basic type (like int, float, char etc) or any user defined type (Class or Structure).  The keyword void specifies that the function has no return value  A function can accept any number/type of arguments (also called parameters list).  The empty parentheses indicate that it takes no arguments.
  • 8. Calling the Function  The following statement will call the function starline().  starline();  This is all we need to call the function: the function name, followed by parentheses.  The syntax of the call is very similar to that of the declaration, except that the return type is not used.  The call is terminated by a semicolon.  Executing the call statement causes the function to execute; i.e.,  control is transferred to the function,  the statements in the function definition are executed,  The control returns to the statement following the function call.
  • 9. The Function Definition  The function definition contains the actual code for the function.  The definition consists of a line called the declarator, followed by the function body .  The function body is composed of the statements that make up the function, delimited by braces.  The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type.  Notice that the declarator is not terminated by a semicolon.
  • 12. Comparison with Library Functions  Library functions are inbuilt functions which are grouped together and placed in common place called library.  Each library function performs a specific task.  We have already used some of the library functions, such as  ch = getch();  Where are the declaration and definition of this library function?  The declaration is in the header file specified at the beginning of the program.  The definition (compiled into executable code) is in a library file that’s linked automatically to your program when you build it.  Note that the getch() function returns a character and its does not accept any arguments.
  • 13. Eliminating the Declaration  The second approach to inserting a function into a program is to eliminate the function declaration and place the function definition (the function itself) in the listing before the first call to the function.
  • 14. Eliminating the Declaration #include <iostream> using namespace std; void starLine(){ for(int i=0; i<30; i++) cout<<"*"; cout<<endl; return; } int main(){ starLine(); cout<<"NtN*10tN*100tN*1000n"; starLine(); for(int i=0; i<5; i++){ cout<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } starLine(); }
  • 15. Passing Arguments to Functions  An argument is a piece of data (an int value, for example) passed from a program to the function.  Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.
  • 16. Passing constants #include <iostream> using namespace std; void starLine(char ch, int n); int main(){ starLine('-',50); cout<<'t'; starLine('=',30); cout<<"tNtN*10tN*100tN*1000n"; cout<<"t"; starLine('=',30); for(int i=0; i<5; i++){ cout<<"t"<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } cout<<'t'; starLine('=',30); starLine('-',50); cout<<endl; } void starLine(char ch, int n){ for(int i=0; i<n; i++) cout<<ch; cout<<endl; return; }
  • 18.  The function declaration looks like  void starLine(char ch, int n);  The items in the parentheses are the data types of the arguments that will be sent to the function.  These are called parameters.  In a function call, specific values—constants in this case—are inserted in the appropriate place in the parentheses. These are called arguments:  starLine(‘=‘, 30);  The values supplied in the call must be of the types specified in the declaration: the first argument must be of type char and the second argument must be of type int.  The types in the declaration and the definition must also agree.
  • 19. Passing Variables #include <iostream> using namespace std; void repchar(char, int); int main() { char chin; int nin; cout << "Enter a character: "; cin >> chin; cout << "Enter number of times to repeat it: "; cin >> nin; repchar(chin, nin); return 0; } void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl; }
  • 21. Passing arguments to a function  There are two ways to pass arguments to a function.  Passing by value  Passing by reference
  • 22. Passing by Value  In passing by value, function creates a new variable for each of the parameter.  The parameters are initialized with the values of the arguments.  When the function finishes its execution, these variables are deleted from the memory.  If you change the value of a parameter, the original value remains unchanged.
  • 24. Returning Values from Functions  When a function completes its execution, it can return a single value to the calling program.  Usually this return value consists of an answer to the problem the function has solved.  When a function returns a value, the data type of this value must be specified.  When a function returns a value, the value from the variable in the called function is copied to the one assigned to the function call into the variable in the calling function.
  • 25. Example #include <iostream> using namespace std; float lbstokg(float); //declaration int main() { float lbs, kgs; cout << "nEnter your weight in pounds: "; cin >> lbs; kgs = lbstokg(lbs); cout << "Your weight in kilograms is " << kgs << endl; return 0; } float lbstokg(float pounds) { float kilograms = 0.453592 * pounds; return kilograms; }
  • 28. Eliminating Unnecessary Variables #include <iostream> using namespace std; float lbstokg(float); //declaration int main() { float lbs; cout << “nEnter your weight in pounds: “; cin >> lbs; cout << “Your weight in kilograms is “ << lbstokg(lbs); cout << endl; return 0; } float lbstokg(float pounds) { return 0.453592 * pounds; }
  • 29. Pass by reference  A reference provides an alias — i.e., a different name — for a variable.  One of the most important uses for references is in passing arguments to functions.  Passing arguments by reference uses a different mechanism. Instead of a value being passed to the function, a reference to the original variable, in the calling program, is passed.  An important advantage of passing by reference is that the function can access the actual variables in the calling program
  • 30. Example #include <iostream> using namespace std; int main() { void intfrac(float, float&, float&); //declaration float number, intpart, fracpart; //float variables do { cout << “nEnter a real number: “; //number from user cin >> number; intfrac(number, intpart, fracpart); //find int and frac cout << “Integer part is “ << intpart //print them << “, fraction part is “ << fracpart << endl; } while( number != 0.0 ); //exit loop on 0.0 return 0; } //-------------------------------------------------------------- void intfrac(float n, float& intp, float& fracp) { long temp = static_cast<long>(n); //convert to long, intp = static_cast<float>(temp); //back to float fracp = n - intp; //subtract integer part }
  • 33. Swapping of variables #include <iostream> using namespace std; void swap_nums(int&, int&); int main() { int n1=99, n2=11; int n3=22, n4=77; swap_nums(n1, n2); swap_nums(n3, n4); cout << "n1=" << n1 << endl; //print out all numbers cout << "n2=" << n2 << endl; cout << "n3=" << n3 << endl; cout << "n4=" << n4 << endl; return 0; } void swap_nums(int& numb1, int& numb2) { int temp = numb1; //swap them numb1 = numb2; numb2 = temp; }
  • 35. Function Overloading  An overloaded function appears to perform different activities depending on the kind of data sent to it.  Overloading is like the joke about the famous scientist who insisted that the thermos bottle was the greatest invention of all time. Why? “It’s a miracle device,” he said. “It keeps hot things hot, but cold things it keeps cold. How does it know?”
  • 36. Overloaded Functions  Two functions with same name but different number/type of arguments are called overloaded functions.  Example (different type of arguments)  int sum (int x, int y);  float sum (float x, float y);  Example (different number of arguments)  double inchToMeter (int feet, double inches);  double inchToMeter (double feet);
  • 37. Example #include <iostream> using namespace std; void repchar(); //declarations void repchar(char); void repchar(char, int); int main() { repchar(); repchar(‘=’); repchar(‘+’, 30); return 0; } void repchar() { for(int j=0; j<45; j++) cout << ‘*’; // always prints asterisk cout << endl; } void repchar(char ch) { for(int j=0; j<45; j++) cout << ch; cout << endl; } void repchar(char ch, int n) { for(int j=0; j<n; j++) cout << ch; cout << endl; } This program prints out three lines of characters. Here’s the output: ********************************************* ============================================= ++++++++++++++++++++++++++++++
  • 39. Recursion  A function can call itself, and this is called recursion.  when used correctly this technique can be surprisingly powerful.
  • 40. Example: Factorial #include <iostream> using namespace std; unsigned long factfunc(unsigned long); //declaration int main() { int n; //number entered by user unsigned long fact; //factorial cout << "Enter an integer: "; cin >> n; fact = factfunc(n); cout << "Factorial of " << n << " is " << fact << endl; return 0; } unsigned long factfunc(unsigned long n) { if(n > 1) return n * factfunc(n-1); //self call else return 1; }
  • 41. Inline Functions  Functions save memory space because all the calls to the function cause the same code to be executed; the function body need not be duplicated in memory.  When the compiler sees a function call, it normally generates a jump to the function.  At the end of the function it jumps back to the instruction following the call.  While this sequence of events may save memory space, it takes some extra time.  To save execution time in short functions, you may elect to put the code in the function body directly inline with the code in the calling program.
  • 43. Inline Functions  To declare a function inline, you need to specify the keyword inline.  You should be aware that the inline keyword is actually just a request to the compiler.  Sometimes the compiler will ignore the request and compile the function as a normal function. It might decide the function is too long to be inline, for instance.
  • 44. Example #include <iostream> using namespace std; inline float lbstokg(float pounds) { return 0.453592 * pounds; } //-------------------------------------------------------------- int main() { float lbs; cout << "nEnter your weight in pounds: "; cin >> lbs; cout << "Your weight in kilograms is " << lbstokg(lbs) << endl; return 0; }
  • 45. Default Arguments  A function can be called without specifying all its arguments.  For this to work, the function declaration must provide default values for those arguments that are not specified.  These are called default arguments.
  • 46. Example #include <iostream> using namespace std; void repchar(char='*', int=45); //declaration with //default arguments int main() { repchar(); //prints 45 asterisks repchar('='); //prints 45 equal signs repchar('+', 30); //prints 30 plus signs return 0; } //-------------------------------------------------------------- void repchar(char ch, int n) //defaults supplied { // if necessary for(int j=0; j<n; j++) //loops n times cout << ch; //prints ch cout << endl; }
  • 47. Default Arguments  Remember that missing arguments must be the trailing arguments—those at the end of thr argument list.  You can leave out the last three arguments, but you can’t leave out the next-to-last and then put in the last.
  • 48. Scope and Storage Class  The scope of a variable determines which parts of the program can access it, and its storage class determines how long it stays in existence.  Two different kinds of scope are important here: local and file.  Variables with local scope are visible only within a block.  Variables with file scope are visible throughout a file.  There are two storage classes: automatic and static.  Variables with storage class automatic exist during the lifetime of the function in which they’re defined.  Variables with storage class static exist for the lifetime of the program.  A block is basically the code between an opening brace and a closing brace. Thus a function body is a block.
  • 49. Local variables  Variables defined within a function body are called local variables. A variable scope is also called visibility.  They have local scope, i.e., they can only be accessed inside the block where they are defined.  However, they are also sometimes called automatic variables, because they have the automatic storage class.  The time period between the creation and destruction of a variable is called its lifetime.  The lifetime of a local variable coincides with the time when the function in which it is defined is executing.
  • 50. Example void somefunc() { int somevar; //local variables float othervar; somevar = 10; //OK othervar = 11; //OK nextvar = 12; //illegal: not visible in somefunc() } void otherfunc() { int nextvar; //local variable somevar = 20; //illegal: not visible in otherfunc() othervar = 21; //illegal: not visible in otherfunc() nextvar = 22; //OK }
  • 51. Global Variables  A global variable is visible to all the functions in a file.  More precisely, it is visible to all those functions that follow the variable’s definition in the listing.  While local variables are defined within functions, global variables are defined outside of any function.  Usually you want global variables to be visible to all functions, so you put their declarations at the beginning of the listing.  Global variables are also sometimes called external variables, since they are defined external to any function.
  • 52. Exmaple #include <iostream> using namespace std; #include <conio.h> //for getch() char ch = ‘a’; //global variable ch void getachar(); //function declarations void putachar(); int main() { while( ch != ‘r’ ) //main() accesses ch { getachar(); putachar(); } cout << endl; return 0; } //-------------------------------------------------------------- void getachar() //getachar() accesses ch { ch = getch(); } //-------------------------------------------------------------- void putachar() //putachar() accesses ch { cout << ch; }
  • 53. Global Variables: Initialization  If a global variable is initialized, it takes place when the program is first loaded.  If a global variable is not initialized explicitly by the program, then it is initialized automatically to 0 when it is created.  This is unlike local variables, which are not initialized and probably contain random or garbage values when they are created
  • 54. Lifetime and Visibility  Global variables have storage class static, which means they exist for the life of the program  Memory space is set aside for them when the program begins, and continues to exist until the program ends.  You don’t need to use the keyword static when declaring global variables; they are given this storage class automatically.  Global variables are visible in the file in which they are defined, starting at the point where they are defined.
  • 55. Static Local Variables  A static local variable has the visibility of an automatic local variable (that is, inside the function containing it).  However, its lifetime is the same as that of a global variable, except that it doesn’t come into existence until the first call to the function containing it.  Thereafter it remains in existence for the life of the program.  Static local variables are used when it’s necessary for a function to remember a value when it is not being executed; that is, between calls to the function.
  • 56. Example #include <iostream> using namespace std; float getavg(float); //declaration int main() { float data=1, avg; while( data != 0 ) { cout << “Enter a number: “; cin >> data; avg = getavg(data); cout << “New average is “ << avg << endl; } return 0; } //-------------------------------------------------------------- float getavg(float newdata) { static float total = 0; //static variables are initialized static int count = 0; // only once per program count++; //increment count total += newdata; //add new data to total return total / count; //return the new average }
  • 57. Static variables  Initialization: When static variables are initialized, as total and count are in getavg() , the initialization takes place only once—the first time their function is called. They are not reinitialized on subsequent calls to the function, as ordinary local variables are.  Storage: local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.