Chapter Two
Basics of Programming
• In order to write a program you need to go through
several stages. These are:
– Type the text of the program into the computer
– Translate the program text into a form the computer
can use
– Run the translated program
NB: If you make a mistake during step 1 then it is likely that
the computer will not be able to translate the program. so you
will never reach step 3.
1
• The text of a program is known as the source of the program
• The translation of the program is known as compilation
• The result of the translation or compilation is the executable or
binary version of the program.
• The complete development cycle in C++ is:
– Write the program, compile the source code, link the program,
and run it.
IDE
• IDE stands for Integrated Development Environment
– Includes the compiler and the linker
– Has tools to assist the programmer
– Automates and simplifies the programming process
2
Writing a program
• The files you create with your editor are called source files, and for
C++ they typically are named with the extension .CPP.
Compiling
• Your source code file can't be executed, or run, as a program can.
• To turn your source code into a program, you use a compiler.
• After your source code is compiled, an object file is produced. This
file is often named with the extension .OBJ.
• This is still not an executable program, however. To turn this into an
executable program, you must run your linker.
Linking
• C++ programs are typically created by linking together one or more
OBJ files with one or more libraries(a collection of linkable files ).
3
The Programming Process
Summary
The steps to create an executable file are
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an
executable program.
Machine
Code
#include<iostream>
int main( 10101
Compile LINK
{
00101
0101
… Object
Code
Source
Code
Libraries, RUN
Other Object
Code
4
Basic Elements
1. Keywords (reserved words)
– have a unique meaning within a C++ program
– must not be used for any other purposes
– All reserved words are in lower-case letters
The following are some of the reserved words of C++.
asm auto bool break case catch
const_cast class const char continue default
dynamic_cast do double delete else enum
explicit extern false float for friend
goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this
throw true try typedef typeid typename
union unsigned using virtual void volatile
wchar_t
NB: for practical purposes you are advised to treat main, cin, and cout as if they were
reserved as well even though they aren’t.
5
2. Identifiers
• is name associated with a function or data object and used to refer to that
function or data object.
An identifier must:
– Start with a letter or underscore
– Consist only of letters, the digits 0-9, or the underscore symbol _ or dollar
sign $
– Not be a reserved word
• use of two consecutive underscore symbols, _ _, is forbidden.
$int
NB: C++ is case-sensitive 6
3. Comments
• A comment is a piece of descriptive text which explains some aspect of a
program.
• Program comments are totally ignored by the compiler and are only
intended for human readers.
C++ provides two types of comment delimiters:
• Anything after // (until the end of the line on which it appears) is
considered a line comment.
• Anything enclosed by the pair /* and */ is considered as Block comment.
7
Variables, Data Types, and Operators
1. Variables
• is a symbolic name for a memory location in which data can be stored
• used for holding data values
All variables have two important attributes:
• A data type, which is, established when the variable is defined (e.g.,
integer, float, character, bool,…).
– Once defined, the type of a C++ variable cannot be changed.
• A value, which can be changed by assigning a new value to the variable.
The kind of values a variable can assume depends on its type.
Variable Declaration
• means defining (creating) a variable by stating its type, followed by one or
more spaces, followed by the variable name and a semicolon.
Example: the following statement defines an integer variable called myAge:
int myAge;
IMPORTANT- Variables must be declared before used!
8
More Concepts - Variables
• Variables are a way of representing data in your programs. You
can think of them as containers for a value.
Example:
Do the following exercise and you are not allowed to paper and pen:
1. Add 5 and 6 and remember the result
2. Subtract 4 from 7 and remember the result
3. Multiply result 1 with 6 and remember the result
4. Divide result 3 by result 2 and tell me the value
9
Variables…..cont’d
• Its also possible to create more than one variable of the same type in one
statement
Example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
• Assign a value to a variable by using the assignment operator (=)
Example:
int Width;
Width = 5;
• Can combine these steps and initialize Width when you define it by writing
int Width = 5;
• You can also initialize more than one variable at creation.
Example:
// create two int variables and initialize them
int width = 5, length = 7;
10
Basic Data Types
• While defining a variable, you must tell the compiler what kind of variable it is.
• Basic (fundamental) data types in C++ can be conveniently divided into numeric
and character types.
Numeric variables
– integer variables- hold only integers
– floating-point variables- can accommodate real numbers
• Both the numeric data types offer modifiers(short, long, signed and unsigned.) that
are used to vary the nature of the data to be stored.
Table: shows the variable type, how much room it takes in memory, and what kinds of 11values
can be stored in these variables.
Basic Data Types…….cont’d
• Integers (short and long) without the word "unsigned" are assumed to be signed.
– Signed integers are either negative or positive.
• Unsigned integers are always positive.
• Example: A demonstration of adding too large a number to a signed and unsigned integer.
#include <iostream>
using namespace std;
int main()
{
unsigned short int smallNumber1;
smallNumber1 = 65535;
short int smallNumber2;
smallNumber2 = 32767;
cout << "small numbers:" << smallNumber1<<“ “ << smallNumber2 << endl;
smallNumber1++;
smallNumber2++;
cout << "small numbers:" << smallNumber1 << “ “<<smallNumber2 << endl;
smallNumber1++;
smallNumber2++;
cout << "small numbers:" << smallNumber1 << “ “<<smallNumber2 << endl;
return 0;
}
OUTPUT: small numbers: 65535 32767
small numbers: 0 -32768
small numbers:1 -32767
12
Characters
• Character variables (type char) are typically 1 byte, enough to hold 256 values
• A char can be interpreted as a small number (0-255)
• All the lower- and uppercase letters, all the numerals, and all the punctuation marks
are assigned values between 1 and 128
Characters and Numbers
• When you put a character, for example, ‘a’, into a char variable, what is really there
is just a number between 0 and 255.
Example: lowercase "a" is assigned the value 97
• However, there is a big difference between the value 5 and the character ‘5’. The
latter is actually valued at 53, much as the letter `a' is valued at 97.
13
14
Operators
1. Assignment Operators
• is used for storing a value at some memory location (typically denoted by a
variable).
• Any number of assignments can be concatenated in this fashion to form one
expression.
Example: int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = 100;
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
m += n = p = 10; // means: m = m + (n = p = 10); 15
#include <iostream>
using namespace std;
int main ()
{
int a, b;
a = 2; // 2 is assigned to a
b = 7; // 7 is assigned to b
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "After a += b" << endl; // assigning the sum of a and b to a
a += b; // a = a +b
cout << "a = " << a << endl;
return 0;
}
16
2. Arithmetic Operators
• C++ provides five basic arithmetic operators
• Except for remainder (%) all other arithmetic operators can accept a mix of integer
and real operands.
• Generally, if both operands are integers then the result will be an integer. However,
if one or both of the operands are reals then the result will be a real (or double to be
exact)
• Integer division always results in an integer outcome (i.e., the result is always
rounded down).
For example:
9/2 // gives 4, not 4.5!
-9/2 // gives -5, not -4! exact).
17
#include <iostream>
using namespace std;
int main ()
{
int a, b;
a = 7;
b = 2;
cout << "a + b = " << (a + b) << endl; // printing the sum of a and b
cout << "a - b = " << (a - b) << endl; // printing the difference of a and b
cout << "a * b = " << (a * b) << endl; // printing the product of a and b
cout << "a / b = " << (a / b) << endl; // printing the division of a by b
cout << "a % b = " << (a % b) << endl; // printing the modulo of a by b
return 0;
}
18
3. Relational Operators
• C++ provides six relational operators for comparing numeric quantities.
• Evaluate to 1 (representing the true outcome) or 0 (representing the false outcome).
• Characters are valid operands since they are represented by numeric values.
Example: 'A' < 'F' // gives 1 (is like 65 < 70)
• Should not be used for comparing strings, because this will result in the string
addresses being compared, not the string contents.
– The outcome may be 0 or 1, as the addresses are determined by the compiler
19
#include <iostream>
using namespace std;
int main ()
{
int a, b;
a = 3;
b = 5;
bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;
result = (a != b); // true
cout << "3 != 5 is " << result << endl;
result = a > b; // false
cout << "3 > 5 is " << result << endl;
result = a < b; // true
cout << "3 < 5 is " << result << endl;
result = a >= b; // false
cout << "3 >= 5 is " << result << endl;
result = a <= b; // true
cout << "3 <= 5 is " << result << endl;
return 0;
}
20
4. Logical Operators
C++ provides three logical operators for combining logical expression.
• In general, any nonzero value can be used to represent the logical true, whereas
only zero represents the logical false.
Example: Some valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 ||5.5 // gives 1
10 && 0 // gives 0
21
#include <iostream>
using namespace std;
int main ()
{
bool result;
result = (3 == 5) || (3 > 5); // false
result = (3 != 5) && (3 < 5); // true
cout << "(3 == 5) || (3 > 5) is " << result << endl;
cout << "(3 != 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 < 5); // false result = !(5 == 2); // true
cout << "(3 == 5) && (3 < 5) is " << result << endl; cout << "!(5 == 2) is " << result << endl;
result = (3 == 5) && (3 > 5); // false
result = !(5 == 5); // false
cout << "(3 == 5) && (3 > 5) is " << result << endl;
result = (3 != 5) || (3 < 5); // true cout << "!(5 == 5) is " << result << endl;
cout << "(3 != 5) || (3 < 5) is " << result << endl; return 0;
result = (3 != 5) || (3 > 5); // true
}
cout << "(3 != 5) || (3 > 5) is " << result << endl;
22
5. Increment/decrement Operators
• The auto increment (++) and auto decrement (--) operators provide a
convenient way of, respectively, adding and subtracting 1 from a numeric
variable.
• Both operators can be used in prefix and postfix form.
– When used in prefix form, the operator is first applied and the outcome is
then used in the expression.
– When used in the postfix form, the expression is evaluated first and then
the operator applied.
23
Increment and Decrement Operators…
Note: the prefix version returns an lvalue, the postfix version returns an rvalue;
25