Functions & Libraries

Size: px
Start display at page:

Download "Functions & Libraries"

Transcription

1 Chapter 6 Functions & Libraries F unctions are named "chunks" of code that calculate a value or that carry out an action. The essential characteristic of a C++ function is that it associates a computation specified by a block of code that forms the body of the function with a particular name. Functions can reduce bugs and make your maintenance more effective by allowing you to reuse proven code that you've written, instead of duplicating it. In this chapter we're going to look at packaging your functions into libraries, so that you can reuse them without resorting to "cut and paste". As usual, we'll start by working through a homework assignment. Upload the H09 starter code to your workspace. Once that's done, we'll write some functions to get some help with integers, and then place them into a library. Our library will have the following three functions: int firstdigit(int n), returning the first digit of its argument int lastdigit(int n), returning the last digit of its argument int numdigits(int n), returning the number of digits of its argument Here's how the functions will work. Calling firstdigit(1729) will return 1, calling lastdigit(1729) will return 9, while calling numdigits(1729) returns 4. Here are some hints that should help you write these functions: n % 10 returns the right-most digit of any integer n You can find the left-most digit by repeatedly dividing n by 10 until n is < 10. Dividing n by 10 until n is < 10, the number of iterations is the number digits. In the last chapter, you implemented functions that I already declared and documented for you. In this chapter, you'll learn how to declare, document and define and implement your own functions.

2 D E F I N I N G A L I B R A R Y P A G E 6-2 Defining a Library To define a library in C++, you supply two parts: the interface, which provides the information needed to use the library but leaves out the details about how the library works. the implementation, which specifies the underlying details. A typical interface will contain several definitions, including functions, types, and constants. In C++, the interface and implementation are usually written as two separate files: a header file and an implementation file. The header or interface file usually ends with.h, or, for libraries that contain template code,.hpp or.hxx The implementation file usually has the same root or base name, but a different extension. We'll use.cpp. in this class but other conventions include.cxx,.cc, and.c (a capital 'c'). Following this convention, our integer 411 library (for H09) interface will be declared in h09.h and defined or implemented in h09.cpp. Creating the Interface File When you open h09.h, you'll see that it is essentially an empty file. Get started by adding the file header documentation for Doxygen, and then just copying the three prototypes from the problem specification (at the beginning of this chapter.) Here is what the h09.h interface looks like after I've done that. Prototype Notes The prototypes for the three functions in our library look exactly as they would (except for the semicolon) if they appeared in our source file. There is one time, however, when the interface form of the prototype will be different: if the prototype includes any types from the standard library (such as string or vector). Comparing the interface version of the zipzap() function with its implementation: std::string zipzap(const std::string& str); // interface form string zipzap(const string& str) // implementation form

3 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S Inside the interface, both the parameter and the return type use the name std::string to indicate that string comes from the std namespace. Interfaces should never use identifiers from that namespace without explicitly including the std:: qualifier. Here are three rules to remember. 1. Never add using namespace std to a header file. Because interface or header files are #included in other files, doing so changes the environment of that file. 2. Always add std:: in front of every library type parameter, such as std::string, but never in front of primitive types like double. 3. Remember for all library types, you must #include the appropriate header file inside your header file. The error interface uses the std::string type, so it must #include <string> Documenting the Interface The comments shown here can be processed by a documentation tool named Doxygen to generate HTML and other kinds of documentation. According to the Web site: Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and UNO/OpenOffice flavors), Fortran, VHDL, Tcl, and to some extent D. Find more extensive information on the Web site. If you want to experiment on your own, use sudo apt-get install doxygen to install the software into your workspace. For now, I just want you to use these: The File Comment The interface file should have a file comment that contains these common Name of the file. Required if you are going to document functions, global variables and constants. Always use your date it was created, then edited (can be version information about the library (optional)

4 P R E P R O C E S S O R H E A D E R G U A R D S P A G E 6-4 Function Comments Each function should also be documented. Here are the tags you should generally a one line description. If you start your comment block with a single line ending in a period, you can omit the name and description of every parameter to your if the function returns a value, you should add this tag You may also want to include the a block of code that will be syntax highlighted in the generated documentation. This block must end with tag. Go ahead and add your own comments (in front of) each of the functions. On the next page, after I discuss preprocessor header guards, you'll see the comments that I added and you can check them against your own code. Preprocessor Header Guards Suppose you have the following situation: #include the header file a.h that has a single line: #include "b.h" File b.h should also have a single line: #include "a.h" I'm sure you see the problem. This is not an artificial situation. If you include <iostream>, it normally includes the <string> header, because the stream objects have to know how to read and write string objects. However, because the <string> header contains the prototype for the function getline(), the <string> header also needs to know about the istream and ostream classes, so it needs to include the <iostream> header which includes <string> once again ad infinitum. This is the same situation we started with. We something to make sure that the compiler doesn t include the same interface twice. Do that by adding three lines to every header file that are known as the interface boilerplate, or header guards. The basic structure looks like this: #ifndef FILE_IDENTIFIER #define FILE_IDENTIFIER // Entire contents of the header file #endif

5 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S This pattern of lines will appear in every interface. Header guards are instructions to the preprocessor, a program that examines your code before it is sent to the compiler. The boilerplate consists of the #ifndef and #define lines at the beginning of the interface, combined with the matching #endif line at the end. The #ifndef preprocessor directive checks whether the FILE_IDENTIFIER symbol has been defined. When the preprocessor reads this interface file for the first time, the answer is no. The next line, however, tells the preprocessor to define that symbol. Thus, if the preprocessor is later asked to #include the same interface, the FILE_IDENTIFIER symbol will already be defined, and the preprocessor will skip over the contents of the interface this time around. A common convention is to simply capitalize the name of the file itself, replacing the dot with an underscore. You may use another convention if you like. The specific name you are asked to check is not as important as making sure that the name will be unique when you build your project. The Finished Interface Here's my version of the finished interface file (for the first function). #ifndef H09_H #define H09_H /** h06.h Stephen Gilbert Fall 2017 */ /** * Returns the first digit in any integer n. n the integer to check. May be negative. the first digit of the integer n. * int a = firstdigit(215); // returns 2 * int b = firstdigit(-79); // returns 7 (not -7) */ int firstdigit(int n); // Rest of the functions here #endif

6 T H E I M P L E M E N T A T I O N P A G E 6-6 The Implementation To implement the functions in our library we need to follow the same steps you did for homework assignments in the last chapter. You need to: Create an implementation file using the extension.cpp. Your starter code for H09 already comes with h09.cpp. Remember to add a file comment to the top of the file, and to #include the interface file for the library. Next, copy the prototypes from each of the functions into the implementation file. You don't need to bring across the documentation. Stub out each of the functions, by removing the semicolon at the end of the function, adding braces, and creating and returning a result from each function that requires it. This is a purely mechanical process, and you want to practice it until it becomes second nature. You should memorize this part, so you don't have to expend any brain cells to complete it. Warning. Make sure your stub includes a return statement of the correct type, or your function will crash at runtime. Planning your Functions Start the implementation by creating a plan and documenting it, adding implementation comments to each function. These comments are intended for programmers, not for the clients of the function. Don't use DOXYGEN tags, but describe the algorithms and important implementation details. Here, for instance is my plan for lastdigit(): /* * Return the right-most digit of n. * * 1. If n is negative, convert to a positive * 2. Return n % 10 */ In the picture here I've used multiline comments, but single-line comments may be easier since most editors will comment and un-comment a portion of code, using only a single keystroke. In the CS50 ide, that keystroke is Shift+/.

7 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S Implementing lastdigit I'd encourage you to write your comments first, and then implement the function. Of course, with small functions like this, you often will plan it out, and then simply write the code directly from the comment. int lastdigit(int n) { int result = n < 0? -n : n; return result % 10; } In this case, I've used the conditional operator to set the result to convert n to a positive number. I could also easily have used the abs() function in <cstdlib>. The only problem with using abs() is that there are separate versions in <cmath> (for integer), and in <cstdlib> for (floating-point numbers), and I find it easy to get them confused some times. Parameters and Local Variables Notice that instead of changing n itself, I've created a separate variable named result. This is generally considered better style, because it doesn't confuse the concept of a parameter or input variable, with that of a local variable used for the function output. Of course, since n is a value parameter, in this case it doesn't make any actual difference to the code. Later in this chapter, you'll learn about reference parameters where it will. Introducing the Limit Loop The other two functions are a little more difficult. Both of them require you to learn about a new kind of loop bounds, called limit bounds. Loops that do some processing and then check the results against some boundary condition are limit loops. Here is a limit loop which computes the sum of the digits in an integer, n: int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } This loop depends on the following observations: The expression n % 10 always returns the last digit in a positive integer n. The expression n / 10 returns a number without its final digit.

8 I N T R O D U C I N G T H E L I M I T L O O P P A G E 6-8 In this case, the condition that is being tested is the value of n, which is changed each time through the loop. Once n reach its limit (0), the loop terminates. Here are some other limit loop uses. Successive approximations that compare a calculation to the result from the previous iteration, and stop when the results are approximately equal. Bisection methods that are used to calculate approximations, and compare them to some previously known value (such as π). Non-convergence tests that monitor the direction of a series of calculations. Here is the plan I created for each function. Using limit loops, you should be able to complete these. If you get stuck, ask for help on Piazza. The firstdigit Function /* * Returns the first digit of n. * * 1. If n is negative, convert it to a positive * 2. While n is >= 10 * 3. Divide n by 10 * 4. Return n. */ The numdigits Function /* * Returns the number of digits in n. * * We'll assume that 0 is 1 digit. Can't have 0 digits. * 1. If number is negative, convert it. * 2. Create a counter, set to 1. * 3. While number is >= 10 * 4. Divide by 10 * 5. Increase counter * 4. Return the counter. */ Once you've completed the functions, be sure to check your code (make test) and submit the results (make submit) before the deadline.

9 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S Part 2 - More Function Features W hile we have already covered the basics of using functions in C++, there are several additional features you might want to use. Function overloading allows you to use the same name for several different functions, provided that each version of the function takes a different type or number of parameters. Default parameters allow you to write a single function that can be called in several different ways. And, finally and most importantly, reference parameters allow you to write functions that pass information back to the caller through the parameter list, instead of through the return statement. Function Overloading In C++, it is legal to give the same name to more than one function as long as the pattern of arguments is different. This is called function overloading. The pattern of arguments taken by a function which refers only to the number and types of the arguments and not the parameter names is called its signature. For example, both <cmath> and <cstdlib> have several versions of the function abs(). In <cstdlib> library you'll find these three versions of abs(): int abs(int n); long abs(long n); long long abs(long long n); while <cmath> has these five versions: double abs(double x); float abs(float x); long double abs(long double x); double abs(t x); There are even versions for complex numbers in the library <complex>. The only difference between these functions is the type of argument used as the parameter. The compiler chooses which version to invoke by looking at the types of the arguments the caller provides. If abs() is called with an int, the compiler calls the int version of the functions and returns a value of type int. If you call abs() with a double, then the compiler will choose the version that takes a double.

10 D E F A U L T P A R A M E T E R S P A G E 6-10 If you call abs() with an integer, and only include <cmath>, but forget <cstdlib>, then a special generic version of abs() that takes a type T parameter will be called. The difference between the generic version, and the overloaded abs(int) version, is that the generic version always returns a double, not an int. The advantage of using overloading is that it makes it easier for programmers to keep track of different function names for the same operation when applied in slightly different contexts. Without overloading we'd need to have different function names for each version: iabs, fabs, dabs, labs, llabs, and so on. Default parameters In addition to overloading, C++ makes it possible to specify that certain parameters are optional. Such parameter declarations still appear in the function header line, but include a value to be used if no value is supplied when calling the function. These optional parameters are called default parameters. To indicate that a parameter is optional, you include an initial value in the declaration of that parameter in the function prototype, exactly as if you were initializing a local variable. For example, you might define a procedure with the following prototype: void formatincolumns(int ncolumns = 2); The formatincolumns() procedure takes the number of columns as an argument, but the =2 in the prototype declaration means that this argument may be omitted. If you leave it out and call formatincolumns(); the parameter variable ncolumns will automatically be initialized to 2. Default Parameter Rules When you use default parameters, it helps to keep the following rules in mind: The default value appears only in the function prototype and not in the function definition. Default parameters must appear at the end of the parameter list and cannot be followed by a non-default parameter. It is always possible and often preferable to achieve the same effect through overloading. Suppose, for example, that you want to define a procedure named setinitiallocation() that takes an x and a y coordinate as arguments. The prototype presumably looks like this:

11 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S void setinitiallocation(double x, double y); Now suppose that you want to change this definition so that the initial location defaults to the origin (0, 0). One way to accomplish that goal is to add initializers to the prototype, like this, so that x and y are both default arguments. void setinitiallocation(double x = 0, double y = 0); The problem with this is that it makes it possible to call setinitiallocation() with only one argument, which would almost certainly be confusing to anyone reading the code. It is better to just define an overloaded version of the function like this: void setinitiallocation() { setinitiallocation(0, 0); } Reference Parameters In C++, whenever you pass a simple variable from one function to another, the function gets a copy of the calling value. Assigning a new value to the parameter as part of the function changes the local copy but has no effect on the calling argument. For example, if you try to write a procedure that initializes a variable to zero like this: void settozero(int var) { var = 0; } the procedure ends up having no effect whatever. If you call it like this: settozero(x); the parameter variable named var is initialized to a copy of whatever value is stored in the variable x. The assignment statement var = 0; inside the function sets the local parameter variable to 0 but leaves x unchanged in the calling program. That's why, in the lastdigit() function, we could have used the parameter variable n to do our calculations, instead of creating a separate result variable.

12 R E F E R E N C E P A R A M E T E R S P A G E 6-12 The practice of making a copy of arguments when calling a function, and then placing those copies into the appropriate parameter variable is known as pass by value or call by value, and the parameter x is known as a value parameter. Reference Parameters If you want to change the value of the calling argument, you can change the parameter from a value parameter into a reference parameter by adding an ampersand between the type and the name in the function header, like this: void settozero(int& var) { var = 0; } Unlike value parameters, reference parameters are not copied. What happens instead is that the function receives a reference to the original variable, which means that the memory used for that variable is shared between the function and its caller. The parameter variable is not a new variable, but simply an alias for an existing variable. L-values and R-values This style of parameter passing is known as call by reference. When you use call by reference, the argument corresponding to the reference parameter must be an assignable value, such as a variable; this is called a modifiable L-value. (The L means it can appear on the left of an assignment.) Calling settozero(x) correctly sets the integer variable x to 0. However calling settozero(y) does not work because even though y can appear on the left-hand-side of an assignment expression, it cannot be modified once it has been given a value. The constant y is an L-value, but it is non-modifiable. Finally, it is illegal to call setto- Zero(3) because 3 is not assignable; since it can only appear on the right-hand-side of an assignment operation, we call it an R-value.

13 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S Input & Output Parameters To return more than one value from a function, we can use reference parameters to pass values back and forth through the argument list. As an example, suppose that you are writing a program to solve the quadratic equation ax 2 + bx + c = 0 You want to structure that program into three IPO phases like this. Using top-down design, your main might look like: int main() { double a, b, c, root1, root2; getcoefficients(a, b, c); solvequadratic(a, b, c, root1, root2); printroots(root1, root2); } return 0; The variables a, b and c will hold our three coefficients, while the variables root1 and root2 will hold the two roots. The getcoefficients function will ask the user for the three values and place them into the three variables a, b and c, which are passed by reference. If a function needs to return more than one piece of information, it can use reference parameters. Here is one possible implementation of the function: /** * getcoefficients(a, b, c) * Reads the coefficients into three reference parameters. * x the first coefficient. y the second coefficient. z the third coefficient. */ void getcoefficients(double& x, double& y, double& z) { cout << "Enter three coefficients separated by spaces: "; cin >> x >> y >> z; } Note that when you call getcoeffients, information does not flow from main into the function; instead, information flows out of the function into main, through the three output parameters x, y, and z, which are not new variables, but are simply new names or aliases for the variables a, b, and c that were used when calling the function.

14 R E F E R E N C E P A R A M E T E R S P A G E 6-14 There are two other features you should notice in this function: Instead of separate input statements, you can read three variables using a single input statement as I've done here. The values typed or entered by the user must be separated from each other by whitespace, not commas. Spaces, tabs or newlines all work fine. When documenting your function parameters, the documentation tool we are using (DOXYGEN) allows you to annotate each of the parameters with the direction of the information flow: [in], [in,out], [out]. If you don't annotate a parameter it is assumed to be an input parameter. Input and Output Parameters The solvequadratic function uses both input and output parameters. The arguments a, b, and c are used as input to the function and give it access to the three coefficients, while the arguments root1 and root2 are output parameters and allow the function to pass back the two roots of the quadratic equation to main. /** * Solves the quadratic equation for roots a, b, and c. * a the first coefficient b the second coefficient c the third coefficient x1 the first root x2 the second root */ void solvequadratic(double a, double b, double c, double& x1, double& x2) { if (a == 0) error("the coefficient for a must be non-zero."); double disc = b * b - 4 * a * c; if (disc < 0) error("this equation has no real roots."); } double sqrtdisc = sqrt(disc); x1 = (-b + sqrtdisc) / (2 * a); x2 = (-b - sqrtdisc) / (2 * a); Introducing Error Handling This program also introduces a new strategy for reporting errors. Whenever the code encounters a condition that makes further progress impossible, it calls a function named error() that prints a message indicating the nature of the problem and then terminates the execution of the program. The code for error looks like this:

15 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S void error(const string& msg) { cerr << msg << endl; exit(exit_failure); } The code for error() uses three C++ features that we have not yet talked about. The parameter variable msg is passed by const reference. We'll always use const reference parameters when we have large objects that we don't want to copy (that's what the & does), and, when we want to make sure that the function does not modify the parameter in the caller (that's the const). The cerr stream is similar to cout, but is reserved for reporting errors. The exit() function terminates the execution of the main program immediately, using the value of the parameter to report the program status. The constant EXIT_FAILURE, defined in the <cstdlib> library, is used to indicate that some kind of failure occurred. The error() function, of course, would be useful in many applications beyond this. Although you could easily copy the code into another program, it would make much more sense to save the error function in a library. On your Own Going Postal For the second program in this chapter (H10), I'm going to leave you on your own. Upload the starter code to your workspace, and then complete the following problem Going Postal using the same techniques you learned in this chapter. (I have already supplied the headers and documentation, however.) For faster sorting of letters, the United States Postal Service encourages companies that send large volumes of mail to use a bar code denoting the zip code as shown here: The encoding scheme for a five-digit zip code is shown below.

16 O N Y O U R O W N G O I N G P O S T A L P A G E 6-16 There are full-height frame bars on each side. The five encoded digits are followed by a check digit, which is computed by adding up all digits, and choose a check digit to make the sum a multiple of 10. For example, the number has a sum of 19, so the check digit is 1 to make the sum equal to 20. Each digit of the zip code, and the check digit, is encoded according to the following table where 0 denotes a half bar and 1 a full bar. To solve this problem, you'll write three functions: string codefordigit(int digit) which takes one digit and returns the appropriate code for that digit, using the table above. Use ':' for the half-bars and ' ' for the full bars.

17 C H A P T E R 6 F U N C T I O N S & L I B R A R I E S int checkdigit(int zip) which calculates the check digit according to the rules shown above. string barcode(int zip) which returns an entire bar code by breaking the number into individual digits, encoding that digit, and adding it to the string return value. Finally, calculate and encode the check digit, surround the entire code with the frame bars, and return it. You'll find the starter code in the download folder. Start with the codefordigit() function first. Run the tests for that. Next, calculate the checkdigit() function and run the tests for that. Finally, finish up the barcode() function. If you get stuck, ask for help on Piazza. Study Guide Questions Interface files end with while implementation and client files end with. Describe the parts that make up an interface header guard. Write one for zzy.h List several documentation tags and describe their meanings. Add the appropriate documentation and tags for the following function: int countvowels(const string& str); Functions that have the same name are said to be. We distinguish between multiple functions with the same name by examining the function's. You can call a single function in several different ways, by giving the function. To allow a function to change an argument passed to it, declare the parameter as. Arguments that are passed to functions taking reference parameters must be. A named constant, which can only be assigned a value once, is known as a. A value that can only be used on the right-side of an assignment is called a(n), Look at the code below and choose the best prototype to use in this situation. Note that these are NOT overloaded functions; only one will be used.

18 S T U D Y G U I D E Q U E S T I O N S P A G E 6-18 Look at the code below and choose the best prototype to use in this situation. Note that these are NOT overloaded functions; only one will be used. Examine the prototypes for the overloaded functions shown here. All of these functions appear in the same file. They are legal and they compile. Which function is invoked when making the following calls? fn(1, 2, 3, 4); fn(1, 2, 3); double n = 3.5; fn(1, 2, n); fn();

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

COP Programming Assignment #7

COP Programming Assignment #7 1 of 5 03/13/07 12:36 COP 3330 - Programming Assignment #7 Due: Mon, Nov 21 (revised) Objective: Upon completion of this program, you should gain experience with operator overloading, as well as further

More information

Understanding main() function Input/Output Streams

Understanding main() function Input/Output Streams Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout

More information

Spring CS Homework 12 p. 1. CS Homework 12

Spring CS Homework 12 p. 1. CS Homework 12 Spring 2018 - CS 111 - Homework 12 p. 1 Deadline 11:59 pm on Friday, May 4, 2018 Purpose CS 111 - Homework 12 To practice with sentinel- and question-controlled loops, file input and file output, and writing

More information

CS Software Engineering for Scientific Computing. Lecture 5: More C++, more tools.

CS Software Engineering for Scientific Computing. Lecture 5: More C++, more tools. CS 294-73 Software Engineering for Scientific Computing Lecture 5: More C++, more tools. Let s go back to our build of mdarraymain.cpp clang++ -DDIM=2 -std=c++11 -g mdarraymain.cpp DBox.cpp -o mdarraytest.exe

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Deadline. Purpose. How to submit. Important notes. CS Homework 9. CS Homework 9 p :59 pm on Friday, April 7, 2017

Deadline. Purpose. How to submit. Important notes. CS Homework 9. CS Homework 9 p :59 pm on Friday, April 7, 2017 CS 111 - Homework 9 p. 1 Deadline 11:59 pm on Friday, April 7, 2017 Purpose CS 111 - Homework 9 To give you an excuse to look at some newly-posted C++ templates that you might find to be useful, and to

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

Lab Instructor : Jean Lai

Lab Instructor : Jean Lai Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.

More information

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in: CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also

More information

CS Exam 2 Study Suggestions

CS Exam 2 Study Suggestions CS 131 - Fall 2009 p. 1 last modified: 11-10-09 CS 131 - * Remember: anything covered in lecture, in lab, or on a homework, is FAIR GAME. * You are responsible for all of the material covered through Week

More information

CS Homework 10 p. 1. CS Homework 10

CS Homework 10 p. 1. CS Homework 10 CS 131 - Homework 10 p. 1 Deadline: 5:00 pm on Friday, December 3 How to submit: CS 131 - Homework 10 When you are done with the following problems: make sure that your current working directory on nrs-labs

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes

More information

Homework 11 Program Setup (with some IMPORTANT NEW STEPS!)

Homework 11 Program Setup (with some IMPORTANT NEW STEPS!) Spring 2018 - CS 111 - Homework 11 p. 1 Deadline 11:59 pm on Friday, April 27, 2018 Purpose To practice with loops, arrays, and more! How to submit CS 111 - Homework 11 Submit your main.cpp (or it may

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016 Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.096 Lecture 3 Notes

More information

Chapter 6 : Modularity Using Functions (pp )

Chapter 6 : Modularity Using Functions (pp ) Page 1 of 56 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

C++ Support Classes (Data and Variables)

C++ Support Classes (Data and Variables) C++ Support Classes (Data and Variables) School of Mathematics 2018 Today s lecture Topics: Computers and Programs; Syntax and Structure of a Program; Data and Variables; Aims: Understand the idea of programming

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin Functions CS111 Lab Queens College, CUNY Instructor: Kent Chin Functions They're everywhere! Input: x Function: f Output: f(x) Input: Sheets of Paper Function: Staple Output: Stapled Sheets of Paper C++

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Fundamentals of Programming Session 23

Fundamentals of Programming Session 23 Fundamentals of Programming Session 23 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

LAB: INTRODUCTION TO FUNCTIONS IN C++

LAB: INTRODUCTION TO FUNCTIONS IN C++ LAB: INTRODUCTION TO FUNCTIONS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 2 Introduction This lab will provide students with an

More information

4. Structure of a C++ program

4. Structure of a C++ program 4.1 Basic Structure 4. Structure of a C++ program The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Starting to Program in C++ (Basics & I/O)

Starting to Program in C++ (Basics & I/O) Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and

More information

Documentation Requirements Computer Science 2334 Spring 2016

Documentation Requirements Computer Science 2334 Spring 2016 Overview: Documentation Requirements Computer Science 2334 Spring 2016 These requirements are based on official Java coding conventions but have been adapted to be more appropriate to an academic environment.

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) A Server-side Scripting Programming Language An Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. It is a server-side

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

CS Homework 10 p. 1. CS Homework 10

CS Homework 10 p. 1. CS Homework 10 CS 111 - Homework 10 p. 1 Deadline 11:59 pm on Friday, December 2, 2016 How to submit Each time you would like to submit your work: CS 111 - Homework 10 If your files are not already on nrs-labs, be sure

More information

Comp151 Lab Documentation using Doxygen

Comp151 Lab Documentation using Doxygen Comp151 Lab Documentation using Doxygen Supplementary Notes By Adam Information in this slide is extracted from Doxygen homepage: http://www.stack.nl/~dimitri/doxygen/ and Javadoc reference: http://java.sun.com/j2se/javadoc/writingdoccomments/

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout

More information

CS 106B Lecture 2: C++ Functions

CS 106B Lecture 2: C++ Functions CS 106B Lecture 2: C++ Functions parameters Wednesday, September 28, 2016 Programming Abstractions Fall 2016 Stanford University Computer Science Department Lecturer: Chris Gregg reading: Programming Abstractions

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 25, 2017 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Function Details Assert Statements

More information

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics

More information

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto Side Effects The 5 numeric operators don't modify their operands Consider this example: int sum = num1 + num2; num1 and num2 are unchanged after this The variable sum is changed This change is called a

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

I/O Streams and Standard I/O Devices (cont d.)

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School Objectives To understand the concepts of modularity and bottom up testing. To be aware of the use of structured

More information

What have we learned about when we learned about function parameters? 1-1

What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? Call-by-Value also known as scalars (eg. int, double, char,

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review. Modules. CS 151 Review #6. Sample Program 6.1a: Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

CSE 333 Autumn 2013 Midterm

CSE 333 Autumn 2013 Midterm CSE 333 Autumn 2013 Midterm Please do not read beyond this cover page until told to start. A question involving what could be either C or C++ is about C, unless it explicitly states that it is about C++.

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

CIS 130 Exam #2 Review Suggestions

CIS 130 Exam #2 Review Suggestions CIS 130 - Exam #2 Review Suggestions p. 1 * last modified: 11-11-05, 12:32 am CIS 130 Exam #2 Review Suggestions * remember: YOU ARE RESPONSIBLE for course reading, lectures/labs, and especially anything

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 9 Variable Scope and Functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Variable Scope and Class Variables are defined by two attributes: Scope The area where a

More information

Chapter 2 C++ Fundamentals

Chapter 2 C++ Fundamentals Chapter 2 C++ Fundamentals 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Reuse existing code in your programs with #include Obtain input data from the user

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

CS Homework 11 p. 1. CS Homework 11

CS Homework 11 p. 1. CS Homework 11 CS 111 - Homework 11 p. 1 Deadline 11:59 pm on Monday, May 2, 2016 How to submit Each time you would like to submit your work: CS 111 - Homework 11 If your files are not already on nrs-labs, be sure to

More information

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

More information