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

Lec3. C++ Functions

The document discusses the basics of functions in C++ including predefined functions, programmer-defined functions, function parameters and return types, and scope rules. Functions are building blocks of programs that perform specific tasks and can call other functions. Programmer-defined functions are defined with a declaration, definition, and function calls.

Uploaded by

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

Lec3. C++ Functions

The document discusses the basics of functions in C++ including predefined functions, programmer-defined functions, function parameters and return types, and scope rules. Functions are building blocks of programs that perform specific tasks and can call other functions. Programmer-defined functions are defined with a declaration, definition, and function calls.

Uploaded by

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

Chapter 3

Function Basics

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Introduction to Functions
• Building Blocks of Programs
• Other terminology in other languages:
– Procedures, subprograms, methods
– In C++: functions
• I-P-O
– Input – Process – Output
– Basic subparts to any program
– Use functions for these "pieces“
• C++ Predefined Functions : C++ Libraries full of functions for
our use!
• Programmer-Defined Functions: You can write your own
functions

3-2
Predefined Functions
• Must "#include" appropriate library such as
– <cmath>, <cstdlib> (Original "C" libraries)
– <iostream> (for cout, cin)

• Might return a value or might not (void)


• Math functions are found in library <cmath.h>
– Example: theRoot = sqrt(9.0);
• Components:
sqrt = name of library function
theRoot = variable used to assign "answer" to (here is 3)
9.0 = argument or "starting input" for function
– Function Call: expression "sqrt(9.0)" is known as a function
call, or function invocation
– call itself can be part of an expression: bonus = sqrt(sales)/10;
– argument in a function call (9.0) can be a literal, a variable, or an expression
3-3
//Computes the size of a doghouse that can be purchased
//given the user's budget.
#include <iostream> A Predefined Function
#include <cmath>
using namespace std; That Returns a Value
int main( ){
const double COST_PER_SQ_FT = 10.50;
double budget, area, lengthSide;
cout << "Enter the amount budgeted for your doghouse $";
cin >> budget;
area = budget / COST_PER_SQ_FT;
lengthSide = sqrt(area);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of $" << budget << endl
<< "I can build you a luxurious square doghouse\n"
<< "that is " << lengthSide
<< " feet on each side.\n";
return 0;
} Enter the amount budgeted for your doghouse $25.00
For a price of $25.00
I can build you a luxurious square doghouse
that is 1.54 feet on each side. 3-4
Some Predefined Math
Functions in cmath or
cstlib libraries

3-5
Predefined void Functions
• No returned value: Performs an action, but sends no "answer"
– exit(1); // No return value, so not assigned
• This call terminates program
• void functions can still have arguments
• same as functions that "return a value“ but just don’t return a value!

#include <iostream>
#include <cstdlib>
using namespace std;
int main( ){
cout << "Hello Out There!\n";
exit(1);
cout << "This statement is pointless,\n"
<< "because it will never be executed.\n"
<< "This is just a toy program to illustrate exit.\n";
return 0;
}

3-6
Random Number Generator
• Return "randomly chosen" number
– rand() : Takes no arguments and returns value between 0 & RAND_MAX
– Scaling: Squeezes random number into smaller range
• rand() % 6 : Returns random value between 0 & 5
• "%" is modulus operator (remainder)
– Shifting : rand() % 6 + 1
• Shifts range between 1 & 6 (e.g., die roll)

• Random Examples
– Random double between 0.0 & 1.0:
(RAND_MAX – rand())/static_cast<double>(RAND_MAX)
• Type cast used to force double-precision division
– Random int between 10 & 20: rand() % 10 + 10

3-7
Random Number Seed
• Pseudorandom numbers
– Calls to rand() produce given "sequence“ of random numbers
• Use "seed" to alter sequence: srand(seed_value);
– void function that receives one argument, the "seed"
– Can use any seed value, including system time: srand(time(0));
• time() returns system time as numeric value
• Library <time> contains time() functions

3-8
A Function Using a Random
Number Generator

Welcome to your friendly weather program.


Enter today's date as two integers for the month
and the day:
2 14
Weather for today:
The day will be cloudy.
Want the weather for the next day?(y/n): y
The day will be cloudy.
Want the weather for the next day?(y/n): y
The day will be stormy!
Want the weather for the next day?(y/n): y
The day will be stormy!
Want the weather for the next day?(y/n): y
The day will be sunny!!
Want the weather for the next day?(y/n): n
That's it from your 24-hour weather program.

3-9
Programmer-Defined Functions
• Write your own functions!
• Building blocks of programs
– Divide & Conquer, Readability, Re-use
• Your "definition" can go in either:
– Same file as main()
– Separate file so others can use it, too
• Components of Function Use : 3 Pieces
– Function Declaration/prototype: Information for compiler to properly
interpret calls
– Function Definition: Actual implementation/code for what
function does
– Function Call : Transfer control to function

3-10
Function Declaration/prototype
– Syntax: <return_type> FnName(<formal-parameter-list>);
double totalCost(int numberParameter, double priceParameter);
• Placed before any calls in declaration space of main() or above
main() in global space

Function Definition
double totalCost(int numberParameter, double priceParameter)
{
const double TAXRATE = 0.05;
double subTotal;
subtotal = priceParameter * numberParameter;
return (subtotal + subtotal * TAXRATE);
}

• Function Definition Placement: after function main() NOT


"inside"!
• Functions are "equals"; no function is ever "part" of another
Function call: Just like calling predefined function
double bill = totalCost(number, price);
3-11
Enter the number of items purchased: 2
Enter the price per item: $ 10.10
2 items at $10.10 each.
Final bill, including tax, is $21.21

3-12
Functions Calling Functions
• We’re already doing this!
– main() IS a function!
• Only requirement: Function’s declaration must appear first
• Common for functions to call many other functions
• Function can even call itself  "Recursion"

3-13
Boolean Return-Type Functions & Void Function
• Boolean Return-Type Functions: returns "true" or "false"
bool appropriate (int rate) {
return (((rate>=10)&&(rate<20))||(rate==0);
}

• Function call from some other function: if (appropriate(entered_rate))


cout << "Rate is valid\n";

• Declaring void functions: Similar to functions returning a value


– Return type specified as "void“ : nothing is returned
– Function declaration example:
void showResults(double fDegrees, double cDegrees);

void showResults(double fDegrees, double cDegrees){


cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
cout << fDegrees << " degrees fahrenheit equals \
n"
<< cDegrees << " degrees celsius.\n";
}
– Calling Void Functions: showResults(32.5, 0.3); 3-14
More on Return & Preconditions/Postconditions
• More on return statements: Transfer control back to "calling"
function
– For return type other than void, MUST have return statement
– Typically the LAST statement in function definition
– return statement optional for void functions
• Closing } would implicitly return control from void function

• Preconditions and Postconditions


– Comment function declaration:
void showInterest(double balance, double rate);
//Precondition: balance is nonnegative account balance
// rate is interest rate as percentage
//Postcondition: amount of interest on given balance,
// at given rate …

– Often called Inputs & Outputs

3-15
main(): "Special"
• Recall: main() IS a function
• "Special" in that: One and only one function called main() will exist in a
program
• Who calls main()?
– Operating system
– Tradition holds it should have return statement
• Value returned to "caller"  Here: operating system
– Should return "int" or "void"

3-16
Scope Rules
• Local variables: data declared inside body of given function are
available only within that function
• Can have variables with same names declared in different functions
– Scope is local: "that function is it’s scope"
• Global constants and clobal cariables: declared "outside"
function body and global to all functions in that file
– Global declarations typical for constants: const double TAXRATE = 0.05;
– Global variables: Possible, but SELDOM-USED
• Local variables preferred: Functions should declare whatever
local data needed to "do their job“
• Blocks-scope: scope of data declared inside compound statement
for (int ctr=0;ctr<10;ctr++){
sum+=ctr;
}
– Variable ctr has scope in loop body block only 3-17
Enter a radius to use for both a circle
and a sphere (in inches): 2
Radius = 2 inches
Area of circle = 12.5664 square inches
Volume of sphere = 33.5103 cubic inches
3-18

You might also like