0% found this document useful (0 votes)
10 views9 pages

CH 2

Uploaded by

matias bahiru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

CH 2

Uploaded by

matias bahiru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

Arba Minch University Engineering Faculty

Computer Science Department


Comp207 - Introduction to Basics of Computer
Programming
CHAPTER-2: Introduction to C++ Programming

5.1 History of C++

C++ is an Object Oriented Programming Language. It was initially named ‘C with


classes’, C++ was developed by Bjarne Stroustrup at AT&T Bell laboratories in Murray Hill,
New Jersey, USA, in the early eighties. Stroustrup, an admirer of Simula67 and a strong
supporter of C, wanted to combine the best of both languages and create a more powerful
language that could support object-oriented programming features and still retain the power
and elegance of C. The result was C++. Stroustrup called the new langrage ‘C with classes’.
However, later in 1983, the name was changed to C++. C++ is a super set of C. Therefore,
almost all C programs are also C++ programs.

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++.

5.2. Basic Program structure

Given below is the basic structure of any program written in C+ + which when executed
displays the letters “Hello World” on the display unit.

// First C+ + Program --- Comment Line


# include <iostream.h> --- Inclusion of header files called as pre processor statements.
void main ( ) --- Name of the main function or start of main () function.
{ --- Indicates beginning of main ()
cout<< “Hello World”; --- Executable output statement.
} --- End of main ()

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,

Introduction to Basics of Computer programming Page 1 of 9


/* this is an example of C++ program to illustrate some of its features */
The comment lines in the program are ignored by the compiler.

5.4. Input/Output statements in c++


Example:
#include <iostream.h>
void main ()
{
int a, b, c;
cout<<”enter values of a, b”;
cin>>a>>b;
c=a+b;
cout<<”The result is:“<<c;
}

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.

5.5. Built in data types

1) integer: They are the numbers without decimal part.Ex:69,360,32330


2) float, double: They are the numbers with decimal point. Ex:69.65,3.1415
3) character: Any letter enclosed within single quotes comes under character.
The modifiers signed, unsigned, long, and short may be applied to character and integer
basic data types. However, the modifier long may also be applied to double. The following
table lists all combinations of the basic data types and modifiers along with their size and
range.

Table: size and range of C++ basic data types

Type Bytes Range


Char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535

Introduction to Basics of Computer programming Page 2 of 9


signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4E -38 to 3.4E +38
double 8 1.7E -308 to 1.7E +308
long double 10 304E -4932 to 1.1E +4932

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.

Introduction to Basics of Computer programming Page 3 of 9


Once declared, variables a and mynumber can be used within the rest of their scope in the
program.

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:

type identifier = initial_value ;

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 ():

type identifier (initial_value) ;

For example:
int a (0);
Both ways are valid and equivalent in C++.

There also exist non-numerical constants, like:

'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:

Introduction to Basics of Computer programming Page 4 of 9


x
'x'

x refers to variable x, whereas 'x' refers to the character constant 'x'.

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(!=).

3. Logical operators: C++ has the following three logical operators.


&& (meaning logical AND), || (logical OR), ! (logical NOT).

Introduction to Basics of Computer programming Page 5 of 9


Table: Truth table for AND and OR operations.

op-1 op-2 op-1 && op-2 op-1 || op-2

false false false false


false true false true
true false false true
true true true true

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).

5. Auto increment / decrement (+ + / - - ): used to automatically increment


and decrement the value of a variable by 1.there are 2 types.
1. Prefix auto increment / decrement --- Adds /subtracts 1 to the operand & result
is assigned to the variable on the left.

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.

6. Conditional operator (ternary operator): Conditional expressions are of the following


form.

exp1 ? exp2 : exp3 ;

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

Introduction to Basics of Computer programming Page 6 of 9


word. There are 4 operators.

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

5. Bitwise Shift operators:


(a) (<<) shift left – shifts bits to left
a=8, b=2 & c=a<<b i.e., a is to be shifted 2 places left so c becomes 32
(2b times multiplied)
a = 00001000 after shift c=00100000

(b) (>>) Shift right – shifts bits right


a=8, b=2 & c=a<<b i.e., a is to be shifted 2 places right so c becomes 2
(2b times divided)
a = 00001000 after shift c=00000010.

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:

Priority Operator Description Associativity


1 :: scope Left
2 () [ ] -> . sizeof Left

Introduction to Basics of Computer programming Page 7 of 9


++ -- increment/decrement
~ Complement to one (bitwise)
! unary NOT
3 Right
& * Reference and Dereference (pointers)
(type) Type casting
+ - Unary less sign
4 * / % arithmetical operations Left
5 + - arithmetical operations Left
6 << >> bit shifting (bitwise) Left
7 < <= > >= Relational operators Left
8 == != Relational operators Left
9 & ^ | Bitwise operators Left
10 && || Logic operators Left
11 ?: Conditional Right
= += -= *= /= %=
12 >>= <<= &= ^= |= Assignation Right
13 , Comma, Separator Left

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.

5.7. Library Functions

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.

Introduction to Basics of Computer programming Page 8 of 9


Sample program 1: Write a c++ program to calculate area of a circle for given diameter d,
using formula r2 where r=d/2.
// to calculate area of circle
#include<iostream.h>
void main()
{
float A, pi=3.1415;
float d, r;
cout<<”enter the diameter of circle\n”;
cin>>d;
r=d / 2;
A= pi * r * r;
Cout<< “Area of circle is”<<A;
}

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;
}

Introduction to Basics of Computer programming Page 9 of 9

You might also like