Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Type Conversion

Type Conversion
// mixed.cpp
// shows mixed expressions

#include <iostream>
using namespace std;
int main()
{
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
cout << “totalWeight=” << totalWeight << endl;
return 0;
}
Automatic Conversions
TABLE 2.4 Order of Data Types

Data Type Order


Long double Highest
Double
Float
Long
Int
Short
Char Lowest
Casts
• In C++ the term applies to data conversions specified by the programmer, as
opposed to the automatic data conversions.
• Casts are also called type casts.
• Use: 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.
• kinds of casts in Standard C++:
• static casts,
• dynamic casts,
• reinterpret casts,
• const casts.
• 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);
Arithmetic Operators
•+
•-
•*
•/
• % (remainder operator or modulus operator)
• +=,-=,*=,/= (Arithmetic Assignment operator)
• ++,-- (Increment and Decrement Operator) (post and pre)
Relational Operators
compares two values
Loops
• Loops cause a section of your program to be repeated a certain
number of times.
• The repetition continues while a condition is true.
• When the condition becomes false, the loop ends and control passes to the
statements following the loop.
• three kinds of loops in C++:
• for loop
• while loop
• do loop.
For Loop
#include <iostream>
using namespace std;
int main()
{
int j; //define a loop variable
for(j=0; j<15; j++) //loop from 0 to 14,
cout << j * j << “ “; //displaying the square of j
cout << endl;
return 0;
}

Note: Factorial using For loop (decrement operator)


While loop
sometimes you want to guarantee that the loop body is executed at least once, no matter
Do loop what the initial state of the test expression

You might also like