0% found this document useful (0 votes)
29 views40 pages

CSC233-CSC211 2024 - 2025 Lecture 3

csc

Uploaded by

olawal.2300652
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 views40 pages

CSC233-CSC211 2024 - 2025 Lecture 3

csc

Uploaded by

olawal.2300652
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/ 40

Lecture 3

Programming With C++

The CSC233 Team


[2024|2025]
Main Text for this Course

Title
Introduction to Programming With C++
Third Edition

Author
Daniel Y. Liang

2
LECTURE OUTLINE
 Defining a Function
 Inline Functions
 Calling a Function
 Local, Global, and
 Void Functions Static Local Variables
 Passing Arguments by  Passing Arguments by
Value Reference
 Overloading Functions  Constant Reference
 Function Prototypes Parameters
 Default Arguments

3
Instructions to Students:
Running the code examples

 Always keep in mind that the two lines of code below


should be in every C++ program you write involving
input and/or output operations.
#include <iostream>
using namespace std;
 Even if the sample codes in the slides do not have
them, do not forget their usage.
4
Defining a Function

 A function definition consists of its function name,


parameters, return value type, and body.
 The syntax for defining a function is as follows:
returnValueType functionName(list of parameters)
{
// Function body;
}

5
Defining a Function 6
Defining a Function

 The function header specifies the function’s return


value type, function name, and parameters.
 A function may return a value.
 The returnValueType is the data type of that value.
Some functions perform desired operations without
returning a value.
 In this case, the returnValueType is the keyword void.

7
Defining a Function
 The function that returns a value is called a value-
returning function and the function that does not return
a value is called a void function.
 The variables declared in the function header are known
as formal parameters or simply parameters.
 A parameter is like a placeholder.
 When a function is invoked, you pass a value to the
parameter.

8
Defining a Function
 This value is referred to as an actual parameter or
argument.
 The parameter list refers to the type, order, and number
of the parameters of a function.
 The function name and the parameter list together
constitute the function signature.
 Parameters are optional; that is, a function may contain
no parameters.
 For example, the rand() function has no parameters.
9
Defining a Function
 The function body contains a collection of statements
that define what the function does.
 The function body of the max function uses an if
statement to determine which number is larger and
returns the value of that number.
 A return statement using the keyword return is required
for a value-returning function to return a result.
 The function exits when a return statement is executed.
10
Calling a Function

 Calling a function executes the code in the function


 To use a function, you have to call or invoke it.
 For example,
 int larger = max(3, 4);
 The statement calls max(3, 4) and assigns the result
of the function to the variable larger.

11
int max(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1; Define max function
else
result = num2; The main function
return result;
}

int main()
{
int i = 5;
int j = 2;
int k = max(i, j); // invoke the max function
cout << "The maximum between " << i << " and " << j << " is " << k << endl;
return 0;
}

Calling a Function (Example 1) 12


Calling a Function
(Example1 + process)
 When the max function is invoked, the flow of control
transfers to it.

13
Void Functions(Example 2)

 A void function does not return a value.


 Write a program that defines a function named
printGrade and invokes it to print the grade for a
given score.
 Make the grade be based on the categorization used
by your school, e.g.
 70-100 (A), 60-69 (B), 50-59 (C), 45-49 (D), Below 45 (F).

14
// Print grade for the score // Main function definition
void printGrade(double score) int main()
{ {
if (score >= 70.0) cout << "Enter a score: ";
cout << 'A' << endl; double score;
else if (score >= 60.0) cin >> score;
cout << 'B' << endl; cout << "The grade is ";
else if (score >= 50.0) printGrade(score);
cout << 'C' << endl;
else if (score >= 45.0) return 0;
cout << 'D' << endl; }
else
cout << 'F' << endl;
}

void Functions (Example 2 + solution) 15


Passing Arguments by Value
 By default, the arguments are passed by value to
parameters when invoking a function.
 When calling a function, you need to provide arguments,
which must be given in the same order as their respective
parameters in the function signature.
 This is known as parameter order association.
 For example, the following function (on the next slide)
prints a character n times:

16
Passing Arguments by Value – Cont’d

 You can use nPrint('a', 3) to print 'a' three times.


 The nPrint('a', 3) statement passes the actual char
parameter, 'a', to the parameter, ch; passes 3 to n; and
prints 'a' three times.
 However, the statement nPrint(3, 'a') has a different
meaning, it passes 3 to ch and 'a' to n.
17
The nPrint('a', 3) statement causes the first output.

The nPrint(3, 'a') statement causes the second output.

Note: You will not always be ‘lucky’ if you misarrange the arguments of a
function call, i.e. if the order does not match the parameter order, like in
the function call below.
nPrint(3, 'a')

Some times in this disarrangement scenario, an error occurs.

Can you explain the second line in the output? 18


Overloading Functions – Example 3

 Overloading functions enables you to define the functions


with the same name as long as their signatures are
different.
 For example
 Write a program that has three functions. The first finds the
maximum integer, the second finds the maximum double, and
the third finds the maximum among three double values.
 All three functions are named max.

19
// Return the max between two int values
int max(int num1, int num2){
if (num1 > num2)
return num1;
else
return num2;
}

// Return the max between two double values


double max(double num1, double num2){
if (num1 > num2)
return num1;
else
return num2;
}

// Return the max among three double values


double max(double num1, double num2, double num3){
return max(max(num1, num2), num3);
}

Overloading Functions (Example 3 + solution) 20


int main()
{
// Invoke the max function with int parameters
cout << "The maximum between 3 and 4 is " << max(3, 4) << endl;

// Invoke the max function with the double parameters


cout << "The maximum between 3.0 and 5.4 is " << max(5.4, 3.0) <<
endl;

// Invoke the max function with three double parameters


cout << "The maximum between 3.0, 5.4, and 10.14 is "
<< max(3.0, 10.4, 5.14) << endl;

return 0;
}

Testing Function Overloads 21


Function Prototypes
 A function prototype declares a function without
having to implement it. It is also known as function
declaration, is a function header without
implementation.
 Before a function is called, its header must be
declared.
 One way to ensure this, is to place the definition before all
function calls.
 Another approach is to define a function prototype before the
function is called.
22
// Function prototype
double max(double num1, double num2);

int main()
{
cout << "The maximum between 3.0 and 5.4 is " << max(5.4, 3.0) << endl;

return 0;
}

// Return the max between two double values


double max(double num1, double num2){
if (num1 > num2)
return num1;
else
return num2;
}

Function Prototypes (Example 4): Using a function prototype 23


#include <iostream>
#include <string> Observe the parameter of the function length_of_name,
using namespace std; what do you notice, compared to the previous functions
we have defined in this lecture?
int length_of_name(string name = "Steve")
{
return name.length();
}

int main()
{
cout << "The length of the name is equal to " << length_of_name() <<
endl;
cout << "The length of the name is equal to " <<
length_of_name("Chinonso");
}

What are default Arguments (Example 5)? Observe the output for each function call
24
Inline Functions

 C++ provides inline functions for improving


performance for short functions.
 Inline functions are not called; rather, the compiler
copies the function code in line at the point of each
invocation.
 To specify an inline function, precede the function
declaration with the inline keyword.

25
inline void info_display(int year_of_adm, string name = "Steve")
{
cout << "Length of " << name << " is " << name.length();
cout << ". Admitted in the year " << year_of_adm;
}

int main()
{
string name = "Jemimah"; int adm_year = 2009;
info_display(adm_year);
cout << endl;
info_display(adm_year, name);
}

Inline Functions (Example 6 + Solution) 26


Local, Global, and Static Local Variables

 A variable defined inside a function is referred to as a


local variable. While global variables are declared
outside all functions and are accessible to all functions in
their scope.
 Local variables do not have default values, but global
variables are defaulted to zero.

27
Local, Global, and Static Local
Variables(Example 7)
 Demonstrates the scope of local and global variables

28
The Scope of Variables in a for Loop

 A variable declared in the initial-action part of a for-loop


header has its scope in the entire loop.
 For example;

29
Static Local Variables
 After a function completes its execution, all its local
variables are destroyed.
 These variables are also known as automatic variables.
 Sometimes it is desirable to retain the values stored in
local variables so that they can be used in the next call.
 C++ allows you to declare static local variables using the
keyword static.
 Static local variables are permanently allocated in the
memory for the lifetime of the program.
30
void t1(); // Function prototype

int main()
{
t1(); // Call function t1
t1(); // Call function t1 again
return 0;
}

void t1()
{
static int x = 1; // x is permanently allocated in the memory for the lifetime of the
program.
int y = 1;
x++;
y++;
cout << "x is " << x << endl;
cout << "y is " << y << endl;
}
Static Local Variables - Demo 31
Passing Arguments by Reference
 When you invoke a function with a parameter, as
described in the preceding sections, the value of the
argument is passed to the parameter. This is referred
to as pass-by-value.
 Parameters can also be passed by reference, which
makes the formal parameter an alias of the actual
argument.
 Thus, changes made to the parameters inside the
function are also made to the arguments.
32
void increment(int n)
{ void increment(int& n)
n++; {
cout << "The value of n inside the n++;
function is " cout << "The value of n inside the function is
<< n << endl; "
} << n << endl;
}
int main()
{ int main()
int x = 1; {
cout << "Before the call, x is " << x << int x = 1;
endl; cout << "Before the call, x is " << x << endl;
increment(x); increment(x);
cout << "After the call, x is " << x << cout << "After the call, x is " << x << endl;
endl;
return 0;
return 0; }
}

Demo: Pass-by-Value in the blue box, Pass-by-Ref in the red box. 33


Passing Arguments by Reference

 Invoking increment(x) in the pass-by-ref example


passes the reference of variable x to the reference
variable n in the increment function.
 Now n and x are the same, as shown in the output.
 Incrementing in the increment() function is the
same as incrementing . So, before the function is
invoked, x is 1, and afterward, becomes 2.

34
Constant Reference Parameters
 If your program uses a pass-by-reference parameter
and the parameter is not changed in the function, you
should mark it constant to tell the compiler that the
parameter should not be changed.
 To do so, place the const keyword before the
parameter in the function declaration.
 Such a parameter is known as constant reference
parameter.
35
Constant Reference Parameters
 For example, num1 and num2 are declared as constant
reference parameters in the following function and they
should not be changed within the function.

36
•Write a C++ function named sum that takes two integers as parameters and returns their sum. Use this function in main() to add two numbers input by the user.

Exercises (1)
1. Write a C++ function named ‘sum’ that takes two
integers as parameters and returns their sum.
 Use this function in ‘main()’ to add two numbers input by the
user.

2. Define a function called ‘square’ that takes an integer


as input, returns the square of that number, and call it
from ‘main()’.
37
•Write a C++ function named sum that takes two integers as parameters and returns their sum. Use this function in main() to add two numbers input by the user.

Exercises (2)

3. Create a void function ‘printSum’ that takes two


integers, adds them, and prints the result. Call the
function with different pairs of numbers in ‘main()’.

4. Create an inline function ‘triple’ that multiplies a


number by 3 and returns the result.
 Use it to triple two different numbers in ‘main()’.
38
Exercises (3)

 The mathematical quantity can be computed using


the following series:

 Write a function that returns f(n) for a given n and


write a test program that displays the table depicted
in the next slide.

39
Exercises (3) – Cont’d 40

You might also like