Download
cs 215 sec 401 fall 2014 lecture 5 n.
Skip this Video
Loading SlideShow in 5 Seconds..
CS 215 – Sec 401 Fall 2014 Lecture 5 PowerPoint Presentation
Download Presentation
CS 215 – Sec 401 Fall 2014 Lecture 5

CS 215 – Sec 401 Fall 2014 Lecture 5

133 Views Download Presentation
Download Presentation

CS 215 – Sec 401 Fall 2014 Lecture 5

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. CS 215 – Sec 401Fall 2014Lecture 5 Output Format, Scope, Input & Functions An Equal Opportunity University

  2. 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.

  3. 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.

  4. 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.

  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

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

  7. 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

  8. 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.

  9. Recapping Loops An Equal Opportunity University

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

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

  12. 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; }

  13. 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; }

  14. Wrong Use of Variable's Scope a can only be used inside the scope of the green box #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; } You will get compile error here, and there will be red line under a

  15. 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; }

  16. Variable Declared More Than Once What will be the output of the last line? What is the value of a here? #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; }

  17. Correct Last Misleading Slide • First: It is very veryveryvery 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.

  18. 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 !!!

  19. Another Common Error Use The Variable Outside Its Scope a can only be used inside the scope of the green box #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; } You will get compile error here, and there will be red line under i

  20. 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.

  21. 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.

  22. 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 theirscope. • 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 theirscope. • 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.

  23. Global Variables • A named constant declared outside the body of any function definition is said to bea 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 variablesor 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.

  24. 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).

  25. cin Library && syntax • Library: #include <iostream> cin like cout is in <iostream> • Syntax: cin >> variable_name;

  26. 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);

  27. 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.

  28. Strings Input through cin #include<iostream> #include<string> usingnamespace std; intmain () { string name; cout << "Please, enter your full name: "; cin >>cin; cout << "Hello, " << name << "!\n"; system ("Pause"); return 0; }

  29. cin Result

  30. Input String Through geline #include<iostream> #include<string> usingnamespace std; int main () { string name; cout << "Please, enter your full name: "; getline (cin, name); cout << "Hello, " << name << "!\n"; system ("Pause"); return 0; }

  31. getline Result

  32. Functions

  33. 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.

  34. 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.

  35. Function We Already KnowThe Main Function

  36. Functions Types We have two types of functions: • Predefined Functions Inside the Language. • Programmer’s Function

  37. 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

  38. 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.

  39. 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.

  40. 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.

  41. Function’s Syntax

  42. 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

  43. 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

  44. Calling a Function int 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.

  45. Calling a function • By using the expression: pow(2, 3), main calls the pow function, asking it to compute 23 • The main function is temporarily suspended. • The instructions of the pow function execute and compute the result. • The pow function returns its result back to main, and the main function resumes execution. • A function must be declared before the first call of this function.

  46. Function’s Call Sequence

  47. 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_valueFunction_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

  48. 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.”

  49. Example of Programmer Defined Function (1) #include<iostream> usingnamespace std; doubletotal_cost(intnumber_par, doubleprice_par); //Computes the total cost, including 5% sales tax, //on number_par items at a cost of price_par each. int main( ) { double price, bill; int number; cout << "Enter the number of items purchased: "; cin >> number; cout << "Enter the price per item $"; cin >> price; bill = total_cost(number, price); cout << number << " items at $" << price << " each.\n" << "Final bill, including tax, is $" << bill <<endl; return 0; } Function Prototype Function Call

  50. Example of Programmer Defined Function (2) doubletotal_cost(intnumber_par, doubleprice_par) { constdouble TAX_RATE = 0.06; //6% sales tax doublesubtotal; subtotal = price_par * number_par; return (subtotal + subtotal*TAX_RATE); } Function Header