Sei sulla pagina 1di 62

Introduction to Programming

Engr. Rashid Farid Chishti


chishti@iiu.edu.pk
Chapter 02: C++ Programming Basics

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk

Basic Program Construction


1
2
3
4
5
6
7
8
9

//first.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
cout << "Welcome to this course\n";
system("PAUSE");
return 0;
}

Explanation:
This program consists of a single function
called main().

Basic Program Construction

Because of the parentheses() the compiler


comes to know that this a function not a
variable.
The parentheses arent always empty. Theyre
used to hold function arguments (values passed
from the calling program to the function).
Line number 2 and 3 are not part of the
function.
The word int preceding the function name
indicates that this particular function has a
return value of type int.
The body of a function is surrounded by braces
(sometimes called curly brackets).

Basic Program Construction

Every function must use this pair of braces


around the function body.
A function body can consist of many statements
but this function has only three statements
(line number 5, 6 and 7)
You can put several statements on one line and
one statement in over two or more lines.

1
2
3

cout
<<"Welcome to this course\n"
;

cout <<"Welcome Students\n" ; return 0;

Basic Program Construction


We dont recommend these syntax. its
nonstandard and hard to read. but it does
compile correctly.
#include is a preprocessor directive, which
must be written on one line.
#include <iostream> tells the compiler to
first include standard C++ library named
iostream to our project.
A string constant "Welcome to this course\n"
can also be broken into separate lines if u
insert a backslash (\) cout
at the line break or
cout
divide the string into two separate strings,
<<"Welcome \
<<"Welcome "
each surrounded by quotes
to this \
"to this "
course\n"
"course\n"
;
;

Basic Program Construction

A programs may consists of many functions but


the main() function will be executed first.
If there is no function called main() in your
program, an error will be reported when you
run the program.
main() function may also call other functions.

Program Statements

There are two statements this program


cout <<"Welcome to this course\n";
return 0;
The first statement tells the computer to
display the quoted phrase.
A semicolon ; signals the end of the
statement. If you leave out the semicolon, the
compiler will often signal an error.
The return 0; tells main() to return the value
0 to whoever called it, in this case the
operating system or compiler.
you can not give main() the return type of
void, this is an error in new compilers.

Output using cout

cout <<"Welcome to this course\n";


The identifier cout (pronounced C out) is
actually an object. It is predefined in C++ to
correspond to the standard output stream.
A stream is an abstraction that refers to a
flow of data. The standard output stream
normally flows to the screen display although
it can be redirected to other output devices.
The operator << is called the insertion or put
to operator. It directs the contents of the
variable on its right to the object on its
left.
In our program it directs the string constant
<<"Welcome to this course\n" to cout, which
sends it to the display.

Output using cout

(If you know C, youll recognize << as the


left-shift bit-wise operator and wonder how it
can also be used to direct output.
In C++, operators can be overloaded. That is,
they can perform different activities,
depending on the context.

String Constants

The phrase in quotation marks, "Welcome to


this course\n", is an example of a string
constant.
A constant, unlike a variable, cannot be given
a new value as the program runs. Its value is
set when the program is written, and it
retains this value throughout the programs
existence.
The '\n' character at the end of the string
constant is an example of an escape sequence.
The '\n' causes the next text output to be
displayed on a new line.
Line no. 2 and 3 in our program are called
directives. The first is a preprocessor
directive,and the second is a using directive.

Directives

Theyre not part of the basic C++ language,


but theyre necessary anyway.
Preprocessor Directives
#include <iostream>
This is not a program statement or a part of a
function body. It starts with a number sign
(#). Its called a preprocessor directive.
Recall that program statements are instructions to the computer to do something, such as
adding two numbers or printing a sentence.
A preprocessor directive, on the other hand,
is an instruction to the compiler. A part of
the compiler called the preprocessor deals
with these directives before it begins the
real compilation process.

#include Directive

The preprocessor directive #include tells the


compiler to insert another file into your
source file. In effect, the #include directive
is replaced by the contents of the file
indicated.
Using an #include directive to insert another
file into your source file is similar to
pasting a block of text into a document with
your word processor.
#include is only one of many preprocessor
directives, all of which can be identified by
the initial # sign.
The type file usually included by #include is
called a header file.

Header Files

In our program the preprocessor directive


#include tells the compiler to add the source
file IOSTREAM to the FIRST.CPP source file
before compiling.
IOSTREAM is an example of a header file
(sometimes called an include file). Its
concerned with basic input/output operations,
and contains declarations that are needed by
the cout identifier and the << operator.
Without these declarations, the compiler wont
recognize cout and will think << is being used
incorrectly.
The newer Standard C++ header files dont have
a file extension, but some older header files
have the extension .H.

using Directive

A C++ program can be divided into different


namespaces. A namespace is a part of the
program in which certain names are recognized;
outside of the namespace theyre unknown.
The directive using namespace std; says that
all the program statements that follow are
within the std namespace.
Various program components such as cout are
declared within this namespace. If we didnt
use the using directive, we would need to add
the std name to many program elements. e.g.
std::cout << "Welcome to this course\n";
To avoid adding std:: dozens of times in
programs we use the using directive instead.

Comments
Comments help the person writing a program,
and anyone else who must read the source file,
understand whats going on.
The compiler ignores comments, so they do not
add to the file size or execution time of the
executable program.
Comments start with a double slash symbol (//)
and terminate at the end of the line

1
2
3
4
5
6
7
8

//first.cpp
#include <iostream> // preprocessor directive
using namespace std; // "using" directive
int main()
// function name "main"
{
// start function body
cout <<"Welcome to this course\n";
// statement
return 0;
// statement
}
// end of function body

Other Styles of Comments


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

/* this is an old-style comment */


/* this
is a
potentially
very long
multiline
comment
*/

int main(/* a comment within parentheses*/)


{ /* this is comment into the function body */ }

Integer Variable

Variables are the most fundamental part of any


language. A variable has a symbolic name and
can be given a variety of values.
Variables are located in particular places in
the computers memory. When a variable is
given a value, that value is actually placed
in the memory space assigned to the variable.
Integer variables represent integer numbers
like 1, 30,000, and 27. Such numbers are used
for counting discrete numbers of objects, like
11 pencils or 99 bottles of beer.
integers have no fractional part; you can
express the idea of four using integers, but
not four and one-half.

Defining an Integer Variable

Integer variables exist in several sizes, but


the most commonly used is type int.
The amount of memory occupied by the integer
types is system dependent.
On a 32-bit system such as Windows, an int
occupies 4 bytes (which is 32 bits) of memory.
This allows an int to hold numbers in the
range from 2,147,483,648 to 2,147,483,647.
The type int occupies 4 bytes on current
Windows computers, it occupied only 2 bytes in
MS-DOS and earlier versions of Windows.

Figure: A variable of type int in memory

Defining an Integer Variable


// intvars.cpp
// demonstrates integer variables
#include <iostream>
using namespace std;
int main()
{
int var1;
int var2;
var1 = 20;
var2 = var1 + 10;
cout << "var1+10 is ";
cout << var2 << endl;

//
//
//
//
//
//

define
define
assign
assign
output
output

an integer var1
an integer var2
value 20 to var1
value 20+10 to var2
text
value of var2

system("PAUSE");
// Suspend the processing of Program
return 0;
// return the value 0 to whoever called it
}

Code Explanation

The statements int var1; int var2; define two


variables, var1 and var2 of type integer.
These statements, which are called
declarations, must terminate with a semicolon
You must declare a variable before using it.
However, you can place variable declarations
anywhere in a program. Its not necessary to
declare variables before the first executable
statement (as was necessary in C).
A declaration introduces a variables name
(such as var1) into a program and specifies
its type (such as int).
if a declaration also sets aside memory for
the variable, it is also called a definition.

Variable Names

The statements int var1; int var2; in the


program are definitions, as well as declarations, because they set aside memory for var1
and var2.
The program uses variables named var1 and var2
The names given to variables are called
identifiers. You can use upper and lowercase
letters, and the digits from 1 to 9. You can
also use the underscore (_).
The first character must be a letter or
underscore. Identifiers can be as long as you
like, but most compilers will only recognize
the first few hundred characters. The compiler
distinguishes between upper and lowercase
letters, so Var is not the same as var or VAR.

keyword

You cant use a C++ keyword as a variable


name. A keyword is a predefined word with a
special meaning. int, class, if, and while are
examples of keywords. A complete list of
keywords can be found in Appendix B.
A variables name should make clear to anyone
reading the listing variables purpose and how
it is used. Thus a variable int age is better
than something simple like int a or int aa.
The statements var1 = 20; var2 = var1 + 10;
assign values to the two variables.
The equal sign (=), causes the value on the
right to be assigned to the variable on the
left. in the statement var1 = 20; var1, which
had no value, is given the value 20.

Integer constant

The number 20 is an integer constant Constants


dont change during the course of the program.
An integer constant consists of numerical
digits. There must be no decimal point in an
integer constant, and it must lie within the
range of integers.
In the second program line, the plus sign (+)
adds the value of var1 and 10, in which 10 is
another constant. The result of this addition
is then assigned to var2.
The statement cout << "var1+10 is "; displays a
string constant.
The next statement cout << var2 << endl;
displays the value of the variable var2.

cout <<

cout and the << operator know how to treat an


integer and a string differently.
If we send them a string, they print it as
text. If we send them an integer, they print
it as a number.
As you can see, the output of the two cout
statements appears on the same line on the
output screen. No linefeed is inserted
automatically. If you want to start on a new
line, you must insert a linefeed yourself.
Weve seen how to do this with the '\n' escape
sequence. Now well see another way: using
something called a manipulator.

The endl Manipulator

The last cout statement in the INTVARS program


ends with an unfamiliar word: endl. This causes
a linefeed to be inserted into the stream, so
that subsequent text is displayed on the next
line.
It has the same effect as sending the '\n'
character, but is somewhat clearer.
Its an example of a manipulator. Manipulators
are instructions to the output stream that
modify the output in various ways; well see
more of them as we go along. Strictly
speaking, endl (unlike '\n') also causes the
output buffer to be flushed, but this happens
invisibly so for most purposes the two are
equivalent.

C++ Data Types


Data Type
bool

Size
1 byte

Range
true(1) or false(0)

char or
signed char

1 byte
(8 bits)

(-27) ~ (+27-1) = -128 ~ +127

unsigned char

1 byte
(8 bits)

0 ~ 28-1 = 0 to 255 or
256 Different ASCII Characters

short or
signed short

2 bytes
(16 bits)

unsigned short

2 bytes

(-215) ~ (+215-1) =
-32,768 ~ +32,767
0 ~ 216-1 = 0 to 65,535

int or
signed int

4 bytes
(32 bits)

(-231) ~ (+231-1) =
-2,14,74,83,648 ~ +2,14,74,83,647

unsigned int

4 bytes
(32 bits)

0 ~ (232 - 1) =
0 ~ 4,29,49,67,295

long

4 bytes
(32 bits)

(-231) ~ (+231-1) =
-2,14,74,83,648 ~ +2,14,74,83,647

C++ Data Types


Data Type

Size

Range

unsigned long

4 bytes
0 ~ (232 - 1) =
(32 bits) 0 ~ 4,29,49,67,295

float

4 bytes
- (1.2 10-38 ~ 3.4 1038)
(32 bits) + (1.2 10-38 ~ 3.4 1038)

double

8 byte
- (2.2 10-308 ~ 1.7 10308)
(64 bits) + (2.3 10-308 ~ 1.7 10308)

specifying type long will guarantee a four-bit


integer type on a 16-bit system such as MS-DOS
In 16-bit systems, type int has the same range
as type short.
On all systems type short occupies two bytes.

C++ Data Types


// assigns long constant
// 7678 to v1 of type long
Many compilers offer integer types that
explicitly specify the number of bits used.
They are __int8, __int16, __int32, and __int64
char data type is used to store numbers that
confine themselves to a limited range, but it
is commonly used to store ASCII characters.
ASCII character set is a way of representing
English alphabet in a 8-bit space.
Character constants use single quotation marks
around a character, like 'a' and 'b'. (Note
that this differs from string constants, which
use double quotation marks)

long v1 = 7678L;

C++ Data Types

When the C++


compiler
encounters such a
character
constant, it
translates it into
the corresponding
ASCII code.
The constant 'a'
appearing in a
program, for
example, will be
translated into
97, as shown in
Figure.

Dec

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Hex Char Dec

Hex Char Dec

Hex Char Dec

Hex Char

Dec

Hex Char Dec

00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
10
11
12
13
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F

20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F

40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F

60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

!
"
#
$
%
&
'
(
)
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

`
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~

Hex Char Dec

160 A0
161 A1
162 A2
163 A3
164 A4
165 A5
166 A6
167 A7
168 A8
169 A9
170 AA
171 AB
172 AC
173 AD
174 AE
175 AF
176 B0
177 B1
178 B2
179 B3
180 B4
181 B5
182 B6
183 B7
184 B8
185 B9
186 BA
187 BB
188 BC
189 BD
190 BE
191 BF

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

Hex Char Dec

Hex Char

C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF

E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

Programming Example
// charvars.cpp
// demonstrates character variables
#include <iostream>//for cout, etc.
using namespace std;
int main()
{
char charvar1 = 'A';
// char charvar1 = 65;
char charvar2 = '\t'; // char charvar2 = 9;
cout << charvar1;
// display character
cout << charvar2;
// display character
charvar1 = 'B';
// char charvar1 = 66;
cout <<charvar1;
// display character
cout << '\n';
// try cout << char (10);
system("PAUSE");
return 0;
}

Escape sequence

'\t' and '\n', are special character with have


different behavior. These are called escape
sequence. The name reflects the fact that the
backslash causes an escape from the normal
way characters are interpreted.
In this case the t is interpreted not as the
character 't' but as the tab character. A tab
causes printing to continue at the next tab
stop.
cout << "\"Run, \tForrest, run,\" she said.";

Escape sequence
This translates to

"Run,
Forrest, run," she said.
Sometimes you need to represent a character
constant that doesnt appear on the keyboard,
such as the graphics characters above ASCII
code 127.
To do this, you can use the '\xdd' representation, where each d stands for a hexadecimal
digit. If you want to print a solid rectangle,
for example, youll find such a character
listed as decimal number 178, which is
hexadecimal number B2 in the ASCII table.
cout <<'\x01'; cout<<char(1);
// prints
cout <<'\a';
cout<<char(7);
// calls bell
cout << int('\a');
// Prints 7

ASCII TABLE
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
unsigned char ch;
for(ch=0 ; ch<255 ; ch++)
cout << int(ch) << "="
<< ch << "\n" ;
getch();
return 0;

Input with cin


#include <iostream>
//for cout, etc.
#include <conio.h>
using namespace std;
int main(){
int A,B,AVG;
// run again for float data type
cout << "Enter Value of A :";
cin >> A;
cout << "Enter Value of B :";
cin >> B;
cout<<" You told A = "<< A <<" and B = "<< B <<endl;
AVG = (A+B)/2;
cout <<"and their Average = "<< AVG << endl;
cout<<"\n <Thank U> \n";
getch();
return 0;
}

Input with cin


// fahren.cpp
// demonstrates cin, newline
#include <iostream>
using namespace std;
int main()
{
int ftemp;
//for temperature in fahrenheit
cout << "Enter temperature in fahrenheit: ";
cin >> ftemp;
int ctemp = (ftemp-32) * 5 / 9;
cout << "Equivalent in Celsius is: " << ctemp << '\n';
system("PAUSE");
return 0;
}

Input with cin

The statement cin >> ftemp; causes the program to wait


for the user to type in a number.
The resulting number is placed in the variable ftemp. The
keyword cin (pronounced C in) is an object, predefined
in C++ to correspond to the standard input stream.
This stream represents data coming from the keyboard
(unless it has been redirected).
echo 100 |
The >> is
the value
it in the

first.exe (type in DOS)


the extraction or get from operator. It takes
from the stream object on its left and places
variable on its right.

Input with cin

insertion operator << cab be used repeatedly in the


cout statement. This is perfectly legal.
extraction operator >> can be used repeatedly with
cin, allowing user to enter a series of values.
Any arrangement of variables, constants, and
operators that specifies a computation is called an
expression, Thus, alpha+12 and (alpha-37)*beta/2
are expressions.
Statements tell the compiler to do something and
terminate with a semicolon, while expressions
specify a computation.
There can be several expressions in a statement.
If both *(multiply) and -(subtract) are present in
an expression then the multiplication would be
carried out first, since * has higher priority Than
* and / have the same precedence. the one on the
left is executed first

Floating Point Types

They have both an integer part, to the left


of the decimal point, and a fractional
part, to the right.
Floating-point variables represent what
mathematicians call real numbers, which are
used for measurable quantities such as
distance, area, and temperature. They
typically have a fractional part.
There are two kinds of floating-point
variables in C++: float, double.
float data type occupies 4 bytes (32bits)
in memory while double occupies 8 bytes of
memory.

Float Example
// circarea.cpp
// demonstrates floating point variables
#include <iostream> //for cout, etc.
using namespace std;
int main()
{
float rad;

//variable of type float

const float PI = 3.14159F;

// type const float

cout << "Enter radius of circle: ";

// prompt

cin >> rad;

// get radius

float area = PI * rad * rad;

// find area

cout << "Area is " << area << endl; // display answer
system("PAUSE"); return 0;
}

Code Explanation

The number 3.14159F is an example of a


floating-point constant.
The decimal point signals that it is a
floating-point constant, and not an integer.
The F specifies that its type float, rather
than double or long double.
The number is written in normal decimal
notation.
With type long double, use the letter L.
You can also write floating-point constants
using exponential notation e.g. 1234.56 would
be written 1.23456E3.
The keyword const (for constant) specifies
that the value of a variable will not change
throughout the program.

Quadratic Equation: Y

= X2-6X-7

Float Example: Quadratic Equation


// A program to calculate Y = X2-6X-7
#include <iostream>

//for cout, etc.

using namespace std;


int main(){
float X,Y;

//variable of type float

cout << "Enter The Value of X: ";

// prompt

cin >> X;

// get value of x

Y = (X*X)-(6*X)-7;

// find y

// display answer
cout << "For X = " << X << ",Y = " << Y << endl;
system("PAUSE");
return 0;
}

Calculating Roots of Quadratic Equation


// Calculating Roots
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int main(){
double a,b,c,x1,x2; // variable of type float
cout <<" Y = a(X^2) + bX + c \n";
cout<<" Enter The Value of a, b and c: ";
cin >> a >> b >> c; // get first a then b & c
cout << "a=" << a << ", b=" << b << " ,c=" << c << endl;
x1 = (-b+sqrt((b*b-4*a*c)))/(2*a);
x2 = (-b-sqrt((b*b-4*a*c)))/(2*a);
cout << "Roots are x1=" << x1
<< ", x2=" << x2 << endl; // display answer
getch();
return 0;
}

Assignment #1
What is the correct variable type for storing the following
data:

1.

2.

3.

The number of pages in your text book


The cost of this book
The age of a person
The number of people in the world

Write a program that calculates and prints sum, difference


and product of two numbers. Also, use this program to
calculate remainder and quotient in division of these
numbers. Display the output on the screen.
Write a program that gets 6 integers from the user and
displays the sum, average and product of these numbers
on screen.

The setw() Manipulator


#include <iostream>
#include <conio.h>
using namespace std;
int main(){
long pop1=2425785, pop2=47, pop3=9761;
cout << "LOCATION " << "POP." << endl
<< "Portcity " << pop1 << endl
<< "Hightown " << pop2 << endl
<< "Lowville " << pop3 << endl;
getch();
return 0;
}

The setw() Manipulator


#include <iostream>
#include <iomanip>
// for setw
#include <conio.h>
using namespace std;
int main(){
long pop1=2425785, pop2=47, pop3=9761;
cout << setw(8) << "LOCATION"
<< setw(12)<< "POPULATION" << endl
<< setw(8) << "Portcity" << setw(12) << pop1 << endl
<< setw(8) << "Hightown" << setw(12) << pop2 << endl
<< setw(8) << "Lowville" << setw(12) << pop3 << endl;
getch();
return 0;
}

The setw() Manipulator

The setw manipulator causes the number (or string)


that follows it in the stream to be printed within
a field n characters wide, where n is the argument
to setw(n).
The value is right justified within the field.

The Data Types Range


#include <iostream>
#include <conio.h>
using namespace std;
int main(){
signed char ch = 127;
cout<<(int)ch<<endl; ch = ch+1;
cout<<(int)ch<<endl; ch = ch+1;
cout<<(int)ch<<endl; ch = ch+1;
cout<<(int)ch<<endl<<endl;
ch = ch-1;
cout<<(int)ch<<endl; ch = ch-1;
cout<<(int)ch<<endl; ch = ch-1;
cout<<(int)ch<<endl; ch = ch-1;
cout<<(int)ch<<endl; ch = ch-1;
getch();
return 0;
}

The Data Types Range


// signtest.cpp tests signed and unsigned integers
#include <iostream>
using namespace std;
int main(){
int signedVar = 1500000000; //signed
unsigned int unsignVar = 1500000000; //unsigned
signedVar = (signedVar * 2)/3; //calculation exceeds range
unsignVar = (unsignVar * 2)/3; //calculation within range
cout << "signedVar = " << signedVar << endl; //wrong
cout << "unsignVar = " << unsignVar << endl; //OK
system("PAUSE");
return 0;
}

Type Conversion
// shows mixed expressions
#include <iostream>
using namespace std;
int main(){
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
/* the lower-type variable is converted to the type of the
higher-type variable. Thus the int value of count is
converted to type float and stored in a temporary
variable before being multiplied by the float variable
avgWeight. The result (still of type float) is then
converted to double so that it can be assigned to the
double variable totalWeight
*********/
cout << "totalWeight=" << totalWeight << endl;
system("PAUSE");
return 0;
}

Type Conversion

Type Cast

In C++ the term applies to data conversions


specified by the programmer, as opposed to the
automatic data conversions.
Sometimes a programmer needs to convert a value
from one type to another in a situation where the
compiler will not do it automatically or without
complaining.
Heres a statement that uses a C++ cast to change a
variable of type int into a variable of type char:
aCharVar = static_cast<char>(anIntVar);
Here the variable to be cast (anIntVar) is placed
in parentheses and the type its to be changed to
(char) is placed in angle brackets.

Type Conversion
// cast.cpp
// tests signed and unsigned integers
#include <iostream>
using namespace std;
int main()
{
int intVar = 1500000000;
//1,500,000,000
intVar = (intVar * 10) / 10;
//result too large
cout << "intVar = " << intVar << endl; //wrong answer
intVar = 1500000000;
//cast to double
intVar = (static_cast<double>(intVar) * 10) / 10;
cout << "intVar = " << intVar << endl; //right answer
system("PAUSE"); return 0;
}

The Remainder Operator (%)


// remaind.cpp demonstrates
#include <iostream>
using namespace std;
int main(){
cout << 6 % 8 << endl
<< 7 % 8 << endl
<< 8 % 8 << endl
<< 9 % 8 << endl
<< 10 % 8 << endl
<< -2 % 8 << endl
<<-13 % 8 << endl;
system("PAUSE");
return 0;
}

remainder operator

//
//
//
//
//
//
//

6
7
0
1
2
-2
-5

Arithmetic Assignment Operators, += , -= , *= , /= , %=


// demonstrates arithmetic assignment operators
#include <iostream>
using namespace std;
int main(){
int ans = 27;
ans += 10;
//same as: ans = ans + 10;
cout << ans << ", ";
ans -= 7;
//same as: ans = ans - 7;
cout << ans << ", ";
ans *= 2;
//same as: ans = ans * 2;
cout << ans << ", ";
ans /= 3;
//same as: ans = ans / 3;
cout << ans << ", ";
ans %= 3;
//same as: ans = ans % 3;
cout << ans << endl;
system("PAUSE"); return 0;
}
// output is : 37, 30, 60, 20, 2

Increment Operators, ++ , -// increm.cpp demonstrates the increment operator


#include <iostream>
using namespace std;
int main(){
int count = 10;
cout << "count=" << count << endl;

// displays 10

//First increment then use this variable


cout << "count=" << ++count <<endl; // displays 11(prefix)
cout << "count=" << count << endl; // displays 11
//First use this variable then increment
cout<< "count=" << count++ <<endl; // displays 11(postfix)
cout << "count=" << count << endl; // displays 12
system("PAUSE"); return 0;
}

Linker and Compiler

Assignment #2

Answer all questions from Q1 to Q25 and


Exercise 1 to 12 of Chapter2.

Potrebbero piacerti anche