The document discusses control structures in programming, specifically different types of loops. It provides examples of for, do-while, and while loops. It explains the syntax and usage of each loop type, and how to avoid issues like infinite loops. Examples are given to iterate through a range of numbers and display output for each iteration. The document also discusses using loops and conditionals like if statements together in programs.
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Subhajit Sahu
Abstract — Levelwise PageRank is an alternative method of PageRank computation which decomposes the input graph into a directed acyclic block-graph of strongly connected components, and processes them in topological order, one level at a time. This enables calculation for ranks in a distributed fashion without per-iteration communication, unlike the standard method where all vertices are processed in each iteration. It however comes with a precondition of the absence of dead ends in the input graph. Here, the native non-distributed performance of Levelwise PageRank was compared against Monolithic PageRank on a CPU as well as a GPU. To ensure a fair comparison, Monolithic PageRank was also performed on a graph where vertices were split by components. Results indicate that Levelwise PageRank is about as fast as Monolithic PageRank on the CPU, but quite a bit slower on the GPU. Slowdown on the GPU is likely caused by a large submission of small workloads, and expected to be non-issue when the computation is performed on massive graphs.
Show drafts
volume_up
Empowering the Data Analytics Ecosystem: A Laser Focus on Value
The data analytics ecosystem thrives when every component functions at its peak, unlocking the true potential of data. Here's a laser focus on key areas for an empowered ecosystem:
1. Democratize Access, Not Data:
Granular Access Controls: Provide users with self-service tools tailored to their specific needs, preventing data overload and misuse.
Data Catalogs: Implement robust data catalogs for easy discovery and understanding of available data sources.
2. Foster Collaboration with Clear Roles:
Data Mesh Architecture: Break down data silos by creating a distributed data ownership model with clear ownership and responsibilities.
Collaborative Workspaces: Utilize interactive platforms where data scientists, analysts, and domain experts can work seamlessly together.
3. Leverage Advanced Analytics Strategically:
AI-powered Automation: Automate repetitive tasks like data cleaning and feature engineering, freeing up data talent for higher-level analysis.
Right-Tool Selection: Strategically choose the most effective advanced analytics techniques (e.g., AI, ML) based on specific business problems.
4. Prioritize Data Quality with Automation:
Automated Data Validation: Implement automated data quality checks to identify and rectify errors at the source, minimizing downstream issues.
Data Lineage Tracking: Track the flow of data throughout the ecosystem, ensuring transparency and facilitating root cause analysis for errors.
5. Cultivate a Data-Driven Mindset:
Metrics-Driven Performance Management: Align KPIs and performance metrics with data-driven insights to ensure actionable decision making.
Data Storytelling Workshops: Equip stakeholders with the skills to translate complex data findings into compelling narratives that drive action.
Benefits of a Precise Ecosystem:
Sharpened Focus: Precise access and clear roles ensure everyone works with the most relevant data, maximizing efficiency.
Actionable Insights: Strategic analytics and automated quality checks lead to more reliable and actionable data insights.
Continuous Improvement: Data-driven performance management fosters a culture of learning and continuous improvement.
Sustainable Growth: Empowered by data, organizations can make informed decisions to drive sustainable growth and innovation.
By focusing on these precise actions, organizations can create an empowered data analytics ecosystem that delivers real value by driving data-driven decisions and maximizing the return on their data investment.
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...John Andrews
SlideShare Description for "Chatty Kathy - UNC Bootcamp Final Project Presentation"
Title: Chatty Kathy: Enhancing Physical Activity Among Older Adults
Description:
Discover how Chatty Kathy, an innovative project developed at the UNC Bootcamp, aims to tackle the challenge of low physical activity among older adults. Our AI-driven solution uses peer interaction to boost and sustain exercise levels, significantly improving health outcomes. This presentation covers our problem statement, the rationale behind Chatty Kathy, synthetic data and persona creation, model performance metrics, a visual demonstration of the project, and potential future developments. Join us for an insightful Q&A session to explore the potential of this groundbreaking project.
Project Team: Jay Requarth, Jana Avery, John Andrews, Dr. Dick Davis II, Nee Buntoum, Nam Yeongjin & Mat Nicholas
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...pchutichetpong
M Capital Group (“MCG”) expects to see demand and the changing evolution of supply, facilitated through institutional investment rotation out of offices and into work from home (“WFH”), while the ever-expanding need for data storage as global internet usage expands, with experts predicting 5.3 billion users by 2023. These market factors will be underpinned by technological changes, such as progressing cloud services and edge sites, allowing the industry to see strong expected annual growth of 13% over the next 4 years.
Whilst competitive headwinds remain, represented through the recent second bankruptcy filing of Sungard, which blames “COVID-19 and other macroeconomic trends including delayed customer spending decisions, insourcing and reductions in IT spending, energy inflation and reduction in demand for certain services”, the industry has seen key adjustments, where MCG believes that engineering cost management and technological innovation will be paramount to success.
MCG reports that the more favorable market conditions expected over the next few years, helped by the winding down of pandemic restrictions and a hybrid working environment will be driving market momentum forward. The continuous injection of capital by alternative investment firms, as well as the growing infrastructural investment from cloud service providers and social media companies, whose revenues are expected to grow over 3.6x larger by value in 2026, will likely help propel center provision and innovation. These factors paint a promising picture for the industry players that offset rising input costs and adapt to new technologies.
According to M Capital Group: “Specifically, the long-term cost-saving opportunities available from the rise of remote managing will likely aid value growth for the industry. Through margin optimization and further availability of capital for reinvestment, strong players will maintain their competitive foothold, while weaker players exit the market to balance supply and demand.”
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Loops_and_FunctionsWeek4_0.ppt
1. 1
Further Control Structures
I will go over some important topics today.
Loops and conditionals are essential for ones
development in any programming language.
We will look at the three types of looping
mechanisms
for
do-while
while
We will also look again at the if statement only
if it is required.
2. 2
Week 4 Topics
Switch Statement for Multi-way Branching
Can be achieved with an if statement
This was previously looked at
We have to be careful with the “fall through”
mechanism however.
Do-While Statement for Looping
For Statement for Looping
Using break and continue statements
These are used predominantly with the switch
statement
3. 3
Display a menu
Simple Menus
1. Program displays a menu of choices
2. User enters a choice
3. Program responds to choice
4. Go back to to 1
4. 4
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main( ) {
return 0;
}
function prototype consisting of
<type> function name (types of parameters);
So void here means no return type or parameters
expected. It is not required to use void here.
5. 5
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main() {
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************n”;
cout <<endl;
cout << “ 1. Man United” << endl;
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “ 4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
Definition:
like a mini program
or sub program
6. 6
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main() {
int response;
DisplayMenu();
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************n”;
cout <<endl;
cout << “ 1. Man United” << endl;
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “ 4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
Function call
from within
main()
Prompt
7. 7
User enters choice
Prompt was part of function DisplayMenu
use cin to get a response from user.
The function is invoked by a call from
another function, in this case the calling
function is main()
The call is just a writing of the function
name in this case, with no parameters
passed to this function
8. 8
Display a menu and Get response
#include <iostream>
void DisplayMenu(void);
int main() {
int response;
DisplayMenu();
cin >> response;
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************n”;
cout <<endl;
cout << “ 1. Man United” << endl;
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2 or 3 : “;
}
Get response
10. 10
What is
the switch Statement
Similar to the if statement
Can list any number of branches
Used in place of nested if statements
Used only with integer expressions
(true/false or int or char)
Avoids confusion of deeply nested if
statements
11. The switch Statement
Syntax
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
case valueN: statementN;
break;
default: statement;
}
expression must return an integer value, i.e. be an integer
12. The switch Statement
with char expression
switch (choice)
{
case 1: cout << “The greatest ” << endl;
break;
case 2: cout << “Exciting team ”<< endl;
break
case 3: cout << “Boring ” << endl;
break;
case 4: cout << “Bye Bye” << endl;
}
//next statement
13. What is the purpose of the break statement?
The break Statement prevents “fall through”
it makes the computer jump out of the current
block, recall that the switch statement will execute
all statements below the point of entering the
statement. This can be a problem.
14. The switch Statement illustrate fall
through again
switch (choice){
case 1: cout << “The greatest ” << endl;
case 2: cout << “Exciting team ”<< endl;
case 3: cout << “Boring ” << endl;
case 4: cout << “Bye Bye << endl;
}
15. The switch Statement
What will be the output when the user enters 1?
The greatest
Exciting team
Boring
Bye Bye
19. Classic use of switch Statements:
for Menu processing
* * * * Menu * * * *
1. Man United
2. Chelsea
3. Arsenal
4. Quit
Choose either 1, 2, 3 or 4:
20. 20
Example program to Demo
#include <iostream> //see displaymenu3.cpp
Using namespace std;
void DisplayMenu(void);
int main(void) {
int choice;
DisplayMenu();
cin >> choice;
switch (choice) {
case 1: cout << “The greatest“ << endl;
case 2: cout << “Exciting team“ << endl;
case 3: cout << “Boring“ << endl;
case 4: cout << “Bye Bye << endl;
};
return 0;
}
void DisplayMenu(void) {
cout << "*********** MENU **************n";
cout <<endl;
cout << " 1. Man United" << endl;
cout << " 2. Chelsea" << endl;
cout << " 3. Arsenal" << endl;
cout << endl;
cout << "Please choose 1, 2 or 3 : ";
}
21. The switch Default Statement captures
errors or perform default action
e.g. if user enter any other number
switch (choice){
case 1: cout << “The greatest ” << endl;
break;
case 2: cout << “Exciting team ”<< endl;
break;
case 3: cout << “Boring ” << endl;
break;
case 4: cout << “Bye Bye “ << endl;
break;
default: “Incorrect choice” << endl;
}
22. 22
Nested Switch Statements
For example:
switch( CarType )
{
case MONDEO:
switch( EngineCapacity)
{
case 1500:cout << “This is underpowered “;
break;
case 1800: cout << “This is just right”;
break;
case 2000: cout<<“This is expensive to run”;
}; //closes second switch
case FIESTA: break;
default: cout << “Unknown model”;
} //closes first switch
23. 23
Problems with switch
Strange rules, once a condition is tested true
execution proceeds until break or end of
switch.
Control “falls through” the switch
Get in the habit of always putting breaks in and
putting a default condition in.
Less satisfactory to use where floats or
Boolean expressions are tested.
Putting in semi colon ‘;’after case rather than
colon ‘:’
24. 24
Recall Purpose of
Loops/Repetition
To apply the same steps again and
again to a block of statements.
Recall a block of statement is one or
more statement, block usually defined
by braces { … } with syntactically correct
statements inside.
25. 25
Most Common Uses of Loops
You should master all these!
For counting
For accumulating, i.e. summing
For searching
For sorting
For displaying tables
For data entry – from files and users
For menu processing
For list processing
27. 27
C/C++ Loop Structures
Pre-test (the test is made before entering
the loop)
while loops
– general purpose
– Event controlled (variable condition)
for loops
– When you know how many times (fixed condition)
– When you process arrays (more in later lectures)
Post-test (the test is done at the end of the
loop)
do … while loops
– When you do not know how many times, but you know
you need at least one pass.
– Data entry from users
28. 28
Do-While Statement
Is a looping control structure in which the loop
condition is tested after each iteration of the
loop.
SYNTAX
do
{
Statement
} while (Expression) ; //note semi colon
Loop body statement can be a single statement or a block.
29. 29
void GetYesOrNo ( char response )
//see UseofFunction1.cpp
// Inputs a character from the user
// Postcondition: response has been input
// && response == ‘y’ or ‘n’
{
do
{
cin >> response ; // skips leading whitespace
if ( ( response != ‘y’ ) && ( response != ‘n’ ) )
cout << “Please type y or n : “ ;
} while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ;
}
Function Using Do-While
29
30. 30
Do-While Loop vs. While Loop
POST-TEST loop
(exit-condition)
The looping condition
is tested after
executing the loop
body.
Loop body is always
executed at least
once.
PRE-TEST loop
(entry-condition)
The looping condition
is tested before
executing the loop
body.
Loop body may not
be executed at all.
31. 31
Do-While Loop
When the expression is tested and found to be false,
the loop is exited and control passes to the
statement that follows the do-while statement.
Statement
Expression
DO
WHILE
FALSE
TRUE
32. The for Statement Syntax
Example:
for (count=1; count < 7; count++)
{
cout << count << endl;
}
//next C++ statements;
start condition change expression
while condition
33. The for Statement
Used as a counting loop
Used when we can work out in advance the
number of iterations, i.e. the number of times
that we want to loop around.
Semicolons separate the items in the for loop
block
There is no semi colon at the end of the for loop
definition at the beginning of the statement
34. int num;
cout << "NUMBERtSQUAREtCUBEn“;
cout << "------t------t----n";
for (num = 1; num < 11; num++) {
cout << num << “t“;
cout << num * num << “t“;
cout << num * num * num<<“n";
}//see useofFunction2.cpp
A Simple Example
Create a table with a for loop
NUMBER SQUARE CUBE
---------- ---------- ------
1 1 1
2 4 8
. . .
. . .
10 100 1000
35. Use of the for loop
Please see the following files
Harmonic.cpp
BaselSeries.cpp
These are two very important series in
mathematics.
35
36. for and if Statements working
together.
Simple search for divisors
Given an integer number find all the
numbers that divide exactly into it (including
1 and itself).
e.g. if number = 12, divisors are 1,2,3,4,6,12
Think I can
use % operator
to find divisors
37. 37
Solution Design
1. Get the number from user
2. By starting with check number=1 and
finish with number (is this efficient?)
1. find the remainder of dividing number with
current check number
2. if remainder is 0 display current check
number as a divisor.
3. otherwise do not display anything
38. 38
Program fragment for finding divisors of an
integer
cout << “Enter an integer :”;
cin >> number;
for (j = 1; j <= number; j++)
{ if (number % j == 0)
{ cout << j << “ is a divisor of “;
cout << number << endl;
}
}//see useofFunction3.cpp, this program
determines whether we have a perfect
number
39. for (j = 0, j < n, j = j + 3)
// commas used when semicolons needed
for (j = 0; j < n)
// three parts needed
for (j = 0; j >= 0; j++)
?????what is wrong here ?????
for (j=0, j=10; j++);
Common errors in constructing
for Statements
40. 40
Infinite loops example 1
for (j=0; j>=0; j++) {
cout << j << endl;
}
What will happen here?
//see infiniteloop1.cpp
41. 41
Loop design
Seven Loop Design Factors
1. What is the condition that ends the loop?
2. How should the condition be setup or
primed?
3. How should the condition be updated?
4. What processes are being repeated?
5. How do you set up the processes?
e.g. initialise event counters or accumulators
6. How is the process updated?
e.g. update accumulators and counters
7. What is the expected state of the program
at exit from loop?
42. 42
Programming convention
Use of integers called i,j,k
You will see them all the time.
Most commonly used as loop control
variables
Conventionally used for counters
We will see later that counters often have a dual
use as array indices.
arrays to be discussed in later lectures
When you see i,j,k declared expect to see a
loop!
43. 43
Example of Repetition
int n;
for ( int i = 1 ; i <= n ; i++ )
{
cout << i << “ Potato” << endl;
}
//see usefor1.cpp
// useofFunction5.cpp uses an array as a
global variable
56. 56
Example of Repetition
num
When the loop control condition
is evaluated and has value false, the
loop is said to be “satisfied” and
control passes to the statement
following the for statement.
4
false
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
58. Nested Loops
Recall when a control structure is contained
within another control structure, the inner one
is said to be nested.
for ...
if ...
for ...
for...
You may have repetition within decision and
vice versa.
59. Example //see nested1.cpp
int row,col;
for (row = 0; row < 5; row++)
{
cout << "n" <<row; //throws a new line
for (col = 1; col <= 3; col++)
{
cout <<"t" << col;
}
cout << "t**"; //use of tab
}
Nested Loops - Ex.1
for within for
60. 60
CAUTION!
What is the output from this
loop?
int count;
for (count = 0; count < 10; count++) ;
{
cout << “*” ;
}
//see useforloop2.cpp
61. 61
no output from the for loop! Why?
the ; right after the ( ) means that the body
statement is a null statement
in general, the Body of the for loop is whatever
statement immediately follows the ( )
that statement can be a single statement, a
block, or a null statement
actually, the code outputs one * after the loop
completes its counting to 10
Infinite loop example 2
OUTPUT
*
62. Output
0 1 2 3 **
1 1 2 3 **
2 1 2 3 **
3 1 2 3 **
4 1 2 3 **
Nested Loops – Example 1
variable row changes from
0 to 4
variable col changes from
1 to 3 for every time row
changes
63. 63
Break Statement Revisited
break statement can be used with Switch or
any of the 3 looping structures
it causes an immediate exit from the Switch,
while, do-while, or for statement in which it
appears
if the break is inside nested structures,
control exits only the innermost structure
containing it
64. 64
Continue Statement
is valid only within loops
terminates the current loop iteration, but
not the entire loop
in a for or while, continue causes the rest
of the body statement to be skipped--in a
for statement, the update is done
in a do-while, the exit condition is tested,
and if true, the next loop iteration is begun
65. The break Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
break;
cout << “j is “ << j<< ‘n’;
}
cout << “We are out of the loop as j=70.n”;
//see useBreak1.cpp
j is 50
j is 60
We are out of the loop as j=70.
66. The continue Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
continue; //skips the 70
cout << “j is “ << j<< ‘n’;
}//see UseContinue1.cpp
cout << “We are out of the loop” << endl;
j is 50
j is 60
j is 80
We are out of the loop.
69. 69
Functions and Program Structure
A function is a ``black box'' that we have
locked part of our program into.
The idea behind a function is that it
compartmentalizes part of the program,
and in particular, that the code within the
function has some useful properties:
70. 70
More on functions
It performs some well-defined task, which
will be useful to other parts of the program.
It might be useful to other programs as well;
that is, we might be able to reuse it (and
without having to rewrite it).
The rest of the program does not have to
know the details of how the function is
implemented.
This can make the rest of the program
easier to think about.
71. 71
More on functions
The function performs its task well.
It may be written to do a little more than is
required by the first program that calls it, with
the anticipation that the calling program (or
some other program) may later need the extra
functionality or improved performance.
It is important that a finished function do its
job well, otherwise there might be a
reluctance to call it, and it therefore might not
achieve the goal of reusability.
72. 72
Functions
By placing the code to perform the useful task
into a function, and simply calling the function
in the other parts of the program where the
task must be performed, the rest of the
program becomes clearer.
Rather than having some large, complicated,
difficult-to-understand piece of code repeated
wherever the task is being performed, we
have a single simple function call, and the
name of the function reminds us which task is
being performed.
73. 73
Functions
Since the rest of the program does not have
to know the details of how the function is
implemented, the rest of the program does not
care if the function is reimplemented later, in
some different way (as long as it continues to
perform its same task, of course!).
This means that one part of the program can
be rewritten, to improve performance or add a
new feature (or simply to fix a bug), without
having to rewrite the rest of the program.
74. 74
More on functions
Functions are probably the most important
weapon in our battle against software
complexity.
You will want to learn when it is appropriate to
break processing out into functions (and also
when it is not), and how to set up function
interfaces to best achieve the qualities
mentioned above: reuseability, information
hiding, clarity, and maintainability.
75. 75
4.1 Function Basics
So what defines a function?
It has a name that you call it by, and a
list of zero or more arguments or
parameters that you hand to it for it to
act on or to direct its work; it has a body
containing the actual instructions
(statements).
76. 76
Functions
For carrying out the task the function is
supposed to perform; and it may give
you back a return value, of a particular
type.
Here is a very simple function, which
accepts one argument, multiplies it by 2,
and hands that value back to the
function that invoked it, i.e. To the
function that called it.
77. 77
A simple function
int multbytwo(int x)
{
int retval; //a local variable
retval = 2*x;
return retval;
}
78. 78
Explaining the function
On the first line we see the return type of the
function (int), the name of the function
(multbytwo), and a list of the function's
arguments, enclosed in parentheses.
Each argument has both a name and a type;
multbytwo accepts one argument, of type int,
named x.
The name x is arbitrary, and is used only
within the definition of multbytwo.
79. 79
Explaining the function
The caller of this function only needs to
know that a single argument of type int
is expected; the caller does not need to
know what name the function will use
internally to refer to that argument.
In particular, the caller does not have to
pass the value of a variable named x.
80. 80
Explaining the function
Next we see, surrounded by the familiar
braces { }, the body of the function itself.
This function consists of one declaration (of a
local variable retval) and two statements.
The first statement is a conventional
expression statement, which computes and
assigns a value to retval, and the second
statement is a return statement, which causes
the function to return a value to its caller, and
also specifies the value which the function
returns to its caller.
81. 81
Explaining the function
The return statement can return the
value of any expression, so we do not
really need the local retval variable; the
function could be altered to
int multbytwo(int x)
{
return 2*x;
}
82. 82
Calling the function
How do we call a function?
We have been doing so informally since
day one, but now we have a chance to
call one that we have written, in full
detail.
Here is a tiny skeletal program to call
multby2:
83. 83
Calling the function
#include <iostream>
using namespace std;
int multbytwo(int); // function prototype
int main()
{
int i, j;
i = 3;
j = multbytwo(i);
cout << j << endl;
return 0;
}
84. 84
Explaining the call
This looks much like our other test programs,
with the exception of the new line
int multbytwo(int);
This is a function prototype declaration.
It is an external declaration, in that it declares
something which is defined somewhere else.
We have already seen the defining instance of
the function multbytwo, but maybe the
compiler has not seen it yet.
85. 85
Explaining the call
The function prototype declaration
contains the three pieces of information
about the function that a caller needs to
know: the
function's name,
return type,
argument type(s).
86. 86
Explanation
Since we do not care what name the
multbytwo function will use to refer to its first
argument, we do not need to mention it.
On the other hand, if a function takes several
arguments, giving them names in the
prototype may make it easier to remember
which is which, so names may optionally be
used in function prototype declarations.
87. 87
Function prototypes
The presence of the function prototype
declaration lets the compiler know that we
intend to call this function, multbytwo.
The information in the prototype lets the
compiler generate the correct code for calling
the function, and also enables the compiler to
check up on our code (by making sure, for
example, that we pass the correct number of
arguments to each function we call).
88. 88
Function prototypes
In the body of main, the action of the
function call should be obvious: the line
j = multbytwo(i);
calls multbytwo, passing it the value of i
as its argument.
89. 89
Calling the function
When multbytwo returns, the return value is
assigned to the variable j.
Notice that the value of main's local variable i
will become the value of multbytwo's
parameter x; this is absolutely not a problem,
and is a normal sort of affair.
90. 90
Calling the function
This example is written out in ”longhand,” to
make each step equivalent.
The variable i is not really needed, since we
could just as well call
j = multbytwo(3);
And the variable j is not really needed, either,
since we could just as well call
cout << multbytwo(3);
91. 91
More on this function
Here, the call to multbytwo is a subexpression which
serves as the argument to cout.
The value returned by multbytwo is passed
immediately to cout.
Here, as in general, we see the flexibility and
generality of expressions in C++.
An argument passed to a function may be an
arbitrarily complex subexpression, and a function call
is itself an expression which may be embedded as a
subexpression within arbitrarily complicated
surrounding expressions.
92. 92
More on this function
We should say a little more about the
mechanism by which an argument is
passed down from a caller into a
function.
Formally, C++ is call by value, which
means that a function receives copies of
the values of its arguments
93. 93
Passing parameters
We can illustrate this with an example.
Suppose, in our implementation of multbytwo,
we had eliminated the unnecessary retval
variable like this:
int multbytwo(int x)
{
x = 2*x;
return x;
}
94. 94
Passing parameters
We might wonder, if we wrote it this way, what
would happen to the value of the variable i
when we called the function
j = multbytwo(i);
When our implementation of multbytwo
changes the value of x, does that change the
value of i up in the caller?
The answer is no. x receives a copy of i's
value, so when we change x we do not
change i.
95. 95
Passing parameters
However, there is an exception to this
rule.
When the argument you pass to a
function is not a single variable, but is
rather an array, the function does not
receive a copy of the array, and it
therefore can modify the array in the
caller.
96. 96
Passing parameters
The reason is that it might be too expensive to
copy the entire array, and furthermore, it can
be useful for the function to write into the
caller's array, as a way of handing back more
data than would fit in the function's single
return value.
We will see an example of an array argument
(which the function deliberately writes into) in
future lectures.
97. 97
4.2 Function Prototypes
In modern C++ programming, it is considered
good practice to use prototype declarations
for all functions that you call.
As we mentioned, these prototypes help to
ensure that the compiler can generate correct
code for calling the functions, as well as
allowing the compiler to catch certain
mistakes you might make.
98. 98
4.2 Function Prototypes
Strictly speaking, however, prototypes are
optional.
If you call a function for which the compiler
has not seen a prototype, the compiler will do
the best it can, assuming that you are calling
the function correctly.
If prototypes are a good idea, and if we are
going to get in the habit of writing function
prototype declarations for functions we call
that we have written.
99. 99
Function prototypes
Such as multbytwo, what happens for library functions
such as cout? Where are their prototypes? The
answer is in the line
#include <iostream>
We have been including at the top of all of our
programs iostream is conceptually a file full of
external declarations and other information pertaining
to the ``Standard I/O'' library functions, including cout.
The #include directive (which we have been using)
arranges that all of the declarations within iostream
are considered by the compiler, rather as if we had
typed them all in ourselves
100. 100
4.3 Function Philosophy
What makes a good function?
The most important aspect of a good
``building block'' is that have a single, well-
defined task to perform.
When you find that a program is hard to
manage, it is often because it has not been
designed and broken up into functions
“cleanly”.
Two obvious reasons for moving code down
into a function are because:
101. 101
4.3 Function Philosophy
1. It appeared in the main program several
times, such that by making it a function, it can
be written just once, and the several places
where it used to appear can be replaced with
calls to the new function.
2. The main program was getting too big, so it
could be made (presumably) smaller and
more manageable by lopping part of it off and
making it a function.
102. 102
Functions
These two reasons are important, and they represent
significant benefits of well-chosen functions, but they
are not sufficient to automatically identify a good
function. As we have been suggesting, a good
function has at least these two additional attributes:
3. It does just one well-defined task, and does it well.
4. Its interface to the rest of the program is clean and
narrow.
Attribute 3 is just a restatement of two things we said
above.
Attribute 4 says that you should not have to keep
track of too many things when calling a function.
103. 103
Functions
If you know what a function is supposed to do, and if
its task is simple and well-defined, there should be
just a few pieces of information you have to give it to
act upon, and one or just a few pieces of information
which it returns to you when it is done.
If you find yourself having to pass lots and lots of
information to a function, or remember details of its
internal implementation to make sure that it will work
properly this time, it is often a sign that the function is
not sufficiently well-defined.
104. 104
functions
A poorly-defined function may be an arbitrary chunk
of code that was ripped out of a main program that
was getting too big, such that it essentially has to
have access to all of that main function's local
variables.
The whole point of breaking a program up into
functions is so that you do not have to think about the
entire program at once; ideally, you can think about
just one function at a time.
105. 105
Functions
We say that a good function is a ``black
box,'' which is supposed to suggest that
the ``container'' it is in is opaque--callers
can not see inside it (and the function
inside can not see out).
When you call a function, you only have
to know what it does, not how it does it.
106. 106
Functions
When you are writing a function, you only
have to know what it is supposed to do, and
you do not have to know why or under what
circumstances its caller will be calling it.
When designing a function, we should
perhaps think about the callers just enough to
ensure that the function we are designing will
be easy to call, and that we are not
accidentally setting things up so that callers
will have to think about any internal details.
107. 107
Functions
Some functions may be hard to write (if they have a
hard job to do, or if it is hard to make them do it truly
well), but that difficulty should be compartmentalized
along with the function itself.
Once you have written a ``hard'' function, you should
be able to sit back and relax and watch it do that hard
work on call from the rest of your program.
It should be pleasant to notice (in the ideal case) how
much easier the rest of the program is to write, now
that the hard work can be deferred to this workhorse
function.
108. 108
Functions
In fact, if a difficult-to-write function's interface
is well-defined, you may be able to get away
with writing a quick-and-dirty version of the
function first, so that you can begin testing the
rest of the program, and then go back later
and rewrite the function to do the hard parts.
As long as the function's original interface
anticipated the hard parts, you will not have to
rewrite the rest of the program when you fix
the function.
109. 109
Functions
What I have been trying to say in the preceding few
paragraphs is that functions are important for far more
important reasons than just saving typing.
Sometimes, we will write a function which we only call
once, just because breaking it out into a function
makes things clearer and easier.
If you find that difficulties pervade a program, that the
hard parts can not be buried inside black-box
functions and then forgotten about; if you find that
there are hard parts which involve complicated
interactions among multiple functions, then the
program probably needs redesigning.
110. 110
Functions
For the purposes of explanation, we have been
seeming to talk so far only about ``main programs''
and the functions they call and the rationale behind
moving some piece of code down out of a ``main
program'' into a function.
But in reality, there is obviously no need to restrict
ourselves to a two-tier scheme.
Any function we find ourselves writing will often be
appropriately written in terms of sub-functions, sub-
sub-functions, etc. (Furthermore, the ``main program,''
main(), is itself just a function.)
111. 111
More on functions
It performs some well-defined task, which
will be useful to other parts of the program.
It might be useful to other programs as well;
that is, we might be able to reuse it (and
without having to rewrite it).
The rest of the program does not have to
know the details of how the function is
implemented.
This can make the rest of the program
easier to think about.
112. 112
More on functions
The function performs its task well. It may be
written to do a little more than is required by
the first program that calls it, with the
anticipation that the calling program (or some
other program) may later need the extra
functionality or improved performance.
It is important that a finished function do its
job well, otherwise there might be a
reluctance to call it, and it therefore might not
achieve the goal of reusability.