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

Size: px
Start display at page:

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

Transcription

1 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 applications for a non-gui operating systems like MS- DOS. A console application is a computer program that runs in a text-only computer interface, such as the Command Prompt (or MS-DOS), and it does not support GUI. It mainly reads textonly inputs from the keyboard and produce text-only outputs to the screen. In a sense, it is easier and simpler to create a console application. Most textbooks, thus, teaching C++ programming by leading students to create console applications. Interestingly, most students who were born after 1990 s are more familiar with GUI applications and may have little or no experience in MS- DOS. In order to understand the difference between a console application and a GUI-based application, this lecture will review the anatomy of simple C++ console application before the learning of basic programming skills of GUI applications. Consider the following lab2.cpp file, which is a simple C++ console program that uses the cout method to produce string outputs on the screen. You can create this file using Notepad of the Windows OS. // Filename: lab2.cpp #include <iostream> std::cout << "Welcome to Visual C++!" << std::endl; To compile this source file to object file, type the following in a Visual Studio 201n (Developer) Command Prompt (assuming the file is saved to c:\cis223 directory). C:>Program Files\Microsoft Visual Stuio 14.0\VC>cd c:\cis223 C:\cis223>cl lab2.cpp C++ source files are commonly named with filename extension.cpp, such as mycode.cpp, although.cp,.c,.cc, and.cxx may be seen in other C++ compilers environment, too. This lecture recommends the use of.cpp extension as it is used by Visual C++. The iostream file is a basic header file that provides C++ standard library code developed for basic inputs/outputs in most C++ console applications. A header file is generally used to define an interface or set of interfaces within an application. Think of a header file as something that provides the external functionality of a program while omitting the technical implementation details. A header file is also an individual file that allows programmers to separate certain elements of a program s source code into reusable files. In Standard C++, header files use the extension.h for distinguishing purpose. Interestingly, Visual C++ does not require the.h extension. This course, with respect to Visual C++, follows Microsoft s syntax of using preprocessor directive, which is shown below: #include <iostream> // used by this course However, it is necessary to note that other non-visual-c++ compilers may use: #include <iostream.h> // NOT used by this course The most common header files are: iostream: Input/Output, interaction with the program. write, getline. Visual C++ Programming Penn Wu, PhD 23

2 fstream: File input/output. open, close, getline iomanip: For manipulating text with width, tabs, etc. stdlib: Standard library for memory allocation, makes it possible to create integer variables, doubles, floats, etc. sstream: C++ has no built-in string handling. Use this library to copy strings, find string length, etc. stdio: Similar to stdlib but also has some file functions. printf, scanf. The #include directive tells the preprocessor to copy the source code in the iostream file to the above code. A preprocessor is a computer program that modifies data to conform with the input requirements of another program. This statement always looks: #include <iostream> In C++, a preprocessor performs preliminary operations on C++ files before they are passed to the compiler. The preprocessor conditionally compile code, insert files, specify compile-time error messages, and apply machine-specific rules to sections of code. C++ manages its library codes in namespace. A namespaces is a group of entities like classes, objects and methods. For example, the std namespace provides basic input/output methods including: cin: The standard input stream. It can accept inputs from the keyboard. cout: The standard output stream. It can display a string on screen. cerr: Standard output stream for errors. endl: Inserts a new-line character. The scope resolution operator (::) in C++ allows the current program to use methods (or members) of a class or a namespace. A C++ class is a data structure that provides an organized way to implement data in C++. A namespace is a package of classes, so all the classes can be referenced by a single identifier. In the Standard C++, methods like cin and cout are defined in the std namespace; therefore, it requires the scope resolution operator (::), as shown below, to specify what namespace or class a method belongs to. By the way, such an unambiguous name that specifies which object, function, or variable is called a fully qualified name in computer programming. and, std::cout std::endl The following is the statement that demonstrates how to use the scope resolution operator to specify the correct namespaces. Interestingly, it is very redundant to use scope resolution operator over and over again. std::cout << "Welcome to Visual C++!" << std::endl; The using directive declares the members of a namespace to be used in the source file; therefore, programmers can use the member methods by name without using the scope resolution operator to specify the namespace as an explicit qualifier. The following statement, for example, allows all resources in a namespace std to be used without the namespace-name as an explicit qualifier. using namespace std; Visual C++ Programming Penn Wu, PhD 24

3 By officially declare the use of the std namespace, programmers can use the so-called unqualified names of methods (e.g. cout and endl) can be recognized by the compiler. #include <iostream> using namespace std; cout << "Welcome to Visual C++!" << endl; In other words, the using namespace std; statement tells the compiler that the default namespace is std, so automatically assume the namespace is std if any method (such as cout) is not pre-scoped with its namespace. A header file is generally used to define an interface or set of interfaces within an application. Think of a header file as something that provides the external functionality of a program while omitting the technical implementation details. A header file is also an individual file that allows programmers to separate certain elements of a program s source code into reusable files. In Standard C++, header files use the extension.h for distinguishing purpose. Interestingly, Visual C++ does not require the.h extension. This course, with respect to Visual C++, follows Microsoft s syntax of using preprocessor directive, which is shown below: #include <iostream> // used by this course However, it is necessary to note that other non-visual-c++ compilers may use: #include <iostream.h> // NOT used by this course The most common header files are: iostream: Input/Output, interaction with the program. write, getline. fstream: File input/output. open, close, getline iomanip: For manipulating text with width, tabs, etc. stdlib: Standard library for memory allocation, makes it possible to create integer variables, doubles, floats, etc. sstream: C++ has no built-in string handling. Use this library to copy strings, find string length, etc. stdio: Similar to stdlib but also has some file functions. printf, scanf. The above code also illustrates the bare-minimum anatomy of a C++ program. Every C++ program must have a main() method, which is the starting point of the program. Starting point means it is the first part of the program that the computer attempts to read for execution. The main() function must be present in any C++ program with the following format. statements Every C++ instruction is a statement, which ends with a semicolon (;). The keyword int indicates that the main() method must return a value to its calling party which is the operating systems in thi case. The statement will return the value 0 to the operating system to indicate that the program ended normally. Visual C++ Programming Penn Wu, PhD 25

4 Alternately, the main() functions can be declared as void (which means it does not return any value). If you declare main() as void, you do not need to return an exit code to the parent process or operating system using a return statement. Interestingly, C++ allows you to return an exit code with the exit() function when main() is declared as void. The following is the void version of the above C++ code. #include <iostream> using namespace std; // std is a namespace void main() cout << "Welcome to Visual C++!" << endl; exit(0); The cout method is a system method (meaning it comes with the Standard C++ language) to display a variety of things, such as strings, numbers, and individual characters, on the screen. In the following example, the cout method sends a string to the screen: cout << "Welcome to Visual C++!"; A string is a series of characters enclosed in double (or single) quotation marks. Blank spaces inside the quotes are characters as well. Therefore, a string apple tree has 10 characters in it. The two less than signs, <<, is known as insertion operator which indicates the direction of output flows. In a console, the output direction is from the cout method to the screen. For example, #include <iostream> using namespace std; int x, y; // declare two integer variables x and y x = 3; // assign 3 as value of x y = 4; cout << (x * y) << endl; The output is 12, which is the result of x * y because x is 3 and y is 4 (3 * 4). The endl method is used to produce a blank line in the output. For example, the following statement will not display any character, but it does move cursor to the next line. Similarly, cout << endl; #include <iostream> using namespace std; Visual C++ Programming Penn Wu, PhD 26

5 cout << "Hello, " << endl << "world!"; will yield the output of: Hello, world! The cin methods takes inputs given by the users and from the keyboard and processes them. The cin method also pauses a program during execution to allow the user to type an entry. The syntax is: For example, cin >> VariableName; #include <iostream> using namespace std; int age; // declare an integral variable cout << "How old are you? "; cin >> age; cout << "You are " << age << " years old!" << endl; In this example, the cin >> Age; line causes the program to wait for the user to type a value and press [Enter]. It then assigns the value to a variable named age. The cin method is the console input stream, and is a member of the std namespace as specified in the iostream header file. Adding comments Programmers often add comments inside the source file as a note to themselves or other programmers. They are explanatory statements to help human readers understand the source code. All comments are ignored by the compiler. Adding comments do not affect the execution speed of the program, because the compiler does not read and compile them into object codes. C++ language accepts two types of comments: The /* (slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the */ characters. This syntax is the same as ANSI C. The // (two slashes) characters, followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of comment. Therefore, it is commonly called a "single-line comment." The following example illustrates how they work. The lines between /* and */ (enclosed by the dashed borders) are ignored by the compiler, so does the single line after //. /* This file is designed to be an example for CIS223 ONLY! Filename: lab2.cpp */ #include <iostream> Visual C++ Programming Penn Wu, PhD 27

6 using namespace std; // std is a namespace cout << "Welcome to Visual C++!" << endl; From console to GUI Source codes of a console application (non-gui), such as the following, can be converted to codes of a GUI-based Window application. As stated in the previous lecture, GUI-based Windows applications are managed code. #include <iostream> using namespace std; cout << "Welcome to Visual C++!" << endl; The following is the GUI-based version of code. The next section will discuss the.dll file in details. MessageBox::Show("Welcome to Visual C++!" ); The output looks: The following is a Windows Form with a Label control that displays the same message. The Label control of the.net Framework supports several properties such as Text which stores the contents of the Label control, and AutoSize that allows the form to automatically adjust the size of the Label control. Form^ form1 = gcnew Form; Label^ label1 = gcnew Label; Visual C++ Programming Penn Wu, PhD 28

7 label1->text = "Welcome to Visual C++!"; label1->autosize = true; form1->controls->add(label1); Application::Run(form1); The output looks: A later lecture will discuss about hand-coding Windows forms in details. Common Visual C++ libraries A library in C++ is a collection of already-compiled code (known as a module) to be accessed by the code you will write. A simple library can provide basic input/output functions. A complicated one can support the implementation of a particular interface or set of interfaces. The.NET Framework provide libraries to prevent code duplication and encourage re-use. A library can be statically-linked (.lib) or dynamically-linked (.dll). Similar to the header files, code defined in a library is meant to prevent code duplication and encourage re-use. Visual C++ compiler is an optimized C/C++ Compiler designed for Microsoft s.net Framework. In addition to the support of standard C++ language, it also works with.net Framework which recognize several types of header file and libraries including:.h: Traditional header file. It is a source file containing declarations (as opposed to.cpp.cxx etc. containing implementations).lib: Static library that may contain code or just links to a dynamic library. They either declare the binary interface to a dynamic library (DLL) or contain the binary code of a library..dll: Dynamic library. A dynamic link library (DLL) is a collection of small programs, which can be called upon when needed by the executable program (EXE) that is running. Many GUI-based applications created by Visual C++ require the references of dynamic libraries provided by the.net Framework. Consider the following sample code, which references to Windows DLL files. MessageBox::Show("Welcome to CIS223!"); Visual C++ Programming Penn Wu, PhD 29

8 The output looks: The System.dll file is able to monitor applications, manipulate other programs. The System.Windows.Forms.dll file provides basic functions of a Windows form, such as the message box. With these two files and the following using statements, you can call methods provided by the.net Framework (e.g. MessageBox::Show() method) to help you program GUIbased applications. using namespace System::Drawing; The above are the three most frequently referenced namespaces. The using directive allows the members in these namespaces to be referenced without specifying the fully qualified names. You will see the frequently throughout this course. It is necessary to note that Visual C++ does not support a generic GUI-based input box (or prompt box) to take inputs from keyboard. The instructor has to create the following codes and save it as an individual C++ library file (e.g. InputBox.cpp ). This file can be included in other C++ source file through the use of include directive to create a Windows form that serves as an input box. This newly created input box can then take the inputs from keyboard and pass them to it calling party. Do not worry about it if you cannot understand the following code. A later lecture will discuss the details to hand-code Windows form applications. //InputBox.cpp #using <System.Drawing.dll> using namespace System::Drawing; public ref struct InputBox private: Form^ form1; private: Label^ label1; private: TextBox^ textbox1; public: static String^ Text; private: Void button1_click(object^ sender, EventArgs^ e) if (textbox1->text == "") MessageBox::Show("No value given."); Text = ""; else Text = textbox1->text; form1->close(); Visual C++ Programming Penn Wu, PhD 30

9 public: static String^ Show(String^ s) Text = s; InputBox(); return Text; public: InputBox() form1 = gcnew Form; form1->size = Size(300, 160); label1 = gcnew Label; label1->size = Size(260, 25); label1->text = Text; label1->location = Point(10, 10); form1->controls->add(label1); textbox1 = gcnew TextBox; textbox1->size = Size(260, 25); textbox1->location = Point(10, 40); form1->controls->add(textbox1); Button^ button1 = gcnew Button; button1->location = Point(200, 80); button1->text = "OK"; button1->click += gcnew EventHandler(this, &InputBox::button1_Click); form1->controls->add(button1); Application::Run(form1); ; With the above codes as a header file, you can now write the following codes (in another individual source file such as myinput.cpp ) to take inputs from keyboard and then display the results in a message box. #include "InputBox.cpp" String^ str = InputBox::Show("What is your name?"); MessageBox::Show("Welcome, " + str + "!"); The str variable is declared with a handle (^). In a managed code written in Visual C++, the handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible. A variable that is declared with the handle declarator behaves like a pointer to the object. However, the variable points to the entire object, cannot point to a member of the object, Visual C++ Programming Penn Wu, PhD 31

10 and it does not support pointer arithmetic. Use the indirection operator (*) to access the object, and the arrow member-access operator (->) to access a member of the object. The InputBox::Show() method returns a string; therefore, its output can be assigned to a string variable such as str in the above code. To compile, use the following: The output looks: cl.exe /clr 1.cpp /link /subsystem:windows /ENTRY:main The following is another example that uses the output of Input::Show() method as content of the MessageBox::Show() method. #using <System.Drawing.dll> #include "InputBox.cpp" //import code from custom-made library and using namespace System::Drawing; MessageBox::Show(InputBox::Show("How old are you?")); The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. You can organize constant and macro definitions into include files and then use #include directives to add these definitions to any source file. Include files are also useful for incorporating declarations of external variables and complex data types. You need to define and name the types only once in an include file created for that purpose. Concept of escape sequence Programming languages uses wildcard character to present special functions or to define a special meaning to be used within string literals. A wildcard character is special symbol that stands for one or more characters, it is used in a way that is different from its dictionary definition. For example, a pair of double quotes (") is used in C++ to enclose a string literal, as shown below. "How are you?" Interestingly, the uses of wildcard character in programming frequently cause confusing. The following code simply causes syntax error because programming languages like C++ considers a pair of double quotes (") as to denote the start and the end of a string literal. According to the following code, there are two string literals: "He said, " and "". #include <iostream> using namespace std; Visual C++ Programming Penn Wu, PhD 32

11 cout << "He said, "How are you?""; The following is a sample of error message you should receive when you compile the above code. The compiler is confused by all the double quotes ("). c:\program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc 1.cpp(8) : error C2146: syntax error : missing ';' before identifier 'How' 1.cpp(8) : error C2065: 'How' : undeclared identifier 1.cpp(8) : error C2146: syntax error : missing ';' before identifier 'are' 1.cpp(8) : error C2065: 'are' : undeclared identifier 1.cpp(8) : error C2146: syntax error : missing ';' before identifier 'you' 1.cpp(8) : error C2065: 'you' : undeclared identifier 1.cpp(8) : error C2143: syntax error : missing ',' before ';' Escape sequences are typically used to provide such literal mis-representations. It releases a wildcard character or characters that usually have special meanings, such as the double quotation mark ("), from their language-specific definitions. Thus, escape sequence forces the compiler to interprete a special wildcard character by its dictionary definition. So, how would you display the following string? He said, "How are you?" Using the backslash (\) to escape character is the solution to this problem. The backslash forces the compiler to escape from the interpretation of a wildcard character next to the backslash in a string. Placing a backslash before the double quote mark forces the computer to retreat the double quote as a double quote, not an indicator of start or end of a string literal. The following demonstrates the correct way to write the code. // code 1 #include <iostream> using namespace std; cout << "He said, \"How are you?\""; The GUI version of the above code is: MessageBox::Show("He said, \"How are you?\""); The output looks: Visual C++ Programming Penn Wu, PhD 33

12 Invented by Bob Bemer, an escape sequence is two or more characters that often begin with \ to tell the computer to perform a function or a command or specify actions such as carriage returns and tab movements on terminals and printers. The following table lists the character escapes supported by regular expressions in the.net Framework. sequence Description \a Equals to a bell (alarm) character, \u0007. Console only. \t Equals to a tab, \u0009. \r Equals to a carriage return, \u000d. Note that \r is not equivalent to the newline character, \n. \v Equals to a vertical tab, \u000b. \f Equals to a form feed, \u000c. \n Equals to a new line, \u000a. \e Equals to an escape, \u001b. The following code uses \t (tab key) to add indents. It also uses \n to add a new line. String^ str = "City\tState\tZipCode\n"; str += "Burbank\tCA\t91510\n"; str += "Ingham \tmi\t48908\n"; str += "Houston\tTX\t77003\n"; MessageBox::Show(str); The output looks. Try the following program, and observe its result. Is it an ASCII art? Visual C++ Programming Penn Wu, PhD 34

13 void main() String^ str=""; str+= " \\/\\/\\/\\/ " + "\n"; str+= " " + "\n"; str+= " " + "\n"; str+= " (o) (o) " + "\n"; str+= " C _) " + "\n"; str+= ", " + "\n"; str+= " / " + "\n"; str+= " / \\ " + "\n"; str+= " / \\ " + "\n"; str+= "\n"; MessageBox::Show(str); The output looks: Expression and Operators An expression in a programming language is the sequence of operators and operands that are used for performing a special task, such as the performing of basic arithmetic calculations: addition (+), subtraction (-), multiplication (*), and division (/). C++ expressions are typically sequences of operators and operands that are used for computing a value from the operands or designating objects and/or functions. For example, total = unit_price * quantity; Other samples of expressions are: 1 6 * 7 a + b * 3 sin(3) + 7 a > b a? 1 : 0 func() mystring + gimmeastring() + std::string("\n") The following illustrates how to perform simple calculations by writing valid expressions with arithmetic operators. The Label control of the.net Framework supports several properties such as Text which stores the contents of the Label control, and AutoSize that allows the form to automatically adjust the size of the Label control. A control is a graphical user interface (GUI) of a Windows form application. Visual C++ Programming Penn Wu, PhD 35

14 void main() Form^ form1 = gcnew Form; Label^ label1 = gcnew Label; label1->autosize = true; form1->controls->add(label1); // add label to form String^ str=""; // NULL value str += (2+3) + "\n"; // result is 5 str += (7-5) + "\n"; // result is 2 str += (3*6) + "\n"; // result is 18 str += (21/3) + "\n"; // result is 7 str += (17%4) + "\n"; // result is 1 label1->text = str; Application::Run(form1); Notice that += is a compound operator that can append literals to an existing one to form a single literal. In the above code, the variable str was originally assigned a NULL value (blank). The += operator adds the results of (2+3) and another string \n (which means a new line ) to it,; therefore, the value of str now becomes 5\n. Then (7-5) + \n is appended to str; thus, the value of str becomes 5\n2\n (which means display 5, insert a new line, display 2, and then insert another new line ). The output of this above code is shown below. It is necessary to note that you will see this += operator frequently throughout this course. In C++, you frequently need to use parentheses when writing expressions. Parentheses have 3 usages: Grouping to control order of evaluation (operator precedence), or for clarity. Operator precedence is a set of rules that controls the order in which the compiler performs operations when evaluating an expression. E.g., (a + b) * (c - d) After a function name to enclose parameters. E.g., x = sum(a, b); Around a type name to form a type cast. E.g., i = (int) x; void main() String^ str=""; // NULL value str += ((26/4)+1) + "\n"; // 7 str += ((3*2)-4) + "\n"; // 2 MessageBox::Show(str); Visual C++ Programming Penn Wu, PhD 36

15 In general, numeric values of various types can be mixed in an expression. However, the type of the result depends on the type used in the expression. C++ promotes the value with the narrower range (the integer) to the type of value with the wider range (double). The concept can be then illustrated as: 1. an expression involving two integer variables results in an integer. 2. an expression involving two double variables results in a double. 3. an expression involving one integer variable and one double variable result in a double. This is called a promotion. Consider the following example, the output is 6, not It is because integer division truncates the decimal point of the quotient due to the first rule. The Show() method only accept string literal. However, the expression (25/4) will yield a whole number 6 because both 25 and 4 are int type of value. Objects of the int type are value of whole number (integer only); they do not allow fractional part. Although the result of calculation should be 6.25 in the sense of arithmetic s. C++ will apply the definition of data type to the result of calculation and automatically eliminate the fractional part; therefore the output is 6. MessageBox::Show((25/4) + ""); // numerical + string = string The C++ language, as well as many other programming languages, is strictly bound to the type. A later lecture will discuss the data type in details. In the above statement, the Show() method can only display string type of data. Concept of type-casting Type-casting is the concept of converting the value of one type into another type. It is often used to temporarily make a variable of one type to behave like another type for a one-time operation. To cast the type in C++, simply declare the new type inside parentheses in front of the variable name. (NewType) VariableName Type-casting is the solution if you wish to get the real value of the above division. The following example illustrates how type casting in C++ explicitly converts the type of 25 and 4 from integer (int) to a double, which allows fractional values, and the result is MessageBox::Show( double(25) / (double) 4 + ""); The above statement also provides a simple way to temporarily convert a number or other nonstring type to a string: uses the concatenation operator (+) to add a blank string ("") to it. According to the rule of Computer Programming, any type combined with a string become a string. int x = 5; String s = x + ""; // cast x to string Type casting is a feature of the language; thus, it applies to GUI and console programs. The following console code demonstrates how type-casting forces an integer variable x to act like a char. #include <iostream> using namespace std; int x = 35; int y = 36; int z = 37; Visual C++ Programming Penn Wu, PhD 37

16 cout << (char) x << endl; // change x to char cout << (char) y << endl; cout << (char) z << endl; The output looks: # $ % The GUI version of the above code is: void main() int x = 35; int y = 36; int z = 37; MessageBox::Show((char) x + "\n" + (char) y + "\n" + (char) z); The output looks: In the following example, pay close attention to the last two expressions. The keyword int converts the doubles to integers. void main() String^ str = ""; str += (25/4) + "\n"; // 6 str += (double(25)/4) + "\n"; // 6.25 str += (25/double(4)) + "\n"; // 6.25 str += (int(25.96)/(3.15)) + "\n"; // str += (int(25.96)/int(3.15)) + "\n"; // 8 MessageBox::Show(str); The output looks: Visual C++ Programming Penn Wu, PhD 38

17 It is necessary to note that expression is evaluated using a specific order of operations, or operator precedence. Multiplication and division are performed first, followed by addition and subtraction. Two operators of the same precedence are evaluated in order from left to right. Operator precedence can be changed by including parentheses in an expression. The operations within parentheses are evaluated first. By the way, the equal sign (=) is used in a statement which gives a value to a variable or constant. The.NET Frameworks provides a Convert class which converts a base data type to another base data type. They are useful tools for casting types. Details are available at Commonly used are: Method ToDouble() ToInt16() ToInt32() ToString() Description Converts the value of the specified integer to an equivalent doubleprecision floating-point number. Converts the specified value to a 16-bit signed integer. Converts the specified value to a 32-bit signed integer. Converts the specified value to its equivalent string representation. The following is an example that converts user inputs (they are string) to System::Int32. #using <System.Drawing.dll> #include "InputBox.cpp" //import code from custom-made library using namespace System::Drawing; double n1 = Convert::ToDouble(InputBox::Show("1st value:")); double n2 = Convert::ToDouble(InputBox::Show("2nd value:")); MessageBox::Show((n1/n2) + ""); Another example that converts a string to 32-bit integer is: int m = Convert::ToInt32(textBox1->Text); To convert a double type to string, you can use: MessageBox::Show(Convert::ToString(3.1412)); Visual C++ Programming Penn Wu, PhD 39

18 Using built-in functions The.NET Frameworks provides many methods for the programmers to use without spending time and efforts to develop similar features. The methods provided by the.net Framework is referred to as built-in functions in this course. The Show() and ToDouble() methods are examples of them. The Math class provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions. Details are available at The Pow() method can return a specified number of a specified power. The following code returns the result of 2 to the 5 th power. void main() MessageBox::Show(Math::Pow(2, 5)+""); It is necessary to reference the MSDN site for the syntax of these useful methods. For example, the syntax of the Round() method requires the indicator of the fractional digits to be an Int32 type. Math::Round(Double, Int32) The Math::Sqrt() method returns the square root of a specified number. The following demonstrates how to use this method. MessageBox::Show(Math::Sqrt(6.25)+""); // 2.5 Review questions 1. Given the following code, which is a "handle" in managed code of Visual C++? String^ str = InputBox::Show("How are you?"); A. String B. ^ C. str D. InputBox 2. Which is the scope resolution operator of C++? A. // B.. C. -> D. :: 3. The following statement of the main() method will return the value 0 to the to indicate that the program ended normally. Visual C++ Programming Penn Wu, PhD 40

19 A. operating system B. compiler C. memory D. the source code 4. Given the following C++ code, which line will be ignored by the compiler? /* end1 */ MessageBox::Show("Hello, " + "\n" + "world!"); A. using namespace std; B. C. /* end1 */ D. 5. Which can display the following on screen in Visual C++? Jane wrote, "I saw a cow!" A. MessageBox::Show('Jane wrote, "I saw a cow!"'); B. MessageBox::Show("Jane wrote, "I saw a cow!""); C. MessageBox::Show(Jane wrote, "I saw a cow!"); D. MessageBox::Show("Jane wrote, \"I saw a cow!\""); 6. Which is a character combination used in C++ to escape sequence? A. /t B. `t C. $t D. \t 7. The output of the following code is. A. 14 B. 2 * 7 C. (2 * 7) D. (14) int x, y; x = 2; y = 7; MessageBox::Show((x * y) + "") ; Visual C++ Programming Penn Wu, PhD 41

20 8. In C++, the output of the following code segment is. MessageBox::Show("Wait! " + "Jack" + "Kyle" + "!"); A. Wait! JackKyle! B. Wait!JackKyle! C. Wait! Jack Kyle! D. Wait! Jack Kyle! 9. The output of the following code is. A. 1 B. 1.5 C. 0 D. 0.5 MessageBox::Show((3/2) + "") ; 10. The output of the following code is. A. 2.5 B. 2 C D. Sqrt(6.25) MessageBox::Show(Math::Sqrt(6.25) + "") ; Visual C++ Programming Penn Wu, PhD 42

21 Lab #2 C++ Programming Basics Preparation #: 1. Create a new directory called C:\cis223 if it does not exist. 2. Under the C:\cis223 directory, use Notepad to create a new text file named InputBox.cpp with the following codes. Make sure it is free of typo and error. (This is a custom-made library file. It will not execute alone. It is a supportive library that will build an input box when being imported to other C++ file.) #using <System.Drawing.dll> using namespace System::Drawing; public ref struct InputBox private: Form^ form1; private: Label^ label1; private: TextBox^ textbox1; public: static String^ Text; private: Void button1_click(object^ sender, EventArgs^ e) if (textbox1->text == "") MessageBox::Show("No value given."); Text = ""; else Text = textbox1->text; form1->close(); public: static String^ Show(String^ s) Text = s; InputBox(); return Text; public: InputBox() form1 = gcnew Form; form1->size = Size(300, 160); label1 = gcnew Label; label1->size = Size(260, 25); label1->text = Text; label1->location = Point(10, 10); form1->controls->add(label1); textbox1 = gcnew TextBox; textbox1->size = Size(260, 25); textbox1->location = Point(10, 40); form1->controls->add(textbox1); Visual C++ Programming Penn Wu, PhD 43

22 Button^ button1 = gcnew Button; button1->location = Point(200, 80); button1->text = "OK"; button1->click += gcnew EventHandler(this, &InputBox::button1_Click); form1->controls->add(button1); Application::Run(form1); ; Learning Activity #1: Temperature Converter 1. Create a new directory called C:\cis223 if it does not exist. 2. Launch the Developer Command Prompt. Do not use regular Windows Command Prompt. 3. In the prompt, type cd C:\cis223 and press [Enter] to change to the C:\cis223 directory. The prompt change to: C:\cis223> 4. Type notepad lab2_1.cpp and press [Enter] to use Notepad to create a new source file called lab2_1.cpp. Click Yes if the following window appears. 5. Type the following contents: #include "InputBox.cpp" double Fd, Cd; //declare two double variables // calling the Input method String^ str = InputBox::Show("Enter a temperature value in Fahrenheit: "); Fd = Convert::ToDouble(str); // convert to double // Math::Round(value, 2) round to 2nd digit next to decimal point. Cd = Math::Round(5*(Fd-32)/9, 2); MessageBox::Show("The value in Celsius is " + Cd + "!"); Visual C++ Programming Penn Wu, PhD 44

23 6. Click File, and then Save to save the file. 7. In the prompt, type cl /clr lab2_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source code. The compiler creates a new file called lab2_1.exe. C:\cis223>cl /clr lab2_1.cpp /link /subsystem:windows /ENTRY:main Microsoft (R) 32-bit C/C++ Optimizing Compiler Version /out:lab2_1.exe lab2_1.obj 8. Type lab2_1.exe and press [Enter] to test the program. A sample output looks: 9. Download the assignment template, and rename it to lab2.doc if necessary. Capture a screen shot similar to the above figures and paste it to the Word document named lab2.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 lab2_2.cpp and press [Enter] to use Notepad to create a new source file called lab2_2.cpp with the following contents: #include "InputBox.cpp" and String^ FullName; //Declare a string variable double Qty, Uprice, Total; FullName = InputBox::Show("Enter your full name: "); // convert to double Qty = Convert::ToDouble(InputBox::Show("Enter the quantity: ")); Uprice = Convert::ToDouble(InputBox::Show("Enter the unit price: ")); Total = Qty * Uprice; MessageBox::Show(FullName + ", the total is $" + Total + "!"); 3. Type cl /clr lab2_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab2_2.exe and press [Enter] to test the executable file. A sample output looks: Visual C++ Programming Penn Wu, PhD 45

24 5. Capture a screen shot similar to the above figures and paste it to the Word document named lab2.doc (or.docx). Learning Activity #3: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab2_3.cpp and press [Enter] to use Notepad to create a new source file called lab2_3.cpp with the following contents: #include "InputBox.cpp" double Mass, Energy, Hr, Wt; // convert to double and pass value Mass = Convert::ToDouble(InputBox::Show("Enter the mass: ")); Energy = Mass * 3e8 * 3e8; // 3e8 means 3*10^8 MessageBox::Show("It produces " + Energy + " Joules!"); Wt = Convert::ToDouble(InputBox::Show("Enter the watts: ")); Hr = Energy / (Wt * 360); MessageBox::Show("It can power your light for " + Hr + " hours!"); 3. Type cl /clr lab2_3.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab2_3.exe and press [Enter] to test the executable file. A sample output looks: 5. Capture a screen shot similar to the above figures and paste it to the Word document named lab2.doc (or.docx). Learning Activity #4: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab2_4.cpp and press [Enter] to use Notepad to create a new source file called lab2_4.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 46

25 #using <System.Drawing.dll> #include "InputBox.cpp" using namespace System::Drawing; String^ n1 = InputBox::Show("Enter 1st value:"); int n2 = Convert::ToInt32(InputBox::Show("Enter 1st value:")); MessageBox::Show((Convert::ToInt32(n1) * n2) + ""); 3. Type cl /clr lab2_4.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab2_4.exe and press [Enter] to test the executable file. A sample output looks: and and 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab2.doc (or.docx). Learning Activity #5: 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Type notepad lab2_5.cpp and press [Enter] to use Notepad to create a new source file called lab2_5.cpp with the following contents: #using <System.Drawing.dll> void main() Form^ form1 = gcnew Form; form1->size = Drawing::Size(150, 150); // size of form Label^ label1 = gcnew Label; label1->autosize = true; form1->controls->add(label1); String^ str=""; str+= (25/4) + "\n"; // 6 str+= (double(25)/4) + "\n"; // 6.25 str+= (25/double(4)) + "\n"; // 6.25 str+= (int(25.96)/(3.15)) + "\n"; // str+= (int(25.96)/int(3.15)) + "\n"; // 8 Visual C++ Programming Penn Wu, PhD 47

26 // display the content label1->text = str; Application::Run(form1); 3. Type cl /clr lab2_5.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the source file to create the executable object file. 4. Type lab2_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 lab2.doc (or.docx). You can also save the document as.pdf file. Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab2.zip containing ONLY the following self-executable files. Lab2_1.exe Lab2_2.exe Lab2_3.exe Lab2_4.exe Lab2_5.exe Lab2.doc (or lab2.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 02 as response. 5. Upload ex02.zip file to Question 12 as response. Note: You will not receive any credit if you submit file(s) to the wrong question. Programming Exercise 02: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex02.cpp. 3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex02.cpp //Programmer: [YourFullNameHere] #include <iostream> using namespace std; int x, y; x = 3; y = 4; cout << "x * y = " << (x * y); Visual C++ Programming Penn Wu, PhD 48

27 4. Convert the above codes (they are created as codes for a non-gui console application) to a GUI-based Windows Forms application Windows that will display the result in a message box as shown below. Your source code must contain both x and y variable as well as the multiplication operation. 5. Compile the source code to produce executable code. 6. Download the programming exercise template, and rename it to ex02.doc if necessary. Capture a screen similar to the above one and paste it to the Word document named ex02.doc (or.docx). 7. Compress the source file (ex02.cpp), executable code (ex02.exe), and Word document (ex02.doc) to a.zip file named ex02.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 contain both x and y variable as well as the multiplication operation. 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, after reviewing the lecture note, do you agree that the fundamental programming skills and knowledge you might have obtain from other programming course(s) apply to Visual C++? Why or why not? If you can, provide an example to support your perspective. [There is never a right-orwrong 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 49

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

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

Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll> 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

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

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

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

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

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

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

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

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

#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

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

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

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

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

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

Introduction to Programming

Introduction to Programming Introduction to Programming session 5 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

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

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

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

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

Program Organization and Comments

Program Organization and Comments C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look

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

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

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

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq CS 241 Computer Programming Introduction Teacher Assistant Hadeel Al-Ateeq 1 2 Course URL: http://241cs.wordpress.com/ Hadeel Al-Ateeq 3 Textbook HOW TO PROGRAM BY C++ DEITEL AND DEITEL, Seventh edition.

More information

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

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

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

This watermark does not appear in the registered version - Slide 1

This watermark does not appear in the registered version -   Slide 1 Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style

More information

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program? Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set

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

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

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1 Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.1 Introduction of Compiler, Comments, Program Structure, Input Output, Data Types and Arithmetic Operators

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

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

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents: Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language Dr. Amal Khalifa Lecture Contents: Introduction to C++ Origins Object-Oriented Programming, Terms Libraries and Namespaces

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

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

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

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

Your First C++ Program. September 1, 2010

Your First C++ Program. September 1, 2010 Your First C++ Program September 1, 2010 Your First C++ Program //*********************************************************** // File name: hello.cpp // Author: Bob Smith // Date: 09/01/2010 // Purpose:

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

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

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 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. Welcome to 6.096 Lecture

More information

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Fundamentals of Programming. Lecture 3: Introduction to C Programming Fundamentals of Programming Lecture 3: Introduction to C Programming Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department Outline A Simple C

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

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

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

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

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

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

First C or C++ Lab Paycheck-V1.0 Using Microsoft Visual Studio

First C or C++ Lab Paycheck-V1.0 Using Microsoft Visual Studio C & C++ LAB ASSIGNMENT #1 First C or C++ Lab Paycheck-V1.0 Using Microsoft Visual Studio Copyright 2013 Dan McElroy Paycheck-V1.0 The purpose of this lab assignment is to enter a C or C++ into Visual Studio

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

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM Contents 1. Statements 2. C++ Program Structure 3. Programming process 4. Control Structure STATEMENTS ASSIGNMENT STATEMENTS Assignment statement Assigns a value

More information

Chapter 2, Part I Introduction to C Programming

Chapter 2, Part I Introduction to C Programming Chapter 2, Part I Introduction to C Programming C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson Education,

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

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

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm. CHAPTER 1&2 OBJECTIVES After completing this chapter, you will be able to: Understand the basics and Advantages of an algorithm. Analysis various algorithms. Understand a flowchart. Steps involved in designing

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Should you know scanf and printf?

Should you know scanf and printf? C-LANGUAGE INPUT & OUTPUT C-Language Output with printf Input with scanf and gets_s and Defensive Programming Copyright 2016 Dan McElroy Should you know scanf and printf? scanf is only useful in the C-language,

More information

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

On a 64-bit CPU. Size/Range vary by CPU model and Word size. On a 64-bit CPU. Size/Range vary by CPU model and Word size. unsigned short x; //range 0 to 65553 signed short x; //range ± 32767 short x; //assumed signed There are (usually) no unsigned floats or doubles.

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 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

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

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

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

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

More information

Course Outline Introduction to C-Programming

Course Outline Introduction to C-Programming ECE3411 Fall 2015 Lecture 1a. Course Outline Introduction to C-Programming Marten van Dijk, Syed Kamran Haider Department of Electrical & Computer Engineering University of Connecticut Email: {vandijk,

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 1992-2010 by Pearson Education, Inc. All Rights Reserved. 2 1992-2010 by Pearson Education, Inc. All Rights Reserved. 3 1992-2010 by Pearson Education, Inc. All Rights Reserved. 4 1992-2010 by Pearson

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

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