CH 2
CH 2
List of Compilers:
1. Borland C+ + & Turbo C+ + available from Borland International for DOS & OS/2.
2. Zortech C+ + from Zortech International on DOS.
3. Microsoft Visual C+ + by Microsoft Corp.
4. GNU C+ + usually called as G++.
Given below is the basic structure of any program written in C+ + which when executed
displays the letters “Hello World” on the display unit.
C++ program is a collection of functions. The above example contains only one function,
main (). As usual, execution begins at main (). Every C++ program must have a main (). The
C++ statements terminate with semicolon.
5.3. Comments
Single line comment: C++ introduces single line comment // (double slash). Comments starts
with a double slash symbol and terminate at the end of line.
Example: c=5.0/9*(f-32); //conversion formula.
Multi line comment: Multi line comment symbols are /*, */ the following comment is
allowed,
In the above program the statement cin>>a>>b; is an input statement and causes the program
to wait for the user to type two numbers. If we key in two values, say 10 and 20 then 10 will
be assigned to a, 20 to b. The operator >> is known as extraction (or) get from operator.
The statement cout<<”The result is:”<<c; is an output statement causes the string in
quotation marks to be displayed on the screen as it is and then the content of the variable c is
displayed . The operator << is known as insertion (or) put to operator.
The identifier cin pronounced as ‘C in’ and cout pronounced as ‘C out’).
Constant:
Constant in C++ refers to fixed values that do not change during the execution of a program.
Example: const float pi=3.1415;
Variable: A variable is a data name that may be used to store data value. The value of a
variable may vary throughout program means that, a variable may take different values at
different times during execution.
Identifiers
A valid identifier is a sequence of one or more letters, digits or underscores symbols. The
length of an identifier is not limited, although for some compilers only the 32 first characters
of an identifier are significant (the rest are not considered).
Neither spaces nor marked letters can be part of an identifier. Only letters, digits and
underscore characters are valid. In addition, variable identifiers should always begin with a
letter. They can also begin with an underscore character, but this is usually reserved for
external links. They can never begin with a digit.
Another rule that you have to consider when inventing your own identifiers is that they
cannot match any keyword of the C++ language or your compiler's specific ones since they
could be confused with these. For example, the following expressions are always considered
key words according to the ANSI-C++ standard and therefore they must not be used as
identifiers:
asm, auto, bool, break, case, catch, char, class, const, const_cast,
continue, default, delete, do, double, dynamic_cast, else, enum, explicit,
extern, false, float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast,
struct, switch, template, this, throw, true, try, typedef, typeid,
typename, union, unsigned, using, virtual, void, volatile, wchar_t
Additionally, alternative representations for some operators do not have to be used as
identifiers since they are reserved words under some circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Your compiler may also include some more specific reserved keywords. For example, many
compilers which generate 16 bit code (like some compilers for DOS) also include far, huge
and near as key words.
Very important: The C++ language is "case sensitive", that means that an identifier written
in capital letters is not equivalent to another one with the same name but written in small
letters. Thus, for example the variable RESULT is not the same as the variable result nor the
variable Result.
Declaration of variables
In order to use a variable in C++, we must first declare it specifying which of the data types
above we want it to be. The syntax to declare a new variable is to write the data type specifier
that we want (like int, short, float...) followed by a valid variable identifier. For example:
int a;
float mynumber;
Are valid declarations of variables. The first one declares a variable of type int with the
identifier a. The second one declares a variable of type float with the identifier mynumber.
If you need to declare several variables of the same type and you want to save some writing
work you can declare all of them in the same line separating the identifiers with commas. For
example:
int a, b, c;
declares three variables (a, b and c) of type int , and has exactly the same meaning as if we
had written:
int a;
int b;
int c;
Initialization of variables
When declaring a local variable, its value is undetermined by default. But you may want a
variable to store a concrete value the moment that it is declared. In order to do that, you have
to append an equal sign followed by the value wanted to the variable declaration:
For example, if we want to declare an int variable called a that contains the value 0 at the
moment in which it is declared, we could write:
int a = 0;
Additionally to this way of initializing variables (known as c-like), C++ has added a new way
to initialize a variable: by enclosing the initial value between parenthesis ():
For example:
int a (0);
Both ways are valid and equivalent in C++.
'z'
'p'
"Hello world"
"How do you do?"
The first two expressions represent single characters, and the following two represent strings
of several characters. Notice that to represent a single character we enclose it between single
quotes (') and to express a string of more than one character we enclose them between
double quotes (").
When writing both single characters and strings of characters in a constant way, it is
necessary to put the quotation marks to distinguish them from possible variable identifiers or
reserved words. Notice this:
Character constants and string constants have certain peculiarities, like the escape codes.
These are special characters that cannot be expressed otherwise in the sourcecode of a
program, like newline (\n) or tab (\t). All of them are preceded by an inverted slash (\).
Here you have a list of such escape codes:
\n newline
\r carriage return
\t tabulation
\v vertical tabulation
\b backspace
\f page feed
\a alert (beep)
\' single quotes (')
\" double quotes (")
\? question (?)
\\ inverted slash (\)
For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
5.6. Operators
An operator is a symbol that tells the computer to perform certain mathematical (or) logical
manipulations. Operators used in programs to manipulate data and variables.
C++ operators can be classified into number of categories. They include
1. Arithmetic operators. 2. Relational operators. 3.Logical operators.
4. Assignment operators. 5. Increment / Decrement operators.
6. Conditional operators. 7. Bitwise operators.
1. Arithmetic operators: C++ provides all the basic arithmetic operators like add (+),
subtract (-), multiply (*), divide (/), and mod (%).mod gives remainder of division.
Ex for mod: if a = 10; b = 3; c = a % b; c = 1;
2. Relational operators: These are the operators which relate the operands on either side of
them like less than(<),less than or equal(<=),equal(==),Greater than(>),Greater than or
equal(>=)and not equal(!=).
4. Assignment operators: used to assign the result of an expression to a variable and the
symbol used is ‘= ‘ it is of 3 types .
(i) Simple assignment a = 9;
(ii) Multiple assignment a = b = c = 36;
(iii) Compound assignment a + = 15; (add 15 to a equal to a =a +15;)
b - = 5; (subtract 5 from b).
c * = 6; (Multiply c by 6).
d / = 5; (divide d by 5 equal to d =d /5; ).
e % = 10; (divide e by 10 & store
remainder in e).
Eg. : a = 5; a=5;
b=++a; b=--a;
Result a=b=6; a=b=4;
2.Postfix auto increment / decrement --- This first assigns the value to the
variable on the left & then increments/decrements the operand.
Eg. : a = 5; a=5;
b=a++; b=a--;
Result b=5, a=6 b=5,a=4;
Generally a=a+1 can be written as ++a, a++ or a+=1. Similarly a=a-1 can be written as a--, --
a or a -= 1.
exp1 is evaluated first if the result is true then exp2 is evaluated else exp3 is evaluated
and that value becomes the value of the expression.
For example, consider the following statements.
a=10;
b=15;
x = (a>b) ? a : b;
in this example x will be assigned the value of b.
7. Bitwise operators: refers to the testing, setting or shifting of actual bits in a byte or
1. bitwise and (& ) : This adds corresponding bits in its operands, if both are 1 result is I
otherwise 0.
a=8 1000
b=3 0011
0000
2. bitwise or (| ) : this will or corresponding bits in its operands, if one of the bits is 1, then
result is 1. if both are 0’s result is 0.
a=8 1000
b=3 0011
1011
3. Xor (^ ) : this will exclusive or corresponding bits in its operands. If one is 0 and the other
is 1, Then resulting bit is 1, if both are same then result is 0.
a=8 1000
b=3 0011
1011
4. One’s Complement ( ~ ) : This is a unary operator which inverts the bits in its operand
i.e., 1 becomes 0 and 0 becomes 1.
10010 1’s complement 01101
Priority of operators
When making complex expressions with several operands, we may have some doubts about
which operand is evaluated first and which later. For example, in this expression:
a = 5 + 7 % 2
we may doubt if it really means:
a = 5 + (7 % 2) with result 6, or
a = (5 + 7) % 2 with result 0
The correct answer is the first of the two expressions, with a result of 6. There is an
established order with the priority of each operator, and not only the arithmetic ones (those
whose preference we may already know from mathematics) but for all the operators which
can appear in C++. From greatest to lowest priority, the priority order is as follows:
Associativity defines -in the case that there are several operators of the same priority level-
which one must be evaluated first, the rightmost one or the leftmost one.
All these precedence levels for operators can be manipulated or become more legible using
parenthesis signs ( and ), as in this example:
a = 5 + 7 % 2;
might be written as:
a = 5 + (7 % 2); or
a = (5 + 7) % 2;
according to the operation that we wanted to perform.
So if you want to write a complicated expression and you are not sure of the precedence
levels, always include parenthesis. It will probably also be more legible code.
C+ + consists of many library functions which contain the functions that are used in the
program construction of the language. These are the header files that are to be included
before main () & are sometimes termed as preprocessor statements. Here are some files
given.
1. iostream.h - Standard input /output streams like cin, cout etc.
2. math.h - Mathematical functions like sin(), cos(), sqrt(),log() etc.
3. stdlib.h - Standard library functions like conversion of one type to other etc.
4. String.h - String manipulation functions like strcpy (), strcat(), strcmp() etc.
5. ctype.h - Declares functions for testing characters.
eg., isalpha(),isnum(),islower(),toupper(),tolower() etc.
6. time.h - Includes date & time functions.
sample program 2: Write a c++ program to read the temperature in Fahrenheit and convert it
into Celsius. (Formula: c= (5.0/9)*(f-32)).
#include<iostream.h>
Void main ()
{
float c, f;
cout<<”Enter the temperature in farenheit:”;
cin>>f;
c=(5.0 / 9)*(f - 32);
cout<<”The temperature in celcious is: ”<<c;
}