C++ Programming: Nyambati N. Richard

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 104

C++ PROGRAMMING

Nyambati N. Richard
Basic Structure of C++ Program
 Probably the best way to start learning a programming
language is by writing a program. Therefore, here is our
first program:
1. // my first program in C++
2. #include <iostream>
3. using namespace std;
4. int main ()
5. {
6. cout << "Hello World!";
7. return 0;
8. }
Basic Structure of C++ Program
 // my first program in C++ is a comment line.
 #include <iostream>: Lines beginning with a hash sign
(#) are directives for the preprocessor.
 using namespace std; :All the elements of the standard
C++ library are declared within what is called a
namespace, the namespace with the name std.
 int main () : This line corresponds to the beginning of
the definition of the main function. The main function is
the point by where all C++ programs start their
execution
Basic Structure of C++ Program
 cout << "Hello World!"; This line is a C++
statement that prints “Hello World” on the screen
 return 0; The return statement causes the main
function to finish.
Variables
 A variable is a symbolic name for a memory
location in which data can be stored and
subsequently recalled.
 Variables are used for holding data values so that
they can be utilized in various computations in a
program.
Variables
 All variables have two important attributes:
 A type which is established when the variable is
defined (e.g., integer, real, character). 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. For example, an
integer variable can only take integer values (e.g., 2,
100, -12).
Identifiers (Variable Names)

 A valid identifier is a sequence of one or more


letters, digits or underscore characters (_).
 Neither spaces nor punctuation marks or symbols
can be part of an identifier. Only letters, digits and
single underscore characters are valid.
 In addition, variable identifiers always have to
begin with a letter.
Variable Names
 They can also begin with an underline character
(_ ), but in some cases these may be reserved for
compiler specific keywords or external identifiers,
as well as identifiers containing two successive
underscore characters anywhere.
 In no case they can begin with a digit.
Identifiers (Variable Names)

 Another rule that you have to consider when


inventing your own identifiers is that they cannot
match any keyword of the C++ language nor your
compiler's specific ones, which are reserved
keywords. The standard reserved keywords are:
 asm, auto, bool, break, case, catch, char, class, const,
const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern,
false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, operator, private, protected,
Variable Names
 public, register, reinterpret_cast, return, short, signed,
sizeof, static, static_cast, struct, switch, template, this,
throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t,
 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
Identifiers (Variable Names)

 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.
Illustration
 #include <iostream>
 using namespace std.
 int main (void)
 {
 int workDays;
 float workHours, payRate, weeklyPay;
 workDays = 5;
Illustration
 workHours = 7.5;
 payRate = 38.55;
 weeklyPay = workDays * workHours * payRate;
 cout << "Weekly Pay = ";
 cout << weeklyPay;
 cout << '\n';
 }
Simple Input/Output

 C++ provides two useful operators for this purpose:


>> for input and << for output.
 #include <iostream>
 using namespace std;
 int main (void)
 {
 int workDays = 5;
 float workHours = 7.5;
Simple Input/Output

 float payRate, weeklyPay;


 cout << "What is the hourly pay rate? ";
 cin >> payRate;
 weeklyPay = workDays * workHours * payRate;
 cout << "Weekly Pay = ";
 cout << weeklyPay;
 cout << '\n';
 }
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 comment.
 Anything enclosed by the pair /* and */ is considered a
comment.
Comments
 #include <iostream>
 /* This program calculates the weekly gross pay for a
worker,
 based on the total number of hours worked and the
hourly pay
 rate. */
 using namespace std;
 int main (void)
Comments
 {
 int workDays = 5; // Number of work days per week
 float workHours = 7.5; // Number of work hours per
day
 float payRate = 33.50; // Hourly pay rate
 float weeklyPay; // Gross weekly pay
 weeklyPay = workDays * workHours * payRate;
 cout << "Weekly Pay = " << weeklyPay << '\n';
 }
Comments
 Comments should be used to enhance (not to
hinder) the readability of a program.
 The following two points, in particular, should be
noted:
 A comment should be easier to read and understand
than the code which it tries to explain. A confusing or
unnecessarily-complex comment is worse than no
comment at all.
Comments
 Over-use of comments can lead to even less
readability. A program which contains so much
comment that you can hardly see the code can by no
means be considered readable.
 Use of descriptive names for variables and other
entities in a program, and proper indentation of the
code can reduce the need for using comments.
 The best guideline for how to use comments is to
simply apply common sense.
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.
 The memory in our computers is organized in bytes.
A byte is the minimum amount of memory that we
can manage in C++.
Fundamental data types

 A byte can store a relatively small amount of data:


one single character or a small integer (generally an
integer between 0 and 255).
 In addition, the computer can manipulate more
complex data types that come from grouping
several bytes, such as long numbers or non-integer
numbers.
Integer Data Type
 An integer variable may be defined to be of type
short, int, or long. The only difference is that an int
uses more or at least the same number of bytes as a
short, and a long uses more or at least the same
number of bytes as an int. For example, on the
author’s PC, a short uses 2 bytes, an int also 2
bytes, and a long 4 bytes.
 short age = 20;
 int salary = 65000;
 long price = 4500000;
Integer Data Type
 By default, an integer variable is assumed to be
signed (i.e., have a signed representation so that it
can assume positive as well as negative values).
However, an integer can be defined to be unsigned
by using the keyword unsigned in its definition.
The keyword signed is also allowed but is
redundant.
 unsigned short age = 20;
 unsigned int salary = 65000;
 unsigned long price = 4500000;
Real Numbers
 A real variable may be defined to be of type float or
double. The latter uses more bytes and therefore
offers a greater range and accuracy for representing
real numbers.
 For example, on the author’s PC, a float uses 4 and
a double uses 8 bytes.
 float interestRate = 0.06;
 double pi = 3.141592654;
Characters
 A character variable is defined to be of type char.
 A character variable occupies a single byte which
contains the code for the character. This code is a
numeric value and depends on the character coding
system being used (i.e., is machine-dependent).
 The most common system is ASCII (American
Standard
Characters
 Code for Information Interchange). For example,
the character A has the ASCII code 65, and the
character a has the ASCII code 97.
 char ch = 'A';
 Like integers, a character variable may be specified
to be signed or unsigned.
Strings
 A string is a consecutive sequence (i.e., array) of
characters which are terminated by a null
character. A string variable is defined to be of type
char* (i.e., a pointer to character). A pointer is
simply the address of a memory location.
 A string variable, therefore, simply contains the
address of where the first character of a string
appears. For example, consider the definition:
 char *str = "HELLO";
Strings
 A common programming error results from
confusing a single-character string (e.g., "A") with
a single character (e.g., 'A'). These two are not
equivalent.
 The former consists of two bytes (the character 'A'
followed by the character '\0'), whereas the latter
consists of a single byte.
 The shortest possible string is the null string ("")
which simply consists of the null character.
Exercises

 Which of the following represent valid variable definitions?


 int n = -100;
 unsigned int i = -100;
 signed int = 2.9;
 long m = 2, p = 4;
 int 2k;
 double x = 2 * m;
 float y = y * 2;
 unsigned double z = 0.0;
 double d = 0.67F;
Exercises

 float f = 0.52L;
 signed char = -1786;
 char c = '$' + 2;
 sign char h = '\111';
 char *name = "Peter Pan";
 unsigned char *num = "276811";
Exercises

 Which of the following represent valid identifiers?


 identifier
 seven_11
 _unique_
 gross-income
 gross$income
 2by2
 default
 average_weight_of_a_large_pizza
 variable
 object.oriented
Exercises

 Define variables to represent the following entities:


 Age of a person.
 Income of an employee.
 Number of words in a dictionary.
 A letter of the alphabet.
 A greeting message.
Scope of variables

 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 is 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.
Introduction to 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.
Introduction to strings
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
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:
 #define identifier value
 For example:
 #define PI 3.14159
 #define NEWLINE '\n'
Constants
// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
Constants
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
Constants
 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.
Operators

 Assignment (=)
 The assignment operator assigns a value to a variable.
 a = 5;

// assignment operator
#include <iostream>
using namespace std;
int main ()
Operators

{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}
Operators

 Arithmetic operators ( +, -, *, /, % )
 The five arithmetical operations supported by the
C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
a = 11 % 3;
Operators

 Compound assignment (+=, -=, *=, /=, %=, >>=,


<<=, &=,^=, |=)

expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a -5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
Operators

// compound assignment operators


#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}
Operators

 Increase and decrease (++, --)


 Shortening even more some expressions, the increase
operator (++) and the decrease operator (--) increase or
reduce by one the value stored in a variable. They are
equivalent to +=1 and to -=1, respectively. Thus:
 c++;
 c+=1;
 c=c+1;
Operators

 Relational and equality operators ( ==, !=,


>, <, >=, <= )
 In order to evaluate a comparison between
two expressions we can use the relational
and equality operators. The result of a
relational operation is a Boolean value that
can only be true or false, according to its
Boolean result.
Operators

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Operators

 Here there are some examples:


(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Operators

 Logical operators ( !, &&, || )


 ! – NOT
 && - AND
 || - OR
Control Structures
 A program is usually not limited to a linear
sequence of instructions.
 During its process it may repeat code or take
decisions.
 For that purpose, C++ provides control structures
that serve to specify what has to be done by our
program, when and under which circumstances.
Control Structures
 Conditional structure: if and else
 The if keyword is used to execute a statement or block
only if a condition is fulfilled. Its form is:
if (condition) statement
 Where condition is the expression that is being
evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not
executed) and the program continues right after this
conditional structure.
Control Structures
 For example, the following code fragment prints x is 100
only if the value stored in the x variable is indeed 100:
if (x == 100)
cout << "x is 100";
 If we want more than a single statement to be executed in
case that the condition is true we can specify a block using
braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
Control Structures
 We can additionally specify what we want to happen if
the condition is not fulfilled by using the keyword else.
Its form used in conjunction with if is:
if (condition) statement1 else statement2
 For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Control Structures
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Control Structures
 Iteration structures (loops)
 Loops have as purpose to repeat a statement a
certain number of times or while a condition is
fulfilled.
 The while loop
Its format is:
while (expression) statement
and its functionality is simply to repeat
statement while the condition set in expression
is true.
Control Structures
// custom countdown using while
#include <iostream>
using namespace std;
int main ()
{
int n;
Control Structures
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return 0;
}
Control Structures
 The do-while loop
Its format is:
do statement while (condition);

// number echoer
#include <iostream>
using namespace std;
int main ()
Control Structures
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
Control Structures
 The for loop
 Its format is:
for (initialization; condition; increase) statement;
 and its main function is to repeat statement while
condition remains true, like the while loop.

// countdown using a for loop


#include <iostream>
using namespace std;
int main ()
Control Structures
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Control Structures
 Jump statements.
 The break statement

Using break we can leave a loop even if the


condition for its end is not fulfilled. It can
be used to end an infinite loop, or to force it
to end before its natural end. For example,
we are going to stop the count down before
its natural end (maybe because of an engine
check failure?):
Control Structures
// break loop example
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
Control Structures
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
Control Structures
 The continue statement
 The continue statement causes the program to skip the rest
of the loop in the current iteration as if the end of the
statement block had been reached, causing it to jump to the
start of the following iteration.
 For example, we are going to skip the number 5 in our
countdown:
// continue loop example
#include <iostream>
using namespace std;
int main ()
Control Structures
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Control Structures
 The selective structure: switch.
 The syntax of the switch statement is a bit peculiar.
 Its objective is to check several possible constant
values for an expression.
 Something similar to what we did at the beginning of
this section with the concatenation of several if and
else if instructions.
 Its form is the following:
Control Structures
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
Control Structures
group of statements 2;
break;
.
.
.
default:
default group of statements
}
Switch example
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
Arrays
 An array is a series of elements of the same type
placed in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
 That means that, for example, we can store 5 values of
type int in an array without having to declare 5
different variables, each one with a different identifier.
 Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique
identifier.
Arrays
 For example, an array to contain 5 integer values of
type int called billy could be represented like this:

0 1 2 3 4
Bill
y
Arrays
 Where each blank panel represents an element of the
array, that in this case are integer values of type int.
 These elements are numbered from 0 to 4 since in arrays
the first index is always 0, independently of its length.
 Like a regular variable, an array must be declared before
it is used. A typical declaration for an array in C++ is:
type name [elements];
 where type is a valid type (like int, float...), name is a
valid identifier and the elements field (which is always
enclosed in square brackets []), specifies how many of
these elements the array has to contain.
Arrays
 Therefore, in order to declare an array called billy
as the one shown in the above diagram it is as
simple as:
int billy [5];
 In both cases, local and global, when we declare an
array, we have the possibility to assign initial
values to each one of its elements by enclosing the
values in braces { }. For example:
int billy [5] = { 16, 2, 77, 40, 12071 };
Arrays
 In any point of a program in which an array is
visible, we can access the value of any of its
elements individually as if it was a normal variable,
thus being able to both read and modify its value.
 The format is as simple as:
name[index]
Arrays
 For example, to store the value 75 in the third
element of billy, we could write the following
statement:
billy[2] = 75;
 and, for example, to pass the value of the third
element of billy to a variable called a, we could
write:
a = billy[2];
 Therefore, the expression billy[2] is for all purposes
like a variable of type int.
Arrays
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
Arrays
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
Multidimensional arrays

 Multidimensional arrays can be described as "arrays


of arrays". For example, a bidimensional array can be
imagined as a bidimensional table made of elements,
all of them of a same uniform data type.

0 1 2 3 4
0
Jimm 1
y 2
Multidimensional arrays
 jimmy represents a bidimensional array of 3 per 5
elements of type int. The way to declare this array
in C++ would be:
int jimmy [3][5];
 and, for example, the way to reference the second
element vertically and fourth horizontally in an
expression would be:
jimmy[1][3]
Multidimensional arrays
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
Multidimensional arrays
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
Functions
 Using functions we can structure our programs in a
more modular way, accessing all the potential that
structured programming can offer to us in C++.
 A function is a group of statements that is executed
when it is called from some point of the program.
The following is its format:

type name ( parameter1, parameter2, ...) { statements }


Functions
 where:
 type is the data type specifier of the data returned by the function.
 name is the identifier by which it will be possible to call the
function.
 parameters (as many as needed): Each parameter consists of a data
type specifier followed by an identifier, like any regular variable
declaration (for example: int x) and which acts within the function
as a regular local variable. They allow to pass arguments to the
function when it is called.
 The different parameters are separated by commas.
 statements is the function's body. It is a block of statements
surrounded by braces { }.
Functions
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
Functions
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
Functions
 In order to examine this code, first of all remember
something said at the beginning of this tutorial: a C++
program always begins its execution by the main
function. So we will begin there.
 We can see how the main function begins by declaring
the variable z of type int. Right after that, we see a call
to a function called addition.
 Within the main function we called to addition passing
two values: 5 and 3, that correspond to the int a and int
b parameters declared for function addition.
Functions
 At the point at which the function is called from within
main, the control is lost by main and passed to function
addition. The value of both arguments passed in the call (5
and 3) are copied to the local variables int a and int b within
the function.
 Function addition declares another local variable (int r), and
by means of the expression r=a+b, it assigns to r the result
of a plus b. Because the actual parameters passed for a and
b are 5 and 3 respectively, the result is 8.
 The following line of code:
return (r);
Functions
 finalizes function addition, and returns the control back to
the function that called it in the first place (in this case,
main).
 At this moment the program follows it regular course from
the same point at which it was interrupted by the call to
addition. But additionally, because the return statement in
function addition specified a value: the content of variable
r (return (r);), which at that moment had a value of 8.
 This value becomes the value of evaluating the function
call.
Functions
// function example
#include <iostream>
using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}
Functions
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}
Functions
 In this case we have created a function called
subtraction.
 The only thing that this function does is to subtract
both passed parameters and to return the result.
 Nevertheless, if we examine function main we will see
that we have made several calls to function
subtraction.
 We have used some different calling methods so that
you see other ways or moments when a function can
be called.
Functions
 // void function example
 #include <iostream>
 using namespace std;
 void printmessage ()
 {
 cout << "I'm a function!";
 }
 int main ()
 {
 printmessage ();
 return 0;
 }
Object Oriented Programming
 A class is an expanded concept of a data structure:
instead of holding only data, it can hold both data
and functions.
 An object is an instantiation of a class. In terms of
variables, a class would be the type, and an object
would be the variable.
 Classes are generally declared using the keyword
class, with the following format:
Classes
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Classes
 Where class_name is a valid identifier for the class,
object_names is an optional list of names for objects of this
class.
 The body of the declaration can contain members, that can be
either data or function declarations, and optionally access
specifiers.
 By default, all members of a class declared with the class
keyword have private access for all its members.
 Therefore, any member that is declared before one other class
specifier automatically has private access.
 Forexample:
Classes
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
Classes
 Declares a class (i.e., a type) called CRectangle and
an object (i.e., a variable) of this class called rect.
 This class contains four members: two data
members of type int (member x and member y)
with private access (because private is the default
access level) and two member functions with
public access: set_values() and area(), of which for
now we have only included their declaration, not
their definition.
Classes
// classes example
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
Classes
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
Classes
 The most important new thing in this code is the operator of
scope (::, two colons) included in the definition of set_values().
It is used to define a member of a class from outside the class
definition itself.
 You may notice that the definition of the member function area()
has been included directly within the definition of the
CRectangle class given its extreme simplicity, whereas
set_values() has only its prototype declared within the class, but
its definition is outside it.
 In this outside declaration, we must use the operator of scope
(::) to specify that we are defining a function that is a member of
the class CRectangle and not a regular global function.
Classes
 The scope operator (::) specifies the class to which
the member being declared belongs, granting exactly
the same scope properties as if this function
definition was directly included within the class
definition.
 For example, in the function set_values() of the
previous code, we have been able to use the variables
x and y, which are private members of class
CRectangle, which means they are only accessible
from other members of their class.
Classes
 The only difference between defining a class
member function completely within its class or to
include only the prototype and later its definition, is
that in the first case the function will automatically
be considered an inline member function by the
compiler, while in the second it will be a normal
(not-inline) class member function, which in fact
supposes no difference in behavior.

You might also like