Chapter 2 Basics C++ 11
Chapter 2 Basics C++ 11
Object Code
cout
represents the standard output stream in C++, and the meaning of
the entire statement is to insert a sequence of characters (in this
case the Hello World sequence of characters) into the standard
output stream (which usually is the screen).
Notice that the statement ends with a semicolon character (;). This
character is used to mark the end of the statement and in fact it
must be included at the end of all expression statements in all C++
programs
return 0;
The return statement causes the main function to finish.
This is the most usual way to end a C++ console program.
// line comment
/* block comment */
a = 5;
b = 2;
a = a + 1;
result = a - b;
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.
Therefore, we can define a variable as a portion of memory to
store a determined value.
Thus, for example, the RESULT variable is not the same as the result
variable or the Result variable. These are three different variable
identifiers.
2.2.3. Fundamental data types
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,
and they are not going to be interpreted the same way.
double Double precision floating 8 byte +/- 1.7e +/- 308 (~15 digits)
point number.
long double Long double precision 10 +/- 1.7e +/- 308 (~15 digits)
floating point number. byte
March 1, 2025
wchar_t Wide character. 2 0r 4 Mekelle
1 wideUniversity,
characterDepartment of CS
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.4. 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 a;
float mynumber
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.
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;
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:
unsigned short int NumberOfSisters;
signed int MyAccountBalance;
Global
Variables
Local Variables
Instructions
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;
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
2.2.7. Constants
A. Literal Constants
A value typed directly into your program whenever it is needed
For example
int myAge = 39;
myAge is a variable of type int; 39 is a literal constant.
You can't assign a value to 39, and its value can't be
changed.
Literal constants can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.
2.2.7. Constants
B. Symbolic Constants
A symbolic constant is a constant that is represented by a name, just as a
variable is represented.
#define PI 3.14159
#define NEWLINE '\n'
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,
March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
2.2.7. Constants
for example:
// defined constants: calculate circumference
#include <iostream.h>
#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; 31.415
} 9
2.2.7. Constants
With the const prefix you can declare constants with a specific
type in the same way as you would do with a variable:
For example
They are treated just like regular variables except that their
values cannot be modified after their definition.
The biggest difference is that this constant has a type, and the
compiler can enforce that it is used according to its type.
The insertion operator (<<) may be used more than once in a same
sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
Hello, I am a C++ sentence
Input (cin)
Handling the standard input in C++ is done by applying the
overloaded operator of extraction (>>) on the cin stream.
This must be followed by the variable that will store the data that is
going to be read.
For example:
int age;
cin >> age;
declares the variable age as an int and then waits for an input from
You can also use
cin (keyborad) in cin to to
order request more
store it than
in this one datum
integer input from
variable.
the user:
This is equivalent cin >> a;
cin >> a >> b; to: cin >> b;
Fore example
// i/o example
#include <iostream.h>
int main ()
{ int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
2.2.7. Operators
2.2.7. Operators
Arithmetic Operators
2.2.7. Operators
Combined Assignment
Operators
Quite often programs have assignment statements of the following
form:
number = number + 1;
On the right-hand side of the assignment operator, 1 is added to
number.
The result is then assigned to number, replacing the value that was
previously stored there.
Fore example (Assume x=6)
2.2.7. Operators
Combined Assignment
Operators
C++ offers a special set of operators designed specifically for these
jobs.
The following table shows the combined assignment operators, also
known as compound operators or arithmetic assignment operators.
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
2.2.7. Operators
Combined Assignment
Operators
Examples Using Combined Assignment Operators and Arithmetic
Operators
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Example
Notice1 the difference: Example 2
B=3; B=3;
A=++B; A=B++;
//A contains 4, B contains 4 //A contains 3, B contains 4
Example
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
Example
// conditional operator
#include <iostream>
int main () 7
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
sizeof()
a = sizeof (char);
For example:
int i;
float f = 3.14;
i = (int) f;
The type casting operator (int) converts the float number 3.14 to an
integer value 3.
a = 5 + (7 % 2) with result 6, or
a = (5 + 7) % 2 with result 0
The
March correct
1, 2025 answer is the first of the two expressions,
Mekelle University, with a result
Department of CS
Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE
There is an established order with the priority of each operators which can
appear in C++.
From greatest to lowest priority, the priority order is as follows:
Associativit
Priority Operator Description
y
1 :: scope Left
1 () [ ] -> . sizeof Left
++ -- increment/decrement
! unary NOT
Reference and
2 &* Right
Dereference (pointers)
(type) Type casting
+- Unary plus and minus
3 */% arithmetical operations Left
4 +- arithmetical operations Left
5 < <= > >= Relational operators Left
6 == != Relational operators Left
7 && || Logic operators Left
8 ?: Conditional Right
= += -= *= /= %=
9 Assignment Right
March 1, 2025 >>= <<= &= ^= |= Mekelle University, Department of CS
Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE
The following table shows the precedence of the arithmetic operators.
The operators at the top of the table have higher precedence than the
ones below it (Highest to Lowest):
Fore example
y=(3*x)/2 or y= (3/2)*x
i = int ( f );
years * interestRate
Fore example:
int x, y = 4;
double
March 1, 2025 z = 2.7; Mekelle University, Department of CS
Chapter 2
Basics of C++
2.8. TYPE CONVERSION
Implicit Type Conversion
Fore example:
// shows mixed expressions
#include <iostream.h>
int main()
{
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
cout << “totalWeight=” << totalWeight << endl;
return 0;
}
long double
double
float
unsigned long
long
unsigned int
int
short
char
Example;
Here’s an example.
LOCATION POP.
Portcity 2425785
Hightown 47
Lowville 9761
The setw manipulator causes the number (or string) that follows
it in the stream to be printed within a field n characters wide,
where n is the argument to setw(n).
LOCATION POPULATION
Portcity 2425785
Hightown 47
Lowville 9761
Design errors
occur during the analysis, design, and implementation phases.
Syntax Errors
Run-time Errors