# OpenStax CNX

You are here: Home » Content » Basic Elements in C++

### Lenses

What is a lens?

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

#### Affiliated with (What does "Affiliated with" mean?)

This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
• VOCW

This module is included inLens: Vietnam OpenCourseWare's Lens
By: Vietnam OpenCourseWare

Click the "VOCW" link to see all content affiliated with them.

#### Also in these lenses

• Busbee's Compter Science

This module is included inLens: Busbee's Computer Science Lens
By: Kenneth Leroy BusbeeAs a part of collection: "PROGRAMMING FUNDAMENTALS IN C++ "

Click the "Busbee's Compter Science" link to see all content selected in this lens.

Click the tag icon to display tags associated with this content.

### Recently Viewed

This feature requires Javascript to be enabled.

### Tags

(What is a tag?)

These tags come from the endorsement, affiliation, and other lenses that include this content.

# Basic Elements in C++

Module by: Dr Duong Tuan Anh. E-mail the author

Summary: This chapter gets you started immediately writing some simple C++ programs and helps you to understand some basic elements in any high level programming language such as data types, arithmetic operators, output statements and assignment statements.

## Program Structures

### Modular Programs

A large program should be organized as several interrelated segments, arranged in a logical order: The segments are called modules. A program which consists of such modules is called a modular program.

In C++, modules can be classes or functions.

We can think of a function as a program segment that transforms the data it receives into a finished result.

Each function must have a name. Names or identifiers in C++ can made up of any combination of letters, digits, or underscores selected according to the following rules:

• Identifiers must begin within an uppercase or lowercase ASCII letter or an underscore (_).
• You can use digits in an identifier, but not as the first character. You are not allowed to use special characters such as $, &, * or %. • Reserved words cannot be used for variable names. Examples: DegToRadintersectaddNums FindMax1_densityslope Examples of invalid identifiers: 1AB3 E%6 while Note: C++ is a case-sensitive language (i.e. upper and lower case characters are treated as different letters). ### The main() function The main() function is a special function that runs automatically when a program first executes. All C++ programs must include one main() function. All other functions in a C++ program are executed from the main() function. The first line of the function, in this case int main() is called a function header line. The function header line contains three pieces of information: 1. What type of data, if any, is returned from the function. 2. The name of the function 3. What type of data, if any, is sent into the function. int main() {    program statements in here   return 0;   }  Note: The line return 0; is included at the end of every main function. C++ keyword return is one of several means we will use to exit a function. When the return statement is used at the end of main as shown here, the value 0 indicates that the program has terminates successfully. ### The cout Object The cout object is an output object that sends data given to it to the standard output display device. To send a message to the cout object, you use the following pattern: cout << “text”; The insertion operator, <<, is used for sending text to an output device. The text portion of the statement is called a text string. Text string is text that is contained within double quotation marks. Consider the following program.  Example   #include <iostream.h>   int main()   {   cout << "Hello world!”;   return 0;   }  The output of the above program: Hello world! ### Preprocessor Directives Before you can use any runtime libraries in your program, you must first add a header-file into your program, using the #include statement. A header file is a file with an extension of .h that is included as part of a program and notifies the compiler that a program uses run-time libraries. One set of classes you will use extensively in the next few chapters is the iostream classes. The iostream classes are used for giving C++ programs input capabilities and output capabilities. The header file for the iostream class is iostream.h. The #include statement is one of the several preprocessor directives that are used with C++. The preprocessor is a program that runs before the compiler. When it encounters an #include statement, the preprocessor places the entire contents of the designated file into the current file. Preprocessor directives and include statements allow the current file to use any of the classes, functions, variables, and other code contained within the included file. Example: To include the iostream.h file you use the following statement:  #include <iostream.h>  An i/o manipulator is a special function that can be used with an i/o statement. The endl i/o manipulator is part of the iostream classes and represents a new line character. Example:  cout << “Program type: console application” << endl;   cout << “Create with: Visual C++ “<< endl;   cout << “Programmer: Don Gesselin” << endl;  All statements in C++ must end with a semicolon. Large statements can span multiple lines of code. Example:  cout << “Program type: console application,”   << “Create with: Visual C++ “   << “Programmer: Don Gesselin”;  ### Comments Comments are lines that you place in your code to contain various type of remarks. C++ support two types of comments: line and block.  C++ line comments are created by adding two slashes (//) before the text you want to use as a comment. Block comments span multiple lines. Such comments begin with /* and end with the symbols */.  Example:   void main()   {   /*   This line is part of the block comment.   This line is also part of the block   comment.   */   cout << “Line comment 1 “;   cout << “Line comment 2 “;   // This line comment takes up an entire line.   }  All programs should contain comments. They are  remarks, insights, wisdom in code without affecting the program. The compiler ignores comments .  Data Types and OperatorsData TypesA data type is the specific category of information that a variable contains.There are three basic data types used in C++: integers, floating point numbers and characters. Integers An integer is a positive or negative number with no decimal places.- 259 -13 0 200 Floating Point Numbers A floating point number contains decimal places or is written using exponential notations.-6.16 -4.4 2.7541 10.5Exponential notation, or scientific notation is a way of writing a very large numbers or numbers with many decimal places using a shortened format.2.0e11 means 2*1011C++ supports three different kinds of floating-point numbers:float (i.e. single precision numbers), double (i.e. double precision numbers) long double.A double precision floating-point number can contain up to 15 significant digits. The Character Data Type To store text, you use the character data type. To store one character in a variable, you use the char keyword and place the character in single quotation marks.Example:char cLetter = ‘A’;Escape SequenceThe combination of a backlash (\) and a special character is called an escape sequence. When this character is placed directly in front of a select group of character, it tells the compiler to escape from the way these characters would normally be interpreted.Examples:\n : move to the next line\t : move to the next tab The bool Data Type The C++ bool type can have two states expressed by the built-in constants true (which converts to an integral one) and false (which converts to an integral zero). All three names are keywords. This data type is most useful when a program must examine a specific condition and, as a result of the condition being either true or false, take a prescribed course of action.Arithmetic OperatorsMost programs perform arithmetic calculations. Arithmetic operators are used to perform mathematical calculations, such as addition, subtraction, multiplication, and division in C++.A simple arithmetic expression consists of an arithmetic operator connecting two operands in the form: operand operator operand Examples:3 + 718 – 312.62 + 9.812.6/2.0 Example #include <iostream.h> int main() { cout << "15.0 plus 2.0 equals " << (15.0 + 2.0) << '\n' << "15.0 minus 2.0 equals " << (15.0 - 2.0) << '\n' << "15.0 times 2.0 equals " << (15.0 * 2.0) << '\n' << "15.0 divided by 2.0 equals " << (15.0 / 2.0) << '\n'; return 0; } The output of the above program:15.0 plus 2.0 equals 1715.0 minus 2.0 equals 1315.0 times 2.0 equals 3015.0 divided by 2.0 equals 7.5Integer DivisionThe division of two integers yields integer result. Thus the value of 15/2 is 7.Modulus % operator produces the remainder of an integer division.Example:9%4 is 117%3 is 214%2 is 0Operator Precedence and AssociativityExpressions containing multiple operators are evaluated by the priority, or precedence, of the operators.Operator precedence defines the order in which an expression evaluates when several different operators are present. C++ have specific rules to determine the order of evaluation. The easiest to remember is that multiplication and division happen before addition and subtraction. The following table lists both precedence and associativity of the operators.Example: Let us use the precedence rules to evaluate an expression containing operators of different precedence, such as 8 + 5*7%2*4. Because the multiplication and modulus operators have a higher precedence than the addition operator, these two operations are evaluated first (P2), using their left-to-right associativity, before the addition is evaluated (P3). Thus, the complete expression is evaluated as:Expression TypesAn expression is any combination of operators and operands that can be evaluated to yield a value. An expression that contains only integer values as operands is called an integer expression, and the result of the expression is an integer value. Similarly, an expression containing only floating-point values (single and double precision) as operands is called a floating-point expression, and the result of the expression is a floating point value (the term real expression is also used). Variables and Declaration StatementsOne of the most important aspects of programming is storing and manipulating the values stored in variables. A variable is simply a name chosen by the programmer that is used to refer to computer storage locations. The term variable is used because the value stored in the variable can change, or vary.Variable names are also selected according to the rules of identifiers:Identifiers must begin with an uppercase or lowercase ASCII letter or an underscore (_). You can use digits in an identifier, but not as the first character. You are not allowed to use special characters such as$, &, * or %. Reserved words cannot be used for variable names.Example: Some valid identifiersmy_variableTemperaturex1x2_my_variableSome invalid identifiers are as follows:%x1%my_var@x2We should always give variables meaningful names, from which a reader might be able to make a reasonable guess at their purpose. We may use comments if further clarification is necessary.Declaration StatementsNaming a variable and specifying the data type that can be stored in it is accomplished using declaration statement. A declaration statement in C++ programs has the following syntax: type name; The type portion refers to the data type of the variable.The data type determines the type of information that can be stored in the variable.Example: int sum; long datenem; double secnum; Note:A variable must be declared before it can be used. Declaration statements can also be used to store an initial value into declared variables.Example: int num = 15; float grade1 = 87.0; Variable declarations are just the instructions that tell the compiler to allocate memory locations for the variables to be used in a program.A variable declaration creates a memory location but it is undefined to start with, that means it's empty. Example #include <iostream.h> int main() { float price1 = 85.5; float price2 = 97.0; float total, average; total = price1 + price2; average = total/2.0; // divide the total by 2.0 cout << "The average price is " << average << endl; return 0; } The output of the above program:The average price is 91.25Let notice the two statements in the above program: total = price1 + price2; average = total/2.0; Each of these statements is called an assignment statement because it tells the computer to assign (store) a value into a variable. Assignment statements always have an equal (=) sign and one variable name on the left of this sign. The value on the right of the equal sign is assigned to the variable on the left of the equal sign.Display a Variable’s AddressEvery variable has three major items associated with it: its data type, its actual value stored in the variable and the address of the variable. The value stored in the variable is referred to as the variable’s contents, while the address of the first memory location used for the variable constitutes its address.To see the address of a variable, we can use address operator, &, which means “the address of “. For example, &num means the address of num. Example #include <iostream.h> int main() { int a; a = 22; cout << "The value stored in a is " << a << endl; cout << "The address of a = " << &a << endl; return 0; } The output of the above program:The value stored in a is 22The address of a = 0x0065FDF4The display of addresses is in hexadecimal notation. Integer QuantifiersPortable languages like C++ must have flexible data type sizes. Different applications might need integers of different sizes. C++ provides long integer, short integer, and unsigned integer data types. These three additional integer data types are obtained by adding the quantifier long, short or unsigned to the normal integer declaration statements.Example: long int days; unsigned int num_of_days; The reserved words unsigned int are used to specify an integer that can only store nonnegative numbers.The signed and unsigned quantifiers tell the compiler how to use the sign bit with integral types and characters (floating-point numbers always contain a sign). An unsigned number does not keep track of the sign and thus has an extra bit available, so it can store positive numbers twice as large as the positive numbers that can be stored in a signed number. When you are modifying an int with short or long, the keyword int is optional. Now all the built-in data types provide by C++ are given in the following list, ordered descendingly by the size of the data types. Data types --------------long doubledoublefloatunsigned longlong intunsigned intintshort incharData Type ConversionsAn expression containing both integer and floating point operands is called a mixed mode expression.Example: int a; float x = 2.5; a = x + 6; // x + 6 is a mixed mode expression Note: We should avoid mixed-mode expression.Examples: char Ch; int In1 = 129, In2, In3; double Real1 = 12.34, Real2; What happens with the following mixed mode assignments? Ch = In1/2 + 1; // Right side = 65; assigns ‘A’ to Ch In2 = Ch + 1; // Right side = 66; assigns 66 to In2 Real2 = In1/2; // Right side = 64; assigns 64.0 to Real2 In3 = Real1/2.0 // Right side = 6.17; truncates this value and assigns 6 to In3 The general rules for converting integer and floating point operands in mixed mode arithmetic expressions were presented as follows:If both operands are either character or integer operands:when both operands are character, short or integer data types, the result of the expression is an integer value. when one of the operand is a long integer, the result is a long integer, unless one of the operand is an unsigned integer. In the later case, the other operand is converted to an unsigned integer value and the resulting value of the expression is an unsigned value. If any one operand is a floating point value:when one or both operands are floats, the result of the operation is a float value; when one or both operands are doubles, the result of the operation is a double value; when one or both operands are long doubles, the result of the operation is a long double value;Notice that converting values to lower types can result in incorrect values. For example, the floating point value 4.5 gives the value 4 when it is converted to an integer value. The following table lists the built-in data types in order from “highest type” to “lowest type”.Determining Storage SizeC++ provides an operator for determining the amount of storage your compiler allocates for each data type. This operator, called the sizeof() operator.Example:sizeof(num1)sizeof(int)sizeof(float)The item in parentheses can be a variable or a data type. Example // Demonstrating the sizeof operator #include <iostream.h> int main() { char c; short s; int i; long l; float f; double d; long double ld; cout << "sizeof c = " << sizeof(c) << "\tsizeof(char) = " << sizeof( char ) << "\nsizeof s = " << sizeof(s) << "\tsizeof(short) = " << sizeof( short ) << "\nsizeof i = " << sizeof (i) << "\tsizeof(int) = " << sizeof( int ) << "\nsizeof l = " << sizeof(l) << "\tsizeof(long) = " << sizeof( long ) << "\nsizeof f = " << sizeof (f) << "\tsizeof(float) = " << sizeof(float) << "\nsizeof d = " << sizeof (d) << "\tsizeof(double) = " << sizeof(double) << endl; return 0; } The output of the above program:sizeof c = 1sizeof(char) = 1sizeof s = 2sizeof(short) = 2sizeof i = 4sizeof(int) = 4 sizeof l = 4sizeof(long) = 4sizeof f = 4sizeof(float) = 4sizeof d = 8sizeof(double) = 8 Focus on Problem SolvingIn this section, the software development procedure presented in the previous chapter is applied to a specific programming problem. This procedure can be applied to any programming problem to produce a completed program and forms the foundation for all programs developed in this text. Problem: Telephone Switching Networks A directly connected telephone network is one in which all telephones in the network are connected directly and do not require a central switching station to establish calls between two telephones.The number of direct lines needed to maintain a directly connected network for n telephones is given by the formula: lines = n(n-1)/2 For example, directly connecting four telephones requires six individual lines. Using the formula, write a C++ program that determines the number of direct lines for 100 telephones and the additional lines required if 10 new telephones were added to the network. Use our top-down software development procedure.Step 1: Analyze the Problem For this program, two outputs are required: the number of direct lines required for 100 telephones and the additional lines needed when 10 new telephones are added to the existing network. The input item required for this problem is the number of telephones, which is denoted as n in the formula.Step 2: Develop a Solution The first output is easily obtained using the given formula lines = n(n-1)/2. Although there is no formula given for additional lines, we can use the given formula to determine the total number of lines needed for 110 subscribers. Subtracting the number of lines for 100 subscribers from the number of lines needed for 110 subscribers then yields the number of additional lines required. Thus, the complete algorithm for our program, in pseudocode, is: Calculate the number of direct lines for 100 subscribers. Calculate the number of direct lines for 110 subscribers. Calculate the additional lined needed, which is the difference between the second and the first calculation. Display the number of lines for 100 subscribers. Display the additional lines needed. Step 3: Code the Solution The following program provides the necessary code. #include <iostream.h> int main() { int numin1, numin2, lines1, lines2; numin1 = 100; numin2 = 110; lines1 = numin1*(numin1 – 1)/2; lines2 = numin2*(numin2 – 1)/2; cout << “The number of initial lines is “ << lines1 << “.\n”; cout << “There are “ << lines2 – lines1 << “ additional lines needed.\n”; return 0; } Step 4: Test and Correct the Program The following output is produced when the program is compiled and executed:The number of initial lines is 4950.There are 1045 additional lines needed.Because the displayed value agrees with the hand calculation, we have established a degree of confidence in the program. 
 Content actions Share content Share module: Give feedback: E-mail the module author Download module as: PDF | EPUB (?) What is an EPUB file? EPUB is an electronic book format that can be read on a variety of mobile devices. Downloading to a reading device For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link. | More downloads ... Add module to: My Favorites Login Required (?) 'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'. | A lens I own Login Required (?) Definition of a lens Lenses A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust. What is in a lens? Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content. Who can create a lens? Any individual member, a community, or a respected organization. What are tags? Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens. | External bookmarks Footer More about this module: Metadata | Downloads | Version History How to reuse and attribute this content How to cite and attribute this content This work is licensed by Dr Duong Tuan Anh under a Creative Commons Attribution License (CC-BY 3.0), and is an Open Educational Resource. Last edited by Vietnam OpenCourseWare on Jul 6, 2009 11:37 pm +0000. 
 
 var _gaq = _gaq || []; function trackthisGoogleAnalytics(strCode) { try { _gaq.push(['user._setAccount', strCode]); _gaq.push(['user._trackPageview']); } catch(err) {} } var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-7903479-1']); _gaq.push(['_setDomainName', '.cnx.org']); _gaq.push(['_trackPageview']); _gaq.push(['hewlett._setAccount', 'UA-5033010-1']); _gaq.push(['hewlett._setDomainName', '.cnx.org']); _gaq.push(['hewlett._trackPageview']);