Vous êtes sur la page 1sur 62

Introduction to Programming

Chapter 02
C++ Programming Basics

Engr. Rashid Farid Chishti


chishti@iiu.edu.pk
International Islamic University H-10, Islamabad, Pakistan
http://www.iiu.edu.pk
Basic Program Construction
1 //first.cpp
2 #include <iostream>
3 #include <stdlib.h>
4 using namespace std;
5 int main(){
6 cout << "Welcome to this course\n";
7 system("PAUSE");
8 return 0;
9 }

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 cout
2 <<"Welcome to this course\n"
3 ;

1 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
cout at the line break or
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 instruct-
ions 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 //first.cpp
2 #include <iostream> // preprocessor directive
3 using namespace std; // "using" directive
4 int main() // function name "main"
5 { // start function body
6 cout <<"Welcome to this course\n"; // statement
7 return 0; // statement
8 } // end of function body
Other Styles of Comments
1 /* this is an old-style comment */
2
3 /* this
4 is a
5 potentially
6 very long
7 multiline
8 comment
9 */
10
11
12 int main(/* a comment within parentheses*/)
13
14 { /* this is comment into the function body */ }
15
16
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; // define an integer var1
int var2; // define an integer var2
var1 = 20; // assign value 20 to var1
var2 = var1 + 10; // assign value 20+10 to var2
cout << "var1+10 is "; // output text
cout << var2 << endl; // output 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 declara-
tions, 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 Size Range
bool 1 byte true(1) or false(0)
char or 1 byte (-27) ~ (+27-1) = -128 ~ +127
signed char (8 bits)
unsigned char 1 byte 0 ~ 28-1 = 0 to 255 or
(8 bits) 256 Different ASCII Characters
short or 2 bytes (-215) ~ (+215-1) =
signed short (16 bits) -32,768 ~ +32,767
unsigned short 2 bytes 0 ~ 216-1 = 0 to 65,535
int or 4 bytes (-231) ~ (+231-1) =
signed int (32 bits) -2,14,74,83,648 ~ +2,14,74,83,647
unsigned int 4 bytes 0 ~ (232 - 1) =
(32 bits) 0 ~ 4,29,49,67,295
long 4 bytes (-231) ~ (+231-1) =
(32 bits) -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
long v1 = 7678L; // 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)
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 Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char
0 00 32 20 64 40 @ 96 60 ` 128 80 160 A0 192 C0 224 E0
1 01 33 21 ! 65 41 A 97 61 a 129 81 161 A1 193 C1 225 E1
2 02 34 22 " 66 42 B 98 62 b 130 82 162 A2 194 C2 226 E2
3 03 35 23 # 67 43 C 99 63 c 131 83 163 A3 195 C3 227 E3
4 04 36 24 $ 68 44 D 100 64 d 132 84 164 A4 196 C4 228 E4
5 05 37 25 % 69 45 E 101 65 e 133 85 165 A5 197 C5 229 E5
6 06 38 26 & 70 46 F 102 66 f 134 86 166 A6 198 C6 230 E6
7 07 39 27 ' 71 47 G 103 67 g 135 87 167 A7 199 C7 231 E7
8 08 40 28 ( 72 48 H 104 68 h 136 88 168 A8 200 C8 232 E8
9 09 41 29 ) 73 49 I 105 69 i 137 89 169 A9 201 C9 233 E9
10 0A 42 2A * 74 4A J 106 6A j 138 8A 170 AA 202 CA 234 EA
11 0B 43 2B + 75 4B K 107 6B k 139 8B 171 AB 203 CB 235 EB
12 0C 44 2C , 76 4C L 108 6C l 140 8C 172 AC 204 CC 236 EC
13 0D 45 2D - 77 4D M 109 6D m 141 8D 173 AD - 205 CD 237 ED
14 0E 46 2E . 78 4E N 110 6E n 142 8E 174 AE 206 CE 238 EE
15 0F 47 2F / 79 4F O 111 6F o 143 8F 175 AF 207 CF 239 EF
16 10 48 30 0 80 50 P 112 70 p 144 90 176 B0 208 D0 240 F0
17 11 49 31 1 81 51 Q 113 71 q 145 91 177 B1 209 D1 241 F1
18 12 50 32 2 82 52 R 114 72 r 146 92 178 B2 210 D2 242 F2
19 13 51 33 3 83 53 S 115 73 s 147 93 179 B3 211 D3 243 F3
20 14 52 34 4 84 54 T 116 74 t 148 94 180 B4 212 D4 244 F4
21 15 53 35 5 85 55 U 117 75 u 149 95 181 B5 213 D5 245 F5
22 16 54 36 6 86 56 V 118 76 v 150 96 182 B6 214 D6 246 F6
23 17 55 37 7 87 57 W 119 77 w 151 97 183 B7 215 D7 247 F7
24 18 56 38 8 88 58 X 120 78 x 152 98 184 B8 216 D8 248 F8
25 19 57 39 9 89 59 Y 121 79 y 153 99 185 B9 217 D9 249 F9
26 1A 58 3A : 90 5A Z 122 7A z 154 9A 186 BA 218 DA 250 FA
27 1B 59 3B ; 91 5B [ 123 7B { 155 9B 187 BB 219 DB 251 FB
28 1C 60 3C < 92 5C \ 124 7C | 156 9C 188 BC 220 DC 252 FC
29 1D 61 3D = 93 5D ] 125 7D } 157 9D 189 BD 221 DD 253 FD
30 1E 62 3E > 94 5E ^ 126 7E ~ 158 9E 190 BE 222 DE 254 FE
31 1F 63 3F ? 95 5F _ 127 7F 159 9F 191 BF 223 DF 255 FF
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' representa-
tion, 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 | first.exe (type in DOS)
The >> is the extraction or get from operator. It takes
the value from the stream object on its left and places
it in the 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
1. What is the correct variable type for storing the following
data:
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
2. 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.
3. 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 remainder operator
#include <iostream>
using namespace std;
int main(){
cout << 6 % 8 << endl // 6
<< 7 % 8 << endl // 7
<< 8 % 8 << endl // 0
<< 9 % 8 << endl // 1
<< 10 % 8 << endl // 2
<< -2 % 8 << endl // -2
<<-13 % 8 << endl; // -5
system("PAUSE");
return 0;
}
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.

Vous aimerez peut-être aussi