You are on page 1of 15

CS 503: C++ programming language

Course Materials:
1. Lecture notes
2. Textbooks:
a. Robert Lafore: Object-Oriented Programming in C++, 4th edition, Sams Publishing, 2002.
b. D.S. Malik: C++ Programming: From Problem Analysis to Program Design, Cengage Learning, 2013
3. Other recommended references:
a. Richard L. Halterman: Fundamentals of C++ Programming, 2015.
b. Deitel, P., and Deitel H.: C++ How To Program, 9th edition, Pearson Education, 2013.
Topics:
1. C++ Programming Basics
2. Decisions and Loops
3. Functions
4. Structs
5. Arrays
6. Pointers
7. Objects, Classes, and inheritance

Student Assessment:
1. Midterm exam (22/3/2018, 20 points).
2. Practical assignments (5 points).
3. Non-credit homework for your practice and we can discuss it in the next lecture.
4. The final exam (75 points).

I recommend that you type all of the examples in every lecture, even
when they are very simple. Keying stuff makes it less likely that you
will forget things later. Don’t be afraid to experiment with the code.
Making mistakes is very educational in programming. The more
mistakes you make early, the more you are likely to learn.

The best way to learn to program is by writing programs! At the end of


each lecture and lap, you will find some exercises and/or a quiz.
Please answer them and evaluate your work. The later lectures build
on what you have learned in the earlier ones, so be certain you fully
understand the material before moving on.

The exercises further reinforce learning and challenge students to write


C++ programs with a specified outcome.

١
Lecture 1:
THE BASIC ELEMENTS OF C++

This lecture explains the basic elements of C++. After completing this
lecture, students become familiar with the basics of C++ and are
ready to write programs that are complicated enough to do some
computations. These programs teach problem-solving skills.

Getting Started
Your Development Environment: this will be explained in the laps.

Source files are text files and have extension .CPP

Executable files have the .EXE extension

Compilers take source code and transform it into executable files, which
your computer can run as it does with other programs.

٢
Getting Started (Cont.)

The steps to create an executable file are:


1. Create a source code file with a .cpp extension.

2. Compile the source code into an object file


with the .obj or .o extension.

3. Link your object file with any needed libraries


to produce an executable program.

Names of some symbols that are used frequently in C++:


Semicolon ;
Comma ,

Backslash \
Slash /
Double slash //
Braces {}
Parenthesis ()
Double quotation marks "
Single quotation mark '
Angular brackets <>
Hash #
Colon :

٣
Basic Program Construction

1 // first.cpp

2 // The first program in C++


Comments
3 #include <iostream>
4 Using namespace std;
Written between /* and */ or following a //.
Improve program readability and do not cause the
5 int main() computer to perform any action.
6 {
preprocessor directive
7 cout << "Welcome to C++!";
#include <iostream> tells the preprocessor to
8 include the contents of the file <iostream>, which
9 return 0; // indicate that the
includes input/output operations (such as printing to
program ended successfully
the screen).
10 }
C++ programs contain one or more functions, one of
which must be main
Welcome to C++! Parenthesis are used to indicate a function
Prints the string of characters
int meanscontained between
that main the an integer value.
"returns"
quotation marks.
return 0 means that the program
terminated normally. The entire line, including
A left bracethe
cout, begins
{ << the body
operator, theof every
string "Welcome tofunctionC++!"and anda the
right brace } ends
semicolon (;), it.
is called a statement.

All statements must end with a semicolon.

٤
Comments

- They help understand the code by providing explanation about it, and

- help you remember the key details of your program in future.

Should concentrate on the big picture, clarifying your reasons


for using a certain statement.

The compiler ignores the comments, so they do not add to the


file size or execution time of the executable program.

Comments (Cont.)
Comment Syntax
1. Start with a double slash symbol // and terminate at the end of the line.
(This is one of the exceptions to the rule that the compiler ignores whitespace).

Can start at the beginning of the line or on the same line following a program statement.
Type // without space between them.

EX:
// demonstrates comments // at the beginning of the line
#include <iostream> // following a program statement // preprocessor directive
using namespace std; // “using” directive
int main() // function name “main”
{ // start the function body
cout << “Hello world”; // statement
return 0; // statement
} // end of the function body

٥
Comments (Cont.)

2. Begins with the /* and ends with */ (not with the end of the line).

EX:

/*
This is an old-style comment.

But it is a good approach to make a comment of large text since it


saves inserting // in every line.

It has advantages in special situations. You can write a multi-line


comment with only 2 comment symbols that are /* and */
*/

Directives

1. Preprocessor Directives:
is an instruction to the compiler. It starts with #
EX: #include <iostream>

The preprocessor directive #include tells the compiler to insert another file into
your source file. It will be replaced by ‫ ﺗﺴﺘﺒﺪل ﺑـ‬the contents of the indicated file.

The file usually included by #include is called a header file.


EX: IOSTREAM that is concerned with basic input/output operations, and
contains the declarations that are needed by the cout and the << operator.
Without these declarations, the compiler won’t recognize cout and will think <<
is being used incorrectly.

A preprocessor (that is a part of the compiler) deals with these directives


before it begins the real compilation process.

٦
Directives (Cont.)

2. The using directive:

NOTE: A namespace is a part of the program in which certain names are recognized and
are unknown outside of this namespace.

The directive using namespace std; says that all the program statements
that follow are within the std namespace.
EX: cout is declared within this namespace.

If we don’t use the using directive, we will need to add the std many times.
EX: std::cout << "Welcome to C++!";

To avoid adding std:: dozens of times in programs, we use the using directive.

Always start with main( ) // the space inside ( ) does not matter
The program may consist of many functions, classes, and other program
elements. But on startup, control always goes to main( ). If there is no
function called main( ) in your program, an error will be reported when
you run the program. In most C++ programs, main( ) calls member
functions and other standalone functions.

Function name
The parentheses ( ) following the word main are the distinguishing feature
of a function. They’re used to hold function arguments- values passed
from the calling program to the function.

Braces and the function body


The body of a function is surrounded by ‫ ﻣﺤﺎط ﺑـ‬braces { }. They surround a
block of program statements.
Every function must use this pair of braces around the function body.

٧
Program Statements

Program statements are instructions to the computer to do something such


as adding two numbers or printing a sentence.

A semicolon ; signals the end of the statement. This is a crucial part of the
syntax but easy to forget.

If you leave the semicolon, the compiler will often (although not always)
signal an error. See the next slide.

EX: cout << "Welcome to C++!";

Output using cout


cout causes the phrase in the quotation marks to be displayed on the screen.
It is predefined in C++ to correspond to the standard output stream that is normally
flows to the screen display although it can be redirected to other output devices.
A stream is an abstraction refers to a flow of data.

The operator << is called the insertion operator. It directs the contents of the
variable on its right to the object on its left (the display).
EX1: cout << “Hello world ” ; // write << without space between them.
In this example, the operator << directs the string constant “Hello world ” to cout
which sends it to the display.

Cascading <<
The insertion operator << can be used repeatedly in the same cout
EX2: cout << “Hello ” << “world” ;

Output with cout

٨
White space

The end of a line isn’t important to a C++ compiler.


You can put several statements on one line, separated by any number of spaces or tabs,
or you can run a statement over 2 or more lines. It’s all the same to the compiler.

EX:
The previous example can be written this way:
#include <iostream>
using
namespace std;
int main () { cout
<<
“Hello world !”
; return
0;}

It will be compiled correctly but it is hard to read.

White space (Cont.)

There are several exceptions to the rule that white space is invisible to the
compiler:

1. #include line must be written on one line.

2. Also, string constants, such as “Every age has a language of its own”,
cannot be broken into separate lines. (If you need a long string
constant, you can insert a backslash (\) at the line break or divide the
string into two separate strings, each surrounded by quotes.)

٩
Common Escape Sequences
The name reflects the fact that the backslash causes an “escape” from the normal way characters are
interpreted. EX: t is interpreted not as the character t but as the tab character.
Escape sequences can be used as separate characters or embedded in string constants.
Escape Name Description
Sequence

\n New line Causes the cursor to go to the next line for subsequent
printing
\t Horizontal tab Causes the cursor to skip to the next tab stop

\a Alarm Causes the computer to beep


\b Backspace Causes the cursor to move left one position

\r Return Causes the cursor to go to the beginning of the current line,


not the next line.
\\ Backslash Causes a backslash to be printed
\' Single quote Causes a single quotation mark to be printed

\" Double quotes Causes a double quotation mark to be printed


There are multiple ways to print text as follows.

1 // first.cpp

2 // Printing a line with multiple statements

3 #include <iostream>
1. Load <iostream>
4 using namespace std;

5 int main() 2. main


6 {

7 cout << "Welcome "; //note the space after Welcome 2.1 Print "Welcome"
8 cout << "to C++!\n";
2.2 Print "to C++!"
9

10 return 0; // indicate that program ended successfully


2.3 newline
11 }
2.4 exit (return 0)

Welcome to C++! Program Output

Unless new line “\n” is specified, the text continues


on the same line.

١٠
1 // first.cpp

2 // Printing multiple lines with a single statement

3 #include <iostream>
1. Load <iostream>
4
2. main
5 int main()
2.1 Print "Welcome"
6 {

7 std::cout << "Welcome\nto\n\nC++!\n"; 2.2 newline

8 2.3 Print "to"


9 return 0; // indicate that program ended successfully
2.4 newline
10 }
2.5 newline

2.6 Print "C++!"


Welcome
to
2.7 newline
C++!
2.8 exit (return 0)
Multiple lines can be printed with one
Program Output
statement.

The endl Manipulator

causes a linefeed to be inserted into the stream so that subsequent ‫ اﻟﺘﺎﻟﻲ‬text


is displayed on the next line.

It has the same effect as the “\n” but it is clearer.

Manipulators are instructions to modify the output in various ways.

EX:
cout<<“welcome to C++” <<endl; //write endl without “” and it is read end line;

١١
More Useful Programs

Input
The main objective of a C++ program is to perform calculations and manipulate data.
And the data must be loaded into the main memory before it can be manipulated.

How to put data into the computer’s memory? in a two-step process:

1. instruct the computer to allocate memory using:


a. variables
b. constants

Tell it what names to use for each memory location and what type of data to store in this
location. Knowing the location of data is essential because the stored data in this
location might be needed at several places in the program. Knowing what data type is
crucial for performing accurate calculations. It is also critical to know whether your
data needs to remain fixed throughout the program execution or whether it should
change.

2. statements in the program to put data into the allocated memory:


a. Using C++’s assignment statement.
b. Using input (read) statements.

١٢
1. instruct the computer to allocate memory (using: a. variables, and b. constants)

a) Variables
– In some programs, data needs to be modified during program execution.

– EX: after each test, the average score changes. After each increase, the salary changes.

– A variable is a memory location whose content may change during program execution.

– Must be declared with a name and a data type before they can be used.

– Some common data types are:


• int integer numbers (numbers without a fractional part)
• double floating point numbers
• char characters
• The keywords int, double, and char signal the type of variable.

The syntax for declaring one variable or multiple variables is:

– EX: int myvariable; //Declares a variable named myvariable of type int


– EX: int variable1, variable2; //Declares two variables each of type int separated by ,

These statements which are called declarations must terminate with asemicolon;

You can place variable declarations anywhere in a program. It’s not necessary to
declare variables before the first executable statement. However, it’s more
readable if commonly-used variables are located at the beginning of the
program.

١٣
A variable with a name total and of type int in memory.

Variable names
– Every variable has a name, a type, a size and a value.
– The names given to variables are called identifiers.

The rules for writing identifiers:


– You can use upper and lowercase letters, the digits from 1to9, and theunderscore _
– The first character must be a letter or underscore.
– The compiler distinguishes between ‫ ﻳﻔﺮق ﺑﻴﻦ‬upper and lowercase letters, so
Var is not the same as var or VAR.
– Case Sensitivity: C++ is case sensitive. In other words, uppercase and
lowercase letters are considered to be different. A variable named age is
different from Age, which is different from AGE.
– You can’t use a C++ keyword as a variable name. A keyword is a
predefined word with a special meaning such as int, class, if, while…

Note: if we don’t declare a variable before using it, we’ll receive this error:
error C2065: 'num2' : undeclared identifier

١٤
b) Constants
Some data must stay the same throughout ‫ ﺧﻼل‬a program.

EX: the pay rate for all part-time employees, the passing degree

The const qualifier specifies that the value of a variable will not change
throughout the program.

Any attempt to alter ‫ ﺗﻐﻴﺮ‬the value of a variable defined with this qualifier will
elicit an error message from the compiler.

The syntax to declare a named constant is:


The keyword const precedes the data type

EX:
const int MIN=60;
const int NO_OF_STUDENTS = 20;

١٥

You might also like