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

Introduction To Programming: Engr. Rashid Farid Chishti

This document provides an introduction to basic C++ programming concepts such as program structure, functions, statements, comments, preprocessor directives, headers, namespaces, variables and data types. It explains that a basic C++ program consists of functions like main(), which contain statements separated by semicolons. It also describes common elements like #include directives to link header files, and using namespaces. Integer variables are defined using the int data type to represent numeric values.

Uploaded by

AMAMA KHAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views

Introduction To Programming: Engr. Rashid Farid Chishti

This document provides an introduction to basic C++ programming concepts such as program structure, functions, statements, comments, preprocessor directives, headers, namespaces, variables and data types. It explains that a basic C++ program consists of functions like main(), which contain statements separated by semicolons. It also describes common elements like #include directives to link header files, and using namespaces. Integer variables are defined using the int data type to represent numeric values.

Uploaded by

AMAMA KHAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 64

Introduction to

Programming
Chapter 02
C++ Programming Basics

Engr. Rashid Farid Chishti


[email protected]
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 aren’t always empty. They’re
used to hold function arguments (values passed
from the calling program to the function).
 Line number 2, 3 and 4 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 6, 7 and 8)
 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 don’t recommend these syntax. it’s
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, you’ll 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 program’s
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
 They’re not part of the basic C++ language,
but they’re 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


(#). It’s 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). It’s
concerned with basic input/output operations,
and contains declarations that are needed by
the cout identifier and the << operator.
 Without these declarations, the compiler won’t
recognize cout and will think << is being used
incorrectly.
 The newer Standard C++ header files don’t 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 they’re 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 didn’t
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 what’s 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 computer’s 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
1 // intvars.cpp
2 // demonstrates integer variables
3 #include <iostream>
4 #include <stdlib.h>
5 using namespace std;
6
7 int main()
8 {
9 int var1; // define an integer var1
10 int var2; // define an integer var2
11 var1 = 20; // assign value 20 to var1
12 var2 = var1 + 10; // assign value 20+10 to var2
13
14 cout << "var1+10 is "; // output text
15 cout << var2 << endl; // output value of var2
16
17 system("PAUSE"); // Suspend the processing of Program
18 return 0; // return the value 0 to whoever called it
19 }
20
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. It’s not necessary to
declare variables before the first executable
statement (as was necessary in C).
 A declaration introduces a variable’s 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 can’t 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 variable’s name should make clear to anyone
reading the listing variable’s 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
don’t 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.
 We’ve seen how to do this with the '\n' escape
sequence. Now we’ll 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.
 It’s an example of a manipulator. Manipulators
are instructions to the output stream that
modify the output in various ways; we’ll 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
signed long long 8 bytes (263 ) ~ (263 - 1)
(64 bits) - 9,223,372,036,854,775,808 to
+ 9,223,372,036,854,775,808
unsigned long 8 bytes 0 ~ (264 - 1) =
long (64 bits) 0 to 18,446,744,073,709,551,615
float 4 bytes - (1.17 × 10-38 ~ 3.40 × 1038)
(32 bits) + (1.17 × 10-38 ~ 3.40 × 1038)
double 8 byte - (2.22 × 10-308 ~ 1.79 × 10308)
(64 bits) + (2.22 × 10-308 ~ 1.79 × 10308)
long double 12 byte - (3.36 × 10-4932 ~ 1.18 × 104932)
(96 bits) + (3.36 × 10-4932 ~ 1.18 × 104932)
C++ Data Types
 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.

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
C++ Data Types
 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.
Programming Example
1 // charvars.cpp
2 // demonstrates character variables
3 #include <iostream>//for cout, etc.
4 #include <stdlib.h>
5 using namespace std;
6 int main()
7 {
8 char charvar1 = 'A'; // char charvar1 = 65;
9 char charvar2 = '\t'; // char charvar2 = 9;
10 cout << charvar1; // display character
11 cout << charvar2; // display character
12 charvar1 = 'B'; // char charvar1 = 66;
13 cout <<charvar1; // display character
14 cout << '\n'; // try cout << char (10);
15 system("PAUSE");
16 return 0;
17 }
18
19
20
Escape sequence
 '\t' and '\n', are special character with
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.";
 This translates to
"Run, Forrest, run," she said.
Escape sequence
 Sometimes you need to represent a character
constant that doesn’t 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, you’ll 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
Escape Sequence
#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;
}
Escape Sequence
1 #include <iostream> // TOPIC: Escape Sequence
2 #include <stdlib.h>
3 using namespace std;
4 int main()
5 {
6 cout << "This is\a Bell" <<endl;
7 cout << "This is\b Back Space" <<endl;
8 cout << "This is\f Form Feed" <<endl;
9 cout << "This is\n New Line" <<endl;
10 cout << "This line is over written "
11 "by\rCarriage Return" <<endl;
12 cout << "This is \tTab" <<endl;
13 cout << "This is \\ Back Slash" <<endl;
14 cout << "This is \' Single Quotation Mark" <<endl;
15 cout << "This is \" Double Quotation Mark" <<endl;
16 cout << "This is \? Question Mark Mark" <<endl;
17 cout << "This is \x41 Hexadecimal Notation" <<endl;
18 cout << "This is \0 Null" <<endl;
19 system("PAUSE"); return 0;
20 }
Escape Sequence
Input with cin
1 #include <iostream> //for cout, etc.
2 #include <stdlib.h> //for system().
3 using namespace std;
4
5 int main(){
6 int a,b,c; // run again for float data type
7 cout << "Enter Value of A :";
8 cin >> a; // take first number and store it in A
9
10 cout << "Enter Value of B :";
11 cin >> b; // take first number and store it in B
12
13 cout << "You told A = "<< a <<" and B = " << b << endl;
14 c = (a+b)/2; // Calculate Average and store in c
15
16 cout <<"and their Average = "<< c << endl;
17 cout<<"\n <Thank U> \n";
18 system("PAUSE"); return 0;
19 }
20
Input with cin
1 #include <iostream>
2 #include <stdlib.h>
3 using namespace std;
4
5 int main()
6 {
7 double f; // for temperature in Fahrenheit
8
9 cout << "Enter temperature in Fahrenheit: ";
10
11 cin >> f;
12
13 double c = (f-32) * 5 / 9.0F ;
14
15 cout << "Equivalent in Celsius is: " << c << endl;
16
17 system("PAUSE");
18
19 return 0;
20 }
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: Area of a Circle
1 #include <iostream> // for cout, etc.
2 #include <stdlib.h>
3 using namespace std;
4
5 int main()
6 {
7 float rad; // variable of type float
8 const float PI = 3.14159F; // type const float
9
10 cout << "Enter radius of circle: "; // prompt
11 cin >> rad; // get radius
12
13 float area = PI * rad * rad; // find area
14
15 cout << "Area is " << area << endl; // display answer
16 system("PAUSE");
17 return 0;
18 }
19
20
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 it’s 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
1 // A program to calculate Y = X2-6X-7
2 #include <iostream> //for cout, etc.
3 #include <stdlib.h>
4 using namespace std;
5 int main()
6 {
7 float X,Y; //variable of type float
8
9 cout << "Enter The Value of X: "; // prompt
10 cin >> X; // get value of x
11
12 Y = (X*X)-(6*X)-7; // find y
13
14 // display answer
15 cout << "For X = " << X << ",Y = " << Y << endl;
16
17 system("PAUSE");
18 return 0;
19 }
20
Float Example: Quadratic Formula
1 // Calculating Roots
2 #include <iostream>
3 #include <conio.h>
4 #include <math.h>
5 using namespace std;
6
int main(){
7
double a,b,c,x1,x2; // variable of type float
8
9 cout <<" Y = a(X^2) + bX + c \n";
10 cout<<" Enter The Value of a, b and c: ";
11 cin >> a >> b >> c; // get first a then b & c
12 cout << "a=" << a << ", b=" << b << " ,c=" << c << endl;
13 x1 = (-b+sqrt((b*b-4*a*c)))/(2*a);
14 x2 = (-b-sqrt((b*b-4*a*c)))/(2*a);
15 cout << "Roots are x1=" << x1
16 << ", x2=" << x2 << endl; // display answer
17
getch();
18
19 return 0;
20 }
The setw() Manipulator
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
cout << "LOCATION" << "POP." << endl
<< "Islamabad" << 1015200 << endl
<< "Karachi" << 21213456 << endl
<< "Pakistan" << 212742631 << endl;
getch();
return 0;
}
The setw() Manipulator
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main(){
cout <<setw(10)<<"LOCATION" <<setw(12)<<"POP." << endl
<<setw(10)<<"Islamabad"<<setw(12)<< 1015200 << endl
<<setw(10)<<"Karachi" <<setw(12)<< 21213456 << endl
<<setw(10)<<"Pakistan" <<setw(12)<<212742631 << endl;
getch();
return 0;
}
The setw() Manipulator
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main(){
cout.setf(ios::left); cout <<setw(10)<<"LOCATION";
cout.unsetf(ios::left); cout <<setw(12)<<"POP." << endl;

cout.setf(ios::left); cout <<setw(10)<<"Islamabad";


cout.unsetf(ios::left); cout<<setw(12)<< 1015200 << endl;

cout.setf(ios::left); cout<<setw(10)<<"Pakistan";
cout.unsetf(ios::left); cout<<setw(12)<<212742631 << endl;
getch();
return 0;
}
The setw() Manipulator

setw(10) setw(12)
L O C A T I O N P O P .
I s l a m a b a d 1 0 1 5 2 0 0
K a r a c h i 2 1 2 1 3 4 5 6
P a k i s t a n 2 1 2 7 4 2 6 3 1
The Data Types Range For 4-bit Storage
#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.
 Here’s 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 it’s to be changed to (char) is
placed in angle brackets.
Type Conversion
// tests signed and unsigned integers
#include <iostream>
#include <stdlib.h>

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>
#include <stdlib.h>
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>
#include <stdlib.h>
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>
#include <stdlib.h>

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

You might also like