0% found this document useful (0 votes)
57 views

Programming in C++ (Week 1)

This document provides an overview of the basic elements of C++ programming. It discusses the origin and development of C++, the structure of a simple "Hello World" program, basic syntax elements like comments, preprocessor directives, and functions. It also covers fundamental C++ concepts like variables, data types, input/output streams, and constants. The document serves as an introduction to programming in C++ for beginners.

Uploaded by

Vijay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Programming in C++ (Week 1)

This document provides an overview of the basic elements of C++ programming. It discusses the origin and development of C++, the structure of a simple "Hello World" program, basic syntax elements like comments, preprocessor directives, and functions. It also covers fundamental C++ concepts like variables, data types, input/output streams, and constants. The document serves as an introduction to programming in C++ for beginners.

Uploaded by

Vijay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Programming in C++

(Week 1)

Origin of C++

Developed by Bjarne Stroustrup at Bell Labs in


1980s, as an extension of the C programming
language by adding features from the language
Simula 67.

Initially called C with Classes.

The name C++ was coined from the C increment


operator ++.

The major reason behind the success of C++ is that it


uses object oriented technology.

Basic Elements of C++


First Program:
comment
// first C++ program
preprocessor directive
#include <iostream>
which namespace
using namespace std;
to use
beginning of the function main
int main()
beginning of the body of main
{
cout << Welcome to C++!\n";
action (output)
return 0;
return 0 to operating system
7 }

1
2
3
4
5
6

end of the body of main

Line 1 is a comment. A comment begins with a double


slash // (single line comment).
Comments are ignored by the compiler, but they
immensely help in understanding the program.
Line 2, #include <iostream>, is a preprocessor
directive which instructs the C++ system to include into
the program the contents of the file name iostream.
A line beginning with a pound sign (#) is a
preprocessor directive. It is not considered to be a C++
statement and hence not terminated by a semicolon.

A file whose name appears in #include directive


is called a header file.

Header files contain certain constants, variables,


data types, or function declarations needed by a
program.

The input /output stream header file <iostream>


contains declarations of input/output functions.
(Similarly, we can have preprocessor directive like:
#include <string>
The file string contains declarations for the string
data type.)

Line 3, using namespace std; , is to make


the identifier cout accessible to our program.
The header file <iostream> ( and in fact all
standard header files) declares all of its identifiers
to be in a namespace block called std.
Line 4, int main(), is a part of every C++
program. The parentheses after main indicate that
it is a function. Exactly one function in a C++
program must be main.
In any C++ program, the program execution starts
at main. The function main is, in a sense, the
master function of any program.

The word int in main indicates that main is a


value returning function that should return an integer
value. In this program it returns 0.
Line 5, {, indicates the start of the body of the
function main. Every function body must start with
the left brace, {.
Line 6, cout << Welcome to C++!\n,
instructs the computer to perform an action in this
case, output the string contained between the double
quotation marks.
The characters \n in line 6 is an escape sequence,
denoting here the newline command.

The backslash character (\) is called an escape


character and it indicates that a special character
is to be output.
Line 7, return 0, indicates that the function
main returns value 0 to the operating system. It
indicates here that the program has terminated
successfully.
Line 8, }, indicates the end of the body of the
function main. Every function body must end
with a right brace, }.

Some Special Characters


Character

Name

Description

//

Double Slash

Begins a comment

Pound Sign

Begins preprocessor directive

<>

Open, Close Brackets

Encloses filename used in


#include directive

()

Open, Close Parentheses

Used when naming function

{}

Open, Close Braces

Encloses a group of statements

""

Open, Close Quote Marks

Encloses string of characters

Semicolon

Ends a programming
statement

Tokens, Identifiers and Keywords


A C++ program is a sequence of elements called
tokens.
A token is either an identifier, a punctuation symbol
such as {, or an operator such as <<.
An identifier is a name associated with a function or a
data object and used to refer to that function or data
object.
An identifier must begin with a letter or an underscore.
Normally it should not have length greater than 31.
C++ is case sensitive uppercase and lowercase letters
are different. So, a1 and A1 are different identifiers.

There are some identifiers which are reserved for


specific uses in C++. Such identifiers are called
keywords. For example int, float, if are keywords.
A keyword cannot be used as a programmer defined
identifier.

Valid and invalid identifiers


Identifier
totalSales

Valid ?
Yes

Reason if invalid

total_Sales

Yes

total.Sales

No

Cannot contain
period

4thQtrSales

No

Cannot begin with a


digit

totalSale$

No

Cannot contain ($)

as

No

Cannot use ()

Class-mark
Student, num

No
No

Cannot use dash (-)


Cannot use comma

Student name

No

Cannot use space

Variables
A variable is a symbol that represents a memory
location in computers memory.
Different values may be stored at different times at
this location.
The content of a variable (memory location) is called
the value of the variable.
Declaring a variable means specifying a variable and
its data type. A variable declaration has the following
form:
(optional)

data type

variable name

initializer

For example: int sum = 100;


int count;
char mychar;
float average;
More than one variables of same type can be declared in
the same line as follows:
int count, firstnumber, secondnumber;
char mychar, char1, char2, initial;
float height, weight, average;

A variable can be declared anywhere in the program but


it must appear before it is used.

Since variables correspond to memory locations,


therefore when an input command such as
cin >> number 1;
is executed, the characters typed by the user are
converted into the data type of number1 that is placed into
memory location assigned to number1.
When a new value is assigned to number1, it overwrites
the previous value stored at that place

Constants
A constant is a location in the memory, referenced by
an identifier, that cannot be changed .
Examples:
const float PI = 3.14159;
const int N = 100;
const char BEEP = \b;
A constant must be initialized when it is declared.

Input/Output Streams
Output Stream object cout:
In C++, the output on the standard stream is performed
using the cout output stream object.
Requires iostream file for performing output.
The information is sent to cout object using the output
operator << (also known as put operator or stream
insertion operator).
<< inserts the value of the variable on its right into the
output stream that is named on its left. For example:
cout << area;

More than one item can be displayed using a single


cout object. Such outputs are called cascaded output
operations. For example:
cout << Number = << number

<< endl;

The cout object displays all the items from left to


right, hence the name stream.

Input Stream object cin:


Standard input object.
Like cout, requires iostream file.
The input information is sent to cin using the input
operator >> (also known as get operator or
extraction operator).
>> takes the value from the object named on its left
and places it in the variable on its right.
More than one item can be displayed using a single
cin object. For example:
cin >> number1 >> number 2;

Multiple values from keyboard must be separated by


spaces or [Enter].
Multiples values may have different data types.
User input goes from keyboard to the input buffer,
where it is stored as characters.
The cin object converts the data to the type that
matches the variable
int number;
cout << The number is ";
cin

>> number;

Spacing
Blank spaces are ignored by the compiler except
where needed to separate the identifiers, as in
int main
However, a blank space is given output if it is part of
some string . For example
cout << First number ;

Data Types
In C++, each piece of data must be of a specific data
type.
The data type determines how the data is represented in
the computer and the kind of processing the computer
can perform on it.
C++ supports following classes of data types:
Primary (fundamental) data types,
Derived data types,
User defined data types.

C++ has following primary data types:


char a single character
int an integer
float a single precision floating point number.
double a double precision floating point number.

Character Data Type char:


Describes data consisting of one alpha -numeric
character a letter, a digit, or a special symbol:
A, a, 5, +, $, *,
A char type is actually an integral type whose
variables represent characters.
char c = A;
cout << c = << c << endl;
cout << int (c) = << int(c);
Output:
c = A
int(c) = 65

Integral Data Types:


Represents an integer value a whole number without
fractional part.
C++ has following integral data types:
char, short, int, long, bool
By default an integral data type is a signed integer,
unless it is explicitly declared as unsigned, such as
unsigned int x;
A unsigned integer value is non-negative.
All integral data types can be declared as unsigned,
except bool.
The data types char, short, int, and long
are designed to represent different sizes of integers.

The following table shows memory sizes and the ranges of


different integral data types. These values may be different for
different machines.
Type

Size in
Bytes

Minimum Value Maximum Value

char

-128

127

unsigned char 1

255

short

-32,768

32,768

unsigned
short

65, 535

int

- 231

231- 1

unsigned int

232- 1

long

- 263

263- 1

264- 1

unsigned long 8

Boolean Type:
A bool data type is an integral type consisting of just
two values, the constants true and false. These
values are stored as 1 and 0 respectively.
Example:
bool
cout
flag
cout

flag = false;
<< flag = << flag << endl;
= true;
<< flag = << flag << endl;

Output:
flag = 0
flag = 1

Enumeration Data Type:


An enumeration data type is a user defined data type. It
is an integral type that has the syntax
enum typename{enumeration-list};
where enum is a keyword, typename is the
identifier, and enumeration-list stands for a list of
names for integer constants.
For example :
enum color{red, blue, green};
We can then declare variables of this type:
color = c1, c2;
and we can use them as simple data types:
if(c1==c2)cout<< same colors<< endl;

C++ compiler treats enumeration types as consecutive


integers. In the above example, the identifiers red,
blue, and green are treated as 0, 1, and 2,
respectively. For example, the statements will produce
output c = 1.
color c = blue;
cout << c = <<c;
Constants values can explicitly be specified for the
identifiers, such as
enum color{red=10, blue, green=20};
The enumerator blue will be assigned value 11.

Floating Point Data Types:


Used to represent floating point numbers .
In C++, there are three types of floating point data types:
float, double (double precision), and
long double (extended double precision).
Memory sizes and ranges of floating point data types:
Type

Size in Bytes

Minimum
Positive value

Maximum
Positive Values

float

3.4 E - 38

3.4 E +38

double

1.7 E -308

1.7 +308

long
double

10

3.4 E - 4932

1.1 E +4932

Strings
A string in C++ is just a sequence of consecutive
characters in memory, the last one being the null
character.
The null character has ASCII code 0 and is called the
end of string marker.
For example, the statement
Hello dear;
will be stored in the computer memory as given below:
H e l
Start of the string

e a r \0
Start of the string

A string must be typed entirely on one line. Splitting a


string in more that one line is a syntax error. For
example, the string
C++ is an object
oriented language
is not valid because it is split across two lines.
The quotes are not parts of a string, they only indicate
that the content between them is a string.
A string containing no characters is called a null string
or an empty string. It is written as .
To work with strings, there is also a data type in C++
named string . string is not a standard C++ data
type but supplied by C++ standard library.

Arithmetic Operators and Expressions


Expressions are made up of constants, variables, and
operators.
C++ has following arithmetic operators:
Unary plus +, such as +x;
Unary minus -, such as x;
Addition +, such as x + y;
Subtraction -, such as x y;
Multiplication *, such as x*y;
Division /, such as x/y; (floating point division, integer
division)
Modulus % (remainder from integer division).

The first two operators are unary. The remaining


operators are all binary operators.
Division, such as 5/0, and modulus, such as 5%0, both
produce errors.
In floating point division, an expression such as
5.0/0.0 produces a special infinity value inf.
The modulus operation can be performed only with the
integers. Modulus operation on non integer operands is
a compilation error.
Arithmetic expressions in C++ must be entered into the
computer in a straight line form.
Parentheses in C++ expressions are used in the same
manner as in algebraic expressions, e. g., a*(b + c).

Rules of Operator Precedence:


Expressions within parentheses are evaluated first. In
case of nested parentheses, the innermost pair of
parentheses is applied first.
Multiplication, division, and modulus operations are
applied next. In case of several such operations,
operators are applied from left to right.
Additions and subtractions are applied last. In case of
several additions or subtractions, operators are applied
from left to right.

Type Coercion /Conversion


Integer values and floating point values are stored
differently in computers memory- only the
corresponding type of data can be stored for a defined
variable.
If an integer value is assigned to a variable declared as a
float variable the computer implicitly converts the
integer value into value into a floating point number, or
vice-versa. This is known as type coercion. For example:
int number = 4.5;
cout << number;
will produce the output 4.

Generally, mathematical expressions, consisting of mixed


data types lead to type coercion:
int number1, number2;
float average;
average = (number1+number2)/2.0;

To make a program clear and error-free, we can use


explicit type casting (or type conversion). A C++ cast
operation consists of a data type and then, within
parentheses the expression to be converted:
average = float(number1 + number2)/float(2);
num1 = int(average);

Relational Operators
A relational operator is used to make comparison
between two expressions. These operations are binary.
In C++, we have following relational operators:
Operator

Meaning

Sample
conditions

<
>

Less than
Greater than

x < y
x > y

<=

Less than or
equal to

x <= y

>=

Greater than or
equal to

x >= y

==

Equal to

x == y

!=

Not equal to

x != y

Reversing the pair of symbols in a relational operator is


normally a syntax error.
Confusing the equal to operator == with the assignment
operator = results in a logical error.
Sample C++ statements:
if (number1 < number 2)
cout << number1 << < << number2;
if (number1 == number 2)
cout << number1 << == << number2;
(etc.)

Assignment Operators
The assignment operator = evaluates the expression on
the right and assigns the resulting value to the variable
on its left.
Other than the assignment operator = , C++ provides
several compound assignment operators for
abbreviating assignment operations.
For example, the statement
c = c+3;
can be abbreviated with the addition assignment
operator += as
c += 3;

In general, any statement of the form


variable = variable operator expression;

in which the same variable appears on both sides of the


assignment operator and operator is one of the binary
operator +, -, *, /, or, %, can be written in the form
variable operator= expression;
Examples:
c += 5; for c = c + 5;
d -= 4; for d = d -4;
e *= 3; for e = e * 3;
f /= 4; for f = f / 4;
g %= 7; for g = g % 7;

Increment and Decrement Operators


C++ also provide two unary operations for adding 1 or
subtracting 1 from the value of a numeric variable.
These are the unary increment operator , ++, and the
unary decrement operator, --.
Each of these two operators can be used as prefix or
postfix, and their meaning changes accordingly.
When used as a prefix, the value of the variable is
incremented/decremented before being used in the
expression in which it resides.
But when used as postfix, its value is first used in the
expression and then the value is incremented/
decremented.

These operators are summarized below:


Operato Called
r

Sample
Explanation
Expressio
n

++

Preincreme ++a
nt

++

Post
increment

--

Predecreme --a
nt

Decrement a by 1, then use the new


value of a in the expression in which a
resides.

--

Postdecrem a-ent

Use current value of a in the expression


in which a resides, then decrement a by
1.

a++

Increment a by 1, then use the new


value of a in the expression in which a
resides.
Use current value of a in the expression
in which a resides, then increment a by
1.

When a variable is incremented or decremented in a


statement by itself, then the preincrement (predcrement)
and postincrement (postdecrement) have the same effect.
For example
++m; and m++; will produce the same result.
However, the statements
a = ++b; and
a = b++;
will produce different results. In the first case, b is
incremented first and then its new value is assigned to a. In
the second case, the current value of b is assigned to a and
then the value of b is incremented.

You might also like