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 symbols, identifiers, and comments. Explore simple data types Learn how to write a C++ program Background: A C++ program: is a collection of functions, one of which is the function main. This is where execution begins when you run the program. C++ program has two parts: Preprocessor directives The program The body of the function main has the following form: int main () { declare variables statements return 0; } The first line of a function is called the function s heading : int main() The statements enclosed between the curly braces { and } form the function s body. Contains two types of statements: 1. Declaration statements 2. Executable statements All C++ statements end with a semicolon. Also called a statement terminator Preprocessor directives: are commands that the preprocessor program executes before your program is compiled. All preprocessor directives begin with #. No semicolon at the end of these directives. The most common preprocessor directive is #include, which is how you tell the compiler that you want to use a Standard Library file(many useful operations are provided as a collection of files). Syntax to include a header file: For example: #include <iostream>. Without this, you could not use cout or cin in your program. @Bau University Computer Skills II 2
So the student should know the structure of a simple c++ program, in that, any program may be written according to the following format: #include<iostream> using namespace std; int main() { //Program body return 0; } Note: without that using statement, you would need to type std::cin instead of cin throughout your program. Comments: are for the reader, not the compiler. Two types: Single line: begin with // // Welcome to C++ Programming. Multiple line: enclosed between /* and */ /* You can include comments that can occupy several lines. */ Tokens: the smallest meaningful units of a program. C++ tokens include special symbols, reserved words, and identifiers. Reserved words Identifier Special symbol List of special symbols in C++ : Reserved words (or keywords): You cannot redefine these words. You cannot use them for anything other than their intended use. Example: int,float,double,char,const,void, and return. @Bau University Computer Skills II 3
An identifier is the name of something in a program. Identifiers can contain letters, digits, and the underscore character (_), but no other characters or special symbols like: +,-,*,/,.,;?,>,<,=,.. Identifiers must begin with a letter or underscore (not a digit). Note: C++ is case sensitive. For example, number, Number, and NUMBER are three different identifiers. Data type: set of values together with a set of allowed operations on those values. C++ data types fall into three categories: 1. Simple data types(int, char, bool, double, ) 2. Structured data types 3. Pointers Data Types Simple Data Types Structured Data Types Pointers Integral (int, bool, char, ) Floating-Point (float, double, ) Enumeration Simple Data Types Three categories of simple data: Integral: integers (numbers without a decimal). Can be further categorized: char, short, int, long, long long, bool, unsigned char, unsigned short, unsigned int, unsigned long bool type : Two values: true and false Manipulate logical (Boolean) expressions This is considered an integral data type because it s actually implemented as a 0 for false and a 1 for true. char Data Type: The smallest integral data type Used for characters: letters, digits, and special symbols @Bau University Computer Skills II 4
Each character is enclosed in single quotes.example:'a', 'a', '0', '*', '+'. A blank space is a character and is written ' ', with a space left between the single quotes Floating-point: decimal numbers. Can be further categorized: float: Typical Range: -3.4E+38 to 3.4E+38 (four bytes) double: Typical Range: -1.7E+308 to 1.7E+308 (eight bytes), long double Ranges of data types are system-dependent. We ll generally use double when we want a floating-point number. Enumeration type: user-defined data type. string Type: is a sequence of zero or more characters enclosed in double quotation marks. Example : string UnivName= Bau University ; Unlike the simple data types discussed earlier, the string data type is not built into the core C++ language. It s a programmer-defined type supplied in the C++ Standard Library. So a program that uses strings must have the following line: #include <string> Variable: a memory location whose contents can be changed. When naming your variables, be sure to follow the rules listed earlier for identifiers. o Declaring Variables In C++ you must declare each variable s data type before you can use the variable. Syntax to declare one or more variables: Example: o Putting Data into Variables A variable is said to be initialized the first time you place a value into it. A variable that has not been initialized will hold an unpredictable garbage value. Ways to place data into a variable: Use an assignment statement. Use input (read) statements to let the user enter values from the keyboard. The operator >> is the stream extraction operator. Output Statement: cout is used with << to display values on the screen: @Bau University Computer Skills II 5
The operator << is the stream insertion operator. The expression is evaluated and its value is printed at the current cursor position on the screen. You can use manipulators to format the output. Example: the manipulator endl causes the cursor to move to beginning of the next line. Escape sequences are another way to format output. Debugging and Programming Assignments: Assignment 1: The following program contains several errors: 1. */ Now you should not 2. forget your glasses // 3. #include <stream> 4. int main 5. { 6. cout << "If this text", 7. cout >> " \\\appears on your display, "; 8. cout << " endl;" 9. cout << 'you can pat yourself on ' 10. << " the back!" << endl. 11. ) Resolve the errors and run the program to test your changes. The Errors: --------------------------------------------------------------------------------------------------------------------------- @Bau University Computer Skills II 6
Assignment 2: Write a C++ program that outputs the following on the screen: $********************************************$ $ Welcome to Bau University $ $ C++ Lab $ $ Date:20\2\2016 $ $********************************************$ - Code of Program Assignment 3: What is the output of the following code? #include <iostream.h> using namespace std; int main () { int a, b; char ch1; cin>>a>>b; ch1=98; a = b; b = 7; cout << "a :"<< a; cout << " \t b : "<< b<<"\n"; cout<<ch1; return 0; } - The Output of Program ------ ------ ------------------------------------------------------------------------------------------------------------------------------ @Bau University Computer Skills II 7
Assignment 5: Consider the following program segment: //include statement(s) int main() { //Variable declaration; //Excutable statements; //return statment } Write a C++ statement(s) that accomplish the following: a. Includes the header file iostream. b. That allows you to use cin,cout,and endl without the prefix std::. c. Declare int variables firstnum, SecondNum, and ThirdNum.Initialize firstnum to 25 and SecondNum to 18. d. Declare and initialize a char variable to A. e. Declare a double variable and then prompt the user to enter the number. f. Copy the value of an int variable firstnum into an int variable ThirdNum. g. Swap the contents of the int variables firstnum and SecondNum.(Declare additional variables,if necessary.) h. Print all variables on the screen using a single cout statement Compile and run your program. - A C++ statement (s): a.---------------------------------------------------------------------------------------------------------------------------------- b.---------------------------------------------------------------------------------------------------------------------------------- c.----------------------------------------------------------------------------------------------------------------------------------- d.---------------------------------------------------------------------------------------------------------------------------------- e. ----------------------------------------------------------------------------------------------------------------------------------- f.----------------------------------------------------------------------------------------------------------------------------------- g. ----------------------------------------------------------------------------------------------------------------------------------- -- ----------------------------------------------------------------------------------------------------------------------------------- h. ---------------------------------------------------------------------------------------------------------------------------------- @Bau University Computer Skills II 8
Lab Exercises: Use Visual Studio to write, run, and test the C++ programs listed below. 1. Create a new project named Lab02Message1. After you ve created the project, create a new source-code file named Lab02Message1.cpp. Then write a program that behaves as described in the textbook s Chapter 2, Programming Exercise 1 on page 115. 2. Do the same for Chapter 2 s Programming Exercise 6 on page 117, using the name Lab02Message2. @Bau University Computer Skills II 9