Program
Program
Program
Data types
String (Sentence, Phrases)- One of the most useful data types
supplied in the C++ libraries is the string. A string is a variable that
stores a sequence of letters or other characters, such as "Hello" or
"May 10th is my birthday!". Just like the other data types, to create a string
we first declare it, then we can store a value in it.
Char - (One Letter)-Char is a C++ data type designed for the storage of
letters. Char is an abbreviation for an alphanumeric character. It is an
integral data type, meaning the value is stored as an integer. A char takes
a memory size of 1 byte.
Int (Positive & Negative Numbers) - n int variable contains only whole
numbers
Int, short for "integer," is a fundamental variable type built into the
compiler and used to define numeric variables holding whole numbers.
Other data types include float and double. C, C++, C# and many other
programming languages recognize int as a data type
Float (less precise decimals) is a shortened term for "floating point." By definition,
it's a fundamental data type built into the compiler that's used to define numeric
values with floating decimal points. C, C++, C# and many other programming
languages recognize float as a data type.
The double (more precise decimals) is a fundamental data type built
into the compiler and used to define numeric variables holding
numbers with decimal points. ... A double type can represent fractional
as well as whole values. It can contain up to 15 digits in total, including
those before and after the decimal point.
#include <stdlib.h>
What is stdlib used for in C++?
h is the header of the general purpose standard library of C programming
language which includes functions involving memory allocation, process
control, conversions and others. It is compatible with C++ and is known as
cstdlib in C++.
Standard Library
The header file stdlib. ... h stands for Standard Library. It has the information of memory
allocation/freeing functions
#include <conio.h>
Conio. h is a header file used to include some functions like clrscr(), getch()
etc. You can include these function by simply #include<conio.
...
h> can be broken & simply explained as :
1. In C/C++ Language Symbol # is know as preprocessor,
2. include is a directory and all the header files like stdio. h, conio. .
Preprocessor directives
Preprocessor directives are lines included in the code of programs
preceded by a hash sign (#). These lines are not program statements but
directives for the preprocessor. The preprocessor examines the code
before actual compilation of code begins and resolves all these
directives before any code is actually generated by regular statements.
Let's imagine that I ask you to remember the number 5, and then I ask
you to also memorize the number 2 at the same time. You have just
stored two different values in your memory (5 and 2). Now, if I ask
you to add 1 to the first number I said, you should be retaining the
numbers 6 (that is 5+1) and 2 in your memory. Then we could, for
example, subtract these values and obtain 4 as result.
Obviously, this is a very simple example, since we have only used two
small integer values, but consider that your computer can store
millions of numbers like these at the same time and conduct
sophisticated mathematical operations with them.
Identifiers
A valid identifier is a sequence of one or more letters, digits, or
underscore characters (_). Spaces, punctuation marks, and symbols
cannot be part of an identifier. In addition, identifiers shall
always begin with a letter. They can also begin with an underline
character (_), but such identifiers are -on most cases- considered
reserved for compiler-specific keywords or external identifiers, as
well as identifiers containing two successive underscore characters
anywhere. In no case can they begin with a digit.
alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break,
case, catch, char, char16_t, char32_t, class, compl, const,
constexpr, const_cast, continue, decltype, default, delete, do,
double, dynamic_cast, else, enum, explicit, export, extern, false,
float, for, friend, goto, if, inline, int, long, mutable, namespace,
new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private,
protected, public, register, reinterpret_cast, return, short, signed,
sizeof, static, static_assert, static_cast, struct, switch, template,
this, thread_local, throw, true, try, typedef, typeid, typename,
union, unsigned, using, virtual, void, volatile, wchar_t, while, xor,
xor_eq
Fundamental data types are basic types implemented directly by the language that
represent the basic storage units supported natively by most systems. They can mainly be
classified into:
Character types: They can represent a single character, such as 'A' or '$'. The
most basic type is char, which is a one-byte character. Other types are also
provided for wider characters.
Numerical integer types: They can store a whole number value, such
as 7 or 1024. They exist in a variety of sizes, and can either
be signed or unsigned, depending on whether they support negative values or not.
Floating-point types: They can represent real values, such as 3.14 or 0.01, with
different levels of precision, depending on which of the three floating-point types is
used.
Boolean type: The boolean type, known in C++ as bool, can only represent one
of two states, true or false.
Within each of the groups above, the difference between types is only their size (i.e., how
much they occupy in memory): the first type in each group is the smallest, and the last is
the largest, with each type being at least as large as the one preceding it in the same
group. Other than that, the types in a group have the same properties.
Note in the panel above that other than char (which has a size of exactly one byte), none
of the fundamental types has a standard size specified (but a minimum size, at most).
Therefore, the type is not required (and in many cases is not) exactly this minimum size.
This does not mean that these types are of an undetermined size, but that there is no
standard size across all compilers and machines; each compiler implementation may
specify the sizes for these types that fit the best the architecture where the program is
going to run. This rather generic size specification for types gives the C++ language a lot
of flexibility to be adapted to work optimally in all kinds of platforms, both present and
future.
Type sizes above are expressed in bits; the more bits a type has, the more distinct values
it can represent, but at the same time, also consumes more space in memory:
For integer types, having more representable values means that the range of values they
can represent is greater; for example, a 16-bit unsigned integer would be able to
represent 65536 distinct values in the range 0 to 65535, while its signed counterpart
would be able to represent, on most cases, values between -32768 and 32767. Note that
the range of positive values is approximately halved in signed types compared to unsigned
types, due to the fact that one of the 16 bits is used for the sign; this is a relatively
modest difference in range, and seldom justifies the use of unsigned types based purely on
the range of positive values they can represent.
For floating-point types, the size affects their precision, by having more or less bits for
their significant and exponent.
If the size or precision of the type is not a concern, then char, int, and double are typically
selected to represent characters, integers, and floating-point values, respectively. The
other types in their respective groups are only used in very particular cases.
The types described above (characters, integers, floating-point, and boolean) are
collectively known as arithmetic types. But two additional fundamental types exist: void,
which identifies the lack of type; and the type nullptr, which is a special type of pointer.
Both types will be discussed further in a coming chapter about pointers.
C++ supports a wide variety of types based on the fundamental types discussed above;
these other types are known as compound data types, and are one of the main strengths
of the C++ language. We will also see them in more detail in future chapters.
Declaration of variables
C++ is a strongly-typed language, and requires every variable to be
declared with its type before its first use. This informs the
compiler the size to reserve in memory for the variable and how to
interpret its value. The syntax to declare a new variable in C++ is
straightforward: we simply write the type followed by the variable
name (i.e., its identifier). For example:
1 int a;
2
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 declaring more than one variable of the same type, they can all be
declared in a single statement by separating their identifiers with
commas. For example:
int a, b, c;
To see what variable declarations look like in action within a program, let's have a look at
the entire C++ code of the example about your mental memory proposed at the beginning
of this chapter:
Initialization of variables
When the variables in the example above are declared, they have an undetermined value
until they are assigned a value for the first time. But it is possible for a variable to have a
specific value from the moment it is declared. This is called the initialization of the
variable.
In C++, there are three ways to initialize variables. They are all equivalent and are
reminiscent of the evolution of the language over the years:
The first one, known as c-like initialization (because it is inherited from the C language),
consists of appending an equal sign followed by the value to which the variable is
initialized:
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a value of zero
from the same moment it is declared, we can write:
int x = 0;
int x (0);
Finally, a third method, known as uniform initialization, similar to the above, but using
curly braces ({}) instead of parentheses (this was introduced by the revision of the C++
standard, in 2011):
int x {0};
All three ways of initializing variables are valid and equivalent in C++.
1 // initialization of variables
2
3
#include <iostream>
4 using namespace std;
5 int main ()
6{
7 int a=5; // initial value: 5
8
9 int b(3); // initial value: 3
1 int c{2}; // initial value: 2
0 int result; // initial value undetermined
1
1
a = a + b;
1
result = a - c;
2
cout << result;
1
3
1 return 0;
4}
1
5
1
6
1
7
1
8
Introduction to strings
Fundamental types represent the most basic types handled by the machines where the
code may run. But one of the major strengths of the C++ language is its rich set of
compound types, of which the fundamental types are mere building blocks.
An example of compound type is the string class. Variables of this type are able to store
sequences of characters, such as words or sentences. A very useful feature!
A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type, the program needs to include the header where the type is defined
within the standard library (header <string>):
As you can 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. As
with fundamental types, all initialization formats are valid with strings:
Constants
Constants are expressions with a fixed value.
Literals
Literals are the most obvious kind of constants. They are used to
express particular values within the source code of a program. We
have already used some in previous chapters to give specific values
to variables or to express messages we wanted our programs to print
out, for example, when we wrote:
a = 5;
1 1776
2 707
3 -273
Unsigned may be combined with any of the other two in any order to
form unsigned long or unsigned long long.
For example:
1 75 // int
2
3 75u // unsigned int
4 75l // long
5
75ul // unsigned long
75lu // unsigned long
In all the cases above, the suffix can be specified using either
upper or lowercase letters.
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.
Suffix Type
f or F float
l or L long double
For example:
1 3.14159L // long double
2
6.02e23f // float
x
'x'
For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
Internally, computers represent characters as numerical codes: most
typically, they use one extension of the ASCII character encoding
system (see ASCII code for more info). Characters can also be
represented in literals using its numerical code by writing a
backslash character (\) followed by the code expressed as an octal
(base-8) or hexadecimal (base-16) number. For an octal value, the
backslash is followed directly by the digits; while for hexadecimal,
an x character is inserted between the backslash and the
hexadecimal digits themselves (for example: \x20 or \x4A).
Note how spaces within the quotes are part of the literal, while
those outside them are not.
is equivalent to:
x = "string expressed in two lines"
All the character literals and string literals described above are
made of characters of type char. A different character type can be
specified by using one of the following prefixes:
Note that, unlike type suffixes for integer literals, these prefixes
are case sensitive: lowercase for char16_t and uppercase
for char32_t and wchar_t.
Prefix Description
u8 The string literal is encoded in the executable using UTF-8
R The string literal is a raw string
In raw strings, backslashes and single and double quotes are all
valid characters; the content of the literal is delimited by an
initial R"sequence( and a final )sequence", where sequence is
any sequence of characters (including an empty sequence). The content
of the string is what lies inside the parenthesis, ignoring the
delimiting sequence itself. For example:
1 R"(string with \backslash)"
2 R"&%$(string with \backslash)&%$"
We can then use these names instead of the literals they were defined
to:
1 #include <iostream> 31.4159
2
3
using namespace std;
4 const double pi = 3.14159;const char
5 newline = '\n';
6 int main ()
7{
8
9 double r=5.0; // radius
10 double circle;
11
12 circle = 2 * pi * r;
13 cout << circle;
14 cout << newline;
15 }
After this directive, any occurrence of identifier in the code is interpreted as replacement,
where replacement is any sequence of characters (until the end of the line). This
replacement is performed by the preprocessor, and happens before the program is
compiled, thus causing a sort of blind replacement: the validity of the types or syntax
involved is not checked in any way.
For example:
1 #include <iostream> 31.4159
2
3
using namespace std;
4 #define PI 3.14159
5 #define NEWLINE '\n'
6 int main ()
7{
8
9 double r=5.0; // radius
10 double circle;
11
12 circle = 2 * PI * r;
13 cout << circle;
14 cout << NEWLINE;
15
16 }
Note that the #define lines are preprocessor directives, and as such are single-line
instructions that -unlike C++ statements- do not require semicolons (;) at the end; the
directive extends automatically until the end of the line. If a semicolon is included in the
line, it is part of the replacement sequence and is also included in all replaced occurrences.
Operators
Once introduced to variables and constants, we can begin to operate
with them by using operators. What follows is a complete list of
operators. At this point, it is likely not necessary to know all of
them, but they are all listed here to also serve as reference.
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:
operator description
+ addition
- subtraction
* multiplication
/ division
% modulo
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |
=)
Compound assignment operators modify the current value of a variable
by performing an operation on it. They are equivalent to assigning
the result of an operation to the first operand:
Example 1 Example 2
x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3
Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality
operators. For example, to know if two values are equal or if one is
greater than the other.
operator description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Of course, it's not just numeric constants that can be compared, but
just any value, including, of course, variables. Suppose
that a=2, b=3 and c=6, then:
1 (a == 5) // evaluates to false, since a is not equal to 5
2
3 (a*b >= c) // evaluates to true, since (2*3 >= 6) is true
4 (b+4 > a*c) // evaluates to false, since (3+4 > 2*6) is false
((b=2) == a) // evaluates to true
|| OPERATOR (or)
a b a || b
true true true
true false true
false true true
false false false
For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false )
2
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false )
For example:
1 // conditional operator 7
2
3
#include <iostream>
4 using namespace std;
5 int main ()
6{
7 int a,b,c;
8
9
10 a=2;
11 b=7;
12 c = (a>b) ? a : b;
13
14 cout << c << '\n';
}
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions
that are included where only one expression is expected. When the set
of expressions has to be evaluated for a value, only the right-most
expression is considered.
sizeof
This operator accepts one parameter, which can be either a type or a
variable, and returns the size in bytes of that type or object:
x = sizeof (char);
Other operators
Later in these tutorials, we will see a few more operators, like the
ones referring to pointers or the specifics for object-oriented
programming.
Precedence of operators
A single expression may have multiple operators. For example:
x = 5 + 7 % 2;
Where:
- type is the type of the value returned by the function.
- name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type
followed by an identifier, with each parameter being separated from
the next by a comma. Each parameter looks very much like a regular
variable declaration (for example: int x), and in fact acts within
the function as a regular variable which is local to the function.
The purpose of parameters is to allow passing arguments to the
function from the location where it is called from.
- statements is the function's body. It is a block of statements
surrounded by braces { } that specify what the function actually
does.
At the point at which the function is called from within main, the
control is passed to function addition: here, execution of main is
stopped, and will only resume once the addition function ends. At
the moment of the function call, the value of both arguments
(5 and 3) are copied to the local variables int a and int
b within the function.
Let's examine each of these calls, bearing in mind that each function
call is itself an expression that is evaluated as the value it
returns. Again, you can think of it as if the function call was
itself replaced by the returned value:
1 z = subtraction (7,2);
2 cout << "The first result is " << z;
as:
cout << "The second result is " << 5;
The only addition being that now the function call is also an operand
of an addition operation. Again, the result is the same as if the
function call was replaced by its result: 6. Note, that thanks to the
commutative property of additions, the above can also be written as:
z = subtraction (x,y) + 4;
With exactly the same result. Note also that the semicolon does not
necessarily go after the function call, but, as always, at the end of
the whole statement. Again, the logic behind may be easily seen again
by replacing the function calls by their returned value:
1 z = 4 + 2; // same as z = 4 + subtraction (x,y);
2
z = 2 + 4; // same as z = subtraction (x,y) + 4;
value description
0 The program was successful
The program was successful (same as above).
EXIT_SUCCESS
This value is defined in header <cstdlib>.
The program failed.
EXIT_FAILURE
This value is defined in header <cstdlib>.
This function takes two strings as parameters (by value), and returns
the result of concatenating them. By passing the arguments by value,
the function forces a and b to be copies of the arguments passed
to the function when it is called. And if these are long strings, it
may mean copying large quantities of data just for the function call.
Inline functions
Calling a function generally causes a certain overhead (stacking
arguments, jumps, etc...), and thus for very short functions, it may
be more efficient to simply insert the code of the function where it
is called, instead of performing the process of formally calling a
function.
The call only passes one argument to the function, even though the
function has two parameters. In this case, the function assumes the
second parameter to be 2 (notice the function definition, which
declares its second parameter as int b=2). Therefore, the result is
6.
The call passes two arguments to the function. Therefore, the default
value for b (int b=2) is ignored, and b takes the value passed as
argument, that is 4, yielding a result of 5.
Declaring functions
In C++, identifiers can only be used in expressions once they have
been declared. For example, some variable x cannot be used before
being declared with a statement, such as:
int x;
The declaration shall include all types involved (the return type and
the type of its arguments), using the same syntax as used in the
definition of the function, but replacing the body of the function
(the block of statements) with an ending semicolon.
The parameter list does not need to include the parameter names, but
only their types. Parameter names can nevertheless be specified, but
they are optional, and do not need to necessarily match those in the
function definition. For example, a function
called protofunction with two int parameters can be declared with
either of these statements:
1 int protofunction (int first, int second);int protofunction (int,
2
int);
Anyway, including a name for each parameter always improves
legibility of the declaration.
1 // declaring functions prototypes#include Please, enter number (0 to exit):
2 9
3
<iostream>using namespace std;
4 void odd (int x);void even (int x);
It is odd.
5 int main() Please, enter number (0 to exit):
6{ 6
7
int i; It is even.
8 Please, enter number (0 to exit):
9 do {
10 cout << "Please, enter number (0 to 1030
11 exit): "; It is even.
12 cin >> i; Please, enter number (0 to exit):
13 odd (i); 0
14 } while (i!=0); It is even.
15
return 0;
16
}
17
18 void odd (int x)
19 {
20 if ((x%2)!=0) cout << "It is odd.\n";
21 else even (x);
22 }
23
24 void even (int x)
25 {
26 if ((x%2)==0) cout << "It is even.\n";
27 else odd (x);
28 }
29
Declare the prototype of the functions. They already contain all what
is necessary to call them, their name, the types of their argument,
and their return type (void in this case). With these prototype
declarations in place, they can be called before they are entirely
defined, allowing for example, to place the function from where they
are called (main) before the actual definition of these functions.
Recursivity
Recursivity is the property that functions have to be called by
themselves. It is useful for some tasks, such as sorting elements, or
calculating the factorial of numbers. For example, in order to obtain
the factorial of a number (n!) the mathematical formula would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:
1 // factorial calculator#include 9! = 362880
2
3
<iostream>using namespace std;
4 long factorial (long a)
5{
6 if (a > 1)
7
8
return (a * factorial (a-1));
9 else
10 return 1;
11 }
12 int main ()
13 {
14
15 long number = 9;
16 cout << number << "! = " << factorial
17 (number);
18 return 0;
}