Data Types in C++
Data Types in C++
Chapter Two
Basics of C++ Language
2.1. Introduction
In this chapter, many thinks will be studied as:
1. Structure of Program.
2. Important libraries that programmer need it.
3. Input and output instructions.
4. Define of Variables, strings and constants with difference between them.
The structure of any program written is must be known. The structure of any program
contain four steps as:
1. header files of instructions
2. beginning of program
3. statements
4. end of program
For example, we consider our first program.
Ex:
//my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Header files: there are libraries contain groups of instructions. For first program
shown above, #include <iostram> is most important library for each program written
in C++ language. Other libraries we will use if need it like string library and file
libraries.
Using namespace std; is a phrase must be written under the libraries. Usefulness
of this phrase to translate any instruction in the program and return it to the library.
32
Chapter Two – Basics of C++ Language
Beginning of program must be done by write int main ( ) function. This function
tells the C++ language that the main program will begin from this point.
The statements of program will written between the two brackets { }.
Ending of program will puts before end bracket}. The ending statement
represented by return 0; statement.
Most important rules, for programming in C++ language, must be studied. These
rules is:
5. Comments: are phrases that do nothing. Their purpose is only to allow the
programmer to insert notes or descriptions embedded within the source code. C++
supports two ways to insert comments:
Ex:
// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the pair of
slash signs (//) is found up to the end of that same line. The second one, known as block
comment, discards everything between the /* characters and the first appearance of the
*/ characters, with the possibility of including more than one line.
32
Chapter Two – Basics of C++ Language
When programming, we store the variables in our computer's memory, but the
computer has to know what kind of data we want to store in them. Since it is not going
to occupy the same amount of memory to store a simple number than to store a single
letter or a large number. They are not going to be interpreted the same way.
You have a summary of the basic fundamental data types in C++, as well as the
range of values that can be represented with each one:
Name Description Size Range
* The values of the columns Size and Range depend on the system the program is
compiled for. The values shown above are those found on most 32-bit systems. But for
other systems, the general specification is that int has the natural size suggested by the
system architecture (one "word") and the four integer types char, short, int and long
must each one be at least as large as the one preceding it, with char being always 1 byte
in size. The same applies to the floating point types float, double and long double, where
each one must provide at least as much precision as the preceding one.
32
Chapter Two – Basics of C++ Language
int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable of
type int with the identifier a. The second one declares a variable of type float with the
identifier mynumber. Once declared, the variables a and mynumber can be used within
the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can declare all
of them in a single statement by separating their identifiers with commas.
Ex:-
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly
the same meaning as:
int a;
int b;
int c;
The integer data types char, short, long and int can be either signed or unsigned
depending on the range of numbers needed to be represented. Signed types can
represent both positive and negative values, whereas unsigned types can only represent
positive values (and zero). This can be specified by using either the specifier signed or
the specifier unsigned before the type name.
Ex:-
Int main () {
Int main () {
int MyAccountBalance;
}
With exactly the same meaning (with or without the keyword signed)
An exception to this general rule is the char type, which exists by itself and is
considered a different fundamental data type from signed char and unsigned char,
thought to store characters. You should use either signed or unsigned if you intend to
store numerical values in a char-sized variable.
Short and long can be used alone as type specifiers. In this case, they refer to their
respective integer fundamental types: short is equivalent to short int and long is
equivalent to long int. The following two variable declarations are equivalent:
short Year;
short int Year;
Finally, signed and unsigned may also be used as standalone type specifiers,
meaning the same as signed int and unsigned int respectively. The following two
declarations are equivalent:
unsigned NextYear;
unsigned int NextYear;
In C+ +, there are two instructions for input the variables and output the results.
These functions are:
32
Chapter Two – Basics of C++ Language
int a;
cin >> a ;
return 0;
}
Th above example remain uncompleted, we need a function for output that write
variables, constants, characters, and strings on the output screen. We will use cout
function as:
cout<< -----;
Ex:- in this example, we will input variable (a) as integer number. Then print its value
on screen.
#include <iostream>
using namespace std;
int main ()
{ o/p
int a; a = 25
cin >> a ;
cout << "a="<<a;
return 0;
}
* Any phrase (letters or numbers) putted between two quote (" ") in cout function will
print as written.
When declaring a regular local variable, its value is by default undetermined. But
you may want a variable to store a concrete value at the same moment that it is declared.
In order to do that, you can initialize the variable. There
are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by
the value to which the variable will be initialized:
For example, if we want to declare an int variable called a initialized with a value
of 0 at the moment in which it is declared, we could write:
int a = 0;
32
Chapter Two – Basics of C++ Language
1. Integer Numbers
2. Floating-Point Numbrs
3. Characters
4. Boolean Values.
5. Strings
They are numerical constants that identify integer decimal values. Notice that to
express a numerical constant we do not have to write quotes (") nor any special
character. There is no doubt that it is a constant: whenever we write 1776 in a program,
we will be referring to the value 1776.
In addition to decimal numbers (those that all of us are used to use every day)
C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal
numbers (base 16). If we want to express an octal number we have to precede it with a
0 (zero character). In addition, in order to express a hexadecimal number we have to
precede it with the characters 0x (zero, x). For example, the following literal constants
are all equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
Literal constants, like variables, are considered to have a specific data type. By
default, integer literals are of type int. However, we can force them to either be unsigned
by appending the u character to it, or long by appending l:
32
Chapter Two – Basics of C++ Language
75 //int
75u // unsigned int
75l // long int
75ul // unsigned long int
In both cases, the suffix can be specified using either upper or lowercase letters.
They express numbers with decimals and/or exponents. They can include either
a decimal point, an e character (that expresses "by ten at the Xth height", where X is an
integer value that follows the e character), or both a decimal point and an e character:
3.14159 // 3.14159
6.02e23 // 6.02 * 10^23
1.6e-19 // 1.6 *10^-19
3.0 // 3.0
These are four valid numbers with decimals expressed in C++. The first number
is PI, the second one is the number of Avogadro, the third is the electric charge of an
electron (an extremely small number) -all of them approximated- and the last one is the
number three expressed as a floating-point numeric literal.
The default type for floating point literals is double. If you explicitly want to express a
float or long double numerical literal, you can use the f or l suffixes respectively:
3.14159L // long double
6.02e23f // float
Any of the letters that can be part of a floating-point numerical constant (e, f, l) can
be written using either lower or uppercase letters without any difference in their
meanings.
The first two expressions represent single character constants, and the following
two represent string literals composed of several characters. Notice that to represent a
23
Chapter Two – Basics of C++ Language
single character we enclose it between single quotes (') and to express a string (which
generally consists of more than one character) we enclose it between double quotes (").
When writing both single character and string literals, it is necessary to put the
quotation marks surrounding them to distinguish them from possible variable identifiers
or reserved keywords. Notice the difference between these two expressions:
x
'x'
Character and string literals have certain peculiarities, like the escape codes.
These are special characters that are difficult or impossible to express otherwise in the
source code of a program, like newline (\n) or tab (\t). All of them are preceded by a
backslash (\). Here you have a list of some of such escape codes:
\n newline
\t Tab
\v Vertical Tab
\b Back space
\a Alert (beep)
\' Single quote
\" Double quote
\? Question mark
\\ Back slash
\ Octal number
\x Hexadecimal number
Ex:-
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
23
Chapter Two – Basics of C++ Language
You can express any character by its numerical ASCII code by writing a
backslash character (\) followed by the ASCII code expressed as an octal (base-8) or
hexadecimal (base-16) number. In the first case (octal) the digits must immediately
follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x
character must be written before the digits themselves (for example \x20 or \x4A).
String literals can extend to more than a single line of code by putting a backslash
sign (\) at the end of each unfinished line.
"string expressed in \
two lines"
You can also concatenate several string constants separating them by one or
several blank spaces, tabulators, newline or any other valid blank character:
"this forms" "a single" "string" "of characters"
Wide characters are used mainly to represent non-English or exotic character sets.
There are only two valid Boolean values: true and false. These can be expressed
in C++ as values of type bool by using the Boolean literals true and false.
2.6.5. strings
Variables that can store non-numerical values that are longer than one single
character are known as strings.
The C++ language library provides support for strings through the standard string
class. This is not a fundamental type, but it behaves in a similar way as fundamental
types do in its most basic usage.
A first difference with fundamental data types is that in order to declare and use
objects (variables) of this type we need to include an additional header file in our source
code: <string> and have access to the std namespace (which we already had in all our
previous programs thanks to the using namespace statement).
23
Chapter Two – Basics of C++ Language
Ex:-
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
As you may see in the previous example, strings can be initialized with any valid
string literal just like numerical type variables can be initialized to any valid numerical
literal. Both initialization formats are valid with strings:
string mystring = "This is a string";
string mystring ("This is a string");
Strings can also perform all the other basic operations that fundamental data
types can, like being declared without an initial value and being assigned values during
execution:
Ex:-
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
o/p
This is the initial string content
This is a different string content
22
Chapter Two – Basics of C++ Language
2.7. Constants
Constants are expressions with a fixed value. You can define your own names for
constants that you use very often without having to resort to memory- consuming
variables, simply by using the #define preprocessor directive. Its format is:
This defines two new constants: PI and NEWLINE. Once they are defined, you
can use them in the rest of the code as if they were any other regular constant, for
example:
// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
In fact the only thing that the compiler preprocessor does when it encounters
#define directives is to literally replace any occurrence of their identifier (in the previous
example, these were PI and NEWLINE) by the code to which they have been defined
(3.14159 and '\n' respectively).
The #define directive is not a C++ statement but a directive for the preprocessor;
therefore it assumes the entire line as the directive and does not require a semicolon (;)
22
Chapter Two – Basics of C++ Language
at its end. If you append a semicolon character (;) at the end, it will also be appended in
all occurrences within the body of the program that the preprocessor replaces.
With the const. prefix you can declare constants with a specific type in the same
way as you would do with a variable:
const int pathwidth =100;
const char tabulator = '\t';
Here, pathwidth and tabulator are two typed constants. They are treated just like
regular variables except that their values cannot be modified after their definition.
22
Chapter Two – Basics of C++ Language
Q1-
Write a program to prints these shapes.
****** *** * *
* * * * *** * *
* * * * ***** * *
* * * * * * *
* * * * * * *
* * * * * * *
****** *** * *
Q2-
Write a program to read three letters and print them in reverse order.
Q3-
Write a program to reads three floating-point values, then compute and print their
arithmetic sum, products and their average.
Q4-
Write a program that read your age in years and prints it in days.
Q5-
Write a program to read a time in (hour: minute: second) and prints it in second.
Q6-
Write a program to read unsigned decimal number then print it in all three notation
(decimal, octal and hexadecimal).
Q7-
Write a program that reads the radius of a circle (as double value), and computes and
prints the area, diameter and circumference.
22