VKS-LEARNING HUB

Home » Class-XI » C++ XI » Basics of C++

Basics of C++

A C++ program is a collection of commands, which tell the computer to do “something”. This collection of commands is usually called C++ source codesource code or just code.
Statements and expressions
The most common type of instruction in a program is the statement. A statement in C++ is the smallest independent unit in the language. In human language, it is analogous to a sentence. We write sentences in order to convey an idea. In C++, we write statements in order to convey to the compiler that we want to perform a task. Statements in C++ are terminated by a semicolon.
There are many different kinds of statements in C++. The following are some of the most common types of simple statements:
int x;
x=5;
cout<<x;
int x is a declaration statement. It tells the compiler that x is a variable. All variables in a program must be declared before they are used. We will talk more about variables shortly. x=5  is an assignment statement. It assigns a value (5) to a variable (x).
cout<<x; is an output statement. It outputs the value of x (which we set to 5 in the previous statement) to the screen.
The compiler is also capable of resolving expressions. An expression is an mathematical entity that evaluates to a value. For example, in math, the expression 2+3 evaluates to the value 5. Expressions can involve values (such as 2), variables (such as x), operators (such as +) and functions (which return an output value based on some input value). They can be singular (such as 2, or x), or compound (such as 2+3, 2+x, x+y, or (2+x)*(y-3)).
For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2+3 evaluates to the value of 5. This value of 5 is then assigned to x.
C++ CHARACTER SET
Character set is a set of valid characters that a language can recognize.
Letters
A-Z, a-z
Digits
0-9
Special Characters
Space  +  –  *  /  ^  \  ()  []  {}  =  !=  <>  ‘  “  $  ,  ;  :  %  !  & ? _  #  <=  >=  @
Formatting characters
backspace, horizontal tab, vertical tab, form feed, and carriage return

TOKENS

A token is a group of characters that logically belong together.They are the Building block of a program. The programmer can write a program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

1. Keywords

These are some reserved words in C++ which have predefined meaning to compiler called keywords. A keyword cannot be redefined.Some commonly used Keyword are given below:

asm

auto

break

case

catch

char

class

const

continue

default

delete

do

double

else

enum

extern

inline

int

float

for

friend

goto

if

long

new

operator

private

protected

public

register

return

short

signed

sizeof

static

struct

switch

template

this

Try

typedef

union

unsigned

virtual

void

volatile

while

     

2. Identifiers

Symbolic names can be used in C++ for various data items used by a programmer in his program. A symbolic name is generally  known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rule for the formation of an identifier are:

  • An identifier can consist of alphabets, digits and/or underscores.
  • It must not start with a digit
  • C++ is case sensitive that is upper case and lower case letters are considered different from each other.
  • It should not be a reserved word.

There are two broad categories of identifiers:

Built-in:          It is name of built-in functions, constants, variables, classes and structure. To use built-in identifier we need appropriate header file. Built-in identifier can be redefined.

User-defined: Name created by the programmer like variable names, user-defined function names, constant names, class names and structure names. User-defined identifiers can only be used after they have created or declared.

3. Literals

Literals (often referred to as constants) are data items that never change their value during the execution of the program. The following types of literals are available in C++.

  • Integer-Constants
  • Character-constants
  • Floating-constants
  • Strings-constants

Integer Constants

Integer constants are whole number without any fractional part. C++ allows three types of integer constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0 (zero). For example 124, – 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For example. 014, 012.
Hexadecimal integer constant: It consists of sequence of digits preceded by ox or OX.

Character constants

A character constant in C++ must contain one or more characters and must be enclosed in single quotation marks. For example ‘A’, ‘9’, etc. C++ allows nongraphic characters which cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by using an escape sequence. An escape sequence represents a single character. The following table gives a listing of common escape sequences.

Escape Sequence
Nongraphic Character
\a
Bell (beep)
\n
Newline
\r
Carriage Return
\t
Horizontal tab
 
Null Character

Floating constants

They are also called real constants. They are numbers having fractional parts. They may be written in fractional form or exponent form. A real constant in fractional form consists of signed or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.

String Literals

A sequence of character enclosed within double quotes is called a string literal. String literal is by default (automatically) added with a special character ‘’ which denotes the end of the string. Therefore the size of the string is increased by one character. For example “COMPUTER” will re represented as “COMPUTER” in the memory and its size is 9 characters.

4. Punctuators

The following characters are used as punctuators in C++.

Brackets [  ]
Opening and closing brackets indicate single and multidimensional array subscript.
Parentheses (   )
Opening and closing brackets indicate functions calls,; function parameters for grouping expressions etc.
Braces {   }
Opening and closing braces indicate the start and end of a compound statement.
Comma ,
It is used as a separator in a function argument list.
Semicolon ;
It is used as a statement terminator.
Colon :
It indicates a labeled statement or conditional operator symbol.
Asterisk *
It is used in pointer declaration or as multiplication operator.
Equal sign =
It is used as an assignment operator.
Pound sign#
It is used as pre-processor directive.

Operator: Operators are used in C++ to carry out various functions. Mostly operators are used in arithmetic calculations and in logical expressions. But operators may be used for dynamic memory management. An operator in C++ can be unary, binary and ternary. Examples of operators are given below:

Operator
Expression
Meaning
unary +
+ a
Sign of value stored in a remains unaltered
unary –
– a
Change sign of value stored in a
Binary +
a + b
Adds a and b
Binary –
a – b
Subtract b from a
*
a * b
Multiply a and b
/
a / b
Divide a by b
%
a % b
Remainder of a divided by b
=
a = 10
a is assigned a value 10
++
++a, a++
Increments value stored in a by 1
–a, a–
Decrements value stored in a by 1
+=
a += b
b is added to a and the result is assigned a
-=
a -= b
b is subtracted from a and the result is assigned a
*=
a *= b
a is multiplied by b and the result is assigned a
/=
a /= b
a is divided by b and the result is assigned a
%=
a %= b
a is assigned a value of a % b
==
a == b
a is equal to b
!=
a != b
a is not equal to b
>
a > b
a is greater than b
>=
a >= b
a is greater than equal to b
<
a < b
a is less than b
<=
a <= b
a is less than equal to b
!
!(a < b)
Negate the condition a is less than b
&&
a>=10 && a<=20
a’s value lies between 10 and 20.
||
a<10 || a>20
a’s value is either less than 10 or greater than 20

Unary operator:        An operator that needs one operand.

Examples: Unary -, unary +, ++, — and !.

Binary operator:        An operator that needs two operands.

Example: Binary +, Binary -, *, /, %, C++ short hand operators, logical operators, && and ||.

Ternary operator:     An operator that needs three operands. Ternary operator is also known as Conditional operator. Relational operators (>, >=, <, <=, ==, !=), Logical operators (!, &&, ||) and Ternary operator (?:) will be discussed with ifelse statement.

a)      String: In C++ anything enclosed within a pair of double quotes (“) is a called a String constant. A string is treated as an array of character or as a pointer to a character. Array and pointer will be discussed later. Examples of string are given below:

“India”, “35/8”, “999”, “***”, “GH-14/200”, “6”, “A”, “#”, “”

f)   Comment: Non executable statements of a C++ program are called Comments. Comments are also known as Remarks. A Comment is completely ignored by a compiler. No code is generated for a Comment. Comment is a good tool for Debugging. C++ supports two types of Comments:

Single line Comment:      also known as C++ style Comments. Single Line Comment starts with pair of forward slash (//) and till the end of line is considered as a Comment. Examples of Single Line Comment are given below:

// single line comment

// comment in C++ style

Multi-line comment:        also known as C style comments. Multi-line comment start with forward slash and star (/*) and with star and forward slash (*/). Examples of Multi-Line Comment are given below:

/*

multi-line comments

comment in C style

*/

/* Single line comment */

Compiler directive: instruction given to the compiler. Compiler directive is also called Pre-processor. C++ statement is an instruction given to CPU or to the computer. It is called Pre-Processor because instruction to the compiler given before the processing starts. Every Compiler Directive begins with hash (#). Examples of Compiler Directives are given below:

#include:         to include header files

#define:                        to create C++ macros

C++ Shorthand: C++ allows an expression to be written in a compact form. C++ shorthand works with character (char) type data, integer (int) type data and floating point (float and double) type data. Examples of C++ shorthand are given below:

Operator
Expression
Expansion
Meaning
+=
a += b
a = a + b
Variable a is assigned a value a + b
-=
a -= b
a = a – b
Variable a is assigned a value a – b
*=
a *= b
a = a * b
Variable a is assigned a value a * b
/=
a /= b
a = a / b
Variable a is assigned a value a / b
%=
a %= b
a = a % b
Variable a is assigned a value a % b


Syntax error
: error committed when the syntax of the language (grammar of the language) is violated. Examples of Syntax errors are given below:

a)      Typographical mistakes

b)      Omitted semicolons or coma

c)      References to undeclared variables

d)     Wrong number or type of parameters passed to a function

e)      Call to undefined function

Syntax errors are detected by the compiler. Syntax errors are also known as Compile-Time errors because the errors are flagged by the compiler during compilation time.

Run-time error: Syntactically correct statement performs illegal operation during execution of a program is called Run-Time errors. Illegal operation is performed when the program encounters unexpected data. Run-Time errors are triggered when running the program. Examples of Run-Time errors are given below:

a)      Division by zero (0)

b)      Square root of a negative number

c)      Logarithm of zero (0) or negative number

d)     Inputting character / string value when integer or floating point value is expected

Logical error: An error in program design or program implementation that does not prevent your program from compiling, but causes it to do something unexpected. Examples of Logical errors are given below:

a)      Variables with incorrect or unexpected values

b)      Accumulator or counter not initialised

c)      Incorrect placement of braces (curly brackets) for a block

d)     Missing parenthesis when parenthesis are required

e)      In a logical expression using = instead of ==

C++ Program Structure:

Let us look at a simple code that would print the words Hello World.

#include <iostream.h>

using namespace std;

// main() is where program execution begins.

int main()

{

cout << “Hello World”; // prints Hello World

return 0;

}
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.Let us look various parts of the above program:

  1. The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
  2. The next line // main() is where program execution begins. is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
  3. The line int main() is the main function where program execution begins.
  4. The next line cout << “This is my first C++ program.”; causes the message “This is my first C++ program” to be displayed on the screen.

The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

Semicolons & Blocks in C++:

In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.

For example, following are 4 different statements:

x = 5;

y=x;

y = y+1;

add(x, y);

A block is a set of logically connected statements that are surrounded by opening and closing braces. For example:

{

 cout << “Hello World”; // prints Hello World

return 0;

}

C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where on a line you put a statement. For example:

x = y;

y = y+1;

add(x, y);

is the same as

x = y; y = y+1; add(x, y);

Previous

Solved Examples

Unsolved Questions for Practice

Next


Leave a comment