Learn C++ Programming

¡Supera tus tareas y exámenes ahora con Quizwiz!

void return5 ()

A return type of int means the function returns an integer value to the caller. int means the function returns an integer value to the caller

void returnNothing()

A return type of void means the function does not return a value. This function does not return a value so no return statement is needed

Statement

A statement is a "complete sentence" that tells the compiler to perform a particular task.

Variables

A statement such as x = 5; seems obvious enough. As you would guess, we are assigning the value of 5 to x. But what exactly is x? x is a variable.

Syntax error

A syntax error is a compiler error that occurs at compile-time when your program violates the grammar rules of the C++ language.

Return values

Return values allow a function to return a value back to the caller.

The << symbol

The << symbol is an operator (much like + is an operator) called the output operator.

cout << add(1, add(2, 3)) << endl;

evaluates 1 + (2 + 3) Before the CPU can evaluate the outer call to add(), it must evaluate the inner call to add(2, 3). add(2, 3) evaluates to 5. Now it can evaluate add(1, 5), which evaluates to the value 6. cout is passed the value 6.

What value does the following program print? #include <iostream> int add(int x, int y, int z) { return x + y + z; } int multiply(int x, int y) { return x * y; } int main() { using namespace std; cout << multiply(add(1, 2, 3), 4) << endl; return 0; }

multiply is called where x = add(1, 2, 3), and y = 4. First, the CPU resolves x = add(1, 2, 3), which returns 1 + 2 + 3, or x = 6. multiply(6, 4) = 24, which is the answer.

What's wrong with this program fragment? void multiply(int x, int y) { return x * y; } int main() { cout << multiply(4, 5) << endl; return 0; }

multiply() is defined as returning void, which means it can't return a value. Since the function is trying to return a value, this function will produce a compiler error. The function should return an int.

cout << "Hello world!";

our first statement and it is an output statement.

cout << x;

output statement It outputs the value of x (which we set to 5 in the previous statement) to the screen.

cout << x;

prints the value of x (memory location 140) to the console

using namespace std;

using directive statement.

int y;

define y as an integer variable

y = 4;

4 evaluates to 4, which is then assigned to y

Here is an example of a very simple function that adds two numbers together and returns the result to the caller.

#include <iostream> // add() takes two integers as parameters, and returns the result of their sum // The values of x and y are determined by the function that calls add() int add(int x, int y) { return x + y; } // main takes no parameters int main() { cout << add(4, 5) << :endl; // Arguments 4 and 5 are passed to function add() return 0; }

Write a complete program that reads an integer from the user (using cin, discussed in lesson 1.3a -- A first look at cout, cin, endl, namespaces, and using statements), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.

#include <iostream> int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; int x; cin >> x; cout << doubleNumber(x) << endl; return 0; } /* // The following is an alternate way of doing main: int main() { using namespace std; int x; cin >> x; x = doubleNumber(x); cout << x << endl; return 0; } */

Parameters and Argument example

#include <iostream> using namespace std. // This function has two integer parameters, one named x, and one named y // The values of x and y are passed in by the caller void printValues(int x, int y) { cout << x << std::endl; cout << y << std::endl; } int main() { printValues(6, 7); // This function call has two arguments, 6 and 7 return 0; } When printValues() is called with arguments 6 and 7, printValues's parameter x is created and assigned the value of 6, and printValues's parameter y is created and assigned the value of 7. This results in the output: 6 7

Function with no parameters

// This function takes no parameters // It does not rely on the caller for anything void doPrint() { cout << "In doPrint()" << std::endl; } // This function takes one integer parameter named x // The caller will supply the value of x void printValue(int x) { cout << x << std::endl; } // This function has two integer parameters, one named x, and one named y // The caller will supply the value of both x and y int add(int x, int y) { return x + y; }

y = 2 + 5;

2 + 5 evaluates to 7, which is then assigned to y

cout<<

<< is used with cout, and shows the direction that data is moving from the r-value to the console. cout << 4 moves the value of 4 to the console cout is used to output a value (cout = output)

cin>>

>> is used with cin, and shows the direction that data is moving from the console into the variable. cin >> x moves the value from the console into x cin is used to get an input value (cin = input)

A comment

A comment is a line (or multiple lines) of text that are inserted into the source code to explain what the code is doing. In C++ there are two kinds of comments. The // symbol begins a C++ single-line comment, which tells the compiler to ignore everything to the end of the line.

A function call

A function call is an expression that tells the CPU to interrupt the current function and execute another function. The CPU "puts a bookmark" at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.

A function

A function is a collection of statements that executes sequentially, typically designed to perform a specific job.

A Function

A function is a collection of statements that executes sequentially. Every C++ program must contain a special function called main. When the C++ program is run, execution starts with the first statement inside of function main. Functions are typically written to do a very specific job. For example, a function named "max" might contain statements that figures out which of two numbers is larger. A function named "calculateGrade" might calculate a student's grade.

A function

A function is a reusable sequence of statements designed to do a particular job. You already know that every program must have a function named main() (which is the where the program starts execution). However, most programs use many functions. Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life all the time. For example, you might be reading a book when you remember you need to make a phone call. You put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your book where you left off. A program will be executing statements sequentially inside one function when it encounters a function call.

A function parameter

A function parameter is a variable used in a function where the value is provided by the caller of the function. Function parameters are placed in between the parenthesis after the function identifier, with multiple parameters being separated by commas.

A library

A library is a collection of precompiled code (e.g. functions) that has been "packaged up" for reuse in many different programs. Libraries provide a common way to extend what your programs can do. For example, if you were writing a game, you'd probably want to include a sound library and a graphics library.

A variable

A variable in C++ is a name for a piece of memory that can be used to store information. You can think of a variable as a mailbox, or a cubbyhole, where we can put and retrieve information. All computers have memory, called RAM (random access memory), that is available for programs to use. When a variable is defined, a piece of that memory is set aside for the variable. example integer variables.

Initialization

After a variable is defined a value may be assigned to it via the assignment operator (the = sign): C++ will let you both define a variable AND give it an initial value in the same step. This is called initialization. int x = 5; initialize variable x with the value 5

An argument

An argument is a value that is passed from the caller to the function when a function call is made: printValue(6); // 6 is the argument passed to function printValue() add(2, 3); // 2 and 3 are the arguments passed to function add() Note that multiple arguments are also separated by commas. The number of arguments must match the number of function parameters. Otherwise, the compiler will throw an error.

An expression

An expression is a mathematical entity that evaluates to a value. the expression 2+3 evaluates to the value 5.

An expression

An expression is a mathematical entity that evaluates to a value. Expressions are often used inside of statements.

An integer

An integer is a whole number, such as 1, 2, 3, -1, -12, or 16. An integer variable is a variable that holds an integer value.

An r-value

An r-value refers to any value that can be assigned to an l-value. r-values are always evaluated to produce a single value. Examples of r-values are single numbers (such as 5, which evaluates to 5), variables (such as x, which evaluates to whatever value was last assigned to it), or expressions (such as 2 + x, which evaluates to the value of x plus 2)

How parameters and return values work together

By using both parameters and a return value, we can create functions that take data as input, do some calculation with it, and return the value to the caller.

C++ standard library

C++ standard library that provides additional functionality for your use. One of the most commonly used parts of the C++ standard library is the iostream library.

using std::cout;

Everything in the standard library lives inside a special container (called a namespace) that is named std (short for standard).

Nested functions

Functions can not be defined inside other functions (called nesting) in C++. #include <iostream> using namespace std; int foo() // no longer inside of main() { cout << "foo!"; return 0; } int main() { foo(); return 0; }

Return values

If you remember, when the main() function finishes executing, it returns an integer value back to the operating system (the caller) by using a return statement. Functions you write can return a single value to their caller as well. We do this by setting the return type of the function in the function's definition. The return type is the type declared before the function name. A return type of void means the function does not return a value. A return type of int means the function returns an integer value to the caller.

Functions

In C++, statements are typically grouped into units called functions.

int x;

In order to define a variable, we generally use a declaration statement. Here's an example of defining variable x as an integer variable (one that can hold integer values): int x; When this statement is executed by the CPU, a piece of memory from RAM will be set aside (called instantiation). For the sake of example, let's say that the variable x is assigned memory location 140. Whenever the program sees the variable x in an expression or statement, it knows that it should look in memory location 140 to get the value.

#include <iostream> using namespace std; // void means the function does not return a value to the caller void returnNothing() { // This function does not return a value so no return statement is needed } // int means the function returns an integer value to the caller int return5() { return 5; // this function returns an integer, so a return statement is needed } int main() { cout << return5() << endl; // prints 5 cout << return5() + 2 << endl; // prints 7 returnNothing(); // okay: function returnNothing() is called, no value is returned return5(); // okay: function return5() is called, return value is discarded std::cout << returnNothing(); // This line will not compile. You'll need to comment it out to continue. return 0; }

In the first function call, return5() is executed. The function returns the value of 5 back to the caller, which passes that value to cout. In the second function call, return5() is executed and returns the value of 5 back to the caller. The expression 5 + 2 is then evaluated to 7. The value of 7 is passed to cout. In the third function call, returnNothing() is executed. The function does nothing and returns nothing, so control returns to main(). In the fourth function call, return5() is executed. The value 5 is returned to main(), but main() does nothing with the return value so the return value is discarded. In the fifth function call, returnNothing() returns void. It is not valid to pass void to cout, and the compiler will give you an error when you try to compile this line. You'll need to comment out this line of code in order to make your code compile.

The next pair of statements is relatively easy as well: int a = 5; cout << add(a, a) << endl; // evaluates (5 + 5)

In this case, add() is called where x = a and y = a. Since a = 5, add(a, a) = add(5, 5), which resolves to 10.

add(1, add(2, 3)) => add(1, 5) => 6

Less verbosely:

x = 5;

One of the most common operations done with variables is assignment. To do this, we use the assignment operator, more commonly known as the = symbol x = 5; When the CPU executes this statement, it translates this to "put the value of 5 in memory location 140".

Parameters are important because

Parameters are the key mechanism by which functions can be written in a reusable way, as it allows them to perform tasks without knowing the specific input values ahead of time. Those input values are passed in as arguments by the caller.

What two things are wrong with this program fragment? int multiply(int x, int y) { int product = x * y; } int main() { cout << multiply(4) << endl; return 0; }

Problem 1: main() passes one argument to multiply(), but multiply() requires two parameters. Problem 2: multiply() calculates a value and puts the result in a variable, but never returns the value to the caller. Because there is no return statement, and the function is supposed to return an int, this will either produce a compiler error (on some compilers) or unexpected results (on other compilers).

add(1, multiply(2, 3)) => add(1, 6) => 7

Put less verbosely (where the => symbol is used to represent evaluation)

the caller

The function initiating the function call is called the caller,

main() function

The main() function is mandatory. Every program must have a main() function. Everything between the opening curly brace and the closing curly brace is considered part of the main() function.

Reusing functions

The same function can be called multiple times, which is useful if you need to do something more than once.

What symbol do statements in C++ end with?

The semicolon (;)

#include <iostream> using namespace std; int main() { cout << "Hi!" << endl; cout << "My name is Alex." << endl; return 0; }

This program prints Hi! My name is Alex.

#include <iostream> using namespace std; int main() { cout << "Hi!"; cout << "My name is Alex."; return 0; }

This program prints Hi! My name is Alex.

#include <iostream> using namespace std; // getValueFromUser will read a value in from the user, and return it to the caller int getValueFromUser() { cout << "Enter an integer: "; int a; cin >> a; return a; } int main() { int x = getValueFromUser(); // first call to getValueFromUser int y = getValueFromUser(); // second call to getValueFromUser std::cout << x << " + " << y << " = " << x + y << std::endl; return 0; }

This program produces the following output: Enter an integer: 5 Enter an integer: 7 5 + 7 = 12 In this case, main() is interrupted 2 times, once for each call to getValueFromUser(). Note that in both cases, the value read into variable a is passed back to main() via the function's return value and then assigned to variable x or y!

Note that main() isn't the only function that can call other functions. Any function can call another function! #include <iostream> using namespace std; void printA() { cout << "A" << std::endl; } void printB() { cout << "B" << std::endl; } // function printAB() calls both printA() and printB() void printAB() { printA(); printB(); } // Definition of main() int main() { cout << "Starting main()" << std::endl; printAB(); cout << "Ending main()" << std::endl; return 0; }

This program produces the following output: Starting main() A B Ending main()

#include <iostream> using namespace std; // Definition of function doPrint() void doPrint() // doPrint() is the called function in this example { std::cout << "In doPrint()" << std::endl; } // Definition of function main() int main() { std::cout << "Starting main()" << std::endl; doPrint(); // Interrupt main() by making a function call to doPrint(). main() is the caller. std::cout << "Ending main()" << std::endl; return 0; }

This program produces the following output: Starting main() In doPrint() Ending main() This program begins execution at the top of function main(), and the first line to be executed prints Starting main(). The second line in main() is a function call to the function doPrint(). At this point, execution of statements in main() is suspended, and the CPU jumps to doPrint(). The first (and only) line in doPrint prints In doPrint(). When doPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next statement executed in main prints Ending main(). Note that function calls are made by using the function name, plus a parameter list enclosed in parenthesis (). In this case, since none of our functions use parameters

//#include "stdafx.h" // Visual Studio users need to uncomment this line #include <iostream> int add(int x, int y) { return x + y; } int multiply(int z, int w) { return z * w; } int main() { using namespace std; cout << add(4, 5) << endl; // within add(), x=4, y=5, so x+y=9 cout << multiply(2, 3) << endl; // within multiply(), z=2, w=3, so z*w=6 // We can pass the value of expressions cout << add(1 + 2, 3 * 4) << endl; // within add(), x=3, y=12, so x+y=15 // We can pass the value of variables int a = 5; cout << add(a, a) << endl; // evaluates (5 + 5) cout << add(1, multiply(2, 3)) << endl; // evaluates 1 + (2 * 3) cout << add(1, add(2, 3)) << endl; // evaluates 1 + (2 + 3) return 0; }

This program produces the output: 9 6 15 10 7 6 The first two statements are straightforward. In the third statement, the parameters are expressions that get evaluated before being passed. In this case, 1 + 2 evaluates to 3, so 3 is passed to x. 3 * 4 evaluates to 12, so 12 is passed to y. add(3, 12) resolves to 15.

Why return a value back to the operating system?

This value is called a status code, and it tells the operating system (and any other programs that called yours) whether your program executed successfully or not. By consensus, a return value of 0 means success, and a positive return value means failure. Note that C++ explicitly specifies that main() must return an int, and have a return statement returning an integer value. Some compilers (e.g. Visual Studio) will let you get away with a return type of void, or omit the return statement. In this case, the compiler will return 0 for you. Technically both of these are illegal, so you shouldn't rely on your compiler for this functionality.

#include <iostream> using namespace std; int main() { cout << "Enter a number: "; // ask user for a number int x = 0; cin >> x; // read number from console and store it in x cout << "You entered " << x << std::endl; return 0; }

Try compiling this program and running it for yourself. When you run the program, it will print "Enter a number: " and then wait for you to enter one. Once you enter a number (and press enter), it will print "You entered " followed by the number you just entered. Enter a number: 4 You entered 4

How parameters and arguments work together

When a function is called, all of the parameters of the function are created as variables, and the value of each of the arguments is copied into the matching parameter. This process is called pass by value.

int add(int x, int y)

When function add() is called, parameter x is assigned the value 4, and parameter y is assigned the value 5. The function add() then evaluates x + y, which is the value 9, and returns this value back to function main(). This value of 9 is then sent to cout (by main()) to be printed on the screen. Output: 9

In this case, add() is called where x = a and y = a. Since a = 5, add(a, a) = add(5, 5), which resolves to 10.

When the function add() is executed, the CPU needs to determine what the values for parameters x and y are. x is simple since we just passed it the integer 1, so it assigns x=1. To get a value for y, it needs to evaluate multiply(2, 3) first. The CPU assigns z = 2 and w = 3, and multiply(2, 3) returns the integer value 6. That return value of 6 can now be assigned to the y parameter of the add() function. add(1, 6) returns the integer 7, which is then passed to cout for printing.

Returning to main

You now have the conceptual tools to understand how the main() function actually works. When the program is executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating system. This is why main is defined as int main().

x = 5

assign the value 5 to variable x

int x;

define x as an integer variable

Write a function called doubleNumber() that takes one integer parameter and returns twice the value passed in.

int doubleNumber(int x) { return 2 * x; }

int x

int x is a declaration statement. It tells the compiler that x is a variable.

#include <iostream>

is a special type of statement called a preprocessor directive. Preprocessor directives tell the compiler to perform a special task. In this case, we are telling the compiler that we would like to add the contents of the iostream header to our program. The iostream header allows us to access functionality in the iostream library, which will allow us to write to the screen.

In C++, variables are a type of l-value (pronounced ell-value).

l-value is a value that has an address (in memory). Since all variables have addresses, all variables are l-values.

return 0;

return statement When an executable program finishes running, the main() function sends a value back to the operating system that indicates whether it was run successfully or not. This particular return statement returns the value of 0 to the operating system, which means "everything went okay!". Non-zero numbers are typically used to indicate that something went wrong, and the program had to abort.

IO stream library

the IOstream library contains functionality for writing to the screen and getting input from a console user.

called function

the function being called is the called function.

int x;

this is a variable definition

cout <<

understands that anything sent to it via the output operator should be printed on the screen. In this case, we're sending it the text "Hello world!".

x = x + 1;

x + 1 evaluates to 8, which is then assigned to x. In this statement, the variable x is being used in two different contexts. On the left side of the assignment operator, "x" is being used as an l-value (variable with an address). On the right side of the assignment operator, x is being used as an r-value, and will be evaluated to produce a value (in this case, 7). When C++ evaluates the above statement, it evaluates as: x = 7 + 1; Which makes it obvious that C++ will assign the value 8 back into variable x.

x = 5

x = 5 is an assignment statement. It assigns a value (5) to a variable (x).

x = y;

y evaluates to 7 (from before), which is then assigned to x.


Conjuntos de estudio relacionados

Chapter 6 Values, Ethics, and Advocacy

View Set

Phrasal verbs, idioms and other expressions using 'get ' 1.2

View Set

Poetry Terms Quizlet- Match the term with its definition and example.

View Set

Electrical Level 2 Module 9 Grounding and Bonding

View Set