Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll>

Size: px
Start display at page:

Download "Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll>"

Transcription

1 Lecture #5 Introduction Visual C++ Functions A C++ function is a collection of statements that is called and executed as a single unit in order to perform a task. Frequently, programmers organize statements that must be executed to produce a special results as a function. Consequently, programmers can call the function by name to use it over and over again. Interestingly, functions provided by the.net Framework are known as methods. The terminology is somewhat confusing because function and method are often used interchangeably in C++. This is because programmers can develop Visual C++ application with or without using object-oriented paradigm. However, the.net Framework is objectoriented. All the function provided by the.net Framework are members of a class. It is required to create an object as instance of the class in order to use the functions of the class. Therefore, when a function must be associated with an object of a given C++ class, it is referred to as a method. In other words, method is the object-oriented term of function. Generally speaking, methods are functions that belong to a class, while functions can be on any other scope of the code without being part of a C++ class. The following compares two codes: one illustrates how to create a function that is object-independent, the other demonstrates how a method must be associated to an object. A later lecture will dicuss about object-oriented in details. Function (not a member of any C++ class) #using <System.Windows.Forms.dll> using namespace System::Windows::Forms; void getcube() MessageBox::Show(5*5*5+""); getcube(); Method (object-oriented) using namespace System::Windows::Forms; public ref class MyMath public: static void getcube() MessageBox::Show(5*5*5+""); ; MyMath::getCube(); One can arguably state that all methods are functions, yet not all functions are methods. There are two main types of functions: pre-defined functions and user-defined functions. Pre-defined functions (also known as methods): These are functions provided by C++ language and other supporting libraries as well as the.net Framework. User-defined function: These are function defined by users like you, whenever and wherever is necessary. Calling predefined functions (methods) As the name implies, pre-defined functions already exists in the C++ library in which they reside. You only need to call them; you don t need to define them. The trick is, since they reside in a particular library, you cannot use it until you include the library to your code. For example, the directive #include <cmath> is necessary for the Visual C++ compiler to find the definition of the following pre-defined math functions: acos(), asin(), and atan(). Visual C++ Programming Penn Wu, PhD 121

2 #include <cmath> String^ str=""; str+= acos(0.2) + "\n"; // inverse cosine str+= asin(0.2) + "\n"; // inverse sine str+= atan(0.2) + "\n"; // inverse tangent In the above code, acos is the name of a pre-defined function (aka. method ), 0.2 is the value of parameter, and the calculated result is assigned to a string variable named str. The output looks: In the above example, you call the function by the name with a value as parameter of the function. The following is the.net Framework version of the above code. Trigonometic methods are defined in the System::Math class; therefore, you need to use the scope resolution operator (::) to specify that you want the Acos() method of the Math class. String^ str=""; str+= Math::Acos(0.2) + "\n"; // inverse cosine str+= Math::Asin(0.2) + "\n"; // inverse sine str+= Math::Atan(0.2) + "\n"; // inverse tangent Try an empirical verification of sin(x) function in which x is a variable, and its value can range from 0 to 1.6 with an increment of 0.4. By the way, the following code uses a for loop to iterate. Visual C++ Programming Penn Wu, PhD 122

3 String^ str=""; for (float x =0; x<2; x+=0.4) str += x + "\t" + Math::Sin(x) +"\n"; The output looks: It is necessary to note that x is a variable of the Math::Sin() method. It can temporarily hold a value given by its calling party. In the for loop, there is a calling of Math::Sin(0.2) when i is 0.2. In other words, 0.2 is passed to the Math::Sin() method from the for loop. When a variable is included in a function as a private variable of the function in order to produce different results, it is referred to as a parameter. Creating userdefined functions Programmers can create a function that returns a value to its calling party (known as valuereturning function), programmers can also create a function that does not return any value to its calling party (known as void function). To create a user-defined function, you must determine three things: An identifier (function s name). Be sure to avoid using C++ keywords and reserved words. What, if any, data you must give it (placed in parentheses after its name) What, if any, data the function returns as a result of its operations A user-defined function has two parts: header and body. The header of a function specifies its return type, name, and parameter list. The syntax for creating a C++ function is: [Return Type] FunctionName([Parameters]); In the following code, the cube() function is declared as int type; therefore, it must return a value of int type to its calling party (which is the MessageBox::Show() method within the main() method). int cube() return 5*5*5; Visual C++ Programming Penn Wu, PhD 123

4 MessageBox::Show(cube() + ""); The body of function is the block of arranged statements enclosed by a pair of and to perform the function s action. In the above code, int specifies the return type, cube is the identifier of the function (function s name), and the body is: return 5*5*5; A value-returning function must include the return statement that specifies the value the function will send back to its calling party. It is necessary to note that the return statement has two purposes: it concludes the function, and it returns a value to the calling party. The following is the syntax, in which expression is any expression that can generate a value of the type specified by the function. return expression; Any user-defined function will not be executed unless there is a call somewhere in the program. Programmers must manage to call the user-defined function by name, and the calling process is known as making a function call. The syntax is: functionname() In the above code, the calling is done through the following statement. MessageBox::Show(cube() + ""); Programmers need to decide how to handle the result of a function call. Typically a valuereturning function is used to generate a value to support a main-stream routine. For example, an application needs to find the sum, minimum, maximum, and average of a list of numbers. The programmer can create a value-retuning function to calculate the sum, one function to calculate the average, one function to find the minium, and another to find the maximum. All the four invidual function perform a particular task, they return the result to support the mainstream routine. These type of function are also known as supporting functions. double sum() return ; double average() return ( ) / 4; void main() MessageBox::Show("Sum is " + sum() + ", average is " + average()); Visual C++ Programming Penn Wu, PhD 124

5 The advantage of using value-returning function is that you can create variables to store the results in memory and use it over and over again. In the following example, the result of the sum() function is stored in a double variable n. You can then retrieve the value from n as many times as you need. double sum() return ; void main() double n = sum(); String^ str = n + "\n"; str += n * 2 + "\n"; str += n * 3; A void function simply performs a task defined in its body. The communication between a void function and its calling party is unilateral (one-way). There is no interaction between them because a void function does not return any value to its calling party. After calling the void function, the calling party no longer maintain any communication with the void function. The following illustrates how the void function works. void cube() MessageBox::Show(5*5*5 + ""); cube(); The following is another way to use void type of function. It produces the same output as the above code. In this version, the instructor creates a global variable named x of int type. When the main() method calls the cube() method and passes a value of 5, the result of calculation is stored in x. Finally, the MessageBox::Show() method retrieves the value stored in x and display it. Visual C++ Programming Penn Wu, PhD 125

6 int x; void cube(int n) x = n*n*n; cube(5); MessageBox::Show(x + ""); The result of a void function is not saved in memory, because calling a void function is technically a one-time-only execution. If you wish to get the same result, you will need to call the function again. That being said, the result of execution of a void function vanishes immediately after the execution completes. For example, void sum() MessageBox::Show(( ) + ""); void main() sum(); One way to go around this limit is to store the result of a void function in a global variable. double x; // global variable void sum() x = ; void main() String^ str = ""; sum(); // call the function for calculation for (int i=0; i<5; i++) Visual C++ Programming Penn Wu, PhD 126

7 str += x + "\n"; A user-defined function that calls a predefined functions You can create functions that uses pre-defined function(s) to perform any task, for example, the GetType() method is a pre-defined.net Framework method that gets the data type of an object. The following test() function uses it to return the data type of a value 4.5 and the result is a System.Double. void test() MessageBox::Show(4.5.GetType() + ""); void main() test(); The following is the value-returning function that can produce the same result. String^ test() return 4.5.GetType() + ""; void main() MessageBox::Show(test()); The flow of control between main() and user-defined function Every C++ program must have the main() function which is typically used to handle the mainstream routine. In the following code, the main() function is also used to collect user entry and pass the value to the cube() function. #include "InputBox.cpp" int n; int cube() return n*n*n; Visual C++ Programming Penn Wu, PhD 127

8 n = Convert::ToInt16(InputBox::Show("Enter an integer: ")); MessageBox::Show(n+"^3 = " + cube()); A sample output looks: The cube() function calculates the cube of that value, and returns the calculated result to main(). The main() function then displays the returned calculated result by the line: and MessageBox::Show(n+"^3 = " + cube()); The concatenation of and cube(), as shown below, is a short-hand way of type casting. In C++ anything that concatenates with a string (even a blank string ) produces a new string. n+"^3 = " + cube() Notice that the cube() function is declared above the main() function. This is because C++ compiler must know about the cube() function before it is used in main(). The following is a C++ code that is written in procedural mode; however it will not compile because it reverses the order of main() and cube(). It only generic an error message: error C3861: 'cube': identifier not found. #include "InputBox.cpp" int n; n = Convert::ToInt16(InputBox::Show("Enter an integer: ")); MessageBox::Show(n+"^3 = " + cube()); //what is cube()??? int cube() return n*n*n; The cube() function can be declared as void type. The following illustrates how the void version of code works. Visual C++ Programming Penn Wu, PhD 128

9 #include "InputBox.cpp" int n; void cube() MessageBox::Show(n+"^3 = " + n*n*n); n = Convert::ToInt16(InputBox::Show("Enter an integer: ")); cube(); // calling cube() Using parameter A user-defined function can have one or more parameters to allow the calling party to pass values to the function to produce different results. A parameter can be considered as a variable of the function. The syntax to declare parameter(s) in a function is: functionname(type param1, type param2,..., type paramn) where type is the data type each parameter must be declared as. The following is an example that uses a for loop to pass nine different values (1, 2,.., 9) to the cube() function. Inside the cube() function, there is a variable n, which is the parameter of the function. Each time when a value is passed from the for loop, the cube() function return a different result. int cube(int n) return n*n*n; String^ str; for (int i=1; i<9; i++) str += cube(i) + "\n"; The following is revised version of one of the previous discussed codes, x is the parameter of cube(int x) function. The parameter x is declared as int type. Consequently, the calling party must pass an int value to the cube(int x) function when calling it. Visual C++ Programming Penn Wu, PhD 129

10 #include "InputBox.cpp" int cube(int x) return x*x*x; int n = Convert::ToInt16(InputBox::Show("Enter an integer: ")); MessageBox::Show(n+"^3 = " + cube(n)); //pass value of n to x When calling the cube function, the calling party must pass a value of the type specified by cube(int x). In the above example, the ToInt16() method will convert the user entry to an 16- bit int in order to match with the specified parameter type. You can have two or more parameters. In the following example, the sum() function takes three int parameters: x, y, and z. int sum(int x, int y, int z) return x + y + z; MessageBox::Show(sum(6, 3, 8)+""); In the following example, the user-defined function max() will returns the larger of the two values passed to it. #include "InputBox.cpp" int max(int a, int b) if (a >= b) Visual C++ Programming Penn Wu, PhD 130

11 return a; else return b; int a = Convert::ToInt16(InputBox::Show("The 1st integer: ")); int b = Convert::ToInt16(InputBox::Show("The 2nd integer: ")); MessageBox::Show("Maximum: " + max(a, b)); A sample output looks: Notice that max() has two return statements, one for the if statement; other for else statement. In this example, the return statement is similar to the break statement. It is a jump statement that jumps out of the function that contains it. However, the return statement will returns to whatever calls it, while the break statement won t. One void versions of this program looks: #include "InputBox.cpp" void max(int a, int b) String^ str = ""; if (a >= b) str += a +""; else str += b +""; MessageBox::Show("Maximum: " + str); int a = Convert::ToInt16(InputBox::Show("The 1st integer: ")); and Visual C++ Programming Penn Wu, PhD 131

12 int b = Convert::ToInt16(InputBox::Show("The 2nd integer: ")); max(a, b); A parameter is a variable of the the function; therefore, the value of parameters can be reassigned inside the function. In the following example, the show() function has two parameters a and b. When the main() method calls the test() function, it specifies that a is 6 and b is 2. However, there is a statement, a = 9, inside the test() function to reassign a new value to a. The result is: void show(int a, int b) a = 9; MessageBox::Show("a is " + a + ", and b is " + b); void main() show(6, 2); Parameters with different types may exist in a function. In other words, parameters in a function do not have to be in the same type. In the following example, the sum() function is declared as a double and it takes three paramters. The three parameters are declared as int, double, and float respectively. double sum(int x, double y, float z) return x + y + z; MessageBox::Show(sum(6, 3.5, 8.3)+""); Visual C++ Programming Penn Wu, PhD 132

13 A function and its parameters do not have to be of the same data type. In the following example, the test() function is declared to return String literal(s), but, its parameter x is declared as integer. String^ test(int x) return x + " : Apple"; void main() int x = 1; MessageBox::Show(test(x) +""); The output looks: The following is another example that demonstrates how parameters and the function can have completely different types. String^ sum(int x, double y, float z) return (x + y + z) + ""; MessageBox::Show(sum(6, 3.5, 8.3)); The following is another complete code that demonstrates how to use parameters of different types in a function. #include "InputBox.cpp" Visual C++ Programming Penn Wu, PhD 133

14 String^ cost(string^ productid, int qty, float unitprice) return "Total of " + productid + ": $" + Math::Round(qty * unitprice, 2); int x = Convert::ToInt16(InputBox::Show("The quantity: ")); inputbox2.input("enter the unit price: "); float y = Convert::ToDouble(inputBox2.Text); MessageBox::Show(cost("M1893", x, y)); In the following example, the shuffe function takes an int array as parameter and returns an array to its calling party. array<int>^ shuffle(array<int>^ x) Random^ rn = gcnew Random(); int temp; int n; int max = x->length; for (int i=max-1; i>=0; i--) temp = x[i]; n = rn->next(max); x[i] = x[n]; x[n] = temp; return x; array<int>^ x = gcnew array<int>(54); for (int i = 0; i< 54; i++) x[i] = i; shuffle(x); String^ str = ""; for (int i = 0; i< 54; i++) str += x[i] + " "; Visual C++ Programming Penn Wu, PhD 134

15 Type sensitivity C++ functions are type-sensitive. The declared type strictly determine the result produced by the function. In the following example, int is the return type, cube is the name of function, and it requires a parameter of the int type. int cube(double n) return n*n*n; MessageBox::Show(cube(5.4) + ""); Interestingly, the calling party passes a double value as shown in the following statement, yet the return type of the function is int. Should be output be a double or an int? MessageBox::Show(cube(5.4) + ""); The answer is: the compiler will ignore the fractional part of 5.4, and treate 5.4 as 5. The result is 125 instead of This is because C++ is type-sensitive. That being said, the compiler process data based the declared data type. The avoid this type-related issue, just make sure the return type of the function is declared as double. double cube(double n) return n*n*n; MessageBox::Show(cube(5.4) + ""); Keep or not to keep the results of a function in memory When a function can return a value, you may need to think about how many times you need to use the values. In the following code, for example, the main() method calls the convert() function three times with three sets of values: (4, 6), (17, 2), and (9, 11). The convert() function performs a calculation to convert foot and inches to centimeters (one foot equals 12 inches and one inch equals 2.54 centimeters). After the calculation, the convert() function returns the results to main() method. In the main() method, the str values keeps the results by a programmer-defined format. Visual C++ Programming Penn Wu, PhD 135

16 double convert(int ft, int inch) return (ft * 12 + inch) * 2.54; // display all the result in ONE SINGLE message box String^ str = convert(4, 6) + "\n" + convert(17, 2) + "\n" + convert(9, 11); Interestingly, the calculation results are not stored in memory after the main() method passes them to str. In other words, each of the calculation results are no longer available for retrieving. They are used for only ONE-TIME! When there is a need to keep each calculation results, you can consider assign the results to an individual variables. For example, double convert(int ft, int inch) return (ft * 12 + inch) * 2.54; double n1 = convert(4, 6); double n2 = convert(17, 2); double n3 = convert(9, 11); String^ str = n1 + "\n" + n2 + "\n" + n3; str += "Sum is " + (n1 + n2 + n3) + "\n"; //still retrievable str += "Average is " + (n1 + n2 + n3)/3; //still retrievable Can functions become reusable code? One of the benefits to create function is to make the code reusable. In other words, the codes inside a function can be called over and over again to produce similar but different results. In the following codes, the instructor creates an inc() function which has an integer parameter max. This inc() function can perform a skip counting between from 1 to 49, but the increment Visual C++ Programming Penn Wu, PhD 136

17 is determined by max. After calculation is performed, this inc() function will return the results to it calling party (the Show() method). String^ inc(int max) String^ str; // private property of inc for (int i=1; i<50; i+=max) str += i + "\n"; return str; String^ str = inc(7) + "\n"; // private property of main str += inc(3) + "\n"; str += inc(11); This inc() function is reusable because you can keep on calling it by sending a different parameter (e.g. 7, 3, 11). The inc() will perform the skip counting accordingly. By the way, the inc() method is declared as a String function because the instruction meant to let its return values string literals. This code also demonstrates that every function can have its very own properties. There are two private str variables: one belongs to inc(); the other belong to main(). Since they are declared inside both inc() and main() functions, their scopes are limited to the function they belong to. Remember the formula that To convert from Fahrenheit to Celsius? F=(C 9/5) + 32 You can create a function to calculate a range (from minimum to maximum) and allow the calling party to assign what minimum and maximum values are. In the following example, the convert() function is called three times by the main() function. This code also demonstrates how a variable is used as a private property. String^ convert(double min, double max) String^ str; // property of convert for (double i=min; i<=max; i++) //increment by 1 str += ((i * 9)/5 + 32) + "\n"; Visual C++ Programming Penn Wu, PhD 137

18 return str; String^ str = convert(10, 55) + "\n"; // property of main str += convert(5, 14) + "\n"; str += convert(12, 37); In the above code, the instructor declares the two parameters, min and max, as double, because the instructor anticipates that the calculation results are often floating-point values (e.g. 33.8, 93.2). Likewise, the variable i is declared as double type. You can re-write the above code by changing the convert() function to a void function, and still get the same results. for example, void convert(double min, double max) String^ str; for (double i=min; i<=max; i++) //increment by 1 str += ((i * 9)/5 + 32) + "\n"; convert(10, 55); convert(5, 14); The difference between void and value-returning function is how the function handles the calculation results. In a non-void function, the value must be returned to its calling party. The value-returning function is more like a supporting party. In a void function, the function does not return the results, it has the privilege to decide how to handle the results. At the nut shell, functions make an application easier to develop by allowing programmers to break it down into smaller pieces. These smaller pieces are then, in code, fitted together to perform all your application's tasks. When you create a function, you gain the ability to logically group related statements and to focus on writing your application one function at a time. int vs. void main() Every C++ program requires a function named main(), which is the starting point of the program. Visual C++ compiler expects the main function to have a default return type int. Visual C++ Programming Penn Wu, PhD 138

19 However, you can declare the main() as a void function. It is the Unix convention to have an function that must return a value to the operating system; therefore, an int type of main() function usually has a return statement that returns an integer 0 to the operating systems. Interestingly, this convention is not required in Visual C++. A void main() function does not return any value. For example, // not void using namespace System::Windows::Forms; String^ str=""; for (float x =0; x<2; x+=0.4) str += x + "\t" + Math::Sin(x) +"\n"; // void using namespace System::Windows::Forms; void main() String^ str=""; for (float x =0; x<2; x+=0.4) str += x + "\t" + Math::Sin(x) +"\n"; Both sample codes produce the same output: With the Standard C++, if you want to terminate the program from within a user-defined function other than the main() function, you cannot simply use a return statement. The return statement will only terminate the current function and return control to the invoking function. You need to use the exit() function. For example, #include <iostream> using namespace std; double reciprocal(double x) if (x == 5) exit(1); else return 1.0/x; for (double x = 1.0; x <= 10.0; x+=1.0) cout << reciprocal(x) << endl; Visual C++ Programming Penn Wu, PhD 139

20 This program will be terminated when the main() function attempts to pass the value 5 to the reciprocal() function. The termination is caused by the exit(1) statement. The output looks: Review Questions 1. Given the following code, which is a user-defined function? #include <cmath> A. acos() B. sqr() C. sqrt() D. main() double sqr(double x) return x * x; String^ str=""; str += acos(0.2) + "\n"; str += sqr(0.2) + "\n"; str += sqrt(0.2); 2. Which is a correct declaration and creation of a user-defined function in C++? A. void getit(int x) return x; B. String^ getit() return 5; C. int getit(int x) return x; D. int getit() return x+""; 3. In C++ a void function is. A. a function that simply does nothing. B. a function that simply returns no value. C. a function that simply is disabled. D. a function that has a name void. 4. Given the following code segment, which statement of the main() method can call the function and display the calculation result in a message box and output must be 5? int x; void setx() x = 5; A. setx(); Visual C++ Programming Penn Wu, PhD 140

21 B. setx(); MessageBox::Show(x+""); C. MessageBox::Show(setX()+""); D. MessageBox::Show(x+""); 5. Given the following code segment, which statement of the main() method can call the function and display the calculation result in a message box? double avg(double x, double y) return (x + y) / 2; A. avg(5.1, 7.9); B. avg(5.1, 7.9) + ""; C. MessageBox::Show(avg(5.1, 7.9)); D. MessageBox::Show(avg(5.1, 7.9) + ""); 6. In the following code segment, what does the return statement do? double avg(double x, double y) return (x + y) / 2; A. It simply tells the computer to start the calculation. B. It specifies the value the function will send back to the calling party. C. It indicates that the calculation should only be performed when the user presses the [Return] (or [Enter]) key. D. It returns the values of x and y to the physical memory. 7. Given the following code segment, the output is. A. 3 B. 4 C. 5 D. m void show(int n, int m) n = 3; m = n; MessageBox::Show(m + ""); void main() show(4, 5); 8. Given the following code segment, the output is. String^ test(int x) return x + "234"; Visual C++ Programming Penn Wu, PhD 141

22 A. 1 B. 12 C. 123 D void main() int x = 1; MessageBox::Show(test(x) +""); 9. Given the following code segment, which statement of the main() method will produce a "null" value, an exception or an error message? A. test(4); B. test(4.5); C. test((4 / 2)); D. test("4/2")); void test(double x) MessageBox::Show(x.GetType() + ""); 10. Given the following code segment, the output is. A. 5*5*5 B. 125 C. n*n*n D. 0 void cube(int n) MessageBox::Show(""+n*n*n); cube(5); Visual C++ Programming Penn Wu, PhD 142

23 Lab #5 C++ Functions Learning Activity #1: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab5_1.cpp and press [Enter] to use Notepad to create a new source file called lab5_1.cpp with the following contents: int x, y; double ft2inch(int ft, int inch) return ft * 12 + inch; //One foot equals 12 inches double inch2cm(int inch) return inch * 2.54;//one inch equals 2.54 centimeters void getxy(int i) Random^ rn = gcnew Random(i); x = rn->next(1, 12); y = rn->next(1, 12); // String^ str = "ft\tinch\tcm\n"; getxy(1); // get x and y str += x + "\t" + y + "\t" + inch2cm(ft2inch(x, y)) + "\n"; getxy(2); // get x and y str += x + "\t" + y + "\t" + inch2cm(ft2inch(x, y)) + "\n"; getxy(3); // get x and y str += x + "\t" + y + "\t" + inch2cm(ft2inch(x, y)) + "\n"; 3. Type cl /clr lab5_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab5_1.exe and press [Enter] to test the executable file. A sample output looks: Visual C++ Programming Penn Wu, PhD 143

24 5. Download the assignment template, and rename it to lab5.doc if necessary. Capture a screen shot similar to the above figure and paste it to the Word document named lab5.doc (or.docx). Learning Activity #2: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab5_2.cpp and press [Enter] to use Notepad to create a new source file called lab5_2.cpp with the following contents: double calc_sin(double x) return Math::Sin(x); String^ str="sin\n"; for (double x =0; x<2; x+=0.1) str += x + "\t" + calc_sin(x) + "\n"; // call calc_sin() 3. Type cl /clr lab5_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab5_2.exe and press [Enter] to test the executable file. A sample output looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab5.doc (or.docx). Visual C++ Programming Penn Wu, PhD 144

25 Learning Activity #3: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab5_3.cpp and press [Enter] to use Notepad to create a new source file called lab5_3.cpp with the following contents: float calc_sq(float y) return y*y; float calc_sqrt(float y) return Math::Sqrt(y); // calculate square root String^ str; for (float i = 1; i < 10; i++) str += i + "\t" + calc_sq(i) + "\t" + calc_sqrt(i) + "\n"; 3. Type cl /clr lab5_3.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab5_3.exe and press [Enter] to test the executable file. A sample output looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab5.doc (or.docx). Learning Activity #4: User-defined function 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Make sure the InputBox.cpp file is in the C:\cis223 directory. (See Lab #2) 3. Type notepad lab5_4.cpp and press [Enter] to use Notepad to create a new source file called lab5_4.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 145

26 #include "InputBox.cpp" double avg(int x, int y, int z) return double (x + y + z)/3; int min(int x, int y, int z) int min = x; if (y<min) min = y; if (z<min) min = z; return min; int x, y, z; x = Convert::ToInt32(InputBox::Show("Enter the first integer:")); y = Convert::ToInt32(InputBox::Show("Enter the second integer:")); z = Convert::ToInt32(InputBox::Show("Enter the third integer:")); String^ str = "Average is " + avg(x,y,z) + "\n"; str += "Minimal is " + min(x,y,z) + "\n"; 4. Type cl /clr lab5_4.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 5. Type lab5_4.exe and press [Enter] to test the executable file. A sample output looks: and and and 6. Capture a screen shot similar to the above figure and paste it to the Word document named lab5.doc (or.docx). Learning Activity #5: void function 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab5_5.cpp and press [Enter] to use Notepad to create a new source file called lab5_5.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 146

27 void convert(double min, double max) String^ str; for (double i=min; i<=max; i++) //increment by 1 str += ((i * 9)/5 + 32) + "\n"; convert(5, 14); convert(10, 50); 3. Type cl /clr lab5_5.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab5_5.exe and press [Enter] to test the executable file. A sample output looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab5.doc (or.docx). Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab5.zip containing ONLY the following self-executable files. Lab5_1.exe Lab5_2.exe Lab5_3.exe Lab5_4.exe Lab5_5.exe Lab5.doc (or lab5.docx or.pdf) [You may be given zero point if this Word document is missing] 3. Log in to Blackboard, and enter the course site. 4. Upload the zipped file to Question 11 of Assignment 05 as response. 5. Upload ex05.zip file to Question 12 as response. Note: You will not receive any credit if you submit file(s) to the wrong question. Visual C++ Programming Penn Wu, PhD 147

28 Programming Exercise 05: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex05.cpp. 3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex05.cpp //Programmer: [YourFullNameHere] 4. Given the following statement, write a program that contains one user-defined function named cal which takes three integer parameters: hour, minute, and seconds, as in cal(int hour, int minute, int second), and calculate the total values in seconds. For example, the result of cal(2, 57, 21) is (because 2*60* * = 10641). One hour equals 60 minutes and one minute equals 60 seconds. 5. In the main() method, add appropriate codes to call the cal function to perform the calculations according to the sets of values in the following table. Display their results in ONE single message box, as shown in Figure Ex-05. Hour Minute Second Figure Ex Compile the source code to produce executable code. 7. Download the programming exercise template, and rename it to ex05.doc if necessary. Capture Capture a screen similar to the above one and paste it to the Word document named ex05.doc (or.docx). 8. Compress the source file (ex05.cpp), executable code (ex05.exe), and Word document (ex05.doc) to a.zip file named ex05.zip. Grading criteria: You will earn credit only when the following requirements are fulfilled. No partial credit is given. You successfully submit both source file and executable file. Your source code must be fully functional and may not contain syntax errors in order to earn credit. Your executable file (program) must be executable to earn credit. Threaded Discussion Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at least two messages as responses to the question every week. Each message must be posted on a different date. Grading is based on quality of the message. Question: Class, does it matter to use an access modifier like "private" or "public" when creating a user-defined function? Do you see any benefits of using them? If you can, provide an example to support your perspective. [There is never a right-or-wrong answer for this question. Please free feel to express your opinion.] Be sure to use proper college level of writing. Do not use texting language. Visual C++ Programming Penn Wu, PhD 148

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions

More information

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal.

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal. Lecture #15 Overview Generics in Visual C++ C++ and all its descendent languages, such as Visual C++, are typed languages. The term typed means that objects of a program must be declared with a data type,

More information

However, it is necessary to note that other non-visual-c++ compilers may use:

However, it is necessary to note that other non-visual-c++ compilers may use: Lecture #2 Anatomy of a C++ console program C++ Programming Basics Prior to the rise of GUI (graphical user interface) operating systems, such as Microsoft Windows, C++ was mainly used to create console

More information

Car. Sedan Truck Pickup SUV

Car. Sedan Truck Pickup SUV Lecture #7 Introduction Inheritance, Composition, and Polymorphism In terms of object-oriented programming, inheritance is the ability that enables new classes to use the properties and methods of existing

More information

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10 Lecture #1 What is C++? What are Visual C++ and Visual Studio? Introducing Visual C++ C++ is a general-purpose programming language created in 1983 by Bjarne Stroustrup. C++ is an enhanced version of the

More information

#using <System.dll> #using <System.Windows.Forms.dll>

#using <System.dll> #using <System.Windows.Forms.dll> Lecture #8 Introduction.NET Framework Regular Expression A regular expression is a sequence of characters, each has a predefined symbolic meaning, to specify a pattern or a format of data. Social Security

More information

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition Lecture #6 What is a class and what is an object? Object-Oriented Programming Assuming that the instructor found a new breed of bear and decided to name it Kuma. In an email, the instructor described what

More information

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { }

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { } Lecture #6 User-defined functions User-Defined Functions and Delegates All C# programs must have a method called Main(), which is the starting point for the program. Programmers can also add other methods,

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

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively.

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively. Lecture #9 What is reference? Perl Reference A Perl reference is a scalar value that holds the location of another value which could be scalar, arrays, hashes, or even a subroutine. In other words, a reference

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

Methods CSC 121 Fall 2014 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that

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

C++ Data Types and Variables

C++ Data Types and Variables Lecture #3 Introduction C++ Data Types and Variables Data is a collection of facts, such as values, messages, or measurements. It can be numbers, words, measurements, observations or even just descriptions

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

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

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

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

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

Programming Language. Functions. Eng. Anis Nazer First Semester

Programming Language. Functions. Eng. Anis Nazer First Semester Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities

More information

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

More information

public class Animal // superclass { public void run() { MessageBox.Show("Animals can run!"); } }

public class Animal // superclass { public void run() { MessageBox.Show(Animals can run!); } } Lecture #8 What is inheritance? Inheritance and Polymorphism Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined

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

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

Function. Mathematical function and C+ + function. Input: arguments. Output: return value Lecture 9 Function Mathematical function and C+ + function Input: arguments Output: return value Sqrt() Square root function finds the square root for you It is defined in the cmath library, #include

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

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

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

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Introduction to the C++ Programming Language

Introduction to the C++ Programming Language LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming

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

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs. 1 3. Functions 1. What are the merits and demerits of modular programming? Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

The following table distinguishes these access modifiers.

The following table distinguishes these access modifiers. Lecture #7 Introduction User-Defined Functions and Delegates In programming, a function is defined as named code block that can perform a specific task. Some programming languages make a distinction between

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7 Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7 Ziad Matni Dept. of Computer Science, UCSB Programming in Multiple Files The Magic of Makefiles!

More information

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

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

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

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

CSE100 Principles of Programming with C++

CSE100 Principles of Programming with C++ 1 Instructions You may work in pairs (that is, as a group of two) with a partner on this lab project if you wish or you may work alone. If you work with a partner, only submit one lab project with both

More information

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

Week 4 EECS 183 MAXIM ALEKSA. maximal.io Week 4 EECS 183 MAXIM ALEKSA maximal.io Agenda Functions Scope Conditions Boolean Expressions Lab 2 Project 2 Q&A Lectures 15% 36% 19% 8:30am 10:00am with Bill Arthur 10:00am 11:30am with Mary Lou Dorf

More information

Programming with C++ as a Second Language

Programming with C++ as a Second Language Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to

More information

Local and Global Variables

Local and Global Variables Lecture 10 Local and Global Variables Nearly every programming language has a concept of local variable. As long as two functions mind their own data, as it were, they won t interfere with each other.

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

Preprocessor Directives

Preprocessor Directives C++ By 6 EXAMPLE Preprocessor Directives As you might recall from Chapter 2, What Is a Program?, the C++ compiler routes your programs through a preprocessor before it compiles them. The preprocessor can

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

pointers + memory double x; string a; int x; main overhead int y; main overhead

pointers + memory double x; string a; int x; main overhead int y; main overhead pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;

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

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

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

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

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

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

Chapter 3 Function Basics

Chapter 3 Function Basics Chapter 3 Function Basics Learning Objectives Predefined Functions Those that return a value and those that don t Programmer-defined Functions Defining, Declaring, Calling Recursive Functions Scope Rules

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

بسم اهلل الرمحن الرحيم

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

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

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Computer Programming, I. Laboratory Manual. Experiment #7. Methods Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #7

More information

COP 2000 Note Framework Chapter 5 - Repetition Page 1

COP 2000 Note Framework Chapter 5 - Repetition Page 1 COP 2000 Note Framework Chapter 5 - Repetition Page 1 The programming approach in which all problems are broken down using only three simple control structures, each of which has only one starting point

More information

Binomial pricer (1.1)

Binomial pricer (1.1) 1 Binomial pricer 1.1 Program shell 1.2 Entering data 1.3 Functions 1.4 Separate compilation 1.5 CRR pricer 1.6 Pointers 1.7 Function pointers 1.8 Taking stock In the binomial model the prices of assets

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Unit 7. 'while' Loops

Unit 7. 'while' Loops 1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

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

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Name Section: M/W or T/TH. True or False (14 Points)

Name Section: M/W or T/TH. True or False (14 Points) Name Section: M/W or T/TH True or False (14 Points) 1. (14 pts) Circle T for true and F for false: T F a) In C++, a function definition should not be nested within another function definition. T F b) Static

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; } Ex: The difference between Compiler and Interpreter The interpreter actually carries out the computations specified in the source program. In other words, the output of a compiler is a program, whereas

More information

Lecture 9 - C Functions

Lecture 9 - C Functions ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin

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

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #12 Handling date and time values Handling Date and Time Values In the.net Framework environment, the DateTime value type represents dates and times with values ranging from 12:00:00 midnight,

More information

Data Source. Application. Memory

Data Source. Application. Memory Lecture #14 Introduction Connecting to Database The term OLE DB refers to a set of Component Object Model (COM) interfaces that provide applications with uniform access to data stored in diverse information

More information

Programming Exercise 7: Static Methods

Programming Exercise 7: Static Methods Programming Exercise 7: Static Methods Due date for section 001: Monday, February 29 by 10 am Due date for section 002: Wednesday, March 2 by 10 am Purpose: Introduction to writing methods and code re-use.

More information

3.1. Chapter 3: The cin Object. Expressions and Interactivity

3.1. Chapter 3: The cin Object. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,

More information

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018 Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its

More information

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. The basic commands that a computer performs are input (get data), output (display result),

More information

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (! FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. Assume that all variables are properly declared. The following for loop executes 20 times.

More information

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors Announcements CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start

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

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

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

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) Class 2: Variables and Memory Variables A variable is a value that is stored in memory It can be numeric or a character C++ needs to be told what type it is before it can store it in memory It also needs

More information

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information