+ All Categories
Home > Documents > CS 215 – Sec 401 Fall 2014 Lecture 5

CS 215 – Sec 401 Fall 2014 Lecture 5

Date post: 05-Jan-2016
Category:
Upload: ganesa
View: 29 times
Download: 0 times
Share this document with a friend
Description:
CS 215 – Sec 401 Fall 2014 Lecture 5. Output Format, Scope, Input & Functions.  An Equal Opportunity University. Formatting Output in C++. cout is the output operator in C++. It is easy to use. But it is hard part being controlling the format of the output. - PowerPoint PPT Presentation
Popular Tags:
70
CS 215 – Sec 401 Fall 2014 Lecture 5 Output Format, Scope, Input & Functions An Equal Opportunity University
Transcript
Page 1: CS 215 – Sec 401 Fall 2014 Lecture 5

CS 215 – Sec 401Fall 2014Lecture 5

Output Format, Scope, Input & Functions

An Equal Opportunity University

Page 2: CS 215 – Sec 401 Fall 2014 Lecture 5

Formatting Output in C++

• cout is the output operator in C++.• It is easy to use.• But it is hard part being controlling the

format of the output. • In C we use with the printf to do that,

but printf is not type-safe.

Page 3: CS 215 – Sec 401 Fall 2014 Lecture 5

Manipulators• An output stream has a bunch of member variables

that control the details of what output looks like, and these variables can be controlled by a set of member functions and special objects called Manipulators.

• Most of these variables retain their values until they are changed, but a few only act temporarily - for the next output operation only.

Page 4: CS 215 – Sec 401 Fall 2014 Lecture 5

Manipulators• A manipulators that we already used is endl• The manipulators with no arguments, like endl, are

included in <iostream>• If you use manipulators that take arguments (like

setprecision and setw) you need to #include <iomanip>

• By default, characters and strings are simply output as is, and this is usually satisfactory.

• The main complexity is controlling the format of numbers. There are a zillion variables that control numeric and other formats.

Page 5: CS 215 – Sec 401 Fall 2014 Lecture 5

Manipulators• A double value will be printed using a general format that

usually works fine to represent a number in a small amount of space. The basic amount of space used is determined by the precision.

• The default precision is 6, which means up to 6 significant digits are used to represent the number. This counts digits both to the left and the right of the decimal point.

• The problem with the general format is that if you want to make numbers line up in neat columns, as in a table of data, the general format works very poorly because the total number of characters, and the number of digits to the right of the decimal point, will vary depending on the size of the number

Page 6: CS 215 – Sec 401 Fall 2014 Lecture 5

setw• Controlling minimum field width:• Example:• cout << "*" << setw(4) << 12 << "*" << endl;

• Result:• * 12*

Page 7: CS 215 – Sec 401 Fall 2014 Lecture 5

precision• You can change the maximum number of significant digits used to

express a floating point number by using the precision• member function or manipulator.

• Example:• cout.precision(4); // member function• cout << 1234.56789 << " " << 245.678 << " " << 12345.0 << endl;• or • cout << setprecision(4) // manipulator• << 1234.56789 << " " << 245.678 << " " << 12345.0 << endl; • Result: • 1235 245.7 1.234e+04

Page 8: CS 215 – Sec 401 Fall 2014 Lecture 5

fixed• For neat output of doubles, the fixed format is most useful. (You can also

select a scientific notation format.) • In fixed format, the precision specifies the number of digits to the right of

the decimal point.• Using fixed format together with setting the minimum field width allows

one to arrange numbers that take up a uniform number of characters, providing that they all fit in the minimum field width.

Page 9: CS 215 – Sec 401 Fall 2014 Lecture 5

Recapping Loops

An Equal Opportunity University

Page 10: CS 215 – Sec 401 Fall 2014 Lecture 5

Scope

Scope is how C++ resolves what identifiers (variables, functions, etc) are “known” to the compiler at any particular point.

Page 11: CS 215 – Sec 401 Fall 2014 Lecture 5

Blocks

Blocks are the primary unit of scope.Usually they are determined by the curly braces.

{

}

Page 12: CS 215 – Sec 401 Fall 2014 Lecture 5

Correct Use of Variable’s Scope

#include <iostream>using namespace std;int main (){ int a =10; cout<<“ The value of a is “ << a<<endl;

return 0;}

Page 13: CS 215 – Sec 401 Fall 2014 Lecture 5

Wrong use of Variable's Scope#include <iostream>using namespace std;int main () {

for (int i=1; i<=10;i++){ int a =10;

cout <<“ a * i =“ <<a*i<<endl;}

cout<<“ The value of a is “ << a<<endl; return 0;}

Page 14: CS 215 – Sec 401 Fall 2014 Lecture 5

Wrong Use of Variable's Scope#include <iostream>using namespace std;int main () {

for (int i=1; i<=10;i++){ int a =10; cout <<“ a * i =“ <<a*i<<endl;}

cout<<“ The value of a is “ << a<<endl; return 0;}

a can only be used

inside the scope of the

green box

You will get compile error here, and there will be red line under a

Page 15: CS 215 – Sec 401 Fall 2014 Lecture 5

Correct Previous Slide#include <iostream>using namespace std;int main () {

int a =10;for (int i=1; i<=10;i++){ cout <<“ a * i =“ <<a*i<<endl;}

cout<<“ The value of a is “ << a<<endl; return 0;}

Page 16: CS 215 – Sec 401 Fall 2014 Lecture 5

Variable Declared More Than Once#include <iostream>using namespace std;int main () {

int a =10;for (int i=1; i<=10;i++){ int a =5; cout <<“ a * i =“ <<a*i<<endl;}

cout<<“ The value of a is “ << a<<endl; return 0;}

What will b

e the output of

the last line? What is

the

value of a here?

Page 17: CS 215 – Sec 401 Fall 2014 Lecture 5

Correct Last Misleading Slide• First: It is very very very very bad form. Please

don’t confuse yourself or us by doing that.• Compiler has no problem with that, it is our eyes

and brain who will had a problem interpreting the results later on, which can lead us to mistakes.

• More recent C -derived languages (such as C#) treat this as an error and do not allow this behavior, for good reason.

Page 18: CS 215 – Sec 401 Fall 2014 Lecture 5

Common Error#include <iostream>using namespace std;int main () { cout<<“ The value of a is “ << a<<endl; int a =10; return 0;}

Don’t use the variable before

decalring it !!!

Page 19: CS 215 – Sec 401 Fall 2014 Lecture 5

Another Common Error Use The Variable Outside Its Scope#include <iostream>using namespace std;int main () {

for (int i=1; i<=10;i++){ int a =10; cout <<“ a * i =“ <<a*i<<endl;}

cout<<“ The value of i is “ << i<<endl; return 0;}

a can only be used

inside the scope of the

green box

You will get compile error here, and there will be red line under i

Page 20: CS 215 – Sec 401 Fall 2014 Lecture 5

Global vs. Local Variable• You can use a variable in an inner block that’s

declared in an outer block. • While we normally talk about blocks as being

denoted by curly braces, there is a “global scope” – the block that contains all the other blocks, and you can declare variables there that can be used within any block defined after the variable is declared.

• This is called a global variable, and it is bad form to have them anywhere that is not absolutely necessary.

Page 21: CS 215 – Sec 401 Fall 2014 Lecture 5

Global vs. Local Scope#include <iostream>using namespace std;int a =10;int main () { int b=5;

for (int i=1; i<=10;i++){ cout <<“ b * i =“ <<b*i<<endl;}

cout<<“ The value of a is “ << a<<endl; return 0;}

Global variable, can be

used any where….

Local variable, can only be used

inside the block where it was

defined.

Page 22: CS 215 – Sec 401 Fall 2014 Lecture 5

Local Variables Variables declared within the body of a function

definition are said to be local to that function, or have that function’s block as their scope.

Variables declared within the body of the main function are said to be local to the main function, or to have that function’s block as their scope.

When we say a function is a local variable without further mention of a function, we mean that variable is local to some function definition.

If a variable is local to a function, you can have another variable with the same name that is local to either main or some other function.

Page 23: CS 215 – Sec 401 Fall 2014 Lecture 5

Global Variables• A named constant declared outside the body of any

function definition is said to be a global named constant. A global named constant can be used in any function definition that follows the constant declaration. There is an exception to this we will point out later.

• Variables declared outside the body any function is said to be global variables or to have global scope. Such a variable can be used in any function definition that follows the constant declaration. There is also an exception to this we will point out later.

• Use of global variables ties functions that use the global variables in a way that makes understanding the functions individually nearly impossible. There is seldom any reason to use global variables.

Page 24: CS 215 – Sec 401 Fall 2014 Lecture 5

Input Through cin

So far we talked about output something to the screen. But how about getting input from the user?So far we made all our variables and constant fixed (Literal values). How about letting variables take variable value? (CONST CANT BE CHANGED).The answer for that is using cin (a console input).

Page 25: CS 215 – Sec 401 Fall 2014 Lecture 5

cin Library && syntax

• Library:#include <iostream>

cin like cout is in <iostream>

• Syntax: cin >> variable_name;

Page 26: CS 215 – Sec 401 Fall 2014 Lecture 5

Where Can I Use It & With What?

• You can use it only within a block• You have to use it only with variables, not

with const.• It behave normally with all data types

expect string where it only read the first word of the sentences that it was enter.

• Instead of use cin with string, we use a function called getline. Its syntax is:getline (cin, string_varaible_name);

Page 27: CS 215 – Sec 401 Fall 2014 Lecture 5

Example

• cin used the extraction (>>) operator, basically the reverse of the insertion (<<) operator used for cout.

• Point it at an integer, and it attempts to read an integer in from the console.

Page 28: CS 215 – Sec 401 Fall 2014 Lecture 5

Strings Input through cin

Page 29: CS 215 – Sec 401 Fall 2014 Lecture 5

cin Result

Page 30: CS 215 – Sec 401 Fall 2014 Lecture 5

Input String Through geline

Page 31: CS 215 – Sec 401 Fall 2014 Lecture 5

getline Result

Page 32: CS 215 – Sec 401 Fall 2014 Lecture 5

Functions

Page 33: CS 215 – Sec 401 Fall 2014 Lecture 5

Top Down Design

• Step wise refinement, also known as divide and conquer, means dividing the problem into subproblems such that once each has been solved, the big problem is solved.

• The subproblems should be smaller and easier to understand and to solve than the big problem.

• Those subproblems in C++ is called Functions.

Page 34: CS 215 – Sec 401 Fall 2014 Lecture 5

Functions

• What is a function?– A function is a sequence of instructions with a

name.

• A function body or function block is the implementation of that function enclosed in braces.

• A function is composed of declaration and implementation.

Page 35: CS 215 – Sec 401 Fall 2014 Lecture 5

Function We Already KnowThe Main Function

Page 36: CS 215 – Sec 401 Fall 2014 Lecture 5

Functions Types

We have two types of functions:

•Predefined Functions Inside the Language.

•Programmer’s Function

Page 37: CS 215 – Sec 401 Fall 2014 Lecture 5

Predefined Functions

• C++ comes with libraries of predefined functions.

• How do we use predefined (or library) functions?

• Everything must be declared before it is used. The statement #include <file> brings the declarations of library functions into your program, so you can use the library functions

Page 38: CS 215 – Sec 401 Fall 2014 Lecture 5

Predefined Functions

Before we use such functions we have to include their header files.For example:•We’ll see a lot of functions in the <cmath> header file:

– sin() –takes the sine of the value (in radians)– cos() –takes the cosine of the value (in radians)– tan() –takes the tangent of the value (in radians)– sqrt() –takes the square root of the value

We have other functions, we will cover them later.

Page 39: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer’s Functions

It is defined by the programmer her/himself to do a specific task. It is only known to the programmer her/himself unless s/he choose to share with others so they can use it, but they have to do that according to some rules.

Page 40: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer’s Functions

• Programmer can put his/her functions in the same file as the main function or in a separate file.

• If the programmer put his/her function after the function containing a call to his/her function, or in a separate file, s/he must put a prototype (defined in the next few slide) for her/his function some place in the file where it is called, prior to the call.

Page 41: CS 215 – Sec 401 Fall 2014 Lecture 5

Function’s Syntax

Page 42: CS 215 – Sec 401 Fall 2014 Lecture 5

Function’s Syntax Cont~

Parts of a function:•Return type: what type of value the function returns.•Name: function’s name, what we will know it as later•Parameters: the arguments we pass to the function when we call it•Body: A block (like the body of a loop or if statement), follows normal scoping rules. •Has a return statement if the return type is not void

Page 43: CS 215 – Sec 401 Fall 2014 Lecture 5

Calling a Function• A function call is an expression consisting of

a function name followed by arguments enclosed in parentheses. Multiple arguments are separated by commas.

• Syntax: FunctionName(Arg_List) where Arg_List is a comma separated list of

arguments

Page 44: CS 215 – Sec 401 Fall 2014 Lecture 5

Calling a Functionint main() {

double z = pow (2, 3); cout << “2^3 = ” << z << endl;return 0;

}

What is the sequence of the instructions here when we call the pow function.

Page 45: CS 215 – Sec 401 Fall 2014 Lecture 5

Calling a function1. By using the expression: pow(2, 3), main

calls the pow function, asking it to compute 23

2. The main function is temporarily suspended.3. The instructions of the pow function execute

and compute the result.4. The pow function returns its result back to

main, and the main function resumes execution.

5. A function must be declared before the first call of this function.

Page 46: CS 215 – Sec 401 Fall 2014 Lecture 5

Function’s Call Sequence

Page 47: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer Defined Functionsfunction prototypes

• A function prototype tells you all the information you need to call the function. A prototype of a function (or its definition) must appear in your code prior to any call to the function.

• Syntax: Don’t forget the semicolon– Type_of_returned_value Function_Name (Parameter_list) ;– Place prototype comment here.– Parameter_list is a comma separated list of parameter

definitions:type_1 param_1, type_2 param_2, …. type_N param_N

• Example: double total_weight(int number, double weight_of_one);

// Returns total weight of number of items that each weigh // weight_of_one

Page 48: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer Defined FunctionsA function is like a small program

To understand functions, keep these points in mind:

• A function definition is like a small program and calling the function is the same thing as running this small “program.”

• A function has formal parameters, rather than cin, for input. The arguments for the function are input and they are plugged in for the formal parameters.

• A function of the kind discussed in this chapter does not send any output to the screen, but does send a kind of “output” back to the program. The function returns a return-statement instead of cout-statement for “output.”

Page 49: CS 215 – Sec 401 Fall 2014 Lecture 5

Example of Programmer Defined Function (1)

Function

Call

Function

Prototype

Page 50: CS 215 – Sec 401 Fall 2014 Lecture 5

Example of Programmer Defined Function (2)

Function

Header

Page 51: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer Defined FunctionsCall-by-value Parameters

Consider the function call:bill = total_cost(number, price);

• The values of the arguments number and price are “plugged” in for the formal parameters .

• A function of the kind discussed so far does not send any output to the screen, but does send a kind of “output” back to the program. The function returns a return-statement instead of cout-statement for “output.”

Page 52: CS 215 – Sec 401 Fall 2014 Lecture 5

Programmer Defined FunctionsAlternate form for Function Prototypes

• The parameter names are not required:double total_cost(int number, double price);

• It is permissible to write:double total_cost(int, double );

• Nevertheless, code should be readable to programmers as well as understandable by the compiler, so check for readability and chose to use parameter names when it increases readability.

• Function HEADERS (in the definition) must use parameter names. (There is an exception to this rule that we will not deal with in this course.)

Page 53: CS 215 – Sec 401 Fall 2014 Lecture 5

PITFALL Arguments in the wrong order

When a function is called, C++ substitutes the first argument given in the call for the first parameter in the definition, the second argument for the second parameter, and so on.

There is no check for reasonableness. The only things checked are: i) that there is agreement of argument type with parameter type and ii) that the number of arguments agrees with the number of parameters.

If you do not put correct arguments in call in the correct order, C++ will happily assign the “wrong” arguments to the “right” parameters.

Page 54: CS 215 – Sec 401 Fall 2014 Lecture 5

Functions AbstractionPrinciple of Information Hiding

David Parnas, in 1972 stated the principle of information hiding.

A function’s author (programmer) should know everything about how the function does its job, but nothing but specifications about how the function will be used.

The client programmer -- the programmer who will call the function in her code -- should know only the function specifications, but nothing about how the function is implemented.

Page 55: CS 215 – Sec 401 Fall 2014 Lecture 5

Procedural AbstractionThe Black Box Analogy

Based on the Principle of Information Hiding, the text describes the BLACK BOX analogy.

When using a function, we behave as if we know nothing about how the function does its job, that we know only the specifications for the function.

When writing a function, we behave as if we know nothing but the specifications about how the function is to be used.

In this way, we avoid writing either application code that depends on the internals of the function or writing function code that depends in some way on the internal structure of the application.

Page 56: CS 215 – Sec 401 Fall 2014 Lecture 5

Procedural AbstractionThe Principle

When applied to a function definition, the principle of procedural abstraction means that your function should be written so that it can be used like a black box. This means the user of a function should not need to look at the internals of the function to see how the function works. The function prototype and accompanying commentary should provide enough information for the programmer to use the function.

To ensure that your function definitions have this property, you should adhere to these rules:

The prototype comment should tell the programmer any and all conditions that are required of the arguments to the function and should describe the value returned by the function.

All variables used in the function body should be declared in the function body. (The formal parameters are already declared in the function header.)

Page 57: CS 215 – Sec 401 Fall 2014 Lecture 5

Local Variables Call-by-value Formal Parameters are Local

Variables

Formal parameters are more than just blanks to be filled in with values from arguments.

We promised a more precise discussion of what “value plugged in for the argument” means. Here is that discussion.

Formal parameters are actually local variables that are initialized by the call mechanism to the value of the argument. They may be used in any way that a local variable can be used.

The next slide is an example of a formal parameter used as a local variable.

Page 58: CS 215 – Sec 401 Fall 2014 Lecture 5

Formal Parameter Used as Local Variable 1-2

Page 59: CS 215 – Sec 401 Fall 2014 Lecture 5

Formal Parameter Used as Local Variable 2-2

Page 60: CS 215 – Sec 401 Fall 2014 Lecture 5

Void Function

A subtask may produce one or many values We will see that such functions ordinarily return

no values at all. We will present a mechanism for multiple values to be sent back to the caller.

Such a function is called a void-Function. The essential point is demonstrated here:

void Print( double value){

using namespace std; cout << value << endl;}

Page 61: CS 215 – Sec 401 Fall 2014 Lecture 5

Definition of void-Functions

A C++ void function is defined similarly to functions that return a value. The next slide has an example.

There are two differences between value returning functions and void-functions. void type replaces the more familiar return type

such as int or double. There is no “return expression; “ statement,

though a return; with no expression is allowed. A call to a void function is an executable

statement, rather than being part of an expression

Page 62: CS 215 – Sec 401 Fall 2014 Lecture 5

Pass by Value vs. Pass by Reference

• The important concepts for passing variables to functions: Pass by value, pass by reference. It is very important to understand the difference between the two.

Page 63: CS 215 – Sec 401 Fall 2014 Lecture 5

Pass By Value

When we pass by value, C++ creates a

new variable (and allocates new memory for it) within the function.

Page 64: CS 215 – Sec 401 Fall 2014 Lecture 5

Pass By Reference

When we pass by reference, the same variable gets reused. This happens because the function, instead of just getting the valueof the variable, gets passed its memory location, and can then access the memory that contains the original variable.

Page 65: CS 215 – Sec 401 Fall 2014 Lecture 5

Syntax Difference

Syntax for passing by value: type variable nameExample: int Show_me (int x )

C/C++ actually has pretty simple rules for pass by value/reference; if you see the reference declarator(&), it passes the value by reference, otherwise it passes by value.

Page 66: CS 215 – Sec 401 Fall 2014 Lecture 5

Call By Reference

Syntax for passing by reference: type &variable nameExample: int Show_me (int &x )

Here we have the reference declarator (&); this passes the value by reference, so not only do we reuse the memory location, but this function can now modify the value stored in the variable.

Page 67: CS 215 – Sec 401 Fall 2014 Lecture 5

Const with Call By Reference

Another Syntax for passing by reference: const type &variable nameExample: int Show_me (const int &x )

In this case when we’re passing by reference that we don’t want the function to be able to do this, so we can use the const keyword here to prevent the function from changing the value of the variable.

Page 68: CS 215 – Sec 401 Fall 2014 Lecture 5

Function Call Another Function

• A function may call another function.• The situation is exactly the same as if

the first call had been in the main function.

• The next example shows how to swap the values of two variables if the values are out of order

Page 69: CS 215 – Sec 401 Fall 2014 Lecture 5
Page 70: CS 215 – Sec 401 Fall 2014 Lecture 5

Recommended