Introduction to C++
Chapter 9 · Tamil Nadu State Board
- 31 min read
- 4-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson introduces C++ and its basic building blocks, including tokens, data types, operators, and punctuators. It explains how input and output work and how a simple program is created, compiled, and run. It also introduces common program errors and explains why choosing suitable data types matters. These ideas help students write, execute, and debug simple C++ programs.
Written by AI from this lesson. How we check it
Key points
- C++ supports procedural and Object Oriented Programming, so it is described as a hybrid language.
From your textbook
“supports both procedural and Object Oriented Programming paradigms. Thus, C++ is called as a hybrid language.”
- Tokens are the small individual elements used to construct C++ program statements.
From your textbook
“These individual elements are collectively called as Lexical units or Lexical elements or Tokens.”
- Identifiers are user-defined names, and their names must follow rules such as starting with a letter or underscore.
From your textbook
“The first character of an identifier must be an alphabet or an underscore (_).”
- Literals have values that remain unchanged while a program runs, so they are also called constants.
From your textbook
“Literals are data items whose values do not change during the execution of a program.”
- The >> operator gets input, while the << operator sends values or strings to output.
From your textbook
“Extraction operator( >> ) and Insertion operator (<<) are used to get input and send output in C++.”
- Every C++ program needs a main function, which is where the program begins execution.
From your textbook
“The main( ) function is the starting point where all C++ programs begin their execution.”
- Program creation and execution involve writing and saving source code, compiling it, and then running it.
From your textbook
“For creating and executing a C++ program, one must follow four important steps.”
Formulas in this chapter
- Declaring a variable<data type> <variable name>;Explained here
- Declaring variables of the same type<data type> <var1>, <var2>, <var3> …… <var_n>;Explained here
- Reference declaration<type> <& reference_variable> = <original_variable>;Explained here
- Type casting syntax(type-name) expression;Explained here
C++ and Its Benefits
C++ supports both procedural and Object Oriented Programming. This makes it a hybrid language. It is an extension of C. Bjarne Stroustrup first called it “C with Classes”, and Rick Mascitti later coined the name C++.
Benefits of C++
- It is highly portable and can be used for multidevice, multi-platform app development.
- It supports classes, inheritance, polymorphism, data abstraction and encapsulation.
- It has a rich function library.
- It supports exception handling, inheritance and function overloading, which are not possible in C.
- It is powerful, efficient and fast. It is used for applications ranging from GUI applications to 3D game graphics and real-time mathematical simulations.
Character Sets and Tokens
Definition
- Character set
- A character set is the collection of characters used to write a C++ program.
Characters accepted in C++
- Alphabets: A …. Z, a ….. z
- Numeric characters: 0 …. 9
- Special characters: + - * / ~ ! @ # $ % ^& [ ] ( ) { } = >< _ \ | ? . , : ‘ “ ;
- White space characters include blank space, horizontal tab, carriage return, newline and form feed.
- C++ can process any of the 256 ASCII characters as data.
Definition
- Token
- A token, also called a Lexical unit or Lexical element, is the smallest individual unit in a program.
Types of C++ tokens
- Keywords
- Identifiers
- Literals
- Operators
- Punctuators
Keywords and Identifiers
Definition
- Keyword
- A keyword is a reserved word that gives a specific meaning to the C++ compiler.
C++ is case sensitive, so keywords must be written in lowercase. The keyword list includes words such as asm, auto, break, char, class, const, int, return and while. Other listed keywords include using, namespace, bal, static_cast, const_cast, dynamic_cast, true and false. Avoid identifiers containing a double underscore because they are reserved for C++ implementations and standard libraries.
Definition
- Identifier
- An identifier is a name chosen by the programmer for parts of a program, such as variables, functions, arrays and classes.
Rules for naming identifiers
- The first character must be an alphabet or an underscore (_).
- Only alphabets, digits and underscores are allowed.
- C++ treats uppercase and lowercase characters differently.
- A keyword cannot be used as an identifier.
- C++ places no limit on identifier length, so all its characters are significant.
Valid and invalid identifiers
| Valid | Invalid and reason |
|---|---|
| Num, NUM, _add, total_sales, tamilMark | num-add: contains a special character (-) |
| this: a keyword cannot be an identifier | |
| 2myfile: begins with a digit | |
| total_sales | total sales: contains a blank space |
Literals and Constants
Definition
- Literal
- A literal, or constant, is a data item whose value does not change during program execution.
Kinds of literals
- Numeric constants: integer constants and real constants
- Boolean constants
- Character constants
- String literals
Integer constants are whole numbers without fractions or a decimal point. They may be signed or unsigned. C++ has decimal, octal and hexadecimal integer constants.
Integer constant forms
| Form | Rule and examples |
|---|---|
| Decimal | Uses digits 0 …. 9. Examples: 725, -27, 66. Commas, blank spaces and special characters are not allowed. |
| Octal | Uses digits 0 …. 7 and begins with 0. Examples: 012, -027, +0231. The digit 8 is not allowed. |
| Hexadecimal | Uses digits 0 …. 9 and A …. F, and begins with 0x or 0X. Examples: 0x123, 0X568. |
If 4.56 is used as an integer decimal constant, the compiler keeps 4 and ignores .56. This is called Implicit Conversion. A fractional number that begins with 0 is treated as an integer, not as an Octal. The suffix L or l makes a constant long, while U or u makes it unsigned.
Definition
- Real constant
- A real, or floating point, constant is a numeric constant with a fractional component.
A real constant can use fractional form or exponent form. In fractional form, there must be at least one digit before and after the decimal point. It can have a + or - sign; without a sign, it is positive. Exponent form has a mantissa followed by E or e and an integer exponent.
Worked example
Write 58000000.00 in exponent form.
Try it first, then show the solutionSolution
- Use 0.58 as the mantissa.
- Use 8 as the exponent after E.
Answer: 0.58E8
Other literal types
- Boolean literals represent True or false. Internally, true has value 1 and false has value 0.
- A character constant is one valid character inside single quotes, such as ‘A’, ‘2’ or ‘$’.
- “A” is not a valid character constant because it uses double quotes.
- A single character constant has an equivalent ASCII value. The value of ‘A’ is 65.
- Escape sequences represent non-printable characters. Each is written as a backslash followed by one or two characters.
Remember: Check the starting character, allowed symbols and punctuation when identifying a valid token or constant.
Escape Sequences and String Literals
Escape sequences represent special characters that are not normally shown as symbols. Each escape sequence contains two characters, but C++ treats it as one character constant and allocates one byte in ASCII representation.
Common escape sequences
- \a: Audible or alert bell; \b: Backspace
- \f: Form feed; \n: Newline or linefeed
- \r: Carriage return; \t: Horizontal tab
- \v: Vertical tab; \\: Backslash
- \’: Single quote; \”: Double quote
- \?: Question Mark; \On: Octal number; \xHn: Hexadecimal number
- \0: Null
Definition
- String literal
- A string literal is a sequence of characters enclosed within double quotes.
C++ adds the special character \0 to the end of a string literal. So “welcome” is stored as “welcome\0” and occupies 8 characters, including the null character. “A”, “Welcome” and “1234” are valid string literals; ‘Welcome’ and ‘1234’ are invalid.
Remember: A string literal ends with \0, so its stored size includes that extra character.
C++ Operators and Their Types
Definition
- Operator
- An operator is a symbol used to perform a mathematical or logical operation.
Definition
- Operand
- An operand is a data item or value on which an operator acts.
Operators by number of operands
| Type | Number of operands |
|---|---|
| Unary | One |
| Binary | Two |
| Ternary | Three |
Types of C++ Binary Operators
- Arithmetic operators
- Relational operators
- Logical operators
- Assignment operators
- Conditional operator
Arithmetic operators
| Operator | Operation and example |
|---|---|
| + | Addition: 10 + 5 = 15 |
| - | Subtraction: 10 – 5 = 5 |
| * | Multiplication: 10 * 5 = 50 |
| / | Division: 10 / 5 = 2 (Quotient of the division) |
| % | Modulus: 10 % 3 = 1 (Remainder of the division) |
Increment and decrement operators work on one operand, so they are unary operators. ++ adds 1, and -- subtracts 1. They can appear before a variable as a prefix or after it as a postfix; the prefix version changes the value before the operand is used.
Relational operators
| Operator | Meaning |
|---|---|
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
| == | Equal to |
| != | Not equal |
A relational operator compares two operands. Its result is a Boolean value: 1 represents True, and 0 represents False. All six relational operators are binary.
Logical operators
| Operator | Meaning |
|---|---|
| && AND | Returns 1 (True) if both expressions are true; otherwise returns 0 (false). |
| || OR | Returns 1 (True) if either expression is true; returns 0 (false) if both are false. |
| ! NOT | Reverses the truth value of one expression: 1 becomes 0, and 0 becomes 1. |
Worked example
Evaluate the logical expressions when a = 5, b = 6, c = 7.
Try it first, then show the solutionSolution
- (a<b) && (b<c): both comparisons are true.
- (a>b) && (b<c): the first comparison is false.
- (a<b) || (b>c): the first comparison is true.
- !(a>b): a>b is false, so NOT reverses it.
Answer: (a<b) && (b<c) = 1 (True); (a>b) && (b<c) = 0 (False); (a<b) || (b>c) = 1 (True); !(a>b) = 1 (True).
Remember: && and || are binary operators. ! is a unary operator.
Assignment, Conditional, and Other Operators
The assignment operator = copies the value on its right to the variable on its left. It is a binary operator. Shorthand assignment operators combine an operation with assignment.
Shorthand assignment operators
| Operator | Example and result |
|---|---|
| += | a = 10; c = a += 5; (ie, a = a + 5) c = 15 |
| -= | a = 10; c = a -= 5; (ie. a = a – 5) c = 5 |
| *= | a = 10; c = a *= 5; (ie. a = a * 5) c = 50 |
| /= | a = 10; c = a /= 5; (ie. a = a / 5) c = 2 |
| %= | a = 10; c = a %= 5; (ie. a = a % 5) c = 0 |
Assignment and equality operators
| Operator | Use |
|---|---|
| = | Assigns the value on the right to the variable on the left. |
| == | Checks whether two operands are equal. |
The conditional operator ?: is the only conditional operator in C++. It is also called the Ternary Operator and is used as an alternative to an if … else control statement.
Other operators
- Comma (,): joins several expressions, which are evaluated from left to right.
- Sizeof: a compile time operator that returns the size of a variable in bytes.
- Pointer *: pointer to a variable; &: address of.
- Component selection: . is the direct component selector; -> is the indirect component selector.
- Class member operators: :: is scope access / resolution; .* is dereference; ->* is dereference pointer to class member.
Operator precedence, from higher to lower
- ( ) [ ]: operators within parenthesis are performed first.
- ++, --: Postfix increment / decrement.
- ++, --: Prefix increment / decrement.
- *, /, %: Multiplication, Division, Modulus.
- +, -: Addition, Subtraction.
- <, <=, >, >=: Less than, Less than or equal to, Greater than, Greater than or equal to.
- ==, !=: Equal to, Not equal.
- &&: Logical AND.
- ||: Logical OR.
- ?: Conditional Operator.
Operators are grouped in a logical way for evaluation. This grouping is called Association. Operators are executed according to their order of precedence.
Remember: Do not confuse =, which assigns a value, with ==, which checks equality.
C++ Punctuators and Comments
Definition
- Punctuator
- A punctuator is a symbol used as a delimiter when constructing a C++ program; punctuators are also called separators.
Common punctuators
| Symbol | Use |
|---|---|
| ( ) | Opening and closing parenthesis indicate function calls and function parameters. |
| { } | Opening and closing curly braces mark the start and end of a code block. |
| [ ] | Indicate single and multidimensional arrays. |
| , | Used as a separator in an expression. |
| : | Used to label a statement. |
| ; | Every executable statement in C++ should end with a semicolon. |
A code block containing more than one executable statement is called a compound statement. Comments are ignored by the compiler and are not executed.
Comment forms
| Form | Use |
|---|---|
| // | Begins a single line comment. |
| /* ……….. */ | Marks a multiline comment. |
One symbol can have different meanings in different places in C++. For example, * is used for multiplication and also for a pointer to a variable.
Remember: End every executable C++ statement with a semicolon.
C++ Input and Output Operators
Input and output
| Input with cin | Output with cout |
|---|---|
| >> is the stream extraction or “get from” operator. | << is the stream insertion or “put to” operator. |
| cin identifies the keyboard as the input device. | cout identifies the monitor as the standard output object. |
| The second operand must be a variable. | The second operand may be a constant, variable or expression. |
Both >> and << are binary operators, so each needs two operands. Use >> for each variable when receiving several values. Use << for each item when sending several values to the screen.
Definition
- Cascading of I/O operators
- Using multiple input or output operators in one statement is called cascading of I/O operators.
Examples of cascading
- cin >> x >> y; reads two values, separated by a space, and assigns them to x and y.
- cout << "The sum = " << sum; displays the string first and then the value of sum.
- cout << a + b; evaluates a + b and sends the result to the monitor.
Remember: Use >> with cin to get values, and << with cout to display values.
Parts of a Basic C++ Program
What the program parts do
- // begins a comment. The compiler ignores comments. Use /* ……. */ for multiple lines of comments.
- #include <iostream> tells the preprocessor to include the iostream header file, which contains the definitions of cin and cout.
- using namespace std; tells the compiler to use the standard namespace.
- Every C++ program must have a main( ) function. Program execution begins there.
- Executable statements go inside the curly braces of main( ). Each executable statement must end with a semicolon.
- return is a keyword used to return a value to a function. In the sample program, return 0; returns 0 to main( ).
The sample program displays “Welcome to Programming in C++” on the screen. Its cout statement sends that string to the screen. The iostream header file is needed for input and output using cin and cout.
Remember: The main( ) function is where a C++ program begins its execution.
Steps to Create and Run a C++ Program
Four steps
- Create the source code by typing and editing valid C++ code.
- Save the source code with the extension .cpp.
- Compile it. The compiler checks the code and links library files. If there are no errors, it creates a machine-readable object file with the extension .obj.
- Execute the program. The object file becomes an executable file with the extension .exe. The program can then run without the help of a compiler or IDE.
Remember: Remember the order: create source code, save it as .cpp, compile it, and execute it.
C++ Development Environments and Dev C++
An IDE helps you create, compile and run a C++ program. Many C++ IDEs are open source and available free of cost. The programming techniques and illustrated programs here use Dev C++.
Open source C++ compilers
- Dev C++
- Geany
- Code::blocks
- Code Lite
- Net Beans
- Digital Mars
- Sky IDE
- Eclipse
Create and run a program in Dev C++
- Open Dev C++ by double-clicking its desktop icon.
- Choose File → New → Source file, or press Ctrl + N.
- Type your program and choose File → Save, or press Ctrl + S. Dev C++ adds .cpp to the file name by default.
- Choose Execute → Compile and Run, or press F11.
- If errors are found, they appear under compile log. After successful compilation, the program's output appears in the output console.
Remember: Use F11 to compile and run a program in Dev C++. A saved source file gets .cpp added by default.
Types of Errors in C++
Common program errors
| Error type | What it means |
|---|---|
| Syntax Error | The program breaks C++ grammatical rules. For example, an executable statement without a semicolon has a syntax error. |
| Semantic Error | The program follows grammatical rules but gives an unexpected result because of a mistake in a variable, operator or execution order. It is also called a Logic |
| Run-time error | An error that happens while the program is running because an illegal operation takes place. Trying to open a file that does not exist is an example. |
Remember: Syntax errors break C++ rules; semantic errors affect the result; run-time errors occur during execution.
C++ Programs for Marks and Circle Area
The marks program reads three subject marks and adds them using sum = m1 + m2 + m3. It then displays the sum. The circle program reads a radius and calculates area = 3.14 * radius * radius.
Worked example
Find the total of three subject marks in a C++ program.
Try it first, then show the solutionSolution
- Read the values into m1, m2 and m3.
- Calculate sum = m1 + m2 + m3.
- Display sum.
Answer: The program displays the total as “The sum = ” followed by sum.
Worked example
Calculate the area of a circle using the program shown.
Try it first, then show the solutionSolution
- Read the radius.
- Calculate area = 3.14 * radius * radius.
- Display area.
Answer: The program displays the calculated area of the circle.
Remember: The marks program adds three inputs. The circle program uses area = 3.14 * radius * radius.
Key C++ Terms to Remember
Important terms
- C++ was developed by Bjarne Stroustrup at AT & T Bell Labs during the year 1979.
- A character set is the set of characters allowed in C++ programs.
- Tokens are individual elements in a program. They are also called Lexical units or Lexical elements.
- Keywords are reserved words with specific meanings to the C++ compiler.
- Identifiers are user-defined names for parts of a program, such as variables, functions, arrays and classes.
- Literals are data items whose values do not change during execution. They are also called Constants.
- C++ literals include Integer, Float, Character and String.
- Operators are symbols used for mathematical or logical operations.
- Punctuators are symbols used as delimiters. They are also called Separators.
- The extraction operator ( >> ) gets input. The insertion operator (<<) sends output.
Remember: Know the difference between keywords, identifiers, literals, operators and punctuators.
Data Types and Variables in C++
A data type tells C++ what kind of value is being handled. A variable is a named memory location that holds a value. In C++, declare a variable with its data type before using it.
Kinds of data in the example
| Variable | Value and kind |
|---|---|
| Name | Ram: a sequence of alphabets |
| Age | 15: a whole number |
| Average_Mark | 85.6: a fractional number |
Three categories of C++ data types
- Fundamental data types
- User-defined data types
- Derived data types
C++ has predefined data types called fundamental or built-in data types. Programmers can also create user-defined data types. Derived data types include arrays, functions, pointers and references.
<data type> <variable name>;
Write the data type first, followed by the variable name.
For example, int num1; declares an integer variable. To declare several variables of the same type in one statement, separate their names with commas: int num1, num2, sum;. Marks are usually whole numbers, so int comp_science_marks; is suitable for storing computer science marks.
Fundamental Data Types
The five fundamental data types
- char
- int
- float
- double
- void
What each type is used for
| Data type | Use and behaviour |
|---|---|
| int | Stores integer values. If a fractional value is stored, only its integer portion is accepted and the fractional part is ignored. |
| char | Stores valid ASCII characters. It can also hold an integer value representing a character's ASCII code. |
| float | Stores floating point values, including values between integers and a greater range of values. Floating point operations are slower than integer operations. |
| double | Stores double precision floating point numbers. It occupies double the space than float, can accommodate more fractions, and is larger and slower than float. |
| void | Specifies an empty set of values. It is used as the return type of functions that do not return a value. |
Remember: Use int for whole numbers, float or double for fractional values, char for characters, and void when a function returns no value.
How char Works with ASCII Values
Characters are represented in memory by their associated ASCII Codes. That is why char is often called an integer type. A char variable can hold a character or an integer value.
Worked example
What does cout<<ch display when char ch='A';?
Try it first, then show the solutionSolution
- The variable ch is declared as char.
- The character 'A' is stored in ch.
Answer: It displays A.
Worked example
What does cout<<ch+1; display when char ch='A';?
Try it first, then show the solutionSolution
- The character's associated value is increased by 1.
- The resulting character is displayed.
Answer: It displays B.
In the ASCII input program, an integer entered by the user is stored in n. The statement ch = n; assigns that value to a char variable, which displays the corresponding ASCII character. For example, input 100 produces d.
Memory Used by C++ Data Types
A variable’s data type tells the compiler how much memory to allocate. Data is stored in memory as binary digits. Memory sizes can differ between compilers, so the values below are for the compiler stated.
Fundamental data types in Turbo C++
| Data type | Memory size | Range |
|---|---|---|
| char | 1 byte, 8 bits | -128 to 127 |
| int | 2 bytes, 16 bits | -32,768 to 32,767 |
| float | 4 bytes, 32 bits | 3.4×10-38 to 3.4×1038 -1 |
| double | 8 bytes, 64 bits | 1.7×10-308 to 1.7 × 10308-1 |
Definition
- sizeof( )
- sizeof( ) is an operator that gives the size of a data type.
Remember: Memory allocation depends on the compiler. The sizes shown for fundamental data types are based on Turbo C++.
Data Type Modifiers and Number Suffixes
Modifiers change the memory allocation and storing capacity of fundamental data types, except void. They can expand or reduce the range of values a type can store. The four modifiers are signed, unsigned, long and short.
Integer modifiers in Turbo C++
| Data type | Memory size | Range |
|---|---|---|
| short | 2 bytes, 16 bits | -32,768 to 32,767 |
| unsigned short | 2 bytes, 16 bits | 0 to 65535 |
| signed short | 2 bytes, 16 bits | -32,768 to 32,767 |
| int | 2 bytes, 16 bits | -32,768 to 32,767 |
| unsigned int | 2 bytes, 16 bits | 0 to 65535 |
| signed int | 2 bytes, 16 bits | -32,768 to 32,767 |
| long | 4 bytes, 32 bits | -2147483648 to 2147483647 |
| unsigned long | 4 bytes, 32 bits | 0 to 4,294,967,295 |
| signed long | 4 bytes, 32 bits | -2147483648 to 2147483647 |
A long int uses 4 bytes, while an int uses 2 bytes in Turbo C++. This lets long int store larger integer values. In Dev C++, int and long use 4 bytes.
Character and floating point types
| Data type | Memory size | Range or description |
|---|---|---|
| char | 1 byte, 8 bits | Signed ASCII character; -128 to 127 |
| unsigned char | 1 byte, 8 bits | ASCII character without sign; 0 to 255 |
| signed char | 1 byte, 8 bits | ASCII character with sign; -128 to 127 |
| float | 4 bytes, 32 bits | Signed fractional value; 3.4×10-38 to 3.4 × 10 38 -1 |
| double | 8 bytes, 64 bits | Signed more precision fractional value; 1.7 × 10-308 to 1.7 × 10308 -1 |
| long double | 10 bytes, 80 bits | Signed more precision fractional value; 3.4 × 10-4932 to 1.1 × 104932 -1 |
Memory allocation in Turbo C++ and Dev C++
| Data type | Turbo C++ (bytes) | Dev C++ (bytes) |
|---|---|---|
| short | 2 | 2 |
| unsigned short | 2 | 2 |
| signed short | 2 | 2 |
| int | 2 | 4 |
| unsigned int | 2 | 4 |
| signed int | 2 | 4 |
| long | 4 | 4 |
| unsigned long | 4 | 4 |
| signed long | 4 | 4 |
| char | 1 | 1 |
Number suffixes
- L or l marks a value as long. For example, 45L.
- U or u marks a value as unsigned. For example, 45U.
- F marks a floating point value. For example, 3.14F.
Variables, Declaration and Initialization
Definition
- Variable
- A variable is a user-defined name for a memory location where a value is stored.
The two values linked to a variable
| Term | Meaning |
|---|---|
| R-value | The data stored in a memory location. |
| L-value | The memory address where the R-value is stored. |
A variable must be declared before it is used. The declaration tells the compiler the variable’s type and how much memory to allocate. Memory addresses are shown as hexadecimal values.
<data type> <var1>, <var2>, <var3> …… <var_n>;
Write the data type, then separate the variable names with commas.
Worked example
Declare three integer variables named num1, num2 and sum.
Try it first, then show the solutionSolution
- Write int as the data type.
- Separate the variable names with commas.
Answer: int num1, num2, sum;
A variable declared without an initial value contains an unknown value called a junk or garbage value. Using such a value in a calculation can produce a result based on unknown values.
Definition
- Initialization
- Initialization is giving a variable an initial value when it is declared.
Examples of initialization
- int num = 100;
- float pi = 3.14;
- double price = 231.45;
- int x1 = -1, x2 = 1, x3, n;
Definition
- Dynamic initialization
- Dynamic initialization gives a variable a value during program execution.
Worked example
Set sum to the total of num1 and num2 during program execution.
Try it first, then show the solutionSolution
- Use the values of num1 and num2 in an addition expression.
- Assign the result to sum.
Answer: int sum = num1+num2;
Calculating the Curved Surface Area of a Cylinder
The program declares pi, radius, height and CSA as float variables. It asks for the radius and height, then calculates the curved surface area using CSA = (2*pi*radius)*height.
Worked example
Find the curved surface area when the radius is 7 cm and the height is 20 cm.
Try it first, then show the solutionSolution
- Use CSA = (2*pi*radius)*height.
- Substitute pi = 3.14, radius = 7 and height = 20.
Answer: The Curved Surface Area of a Cylinder is 879.2 sq. cm.
Remember: Initialize variables before using their values in calculations.
Dynamic Initialization in C++
Dynamic initialization gives a variable its value using values already entered or calculated during the program. For example, sum is initialized after num1 and num2 are read. The program then displays sum /2 as the average.
Worked example
Find the average of the entered numbers 78 and 65.
Try it first, then show the solutionSolution
- Read num1 as 78 and num2 as 65.
- Initialize sum with num1 + num2.
- Display sum /2.
Answer: Average: 71
Worked example
Find the perimeter and area of a semicircle when the radius is 14 cm.
Try it first, then show the solutionSolution
- Use pi = 3.14.
- Calculate perimeter as (pi+2)*radius.
- Calculate area as (pi*radius*radius)/2.
Answer: Perimeter of the semicircle is 71.96 cm; area is 307.72 sq.cm.
The const Access Modifier and References
Definition
- const
- const is a keyword that makes a variable constant, so its value cannot be changed during the program.
A variable declared as int num = 100; can be changed while the program runs. If it is declared as const int num = 100;, its value stays 100. Trying to change it causes an error.
Definition
- Reference
- A reference provides an alias for a previously defined variable.
Declare a reference using the variable's base type, an & symbol, and a reference name. Assign it to an existing variable. In the example int &temp = num;, both num and temp show the value 100.
<type> <& reference_variable> = <original_variable>;
type is the base type; reference_variable is the alias name; original_variable is the previously declared variable.
Output Formatting with C++ Manipulators
Definition
- Manipulators
- Manipulators are functions used with the insertion (<<) and extraction (>>) operators to format program input and output.
Common manipulators and their header files
- endl belongs to the iostream header file.
- setw, setfill, setprecision and setf belong to the iomanip header file.
endl and '\n'
| endl | '\n' |
|---|---|
| Inserts a new line and flushes the buffer. | Inserts only a new line. |
Definition
- setw
- setw sets the minimum number of characters in the output field.
The syntax is setw(number of characters). In the salary program, setw(25) sets the label field width and setw(10) sets the value field width. Values are shown from right to left within their fields.
Worked example
Calculate net pay when basic pay is 12000, D.A is 1250 and H.R.A is 1450.
Try it first, then show the solutionSolution
- Calculate gross pay: basic + da + hra.
- Calculate G.P.F: (basic+da) * 0.10.
- Calculate tax: gross * 0.10.
- Calculate net pay: gross - (gpf+tax).
Answer: Gross Pay: 14700; G.P.F: 1325; Income Tax: 1470; Net Pay: 11905.
Definition
- setprecision
- setprecision controls the number of digits displayed for a number.
With setprecision (5), the value 1200.123 is displayed as 1200.1. To set the number of decimal places, use setf() with fixed or scientific before setprecision. With setprecision(2), fixed displays 0.1 as 0.10, while scientific displays it as 1.00e-001.
Remember: Remember: setw sets a field width, while setprecision controls displayed digits or decimal places depending on the ios flag.
C++ Expressions and Their Types
An expression combines operands, such as constants and variables, with operators to produce a value. It can also contain a function call that returns a value. C++ has seven types of expressions.
Types of expressions
- Constant Expression: contains only constant values. Example: int num=100;
- Integer Expression: combines integer or character values or variables with simple arithmetic operators to produce an integer result. Example: sum=num1+num2;
- Float Expression: combines floating point values or variables with simple arithmetic operators to produce a floating point result. Example: Area=3.14*r*r;
- Relational Expression: uses relational operators and produces a bool value. true means 1; false means 0. Example: x>y;
- Logical Expression: uses logical operators and produces a bool value. Example: (a>b)&& (c==10);
- Bitwise Expression: uses bitwise operators. Examples: x>>3; a<<2;
- Pointer Expression: involves a pointer, which is a variable that holds a memory address. Pointer variables are declared using the * symbol. Example: int *ptr;
Remember: Relational and logical expressions produce bool values. A pointer variable holds a memory address.
Implicit Type Conversion
Definition
- Type Conversion
- Type conversion is the process of changing one fundamental data type into another.
Implicit conversion is done automatically by the compiler. It commonly happens when different data types are used together in an expression. The compiler converts the smaller type to the wider type; this is called type promotion.
Worked example
int a=6; float b=3.14; cout << a+b;
Try it first, then show the solutionSolution
- The operands have different types: a is int and b is float.
- The compiler converts a from int to float because float is wider than int.
- The values are added.
Answer: The output is 9.14.
For mixed operands, the conversion pattern depends on the operand types. The table identifies the Right Hand Operand as RHO and the Left Hand Operand as LHO.
Explicit Type Conversion and Type Casting
Definition
- Explicit type conversion
- Explicit type conversion is a conversion that the programmer requests from one data type to another specific data type.
(type-name) expression;
type-name is the valid C++ data type to which the expression is converted.
Worked example
float varf=78.685; cout << (int) varf;
Try it first, then show the solutionSolution
- The programmer converts varf from float to int in the cout statement.
- The converted value is displayed.
Answer: The output is 78.
Implicit and explicit conversion
| Implicit conversion | Explicit conversion |
|---|---|
| The compiler performs it automatically. | The programmer requests it using a type cast. |
| It commonly occurs when different data types are mixed in an expression. | It converts a variable or expression to a specific data type. |
Converting to a type with a greater range does not cause a problem. Converting a larger type to a smaller type may lose precision or data. If the original value is outside the target type's range, the result may be undefined.
Possible problems with explicit conversion
- double to float: precision may be lost.
- float to int: the fractional part may be lost.
- long to short: data may be lost.
Results of Explicit Conversion
Worked example
double varf=178.25255685; cout << (float) varf << endl; cout << (int) varf << endl;
Try it first, then show the solutionSolution
- The first statement converts varf to float.
- The second statement converts varf to int.
Answer: The output is 178.253 and 178.
Remember: A type cast specifies the target type, but converting to a smaller type can lose precision, the fractional part, or data.
Questions students ask
Short, direct answers to what students search for in this chapter.
Why is C++ called a hybrid language?
C++ is called a hybrid language because it supports both procedural and Object Oriented Programming paradigms. It is also an extension of C, but the term hybrid refers to its support for both programming approaches.
What are tokens in C++?
Tokens are the smallest individual units in a C++ program. They are also called Lexical units or Lexical elements. The types include keywords, identifiers, literals, operators and punctuators.
What are the rules for naming identifiers in C++?
An identifier must begin with an alphabet or underscore. It may contain only alphabets, digits and underscores. C++ is case sensitive, so uppercase and lowercase letters differ. Keywords cannot be identifiers, and C++ places no limit on identifier length.
What is the difference between octal and hexadecimal constants in C++?
An octal constant begins with 0 and uses digits 0 …. 7. A hexadecimal constant begins with 0x or 0X and uses digits 0 …. 9 and A …. F. For example, 012 is octal and 0x123 is hexadecimal.
What are escape sequences in C++?
Escape sequences represent non-printable characters, also called non-graphic characters, that cannot be typed directly from a keyboard during program execution. An escape sequence is written using a backslash followed by one or two characters.
What is an escape sequence in C++?
An escape sequence represents a special, non-graphical character. It contains two characters, but C++ treats it as one character constant and allocates one byte in ASCII representation. Examples include \n for a newline and \t for a horizontal tab.
Show 24 more questions
Why does a C++ string literal include a null character?
C++ automatically adds the special character \0 to the end of a string literal. This marks the end of the string. Therefore, “welcome” is represented as “welcome\0” in memory and has a size of 8 characters, including the null character.
What is the difference between = and == in C++?
The = operator assigns the value on its right to the variable on its left. The == operator checks whether two operands are equal. For example, assignment stores a value in a variable, while an equality comparison produces a Boolean result.
What do the logical operators &&, || and ! do in C++?
&& returns 1 (True) when both expressions are true; otherwise it returns 0 (false). || returns 1 (True) when either expression is true and 0 (false) when both are false. ! reverses the truth value of a single expression.
What are punctuators in C++?
Punctuators are symbols used as delimiters when constructing a C++ program. They are also called separators. Parentheses indicate function calls and parameters, curly braces mark code blocks, square brackets indicate arrays, and a semicolon ends an executable statement.
What is the difference between cin and cout in C++?
cin uses the >> operator to get input from the keyboard and store it in a variable. cout uses the << operator to send a constant, variable or expression to the monitor. In short, cin receives values and cout displays them.
What is cascading of I/O operators in C++?
Cascading of I/O operators means using multiple input or output operators in one statement. For example, cin >> x >> y; reads values for two variables, while cout << "The sum = " << sum; displays a string and then the value of sum.
What does #include <iostream> do in C++?
#include <iostream> tells the preprocessor to include the iostream header file in the program. This file contains the definitions of cin and cout, which are used for input and output. Without it, the program cannot use cin and cout correctly.
What are the steps to execute a C++ program?
First create the source code and save it with the extension .cpp. Next, compile it. If there are no errors, compilation creates an object file with the extension .obj. Finally, execute the program, producing an executable file with the extension .exe.
What is an IDE in C++?
An IDE is a program that makes it easier to create, compile and execute C++ programs. Many C++ IDEs are open source and available free of cost. Dev C++ is the IDE used for the programming techniques and illustrated programs here.
How do I compile and run a program in Dev C++?
After saving your source file, choose Execute → Compile and Run or press F11. Dev C++ shows any errors under compile log. If compilation succeeds, the program's output appears in the output console.
What are the types of errors in C++?
The common types are Syntax Error, Semantic Error and Run-time error. A syntax error breaks C++ grammatical rules. A semantic error follows the rules but produces an unexpected result. A run-time error occurs during execution because of an illegal operation.
What is a token in C++?
A token is an individual element in a C++ program. Tokens are also called Lexical units or Lexical elements. Keywords, identifiers, literals, operators and punctuators are terms used to describe elements of C++ programs.
What is a variable in C++?
A variable is a named memory location used to hold a value of a specific data type. In C++, declare a variable with its data type before using it, such as int num1;.
What are the five fundamental data types in C++?
The five fundamental data types in C++ are char, int, float, double and void. They are predefined data types and are also keywords used to define the types of data handled by a program.
Why is char often called an integer type?
A char variable can store a character or an integer value. Characters are represented in memory by their associated ASCII Codes, so char is often called an integer type.
What is the difference between float and double in C++?
Both float and double handle floating point numbers. double is for double precision floating point numbers, occupies double the space than float, and can accommodate more fractions. It is also larger and slower than float.
What is void used for in C++?
void specifies an empty set of values. It is used as the return type for functions that do not return any value.
What do R-value and L-value mean in C++?
The R-value is the data stored in a memory location. The L-value is the memory address where that data is stored. A variable has both: its stored value and the location in memory that holds the value.
What is the difference between initialization and dynamic initialization in C++?
Initialization gives a variable an initial value when it is declared, such as int num = 100;. Dynamic initialization gives a variable a value during program execution, such as assigning sum the result of adding num1 and num2.
What are data type modifiers in C++?
Data type modifiers change the memory allocation or storing capacity of fundamental data types, except void. The four modifiers are signed, unsigned, long and short. They can change the range of values a type can store.
What is a junk value in C++?
A junk or garbage value is an unknown value in the memory allocated to a variable that was declared without an initial value. Using that variable in a calculation can make the result depend on unknown values.
How do number suffixes work in C++?
Suffixes can make a number a different type. L or l marks a value as long, and U or u marks it as unsigned; for example, 45L or 45U. F marks a floating point value, as in 3.14F.
What is dynamic initialization in C++?
Dynamic initialization gives a variable its value using values entered or calculated while the program runs. For example, after reading num1 and num2, a program can initialize sum with num1 + num2.
What does const do in C++?
const declares a variable as a constant. Its value cannot be changed during program execution. For example, const int num = 100; keeps num equal to 100, and trying to assign a different value causes an error.
Book back answers
18 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
SECTION – A Choose the correct answer
Who developed C++?
- (a) Charles Babbage
- (b) Bjarne Stroustrup
- (c) Bill Gates
- (d) Sundar Pichai
Try it, then show the answerAnswer
(b) Bjarne Stroustrup
The chapter identifies Bjarne Stroustrup as the developer of C++.
From the book: “C++ was developed by Bjarne Stroustrup at AT & T Bell Laboratory during 1979.”
What was the original name given to C++?
- (a) CPP
- (b) Advanced C
- (c) C with Classes
- (d) Class with C
Try it, then show the answerAnswer
(c) C with Classes
Stroustrup initially named the language “C with Classes”.
From the book: “Bjarne Stroustrup named his new language as “C with Classes”.”
Who coined C++?
- (a) Rick Mascitti
- (b) Rick Bjarne
- (c) Bill Gates
- (d) Dennis Ritchie
Try it, then show the answerAnswer
(a) Rick Mascitti
The chapter says Rick Mascitti coined the name C++.
From the book: “The name C++ was coined by Rick Mascitti”
The smallest individual unit in a program is:
- (a) Program
- (b) Algorithm
- (c) Flowchart
- (d) Tokens
Try it, then show the answerAnswer
(d) Tokens
The smallest individual unit in a program is called a token or lexical unit.
From the book: “The smallest individual unit in a program is known as a Token or a Lexical unit”
Practice
Why is C++ called a hybrid language?
Exam questions
Practice questions with model answers. These are not from an official paper.
What is a token? Name the types of tokens used in C++.2 marks
A token is the smallest individual unit in a program. C++ tokens include keywords, identifiers, literals, operators, and punctuators.
State two rules for naming an identifier in C++.2 marks
An identifier must begin with an alphabet or underscore. It may contain only alphabets, digits, and underscores; other special characters are not allowed.
Explain the difference between the >> and << operators.2 marks
The >> operator extracts input and assigns it to a variable. The << operator sends a string, value, or expression to output.
Describe the four steps for creating and executing a C++ program.5 marks
Creating and executing a C++ program involves four steps. Each step prepares the program for execution by the computer.
- 1. Create the source code: Type and edit valid C++ code according to the rules followed by the C++ compiler.
- 2. Save the source code: After typing, save the source code with the .cpp extension.
- 3. Compile the program: The compiler links the library files with the source code and checks every line. If there are no errors, it translates the source code into a machine-readable object file with the .obj extension.
- 4. Execute the program: The object file becomes an executable file with the .exe extension. The program can then run without the help of a compiler or IDE.
Following these four steps takes a C++ program from source code to an executable program.
Watch out
- Do not confuse =, which assigns a value, with ==, which checks whether values are equal.
- Do not mix up input and output: >> is used with cin to get input, while << is used with cout to send output.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →