C++ Prog and Appl
C++ Prog and Appl
C++ Prog and Appl
Chapter One
Variables and data types
The program introduced in the previous chapter is not really useful because we had to write several lines of
code, compile them, and then execute the resulting program just to obtain a simple sentence written on the
screen as result. It certainly would have been much faster to type the output sentence by ourselves. However,
programming is not limited only to printing simple texts on the screen. In order to go a little further on and to
become able to write programs that perform useful tasks that really save us work we need to introduce the
concept of variable. A variable is a portion of memory used for the storage of a determined value. Each
variable needs an identifier that distinguishes it from the others.
1. Identifiers
A valid identifier is a sequence of one or more letters, digits or underline characters ( _ ). Neither spaces nor
punctuation marks or symbols can be part of an identifier. In addition, variable identifiers always have to
begin with a letter. They can also begin with an underline character ( _ ), but this is usually reserved for
compiler specific keywords or external identifiers.
Another important rule is that: identifiers should not match any keyword of the C++ language. Some of the
standard reserved keywords are:
asm continue false namespace sizeof typeid
auto default float new static typename
bool delete for operator struct union
break do friend private switch unsigned
case double goto protected template using
catch else if public this virtual
char enum inline register throw void
class explicit int return, true volatile
const export long short try wchar_t
const_cast extern mutable signed typedef while
Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved
words under some circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Very important: The C++ language is a "case sensitive" language. That means that an identifier written in
capital letters is not equivalent to another one with the same name but written in small letters. Thus, for
example, the RESULT variable is not the same as the result variable or the Result variable. These are three
different variable identifiers.
4
Dr. KAMDEM Paul
Uba/HTTTC Bambili – EPET4102 (EE Level 400) C++ programming and applications
When programming, we store the variables in our computer's memory, but the computer has to know what we
want to store, 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, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can
manage in C++. A byte can store a relatively small amount of data: one single character or a small integer
(generally an integer between 0 and 255).
This is a summary of the basic fundamental data types in C++, as well as the range of values that can be
represented with each one:
3. Declaration of variables
In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The
syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed
by a valid variable identifier. For example:
int counter;
float voltage;
If you we want to declare more than one variable of the same type, we can declare all of them in a single
statement by separating their identifiers with commas. For example:
5
Dr. KAMDEM Paul
Uba/HTTTC Bambili – EPET4102 (EE Level 400) C++ programming and applications
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. For example:
To see what variable declarations look like in action within a program, let’s look at this simple C++ code :
// operating with variables (Ohm’s law) 1000 V
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int R, I;
int U;
// process:
R = 500;
I = 1;
I = I + 1;
U = R * I;
// print out the result:
cout << U << “ V ”;;
// terminate the program:
return 0;
}
4. Scope of variables
A scope
pe of a variable is like its lifespan during the execution of the program. A variable can be either of global
or local scope.
A global variable is a variable declared in the main body of the source code, outside all functions, while a local
variable iss one declared within the body of a function or a block. Global variables can be referred from
anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is
limited to the block enclosed in braces ({
( }) where they are declared.
6
Dr. KAMDEM Paul
Uba/HTTTC Bambili – EPET4102 (EE Level 400) C++ programming and applications
5. Initialization of variables
When we declare a 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++:
6. Introduction to strings
Variables that can store non-numerical values that are longer than one single character are known as strings. Its
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.
int main ()
{
string Str = "START";
cout << Str;
return 0;
}
As we can see from the previous example, strings can be initialized with any valid string literal and both
initialization formats are valid:
7. Constants
In C++ we can declare a quantity such that its value will not be modify in the program. It is the case for some
constants used in physics and mathematics. e.g. π=3.14, g=9.81, k=9×109, 6.02×1023, 1.6×10-19 …
7.1. Literals
Literals are used to express particular values within the source code of a program.
Counter = 5;
The 5 in this piece of code is a literal constant. Literal constants can be divided in Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.
7
Dr. KAMDEM Paul
Uba/HTTTC Bambili – EPET4102 (EE Level 400) C++ programming and applications
Integer Numerals
75 // decimal
0113 // octal
0x4b // hexadecimal
All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and
hexadecimal numeral, respectively.
3.14159 // 3.14159
6.02e23 // 6.02 x 1023
1.6e-19 // 1.6 x 10-19
3.0 // 3.0
Character and string literals have certain peculiarities, like the escape codes. Here you have a list of some of
such escape codes:
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
Boolean literals
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.
It is possible to define our own names for constants that we can use very often without having to resort to
memory-consuming variables, simply by using the #define preprocessor directive. Its format is:
#define e 1.6e-19
#define NEWLINE '\n';
int main ()
{
double n=20e12; // number of electrons
double Q;
Q = n * e;
cout << Q << " [C] ";
cout << NEWLINE;
return 0;
}
With the const prefix we can declare constants with a specific type: For Example
To do: Write a program to calculate and display the electrostatic force between two charged bodies A and B
9
Dr. KAMDEM Paul