SlideShare uma empresa Scribd logo
1 de 193
Introduction to Programming 
in 
C++ 
First Year 
Ishik University-Erbil 
Department of Information Technology 
2011-2012
About this course 
This course is an introduction to programming in C++. 
Fundamental concepts such as; variables, memory, data types and 
input/output will be explained. Functions, arrays will be covered later. 
Finally, pointers, addresses and dynamic arrays will be tackled. 
Although the examples will be in C++, the focus is more on the technique 
and skillset needed in program writing and problem solving. 
C++ is a popular and mature language. It is a successor of the famous C 
language that underlies many of the real time systems and operating 
systems. C++ is called to be a hybrid language which means you can write 
both procedural programs as well as object oriented programs. It is also 
said to be a low level language in which you can manipulate bits and 
variable addresses, allocate and free memory. 
These topics and others will be discussed throughout the course. 
Procedural Programming in C++ 2
Goals 
There are two parts to this course: 
- programming principles 
- C++ programming language 
Programming principles are general to all languages and programs. We will 
begin the study of the language starting with the fundamentals of the language 
and simple programs; and as we explore more of the language, we will write 
increasingly larger programs. 
By the end of this year, every student: 
- should learn the essential programming concepts 
- should demonstrate a good familiarity with C++ syntax 
- should be able to write reasonably complex programs 
- should develop a consistent programming style 
- Have a good base for learning other programming languages such 
as Java and C sharp. 
Procedural Programming in C++ 3
Course assessment 
You will have 2 hours theory and one lab session (2 hours) per week. You are 
advised to attend all lectures and lab sessions. They will NOT be repeated. 
The assessment for this course will be made up of: 
Quizzes 10% 
Mid-term Exam 25% 
Practice Exam 25% 
Final Exam 60% 
The pass mark for this course is 60%. But remember, the aim is to learn, it is 
not to get marks. 
Also note that quizzes are not expected. I may consider class participation for 
the 10% above. 
Procedural Programming in C++ 4
Resources 
The recommended textbooks for this course: 
C++ How to Program, 3rd Edition, 2003, Deitel & Deitel 
Thinking in C++, 2nd Ed, Volumes I and II, Bruce Eckel 
For a reference book, you can consult the following: 
C++ The Complete Reference, 4th Edition, 2002, Schildt 
I will put the books on the main computer in the lab, so you will be able to copy 
the books and use them as refernces. I will not use any specific book to follow, 
but you can consult them if you need more explanation and examples on any 
particular topic. 
Bur remember: don't rely on lecture notes only. READ, PRACTICE and 
PRACTICE. Through writing programs you can learn how to program. 
Procedural Programming in C++ 5
COURSE CONTENT 
Week Topic 
1 Introduction. Classification of Programming Languages 
2 Variables. Performing output and input. 
3 Identifiers and Reserved words. Primitive data types. 
4 Arithmetic operators. Predefined functions. 
5 Increment and Decrement operators. Relational operators. 
6 Boolean operators. Short circuiting. Precedence rules. 
7 MIDTERM 
8 Strings. Flow of control. 
9 Branching (if-else) statements. 
10 Multiway if-else statements. Switch statement. 
11 Loops. While and Do-while loops. 
12 Break and Continue statements. For loop. Goto statement. 
13 Arrays. 
14 FINAL
Working in the Labs 
Working in the Labs is a very important part of your programming courses. All 
the software you need for your courses is installed on the computers in the 
Labs. The labs are considered as class presence and you should attend all of 
them. But the goal is to get you to work, not sit in the labs. 
Normally, you need to be in the lab even if the teacher is not there or late. You 
should have enough from the theory to practice and experiment with. But 
generally, I will be in the lab to help you with questions and difficulties. 
There will be guided sessions in the labs or just solving some problems from 
the slides of the theory lesson. In either case, you have access to me (teacher) 
and a lab assistant to help you in your practice. 
I am an Eclipse user, so I am using Eclipse CDT (C++ Development tooling, 
found at http://eclipse.org/cdt/ ). You are fee to use MS Visual Studio or any 
other IDE for your programming. 
Procedural Programming in C++ 7
Programming 
Programming is about solving problems. Most often, a programmer, or a group 
of programmers, is presented with a problem and asked to produce a 
computerized solution for that problem. 
Almost anything that a computer can do, a human can also do. So why do we 
need computers and programs to solve our problems??? 
The basic reason is that humans are not good at doing repetitive asks while 
computers ARE. Humans can perform a few calculations but get tired 
especially if the calculations are long and complex).Computers don't get tired. 
In a perfect world, a computer could carry out endless repetitive and long 
calculations without stop. Another reason is that computers are much faster at 
performing calculations than humans. Modern computers can carry out millions 
of basic instructions per second. 
One important distinction is that computers carry out one step at a time, so 
when writing a program, you have to write every step no matter how trivial they 
are and in the sequence required for the solution to be produced by a 
computer. 
Procedural Programming in C++ 8
Programming 2 
A computer is a complex machine with many components. The part of the 
computer which does the real computing is called the Central Processing Unit 
or the CPU. It is the brain of the computer. 
Computers are capable of doing many interesting tasks. But computers need 
to be told what to do. You can tell a computer what to do by writing a program 
for the computer to execute. 
A program is a list of instructions for the computer to execute. The computer 
executes the instructions one after another, until it reaches the end of the list. 
Before a program is executed, it is stored in the computer's main memory or 
RAM. The CPU fetches the instructions one by one from the memory and 
executes them. This process -- fetch an instruction, execute it, fetch another 
instruction, execute it, and so on forever -- is called the fetch-and-execute 
cycle. 
Procedural Programming in C++ 9
Good Programming 
Programming is a challenge. Often, programs are late, difficult to use, full 
of bugs, un-maintainable, and wrong. When someone writes a program, 
they should not only think about the people who will use it, but also about 
the people who will maintain it. 
Writing good programs comes only after a lot of practice and experience. 
Good programs are programs that are: 
• on time 
• user-friendly 
• reliable and stable 
• maintainable and extensible 
• correct (do what they were intended to do) 
• and above all, simple in a way that they don't make the task more 
difficult or convoluted than its manual counterpart. 
Procedural Programming in C++ 10
Good Programming 2 
To be able to write effective programs, one needs to know a few 
things: 
– mastery of the tools-of-the-trade (programming language, 
development environment etc.) 
– the ability to analyze a 'real world' problem and to construct 
a model for it suitable for programming 
– careful design of an algorithm and user-interface for the 
program at hand 
– knowing the techniques that have made other programmers 
more effective, and a reluctance to reinvent the wheel! 
– Practice and exercise 
Procedural Programming in C++ 11
The syllabus 
The following topics will be covered in this course: 
– introduction 
– variables and assignment 
– basic input and output (I/O), formatting output 
– basic data types 
– a simple C++ program 
– arithmetic operators 
– arrays 
– pointers and references 
– strings 
– flow of control and loops 
– program style, comment and documentation. 
– methods, procedural abstraction 
– local/global variables, constants 
– creating libraries (.h) files. 
– structures 
– file I/O 
Procedural Programming in C++ 12
Variables 
A variable is a placeholder used for storing data. The type of data may be 
numerical, string, character, boolean or any other type that the language 
supports. 
We will study all the basic data types in C++ later in the course. 
The data in a variable is called its value and it can be changed or deleted. 
In order to uniquely identify and keep track of a variable, we need to give 
each variable a name; this is called declaring a variable (variable 
declaration). It is a good idea to use meaningful names for variables. For 
example: 
int books; 
in this variable declaration, we declare a variable named "books" to be of 
type int (int is short for integer which refers to whole numbers like 
1 , 5 , 192 , -8 …) 
Procedural Programming in C++ 13
Variables 2 
In the example on the previous page, we want the variable "books" to hold 
the number of books in a program. 
Also note that here, we used the data type int which represents whole 
numbers. We used this data type because the number of books is a whole 
number like 17 and not 3.6, for example. The data type of numerical values 
with decimals is called double. We will cover all data types later. For now 
keep it in mind that whole numbers are of type int and decimal numbers of 
type double. 
double myWeight; 
in this case, the variable myWeight is of type double because its value can 
be a number with a fraction like 1.3. Note that all variable declarations end 
with a semicolon(;). 
Procedural Programming in C++ 14
Variables 3 
To be more specific, a variable is a memory location which can contain a value 
of some type. A variable declaration like 
int books 
first maps a name (books) to a memory location in the computer's memory and 
tells the computer what type of data will be stored in this variable. A variable 
must be declared before it can be used. 
When the name of a variable appears in a program, its value is obtained. 
It's common to initialize variables upon declaration. If a variable is used in 
a program without being initialized, the results will be unpredictable and it 
usually is a logic error to use uninitialized variables. 
Variable initialization can be performed either during declaration using 
assignment statements (to be discussed shortly) as in 
int books=0; 
Procedural Programming in C++ 15
Assignment Statement 
Values can be assigned or stored in variables with assignment statements: 
books=34; 
An assignment statement is an order, to the computer, to assign the value on 
the right-hand side of the equal sign to the variable on the left-hand side. The 
sign (=) is called the assignment operator. (C++ operators will be covered later 
in the course). Assignment statements end with a semicolon. In fact, every 
statement must end with a semicolon (;). 
The value on the right-hand side can also be another variable or expression: 
books1=books2; 
In an assignment statement, first the value on the right-hand side is evaluated 
and then its result is stored or assigned to the variable on the left-hand side. 
Procedural Programming in C++ 16
Assignment Statement 
When using assignment, we have 2 sides of the operator, l-hand and r-hand, 
for left and right hands respectively, as in this example: 
books=200; 
The l-hand side must be something that can hold a value, i. e. a variable. The 
r-hand side can be an expression that produces a value. For example, literals 
200, 500, -6 …etc. 
int firstSemister=70; 
int myAge=19; 
int temperature=-10; 
Or it could be another value producing expression, such as a variable or an 
operation: 
int yourAge=myAge; 
int hisAge=myAge+3; 
Procedural Programming in C++ 17
Performing Output 
The values of variables, numerical values and strings of text ,may be 
output to the screen using the << operator, read c-out: 
int books=0; 
cout<<books<<endl; 
cout<<71<<endl; 
cout<<"This is a stringn"; 
in the first output statement, the value of variable books will be output on the 
screen, which is 0; in the second, the numerical value 71 will be output to the 
screen, and in the last statement, the string "This is the output" will be output to 
the screen. 
Note that we add <<endl; to produce a new line in the output. Equivalently, we 
put a n in the string to produce the same effect. If you miss these , output 
would follow on the same line. 
Procedural Programming in C++ 18
Performing Output 
The code on previous slide produces the following output: 
If we omit the endl statements, as in: 
int books=0; 
cout<<books; 
cout<<71; 
cout<<"This is a string"; 
The output will be: 
Procedural Programming in C++ 19
Performing Output 
Note the n in the string that causes the output to continue on the next line. 
C++ supports a number of other characters, called escape characters. The 
bellow table is taken from the textbook. How to program 7th ed. 
Procedural Programming in C++ 20
Performing Input 
In C++, the input stream object, cin (read c-in) is used with stream extraction 
operator >> to read input from keyboard Performing input in Java is much more 
difficult than performing output: 
Procedural Programming in C++ 21
Performing Input 2 
We declare a variable called yourAge and initialize it to zero. 
Then the program uses the method >> to ask the user for input. 
The program waits for the user until input is provided at the keyboard. Once 
the user enters a number and presses the Enter key, the inputted value is 
saved (assigned) to the variable yourAge . 
The program finally outputs the value of the variable yourAge onto the screen 
with some other information. The screen capture on the previous slide shows 
the input in green font vs the output in normal black font. 
Procedural Programming in C++ 22
Performing Input 4 
And the output is: 
Procedural Programming in C++ 23
Identifiers and Reserved Words 
An identifier is any symbolic name that refers to something in a Program. For 
example, variable names are identifiers. 
An identifier is a series of characters consisting of letters, digits and 
underscores that does not begin with a digit. C++ is case sensitive; which 
means lowercase and uppercase letters are different. So, a1 and A1 are two 
different identifiers. 
Identifiers can contain numbers but cannot begin with a number. In addition, 
they cannot contain any punctuation characters other than underscores. Also, 
you cannot use any of the keywords of the language such as: 
int, double, if, try, private, long, return, 
case, class, float, static, do, while, super… 
For a complete list of reserved words, see your textbook. 
Procedural Programming in C++ 24
Primitive Data Types 
A variable is used to store a value in a computer's memory. The value could 
have one of several types. C++ supports a number of primitive data types: 
In C++, boolean and characters 
are represented as integers. 
The size of each type depends 
on the underlying implementation. 
That is one reason C++ programs 
are not portable. 
If you need to, you can use the 
Sizeof operator to get the size of any 
Variable. 
int x=90; 
cout<<sizeof(x); 
Outputs 4 on my machine. 
Procedural Programming in C++ 25
Primitive Data Types 2 
C++ has signed/unsigned types. The unsigned types don't allow storing 
negative numbers but use that extra sign bit to represent a larger positive 
value. Usually, they can represent numbers twice as big as the maximum their 
signed counterparts do. 
Characters are of type char; single quotes are used to denote char literals. 
C++ uses one byte for characters which can represent the ASCI characters. 
wchar_t however, uses 2 bytes and can represent Unicode. 
The bool type has two values: true and false. It is used with logical 
testing and in relational operators. 0 means false and anything else means 
true. 
You can declare a variable by specifying a data type followed by an identifier 
for the variable name as in: 
Procedural Programming in C++ 26
Primitive Data Types 3 
int aNumber; 
long aBigNumber; 
double aDecimalNumber; 
char myInitial; 
boolean myAnswer; 
After declaring a new variable, you should always initialize it using an 
assignment statement. C++ compiler does not force you to initialize your 
variables (like other strict languages such as Java), but using un-initialized 
variables is usually a programmer error: 
aNumber=250; 
aBigNumber=6965895; 
aDecimalNumber=256.3333; 
myInitial='K'; 
myAnswer=true; //could mean yes/positive 
Procedural Programming in C++ 27
Primitive Data Types 4 
When you assign a value of one type to a variable of different type, a cast (i.e. 
a conversion) occurs. C++ does not warn about possible data loss. In safe 
languages such as Java, the compiler does not allow you to assign a big value 
to a smaller variable. 
Procedural Programming in C++ 28
Primitive Data Types 5 
You can assign smaller data types to larger ones and they are safe. 
bool->short->int->long->float->double 
The reverse is not usually true and you have to have a good reason to do so. 
They usually represent logic errors in your programs and cause bugs that are 
hard to find. Above is the C-style casts and C++ has a more explicit casting 
syntax. See chapter three in the book (Thinking in C++) for a more in depth 
discussion. 
Unlike a variable, a constant's value cannot be changed. In C++, the 
keyword const is used to denote a constant: 
const double CM_PER_INCH=2.54; 
It's customary to name constants all in upper case. Constants are used to 
represent a value that does not change, for example if you wanted to use the 
PI value, which is 3.14, in a math program, you would not change the value. It 
is also good programming to use constants instead of literals. Can you think of 
a reason why this is the case? 
Procedural Programming in C++ 29
Primitive Data Types 6 
Contrary to constants are volatile variables. Normally, if you have a 
variables that does not change that much, the compiler may replace it with 
literals for optimization, but when marked as const other compiler never does 
any optimization. It is good for instances when the variable could be changed 
outside the scope of your program, such as a register coming from a hardware 
driver. 
Procedural Programming in C++ 30
Your First Program 
The first program programmers of a new language learn is the "Hello World" 
program. We will keep with this tradition: 
As you see, the output is the just a line of text to the console. We will dissect 
the program in the following slides and create it in the lab. 
Procedural Programming in C++ 31
Your First Program 2 
The first two lines will be explained in greater detail later, but for a kick-start, 
they are: 
#include <iostream.h> makes available a library from C++ platform that 
contains all the input/output or i/o operators and objects, such as 
cin,cout,<< and >>. 
The second line contains the definitions of the names. Namespaces will be 
explained later in the course but for now, they are just a way of grouping a set 
of names together to prevent clashes with the same names used by other 
developers. 
The main method is where you put your statements to be executed by the 
system. Here we have only one statement that says, output the text "Hello 
World" to the screen follow it by a new line. 
Every statement must end with a semi colon (;) 
Every code block starts with an opening curly bracket and ends with a closing 
bracket. { } 
C++ is free form language, which means space is not counted and you can put 
as much space in your program as you like to increases readability. 
Procedural Programming in C++ 32
Arithmetic Operators 
An expression is any combination of literals, variables, operators, and 
parentheses used to calculate a value. All the following are examples of 
expressions: 
2 
books 
(2 + 1) 
1 – (Books + 10) 
As in mathematics, you can combine expressions using arithmetic 
operators. Usually, arithmetic operators come in between two expressions 
as in 
expression1 operator expression2 
Or operand1 operator opreand2 
Procedural Programming in C++ 33
Arithmetic Operators 2 
The operand can be either a single variable/number or a composite 
expression. The main arithmetic operators are the following: 
+ for addition 
- for subtraction 
* for multiplication 
/ for division 
% for division remainder 
- unary minus 
+ unary plus-default not written 
All of these operators except the % can be used on floating point numbers and 
on integer numbers. However, the % operator is used on integral numbers. 
The operators behave differently when given different operands. For instance, / 
means "integer division" if both operands are integers, and means "floating 
point division" if one or both operands are floating point. 
Procedural Programming in C++ 34
Arithmetic Operators 3 
You should be careful when using the division operator /. When used with one 
or both operands of type double, the division operator behaves as you would 
expect. (Eg. 10/4.0=2.5) But when used with two operands of type int, the 
division operator / gives only the integer part of the division: 10/3 is 3 and not 
3.333… 
Remainder Operator (%) 
The % operator can be used with operands of type int to recover the 
information lost when you use / to do division with operands of type int; for 
example: 
Procedural Programming in C++ 35
Increment & Decrement Operators 
One of the most common operations with a numeric variable is to add or 
subtract 1. C++ has two operators for these common operations. To 
increment a variable: 
int x=0; 
x++; 
This would increment or increase the value of variable x to 1. Now to 
decrement a variable: 
int x=1; 
x--; 
This would decrement or decrease the value of variable x to 0. These 
operators cannot be applied to numbers themselves (literals). The 
following would be an illegal statement: 
10++; 
You can only apply the operators to variables and the reason is obvious, you 
want to add one and store it back in its location. Literals are constants and are 
not variables. 
Procedural Programming in C++ 36
Increment & Decrement Operators 2 
There are two forms of these operators. The form you have seen is called the 
postfix form. The other form is the prefix form: 
++x; 
--x; 
Both forms change the value of a variable by 1. The difference between 
the two only appears when they are used inside expressions. The prefix 
form does the evaluation first. The postfix form evaluates to the old value 
of the variable: 
Procedural Programming in C++ 37
Relational Operators 
To test for equality of two variables or values, use the equality operator: 
(3==8); 
This expression evaluates to false. For inequality use the != operator: 
(2 != 7); 
Which evaluates to true. C++ also has the usual less than (<), greater than 
(>), less than or equal (<=) and greater than or equal (>=) operators. 
Here is the full list of relational operators and their equivalents in math: 
Procedural Programming in C++ 38
Boolean Operators 
There is && for the logical "and" operator,|| for the logical "or" operator and ! 
for logical not operator. In evaluating Boolean expressions, uses Boolean 
Logic principles are used. 
You can combine two (or more) comparisons using the Boolean Logic 
"and" operator. For example, the expression 
(x>2) && (x <10) 
is true only if both (x>2) and (x<10) expressions are true. To remind you of 
the Boolean Logic truth tables: 
AND OR NOT 
X ! X 
true false 
false true 
Procedural Programming in C++ 39
Short circuiting 
When dealing with logical operators, you run into a phenomenon called "short-circuiting." 
This means that the expression will be evaluated only until the truth 
or falsehood of the entire expression can be unambiguously determined. As a 
result, the latter parts of a logical expression might not be evaluated. Here's an 
example that demonstrates short-circuiting: 
As you can see from the output, the 
statement n++ did not et executed and 
that is why you see the value to be still 5. 
Procedural Programming in C++ 40
Precedence Rules 
You can specify the order of operations using parentheses as illustrated in the 
following expressions: 
1: (x + y) * z 
2: x + (y * z) 
1: the computer first adds x to y and then multiplies the result by z. 
2: the computer first multiplies y by z and then adds the result to x. 
if you omit the parentheses, the computer will follow some rules of precedence. 
So, if you wrote x + y * z, the computer would multiply y by z and add the 
result to x. Because * has higher precedence than + (the same is true for / 
and %) 
It's always best to use parentheses as they remove any ambiguity and make 
the code much clearer to read and understand. Consult a textbook for a full 
listing of C++ precedence rules. 
Procedural Programming in C++ 41
More Assignment Statements 
C++ has a shorthand notation that combines the assignment operator 
(=) and an arithmetic operator. For example: 
int hours=5; 
hours += 7; 
is equivalent to 
hours=hours + 7; 
That is, the new value of the variable hours is equal to its old value plus the 
number literal 7. 
We can use other arithmetic operators too: 
hours -=2; hours=hours-2; 
hours /=3; hours=hours/3; 
hours *=2; hours=hours*2; 
hours %=8; hours=hours%8; 
Procedural Programming in C++ 42
Strings 
A string is a series of characters such as your name or telephone number. C 
used character arrays (more on arrays later) but they were very limited, error 
prone and difficult. C++ introduced the string class(data type) that makes life so 
much easy. We will talk more about string in later parts of this course, but their 
basic use if fairly easy. Just include string (or string.h) and you are good to 
Procedural Programming in C++ 43
Strings 2 
String is like any other data type we have seen (int, bool …etc), but it is not 
primitive which means, it is a class. Classes are created in Object Oriented 
languages. String objects, like s1, s2 and s3 on the previous slide have values, 
but they have behaviors'(methods) as well. We will see more on these 
concepts later, but for now, just look at this example: 
Procedural Programming in C++ 44
Exercises 
Ex. 1) Write a program to ask the user for his/her name and then print out the 
name onto the screen. 
Ex. 2) Modify exercise 1 so that the program outputs the length of the user's 
name. 
Ex. 3) Write a program to ask the user for two names, first name and last 
name, and then concatenate the two names and output the full name. 
Ex. 4) Repeat exercise 3 but this time, have the user input his/her full name 
and you print fisrt name and last name separately. 
Ex. 5) What is the output of the following program: 
int x=0; 
cout<<x++<<endl; 
cout<<--x<<endl; 
Procedural Programming in C++ 45
Flow of Control 
In the simple programs we have seen so far, the program consisted of 
a list of statements which were executed sequentially; one statement after 
another. There we did not specify any order for the program to follow. 
For bigger and more sophisticated programs, you will need some way 
to change the order in which statements are executed. The order in 
which statements are executed is called the flow of control. 
C++ has a number of mechanisms which let you control the flow of 
program execution. 
First, we will study a branching mechanism that allows you to choose 
between two alternative actions. Then we will discuss loops. 
Procedural Programming in C++ 46
Branching (if-else statement) 
There is a statement that chooses between two alternative actions. it is called 
the if-else statement. in fact, there are two versions of this statement. We will 
discuss the first one as the second form is an extension of the first form. 
The general form of the if-else-statement is as follows: 
if (Boolean-expression) 
yes-statement 
else 
no-statement 
When program execution reaches the if-else-statement; only one of the two 
statements is executed, not both. if the Boolean-expression is true then the 
yes-statement is executed. if the Boolean-expression is false then the no-statement 
is executed. 
Procedural Programming in C++ 47
Branching (if-else statement) 2 
Suppose your program asks the user about the amount of time per week 
he/she spends on practicing programming. And you want the program to 
decide whether or not this is enough. Assume that 4 hours/week of practice is 
enough. Anything less is not good enough. 
Procedural Programming in C++ 48
Branching (if-else statement) 3 
Sometimes, your if statement does not have an else statement. In these cases, 
you are interested in conditionally executing a code based on truth/falsehood 
of a condition. 
Procedural Programming in C++ 49
Branching (if-else statement) 4 
In the previous slide, we only had one statement to execute, but if you had 
more than one statement, we had to put them in a set of curly braces { … } 
A list of statements enclosed inside brackets is called a compound 
statement. 
Procedural Programming in C++ 50
Loops 
Sometimes you need to repeat an action several times, for example when you 
need to input names of a list of students. 
A section of a program that repeats a statement or group of statements is 
called a loop. C++ has a number of ways to create loops. One of them is 
called a while-loop. The following program shows how a while loop works: 
Procedural Programming in C++ 51
Loops 2 
In the example on the previous page, the section between the brackets { and } 
is called the body of the while-loop. This is the body (block of statements) 
that is repeated a number of times. Each repetition of the loop is called an 
iteration of the loop. 
If the user enters 0 at the keyboard, the loop body is executed zero times, that 
is, it is not executed at all. Because, the Boolean-expression is not satisfied 
and program execution proceeds with the following line after the while-loop. 
Note that you need some way to make sure that the loop ends at some point. 
Otherwise, the loop will run forever. It will be an infinite loop. In this example, 
we decrease a variable value after each iteration. We decrease it by 1 
(decrement) after each iteration until the Boolean expression becomes false 
and the loop finishes. 
Procedural Programming in C++ 52
Loops 3 
As you know, a while-loop might execute its body zero times. If you know that 
under all circumstances your loop body should be executed at least once, then 
you can use a do-while loop. The do-while loop is similar to the while-loop, 
except that the loop body is executed at least once. Let's rewrite the previous 
example using the do-while loop 
note the semi colon 
after the while 
Same as before Different! 
Procedural Programming in C++ 53
Infinite Loops 
A while-loop or do-while loop does not terminate as long as the boolean 
expression is true. 
This boolean expression normally contains a variable that will be changed by 
the loop body and the value of this variable eventually is changed in a way that 
makes the boolean expression false and therefore terminates the loop. 
However if you make a mistake and write your loop in a way that the 
boolean expression is always true, then the loop will run forever. (an 
infinite loop). 
On the next page we will write two loops, one that does terminate 
and one that does not terminate. Infinite loops are logic errors and does not get 
detected by compiler. The program just seems not responding and it never 
ends. 
Procedural Programming in C++ 54
Infinite Loops 2 
Write positive even numbers less than 12: 
int x=2; 
while ( x ! = 12) { 
cout<<x<<endl; 
x=x+2; 
} 
Write positive odd numbers less than 12: 
int x=1; 
while ( x ! = 12) { 
cout<<x<<endl; 
x=x+2; 
} 
Which is an infinite loop? 
Procedural Programming in C++ 55
Programming Style 
All the variable names in our programs were chosen to suggest their 
use. We tried to use meaningful names for variable names. Also we laid out 
our programs in a particular format. For example, the declarations and 
statement were all indented the same amount. 
This is good programming as it makes our programs 
– easier to read 
– easier to correct, and 
– easier to change 
Indenting 
A program should be laid out so that elements that are naturally 
considered a group are made to look like a group. One way to do this is to 
skip a line between parts that are logically considered separate 
indenting can help to make the structure of the program clearer. A 
statement within a statement should be indented. 
Procedural Programming in C++ 56
Programming Style 2 
Also, the brackets {} determine a large part of the structure of a program. 
Placing each on a separate line by itself, as we have been doing, makes it 
easy to find the matching bracket. 
When one pair of brackets is embedded inside another pair, the inner pair 
should be indented more than the outer pair. 
Comments 
To make programs understandable, you should include some explanatory 
notes at important places in the program. Such notes are called 
comments. Most programming languages have this capability. In C family of 
languages, C, C++ and Java, the symbols // are used to indicate the start of a 
comment to the end of the line. These comments can be as long as a line only. 
If your comment spans more than one line, you can put them between an 
opening /* and closing */ symbols. 
Procedural Programming in C++ 57
Programming Style 3 
Unlike the // comments, which require an additional // on 
each new line, the /* to */ comments can span several lines. Your 
programs should always start with some comments like: 
//File name: hello.cpp 
//Author: Mr. Nice 
//Email: nice@yahoo.com 
//Description: Program to output Hello World 
//Last changed: 28 October 2000 
Use comments sparingly; using two many comments is almost worse 
than no comments at all!. 
Spacing, indenting and comments are only for readability and not ready by the 
C++ compiler. They are not put in the compiled executable, so having more of 
them does not increase the size of the final program. They are only for human 
use. 
Procedural Programming in C++ 58
Programming Style 4 
If you are using some sort of IDE (and you should!), they have a way to format 
your code in a certain style. In Eclipse for example, you can format your code 
by pressing Ctrl+Shift+F to format your current file. If you have multiple files, 
you can select them in the left navigation view and click 
Source -> Format menu to format the selected files. 
You can comment or uncomment your code by selecting Toggle Comment sub-menu 
of the source menu. 
Also Eclipse provides a dictionary for auto-correcting your comments. So, if 
you misspell a word in your comment, eclipse can detect it and suggest a 
correction for you. 
Procedural Programming in C++ 59
Exercises 
Ex. 6) What is the output of the following program fragment? 
int x=10; 
while (x > 0) 
{ 
cout<<x<<endl; 
x=x-3; 
} 
Ex. 7) What output would be produced in the previous exercise if the > 
sign were replaced by <? 
Ex. 8) Write a program fragment to have the same output as Ex. 8 fragment but 
use a do-while loop this time. 
Procedural Programming in C++ 60
Exercises 
Procedural Programming in C++ 61
Exercises 
Ex.12) The following if-else statement will compile and run without any 
Problems. However, it is not laid out in a way that is consistent with 
the other if-else statements we have used in our programs. Rewrite 
it so that the layout is clearer. 
if (x < 0) { x=7; cout<<"x is now positive.";} else 
{ x =-7; cout<<"x is now negative.";} 
Ex.13) What is the output of the following program fragment? 
//this is not a comment 
/* cout<<"Hin"; does nothing 
cout<<"Hi againn"; */ 
cout<<"Hi againn"; //this is a comment 
/*this too is a comment*/ 
Procedural Programming in C++ 62
Exercises 
Ex.14) Write a program fragment to display the numbers that are multiples of 4 
between 0 and 20 inclusive. 
Ex.15) Write a program to ask the user for two whole numbers (int), calculate 
their addition, subtraction, multiplication, division, and molulus. Your 
program should display the results on the screen. 
Ex.16) Write a multiplication calculator program. This program will 
multiply numbers together and display the result on the screen. The program 
should keep asking the user for two numbers until the user enters the 
letter 's' for stop. 
Ex.17) Write a program fragment to check a student's grades for math and 
physics. If either the student's math grade is greater than 50 
and the student's physics grade is greater than 60 then the program will 
output the word 'Passed' otherwise the word 'Failed'. 
Procedural Programming in C++ 63
Exercises 
Ex.18) Write a program fragment that reads in a year (Ex. 1972) and 
checks whether or not this year is a leap year. 
Remember a leap year is a year that has 366 days. To be a leap year, one of 
the following conditions must hold: 
1. The year is divisible by 4 but not by 100, or 
2. The year is divisible by 400 
Ex. 19) Write a program to add a list of numbers entered by the user. The user 
can stop the program by entering 0 when asked for the next number. Before it 
stops, it should print their addition and their average. 
Ex. 20) Rewrite Ex.21 program, but this time, the program should ignore 
even numbers. If the user enters an even number, your program will just 
ignore it; it will only accept odd numbers. 
Procedural Programming in C++ 64
Multi-way if-else statements 
An if-else statement is a two-way branch. it allows a program to choose one of 
two possible actions. Sometimes, you will want to have a three- or four-way 
branch so that your program can choose between more than two alternative 
actions. 
You can do this by nesting if-else statements. For example: 
Procedural Programming in C++ 65
Switch statement 
The if-else statement can be cumbersome when you have to deal with multiple 
selections. The switch-statement is another kind of statement that also 
implements multi-way branches. 
When a switch-statement is executed one of a number of different 
branches is executed. The choice of which branch is executed is 
determined by a control expression given in the parentheses after the 
keyword switch. 
The control expression must always evaluate to either a char or the integer 
types (byte, short, int). When the switch-statement is executed, this control 
expression is evaluated and the computer looks at the constant values given 
after the various occurrences of the identifiers case. if it finds a constant that 
equals the value of the controlling expression, it executes the code for that 
case. 
Let's look at an example involving a switch-statement: 
Procedural Programming in C++ 66
Switch statement 2 
Procedural Programming in C++ 67
Switch statement 3 
Notice that the constant is followed by a colon. Also note that you cannot have 
two occurrences of case with the same constant value after them since that 
would be an ambiguous instruction. 
A break-statement consists of the keyword break followed by a semicolon. 
When the computer executes the statements after a case label, it 
continues until it reaches a break-statement and this is when the switch-statement 
ends. 
Procedural Programming in C++ 68
Switch statement 
if you omit the break-statement, then after executing the code for one case, it 
goes on to execute the code for the following case. 
The grades 50 and 30 cause the same branch to be taken. if the value of 
grade is anything other than 100, 80, , 60, 50, 30 then the output 
statement after the identifier default is executed. However, the default case is 
optional and can be omitted. 
When program execution reaches the break statement, the switch 
statement is exited and program execution follows the switch statement. 
The break statement has other uses, other than switch statement. It can be 
used to exit out of a loop before its exit condition is met. 
Say, for example, you want to break out of a loop when a special input is 
encountered. 
See an example on the next page: 
Procedural Programming in C++ 69
The break statement 
Notice that we have used while(true) which is in itself an infinite loop, but in the 
body of the loop, we are checking for zero to quit the loop using a break 
statement. 
This program keeps accepting numbers from the keyboard till it gets zero. It 
then quits the loop and prints the result of the summation. 
Procedural Programming in C++ 70
The continue statement 
While break statement terminates the loop, continue statement only terminates 
the current iteration of the loop. If the loop has more iterations, they will be 
executed. Let’s rewrite the previous example, but this time, we ignore any 
number that is a multiple of 3. 
Procedural Programming in C++ 71
The continue statement 
Note that the sum does not take into account 3 and 9 in the first run of the 
program, and 12 and 15 in the second run. 
Procedural Programming in C++ 72
For loop 
The while-statement and the do-while statement are all the loop mechanisms 
you need. In fact, the while-statement alone is enough. But there is one kind 
of loop that is so common in programming that we have a special syntax for it. 
In performing numerical calculations, it is common to do a calculation with a 
sequence of numbers. For example to add the numbers 1 through 10 you 
want the computer to perform the following statement ten times with the value 
of n equal to 1 the first time and with n increased by one each subsequent 
time. 
sum=sum + n 
You can do this with a while loop or even a do-while loop. But as you will see 
shortly, it becomes so much easier to do this operation with a for-loop. 
Basically, if the number of iterations is known before hand, for-loop is the most 
elegant way. It also makes a good choice for looping through array elements, 
as we will see later in the course. 
Procedural Programming in C++ 73
For loop 2 
The following is one way to accomplish this with a while statement: 
sum=0; 
n=1; 
while (n<=10) { 
sum=sum + n; 
n++; 
} 
Although a while-loop is OK here, this kind of situation is just what the for-loop 
was designed for. The following for-loop will neatly accomplish the same thing: 
sum=0; 
for (int n=1; n <= 10; n++) 
sum=sum + n; 
Procedural Programming in C++ 74
For loop 3 
An example involving a for-loop: 
int sum=0; 
initialization 
repeat the loop 
as long as this is 
true 
for ( int n=1; n <= 10; n++) { 
sum = sum + n; 
} 
done after each 
loop body iteration 
cout<<" The sum of the numbers 1 to 10 is : “; 
cout<< sum; 
Procedural Programming in C++ 75
Goto statement 
Goto has been around from the beginning of programming languages. It a tool 
programmers have misused to create what we call "spaghetti code". It could 
create very unstructured code and flows of control that were extremely hard to 
follow and debug. In fact, what loop is doing can be done using if statement 
and goto. See the example and its output: 
Although goto is very much discouraged, it can be very useful to break out of 
deeply nested loops. As we know, break/continue only take the innermost loop 
into account. See example in the next slide: 
Procedural Programming in C++ 76
Goto statement … 
And the output will be: 
Procedural Programming in C++ 77
Exercises 
Ex.23) Write a multi-way if-else statement that classifies the value of 
an int variable n into one of the following categories and writes an 
appropriate message: 
n < 0 or 0 <= n <= 100 or n > 100 
Ex.24) What is the output of the following fragment: 
int count=3; 
while (count-- > 0) 
cout<<count << " n"; 
Ex.25) What is the output of the following fragment: 
int count=3; 
while (--count > 0) 
cout<<count << " n"; 
Procedural Programming in C++ 78
Exercises 
Ex.26) What is the output of the following fragment: 
int n=1; 
do 
cout<<n << " n"; 
while (n++ <= 3); 
Ex.27) What is the output of the following fragment: 
int n=1; 
do 
cout<<n << " n"; 
while (++n <= 3); 
Ex.28) What is the output of the following fragment: 
for (int count=1; count < 5; count++) 
cout<<(2 * count) <<" n"; 
Procedural Programming in C++ 79
Exercises 
Ex.29) For each of the following situations, tell which type of loop would 
be better: 
a. summing a series, such as ½ + 1/3 + ¼ + … +1/10 
b. inputting the list of exam marks for one student 
Ex.30) Rewrite the following code as a for-loop: 
int i=1; 
while ( i <= 10) 
{ 
if (i < 5 && i !=2) 
cout<<'X'<<endl; 
i++; 
} 
Procedural Programming in C++ 80
Exercises 
Ex.31) Rewrite the following code as a for-loop: 
int i=1; 
while ( i <= 10) 
{ 
cout<<'X'<<endl; 
i = i + 3; 
} 
Ex.32) Rewrite the following code as a for-loop: 
long m=100; 
do 
{ 
cout<<'X'<<endl; 
m = m + 100; 
}while ( m <= 1000); 
Procedural Programming in C++ 81
Arrays 
An array is a collection of variables all of the same data type that 
are referred to by a common name. A specific element in an array is 
accessed by an index. 
Array elements are stored in contiguous memory locations. 
The lowest address refers to the first element and the highest address 
refers to the last element. Further, array sizes are fixed; once you create 
an array you cannot change its size. C++ supports dynamic arrays with 
pointers and it will be covered later. 
For example, to store a list of exam marks for students we can use 
an array like this: 
int marks[5]; 
This array is of type integer and it can hold 5 variables of type integer. 
'mark' is the name of this array. 
Procedural Programming in C++ 82
Arrays 2 
The array declaration (similar to variable declaration) on the previous 
slide is equivalent to the following declarations: 
int mark1, mark2, mark3, mark4, mark5; 
You can see that the array notation is clearer and more elegant. 
The statement int mark[5; creates an array of type integer that can store 5 
variables all of type integer. 
Array elements are numbered from 0. That is, the index of the first 
element in the array is 0 and the index of the last element is one 
less than the size of the array. ( in this example, first element has 
index 0 and last element has index 4) 
Now you can use array elements like any other variable: 
marks[0]=75; //puts 75 in the first location 
marks[4]=82; //puts 82 in the last location 
cout<<marks[4]; //prints the the last element which is 82 
Procedural Programming in C++ 83
Arrays 3 
One way to create and initialize an array at the same time is like this: 
int mark[5] = { 87, 67, 90, 89, 100}; 
The size of this array is 5. The size of the array need not be declared if it can 
be inferred from the values in the initialization: 
int mark[ ] = { 87, 67, 90, 89, 100}; 
To access array elements we use the array name plus the index of the required 
element. For example to assign 64 to the fourth element: 
marks[3]=64; 
And to print the last element: 
System.out.println(mark[4]); 
Note that valid array index values are 0 to one minus the length. Accessing 
array elements outside the valid indexes is logic error. 
Procedural Programming in C++ 84
Arrays 4 
The following program creates a 5-element array and initializes the array 
elements using user input and shows the values afterwards: 
Note how natural it is to use for loop when 
working with array elements. 
Another thing you need to be aware of is 
lteral values for array size. Always use a 
a constant. See the next slide for an 
improvement in this program using a 
constant. 
Procedural Programming in C++ 85
Arrays 5 
The following program is exactly the same as the one on the previous slide, but 
it is far more readable and extensible just by using the constant instead of 
literal 5: 
Now if you decide to change the elements of the array from 5 to 10, only the 
declaration of the const int SIZE=5 has to change, but in the old version, 
you would have to change the value in 3 places. 
Procedural Programming in C++ 86
Arrays 6 
Array indexed variables are stored in memory in the same way as ordinary 
variables are stored. But with arrays, the locations of the array indexed 
variables are always placed next to one another in the computer's memory. 
For example consider the following array declaration: 
int marks[5]; 
When you declare this array, the computer reserves enough memory to hold 5 
variables of type integer and the computer always places these variables one 
after the other in the memory. The computer then remembers the address of 
the indexed variable mark[0], but it does not remember the address of any 
other indexed variable. 
When your program needs the address of some other indexed element the 
computer calculates the address of this other element from the address of 
mark[0]. 
Procedural Programming in C++ 87
Arrays 7 
The most common programming error made when using arrays is 
attempting to reference a non-existent array index. For example consider the 
following array declaration: 
int marks[5]; 
For this array, every index must evaluate to one of the integers between 0 and 
4. if you write: 
cout<<mark[i]; 
Then i must evaluate to one of: 0, 1, 2, 3, 4. If it evaluates to anything else it 
is an error. This is a logic error and can't be detected by C++ compiler. It even 
is not caught by the runtime and you will get whatever value is in that location. 
Errors like this produce bugs that are very hard to find and fix. 
You can calculate the length of an array by using the sizeof operator. 
Dividing the total bytes for the array by bytes of one of the elements gives you 
the length. 
Procedural Programming in C++ 88
Exercises 
Ex.33) In the array declaration 
double score[6]; 
what is the 
a. the array name 
b. the base type 
c. the declared size of the array 
d. the range of indexes that are OK for accessing the elements 
e. one of the indexed variables (or elements) of this array 
Ex.34) What is the output of the following code fragment: 
char symbol[]= { 'a', 'b', 'c','d'}; 
for (int index =0; index<4; index++) 
cout<<symbol[index]; 
Procedural Programming in C++ 89
Exercises 
Ex.35) What is the output of the following fragment: 
double a[] = { 1.1, 2.2, 3.3}; 
cout<<a[0] <<" " << a[1] << " " << a[2]; 
a[1]=a[2]; 
cout<<a[0] <<" " << a[1] << " " << a[2]; 
Ex.36) What is wrong with the following piece of code: 
int array1[10]; 
for (int index=1; index <= 10; index++) 
array1[index]=index; 
Ex.37) Write a program to fill an array with 5 values of type integer from the 
keyboard. The program should also output the square and square root of each 
array element next to it like a table. 
Procedural Programming in C++ 90
Exercises 
Ex.38) Which of the following is NOT the name of a primitive data 
type? 
a. int b. float c. double d. string 
Ex.39) In which of the following answers does the number of bytes increase 
from fewest (on the left) to most (on the right)? 
a. byte long short int 
b. int byte short long 
c. byte short int long 
d. short byte long int 
Ex.40) Which one of the following is NOT a correct variable name? 
a. 2bad b. zero 
c. theLastValueButOne d. year2000 
Procedural Programming in C++ 91
Exercises 
Ex.41) Which one of the following declarations is NOT correct? 
a. double duty; b. float loan = 84.6; 
c. boole value = 12; d. int start = 34, end = 99; 
Ex.42) Which of the following shows the syntax of an assignment statement? 
a. variableName = expression; b. expression = expression; 
c. expression = variableName; d. dataType = variableName; 
Ex.43) What are the two steps that take place when an assignment statement 
is executed? 
a. (i) Evaluate the Expression, and (ii) Store the value in the variable. 
b. (i) Store the value in the variable, and (ii) Evaluate the Expression. 
c. (i) Reserve memory , and (ii) fill it with a number. 
d. (i) Evaluate the variable, and (ii) store the results. 
Procedural Programming in C++ 92
Exercises 
Ex.44) Which of the following expressions is incorrect? 
a. (34 - 86) / 3 b. (34 - 86) / -3 
c. 34 - 86) / (23 - 3 ) d. ( (34 - 86) / (23 + 3 ) ) 
Ex.45) . What is the result of evaluating the following expression? 
( 1/2 + 3.5) * 2.0 
a. 8.0 b. 8 c. 7.0 d. 0 
Ex.46) How many choices are possible when using a single if-else statement? 
a. 1 b. 2 c. 3 d. 4 
Ex.47) A sequence of statements contained within a pair of braces ("{" and "}") 
is called a: 
a. Block b. Blob c. branch d. brick 
Procedural Programming in C++ 93
Exercises 
Ex.48 What three parts of a counting loop must be coordinated in order for 
the loop to work properly? 
a. initializing the counter, testing the counter, changing the counter 
b. initializing the condition, changing the condition, terminating the loop 
c. the while, the assignment, and the loop body 
d. the while statement, the if statement, and sequential execution. 
Ex.49) Which of the following situation most likely does NOT call for a counting 
loop? 
a. Adding up all the integers between zero and one hundred. 
b. Writing out a table of Fahrenheit and Celsius temperature equivalents. 
c. Prompting the user of a program until the user responds with correct 
information. 
d. Making the computer beep ten times. 
Procedural Programming in C++ 94
Exercises 
Ex.50) What is the meaning of variable++ ? 
a. Add one to the variable. 
b. Add one to the variable after its current value has been used. 
c. Add one to the variable before using its value. 
d. Double the value in the variable. 
Ex.51) What does the following print on the monitor? 
for ( int j = 0; j < 5; j++ ){ 
for ( int k = 0; k < 10 ; k++ ) 
cout<< "*" ; 
cout<<endl; 
} 
Procedural Programming in C++ 95
Exercises 
Ex.52) What is the output of the following code fragment: 
int[] arr = {2, 4, 6, 8 }; 
arr[0] = 23; 
arr[3] = ar[1]; 
cout<<arr[0] <<" "<< arr[3] ; 
Ex.53) What is the output of the following code fragment: 
int z[9]; 
z[0] = 7; 
z[1] = 3; 
z[2] = 4; 
cout<< z[0] <<" "<< z[1] << " " << z[5] ; 
a. 1 0 0 b. 7 3 0 
c. 7 3 4 d. The program is defective and will not compile. 
Procedural Programming in C++ 96
Methods 
A natural way to solve large problems is to break them down into a series of 
smaller sub-problems, which can be solved more-or-less independently and 
then combined to arrive at a complete solution. 
The programs we have written and seen so far have been too small to break 
them down into smaller units. When programs get bigger, you should break 
them down or divide them into smaller sub-programs. 
C++ lets programmers break down complex programs into smaller units. 
These units are called functions (but called methods at times). 
You have already seen method definitions. The most famous one is the main 
method which is required for any program to be run by the operating system. 
Consider a simple method that if you give it two numbers, it will give you the 
one that is bigger, so in other words, it will return the max of two numbers. 
Procedural Programming in C++ 97
Methods 
You have already seen methods such as sqrt() to get the square root of a 
number. This method is from math.h library. There are many more functions 
from that library such as ceil() that rounds a number to the next larger integer 
and floor() that rounds down to the next smaller integer. For example: 
These are examples of pre-defined methods that we can use in our programs. 
Somebody else has defined them; we just use them and we even don't need to 
know how they are defined as long as we know how to use them. 
You can write your own method too. Let's write a method to return the max of 
two numbers: 
Procedural Programming in C++ 98
Methods 
See how we use max just like ceil and floor methods from math.h. Also note 
that, we have to put the method definition above main so it is before its use 
inside main. We will get back to this issue later. 
Procedural Programming in C++ 99
Methods 
The method body checks the 2 numbers and makes max equal to the one that 
is bigger. It then uses return statement to return the larger value. 
Now you can call this method from inside your program and from other 
methods you define. You can call this method as many times as you like. 
A few notes about method: 
• The structure of a method is similar to the structure of main, with its own 
list of variable declarations and statements. 
• A method may have a list of zero or more parameters inside its brackets, 
each of which has its own type. 
• Method declarations are a bit like variable declarations; they specify 
which type the function will return. 
• You can define as many functions as you require provided you declare 
them first. 
Procedural Programming in C++ 100
Methods 
Breaking down functions makes programming easier to write and maintain. 
Now you can use that function many times in your main method. See in the 
following example how you can use max function to find the maximum of any 
number of integers, not just two. 
Procedural Programming in C++ 101
Methods 
See how using the function made possible breaking down the problem of 
finding the maximum of 4 numbers by finding max of w,x first and then y,z. After 
that, the maximum of the results of the previous calls are used to find the 
maximum of all. The idea is very much similar to eliminating teams in sports 
tournaments. 
The method max is called from the main method to add find the maximum of 
w and x. When the method is called, two parameters are passed to this 
method w and x; the method is then executed and returns a value (6 as its 
bigger than 2). The result is then stored in the variable t1. Same thing for y, z 
and t2. 
After the method max returns, program execution continues on the line 
following the method-call line. 
Of course, for a simple program like this you would not write a method. This 
example was for demonstration only. 
Procedural Programming in C++ 102
Methods 
Lets write another method to test if a number is even or not: 
Procedural Programming in C++ 103
Methods 
And the output is: 
Procedural Programming in C++ 104
Methods 
Although methods with return values are the most common, not all methods 
return a value. A method that does not return a value should have a return 
type of void. Void means nothing. In fact you have already seen such a 
method. (?) 
Her is an example: 
public void about(){ 
cout<<"My Simple Video Game"<<endl; 
cout<<"Version 2.2"<<endl; 
cout<<"Copyright 2008-2012 "<<endl; 
} 
In your porgram, you could have the method above and use it any time the 
user clicks (or selects) help->about menu. Without method, you would have 
this code repeated many times. 
Since void methods have no return values, you cannot use them on the right 
hand side of an assignment statement. Beware. 
Procedural Programming in C++ 105
The Black Box 
A person who uses a program should not need to know the details of how the 
program is coded. That person should know how to use the program but not 
how the program works. 
A method is like a small program and should be viewed in a similar way. A 
programmer who uses a method needs to know how to use the function but not 
how the function does its job. This is what is meant when viewing a function as 
a black box. Writing methods so that they can be used as a black boxes is 
sometimes called information hiding or procedural abstraction. 
The word procedure is a general name for methods. The word abstraction is 
intended to convey the idea that when you use a method as a black box, you 
are abstracting away the details of the code in the method body. When we 
used the methods length() or round(), we did not know how they worked. We 
just used them. This is important. Details, although important, can be put 
aside for a later time. 
Procedural Programming in C++ 106
Variable scope 
Variables declared inside a method exist only during the method call. Variables 
declared inside methods are called local variables. The scope of a local 
variable is the method inside which that variable is declared. It doesn't exist 
outside that method. 
As a general rule, the scope of any variable is the next closing brace } that 
comes after it. For example, if you declare a variable inside a loop, it is not 
visible after the loop's block is closed }. 
while(n-->0){ 
int x=n*n; 
cout<<x<<endl; 
} 
x=2;//this is a compiler error. Variable x is 
//not defined at this scope. 
Procedural Programming in C++ 107
Variable shadowing 
Since variables are visible in their scopes, when a variable is defined in a 
schope and a variable with the same name exists in an outer scopes, the 
newly defined variable is said to shadow the outer schope variable. See this 
example: 
Procedural Programming in C++ 108
Variable shadowing 
The output of the program on the prev slide is: 
As another example, see: 
Procedural Programming in C++ 109
Exercises 
Ex.54) Write a method to find the smallest number in an array of type 
int. Declare the array size to be 7 and fill the array from the 
keyboard. The method should take the array as a parameter and 
return the smallest number as the return value. Test the method 
in a complete program. 
Ex.55) Write a method to find the index of the smallest number in an array of 
type int. Declare the array size to be 7 and fill the array from the 
keyboard. The method should take the array as a parameter and 
return the index of the smallest number as the return value. Test the method in 
a complete program. 
Note the difference between these two methods. One returns a number 
(value) and one returns an index of an array. This last exercise will be used as 
a basis for another exercise later. 
Procedural Programming in C++ 110
Exercises 
Ex.56) Write a program that takes 2 dates and then calculates the 
number of days between those 2 dates. The program asks the user for two 
dates (day, month, year) and then passed this information to a method to 
calculate the number of days between them. 
Ex.57) From school you know that the standard quadratic equation 
ax2 + bx + c = 0 
has two solutions given by formula 
Write a function that reads a, b and c and then calculates the two solutions. If 
the quantity under square root is negative it should display an appropriate 
message. You may assume that the value for a is nonzero. 
Procedural Programming in C++ 111
Exercises 
Ex.58) Write a method that takes a string parameter and returns the reverse of 
that parameter string as its return value. 
Ex.59) Write a method that takes a string as a parameter and checks if the 
parameter string a palindrome or not. A palindrome string/word is a word that 
writing it in the reverse gives the same word; like the word "radar" or "noon". 
Ex.60) C++ does not have an operator for raising numbers to a power. 
Assume the method declaration like this: 
double power(double num1, double num2){ 
//your code goes here 
} 
This method raises num1 to the power of num2. Finish the method above and 
test it in main to make sure it works as required. 
Procedural Programming in C++ 112
The & (address of) operator 
When your program is run, it is first loaded into memory; which means, it is 
placed somewhere in the computer's memeory which also means all the 
elements of your program (variables, functions …etc) will have an address. If 
you want to know the address of anything, just precede it with the & operator. 
For example, &i means the address of i. See the example: 
Procedural Programming in C++ 113
The & (address of) operator 
Note that the variables i and j are placed next to each other but it is not 
predictable where these locations are. Also note that changing a variable does 
not change its location(address), only the value stored at that address. 
You may be rightfully wondering 'why do I need to know where a variable is 
located in memory?'. Well, in most cases you don't need to know, but 
sometimes, you do. See the example: 
Procedural Programming in C++ 114
The & (address of) operator 
The problem we are facing is that: whenever we call a method (function), C++ 
makes a copy of the parameters we pass (i and j in our case) and the function 
works on these copies. Whatever the function does to these variables such as 
chaning them, swapping them …etc is not made to the actual variables we 
intented. In such situations, we need to modify our program so that it works on 
the actual variable not a copy of it. To rewrite our program with the & operator: 
Procedural Programming in C++ 115
Pointers 
As you noted, changing the method swap to take address of integer 
void swap(int &x,int &y) changes the actual variables (i and j, swaps 
them). This is very important in some algorithms such as sorting when we want 
to swap to numbers when they are out of order. We will come back to sorting 
later. 
The address operator (&) is also called a references since it refers to a memory 
location. 
In the example above, we passed the address of a variable to a method, but is 
this all we can do with addresses? The answer is "NO". We can store the value 
in another variable. This variable has a special type called a pointer. 
To create a pointer that can point to an integer, we use 
int* p; 
Now, you can have p (a pointer to an integer) point to an actual integer, say a 
int a=25; 
p=&a; 
Now, you can manipulate the variable a via a as well as p. See the example on 
the next slide. 
Procedural Programming in C++ 116
Pointers 
The output: 
Procedural Programming in C++ 117
Pointers 
Now let's rewrite the swap function using pointers. 
As you note, the function takes pointers to integers and we pass it addresses 
of our integers (i and j) 
Procedural Programming in C++ 118
Pointers 
A few notes about pointers: 
You can create them alternatively as 
int *p; 
You can create more than one pointer like: 
int *p1,*p2,*p3; 
You can assign addresses of a variable to an integer as in: 
int a=25,*p=&a; 
cout<<*p<<endl;//should output 25 
You can create pointers that point to other data types such as long, bool, char 
…etc. 
double *d1; 
double d=3.5; 
d1=&d; 
Plus some relationship to arrays that will be explained in the next few slides. 
Procedural Programming in C++ 119
Arrays and pointers 
As we said earlier, an array is just the address of the fist element. Since we 
can print addresses of variables, we can prove that: 
Outputs : 
The output is in hexadecimal, but you can see that both a and the address of 
a[0], the first element of the array, are the same. 
Remember, we said that when you create an array, the size is fixed and you 
can't change it. Also know that arrays are a read-only pointer and you can't 
change them. But with pointers, you can create dynamic arrays. 
int *p, size; 
cin>>size; //get the size from keyboard 
p=new int[size]; 
//use p like an ordinary array 
delete [] p; //you have to release the memory 
Procedural Programming in C++ 120
Sorting 
So far, we have looked at quite a lot of topics. Variables, methods, arrays and 
pointers. It is time to look at making use of such topics to solve a problem. At 
the end of the day, we learn programming languages so that we can solve 
problems. 
The goal of the next few slides is walking you through the steps of solving a 
common problem. 
When presented with a problem, the first thing is to really understand what the 
problem is. After that, a systematic solution needs to be created so that a 
computer can perform the solution. It is usually easier (and a very essential 
problem solving skill) if one can divide a big problem into smaller sub-problems 
that can be solved more or less independently. 
This technique is called Divide and Conquer. In addition to that benefit, divide 
and conquer also supports team work by allowing programmers to solve parts 
of the problem and getting to the final solution by putting together these parts 
of the solution. 
Procedural Programming in C++ 121
Sorting 2 
One of the most common programming tasks is sorting a list of values 
from highest to lowest or vice versa or a list of words into alphabetical order. 
There are many sorting algorithms; some are easy to understand but 
not so efficient while some are efficient but hard to understand. One of the 
easiest sorting algorithms is called selection sort. 
The selection sort algorithm works as follows: 
for( int i=0; i<array_length; i++) 
Place the ith smallest element in a[i] 
Where a is an array and array_length is the declared size of the array. 
Algorithms are usually expressed in pseudo-code. 
Procedural Programming in C++ 122
Sorting 3 
The algorithm iterates through all the elements of the array one by one and at 
each iteration it places the smallest number of the array in the next suitable 
position. 
Now we will implement this algorithm description in C++. We need 
functionality/methods to do the following: 
To find the smallest number in the array(or the location of the smallest 
value in an array) 
To swap two values 
To sort the array 
We will now implement each of these methods separately and then write a 
main method to test the methods. 
For example, if I have the array [9,3,7,2,4], the selection sort routine would go 
through the following sequence of steps: 
Procedural Programming in C++ 123
Sorting 4 
9 3 7 2 4 
2 3 7 9 4 Swap minimum of all five elements with first element 
2 3 7 9 4 Swap minimum of last four elements with second element 
2 3 4 9 7 Swap minimum of last three elements with third element 
2 3 4 7 9 Swap minimum of last two elements with fourth element 
Here is the code for the method that sorts the array. Look, it uses two other 
methods to do its work. 
Procedural Programming in C++ 124
Sorting 5 
Now we will implement the function which will find the index of the next 
smallest element of the array (note how the array was passed to method 
index_of_min in the previous slide; you just give the array's name. 
Procedural Programming in C++ 125
Sorting 6 
Now, the last method that swaps two numbers in an array. We just give the two 
indices to the method and it will swap what is located at those locations. 
Note how we have commented the methods above this helps other 
programmers understand the intent of the method. It is essential that 
programmers don't have to understand a method to use it. 
Procedural Programming in C++ 126
Sorting 7 
Using these methods in a main method would look like this: 
In the lab, put all the methods we described above in one class and run it. Test 
it with a few different arrays and see if it works. Also not that we are using a 
method to_string that takes an array and returns a string representation of it. 
See next slide for that method too. Note that we did not have to know how it 
works to be able to use it. That is why we call method a black box. 
Procedural Programming in C++ 127
Sorting 8 
See this method and not how it uses string stream from sstream that must be 
included as 
#include <sstream> 
Procedural Programming in C++ 128
Managing Separate Compilations 
If you have tried the sorting exercise in the lab (or at home), you probably have 
run into problems such as: In which order should I define my methods? 
For example, we defined swap first, then index_of_min, then sort and 
finally to_string. This was deliberate because in C++, you have to define a 
method before you can use it. So, the order at which we defined our method 
was crucial to get our code to compile successfully. 
Suppose now, if you wanted to call to_string inside the method sort! It 
gives you a compile error because to_string is defined after sort. 
So, what is the solution? 
The solution is separating the method declarations from method definitions. 
Method declaration is only the method signature: return type, method name 
and parameter list. 
Once we declare the methods, we can define them in any order and call any 
one of them from any other. 
This separation is very elegant as we will soon see and it will solve other 
problems not just the method ordering problem. 
Procedural Programming in C++ 129
Managing Separate Compilations 
Another problem is often that we can not put all our code in one single file. A 
relatively small application may compose of a few thousand lines of code! 
Imagine having all of this code in a giant single file! It does not seem right as it 
is too big to be compiled, maintained, transmitted (or deployed) every time we 
make even the slightest change in the program. 
The problem is also that programs in practice often are developed by groups of 
developers and having everything in one monolithic file is by no means a 
solution. There have to be better ways; in fact there is: Separating compilation 
units(files). 
Code for useful and commonly used methods is put in files called libraries and 
included by different applications. For example, we could have created a library 
of our sort methods given them to two different groups of developers to use it 
in their applications just by including it very much the same way you include 
iostream or math libraries. 
In practice, there is no difference between system libraries such as iostream 
and libraries you create except for the location you put the libraries and also 
the way you include them. System libraries are included like <iostream> but 
user libraries are include like "sort-functions.h" 
Procedural Programming in C++ 130
Managing Separate Compilations 
The common practice is to place all method declarations in a header file 
identified by a .h extension. The definition of those methods is put in a normal 
.cpp file with the .h file included. 
At runtime (or just before runtime), a special program called a linker links the 
method definitions to their implementations.: 
Now, let's re-write our sort code in this way and divide it into header file, source 
file and application file. First see the example in its old state, which everything 
in one file: 
Procedural Programming in C++ 131
Managing Separate Compilations 
Let's see how converting the above project into a project with a few separate 
files can be achieved: 
Procedural Programming in C++ 132
Managing Separate Compilations 
Procedural Programming in C++ 133
Managing Separate Compilations 
Procedural Programming in C++ 134
Managing Separate Compilations 
Procedural Programming in C++ 135
Managing Separate Compilations 
Take special note the highlighted code: we have include the "sort-library.hi" (the 
function definitions header file) in both files. First in the implementation of the 
functions (we called them sort-impl.cpp ) and in the application that used the 
sort library to sort an array of integers in its main (sort.cpp) 
This this structure in place, we can have a groups of developers work on the 
same project, each on a sub-part of the bigger problem. 
This way, the compilation units are smaller and more manageable and can be 
developed more or less independently. 
If one developer needs to use another developer's methods, all he/she needs 
to have is the header function included. 
Procedural Programming in C++ 136
Managing Separate Compilations 
Java also comes with several sorting tools for arrays which you can use 
without defining your own algorithms. You could use the following pre-defined 
Java sorting methods for sorting primitive data type arrays in ascending order: 
void sort(byte[] a); 
void sort(short[] a); 
void sort(char[] a); 
void sort(int[] a); 
void sort(float [] a); 
void sort(double[] a); 
To use these pre-defined methods, you must import the package to which they 
belong. All these and many more methods are defined in the class Arrays, in 
the package java.util. 
Procedural Programming in C++ 137
Exercises 
Ex.61) Write a predicate function (whose return value is either true or 
false) that takes an int array as a parameter and returns true if the 
array is sorted in ascending order. Test your function in a program. 
Ex.62) You can sort an int array by following the following procedure: 
Start by going through the array, looking at adjacent pairs of values. 
If the values of a pair are correctly ordered, do nothing; if they are 
out of order, swap them. In either case move on to the next pair. The 
pairs overlap so that the second element of the a pair becomes the 
first of the next pair. Repeat this operation until you make a compl-ete 
pass in which you do not make an exchange or swap of values. 
This algorithm is called the bubble sort, because the values seem to 
bubble up to their eventual positions. 
Procedural Programming in C++ 138
Multi-dimensional Arrays 
In Java, the elements of an array can be of any type. In particular, the 
elements of an array can themselves be arrays. Arrays of arrays are called 
multidimensional arrays. 
The most common form of a multidimensional array is a two-dimensional array 
which is similar to a rectangular structure divided into rows and columns. This 
type of two-dimensional array is called a matrix. 
You can have arrays of 3 or more dimensions. But they are less common. 
Consider the two-dimensional array as a mattrix: 
//two rows, three columns 
int[][] matrix=new int[][]{{2,2,2}, 
{2,2,2}}; 
This is an array (size 2) of two arrays (size 3). 
Procedural Programming in Java 139
Multi-dimensional Arrays 2 
When defining multi-dimensional arrays, like ordinary arrays, you can put the 
array size if you provide an initializer list. The following will be an error: 
int[][] matrix=new int[2][3]{{2,2,2}, //this will not 
{2,2,2}};//compile 
A couple of more examples defining two dimensional arrays: 
Procedural Programming in Java 140
Multi-dimensional Arrays 3 
We will now look at an example involving two-dimensional arrays; in this 
example we will write a method to add 2 matrixes. 
Procedural Programming in Java 141
Multi-dimensional Arrays 4 
Procedural Programming in Java 142
Multi-dimensional Arrays 5 
The output of the previous example is as follows: 
Procedural Programming in Java 143
Multi-dimensional Arrays 6 
For multi-dimensional array parameters and return types, as for arrays, 
dimension sizes should not be given. This makes sense if you think of a multi-dimensional 
array as an array of arrays. In this example we have an array 
each element of which is an int array. Remember that if you have an array 
parameter, you do not have to specify the array size in the square brackets. 
Multi-dimensional arrays are mainly used to perform matrix operations and 
numerical analysis calculations. The base type of a multi-dimensional array 
can be any type; but for numerical calculations the type is usually int or double. 
In the example on the previous page, we saw how to add two matrixes. 
You can also do other matrix operations like matrix multiplication, matrix 
transformations using two-dimensional arrays. 
Procedural Programming in Java 144
Multi-dimensional Arrays 7 
As with ordinary (1-dimensional arrays), the following two 2D-array 
declarations are equivalent: 
int[][] myArray = new int[3][5] ; 
and 
int[][] myArray = { {0,0,0,0,0}, {0,0,0,0,0}, 
{0,0,0,0,0} }; 
The length of a 2D-array is the number of rows it has. For example: 
int[][] uneven = { 
{ 1, 9}, 
{ 0, 2}, 
{ 0, 1} }; 
System.out.println("Length is: " + uneven.length ); 
Procedural Programming in Java 145
Exercises 
Ex.63) Write a method that has one parameter of type int array[][]. 
The function multiplies its parameter by the unit matrix and prints the result. 
Test your method in a Java program. 
Ex.64) Write a method that takes two parameters of type 
int[][] and then multiplies the two matrixes together and writes the result in 
a third matrix. Test you method in Java program. 
Note: You can multiply a matrix nXm only by a matrix that is mXn. 
Ex.65) Write a method that takes a parameter of type int a[5][5] 
and changes the value of every element above the diagonal to 0. 
Ex.66) Write a method that takes a parameter of type int[][] that is a 
square matrix mXm. and exchanges the elements above and below the 
diagonal together but leave the diagonal values unchanged. 
Procedural Programming in Java 146
Writing to Files 
So far we have learnt how to input data from the keyboard and output data to 
the screen. But for many real problems we need to be able to input data from 
a file and output date into a file. 
I/O from and into files can be done using Java streams. Input streams 
for data input from a file/keyboard/network… and output streams for output to 
a file/screen/printer/network… 
You have already used some kinds of streams: System.in (an input stream) 
which is connected to the keyboard and System.out (an output stream) 
which is connected to the screen. 
The main reason behind using I/O streams is because keyboard input and 
screen output deal with temporary data. When the program ends the data 
typed in at the keyboard and the output data to the screen is lost. Files provide 
you with a way to store data permanently. 
Procedural Programming in Java 147
Writing to Files 2 
When your program takes input from a file it is said to be reading from the file 
and when your program sends output to a file it is said to be writing to the file. 
Usually when reading from a file, your program starts reading from the 
beginning of the file and when writing to a file it starts writing to the beginning 
of the file. 
A stream is a special kind of variable known as an object. 
Note that errors are very common when dealing with I/O operations, because 
the program has to deal with the external environment. 
In the following example, we will write a program that opens a specific file (if 
the file does not exist, it will create a new file) and then output a few lines of 
text to the file. 
Procedural Programming in Java 148
Writing to Files 3 
import java.io.*; 
public class WriteTextFile { 
public static void main ( String[] a) throws IOException 
{ 
String fileName = "myFile.txt" ; 
//Following 2 line: open a text file called "myFile.txt 
FileWriter writer = new FileWriter( fileName, true); 
PrintWriter out=new PrintWriter(writer); 
out.println( "Line 1" ); 
out.println( "Line 2" ); 
out.println( "Line 3" ); 
out.println( "Line n" ); 
out.close(); 
} 
} 
Procedural Programming in Java 149
Writing to Files 4 
First we import the java.io package which contains definitions of input/output 
operations. The statement throws IOException is necessary for I/O 
operations. It deals with errors or exceptions. We will cover exceptions later; 
for now, just use this statement every time you use I/O streams. 
Then we create a string variable to represent a filename. 
The two bold lines open a text file called "myFile.txt" and if it does not exist, a 
new file with that name will be created in the current directory. You don't need 
to understand the details of these two statements. They will be explained later. 
The two lines can be combined into one line: 
PrintWriter out=new PrintWriter(new 
FileWriter(filename, true); 
If you leave out (or change it to 'false') the second parameter 'true' in the 
first bold statement, every time you run this program, your file will be 
overwritten. 
Procedural Programming in Java 150
Writing to Files 5 
Notice how the method println works with the variable out. Since out is an 
output stream like System.out, you can use this method the way you use it to 
output to the screen. 
The close() method should always be used when a program is done with a 
file. If a file is not closed, the program might end before the operating system 
has finished writing data to the file. The data written to the file might be lost! 
The method print or println can be used to output any data type to the 
output stream: 
void print(int i); 
Void print(char c); 
Void print(boolean b); 
Void print(double d); 
Void print(String s); 
and a few more… 
Procedural Programming in Java 151
Reading from a File 
Now that we can output to a file, lets see how we can read or input from a file. 
Reading from a text file is as important as writing to a file. 
For this we first create an input stream and connect it to a file on the disk: 
BufferedReader in=new BufferedReader(new 
FileReader ("myFile.txt")); 
As we saw on page 115, the above step could be written in two lines: 
FileReader reader=new FileReader("myFile.txt"); 
BufferedReader in=new BufferedReader(reader); 
You can choose either. Again, don't worry if you don't understand the details of 
the above statements. We will cover them later. 
On the next page, we write a program that outputs all the contents of a file to 
the screen. 
Procedural Programming in Java 152
Reading from a File 2 
import java.io.*; 
class ReadTextFile{ 
public static void main(String[] args) throws IOException { 
String fileName = "reaper.txt" ; 
String line; 
BufferedReader in = new BufferedReader(new 
FileReader( fileName ) ); 
line = in.readLine();//read first line 
while ( line != null ){ //read all the file 
System.out.println( line ); 
line = in.readLine(); 
} 
in.close(); 
} 
} 
Procedural Programming in Java 153
Reading from a File 3 
The file "reaper.txt" is opened for reading when a FileReader stream is 
constructed. If the file does not exist in the current directory, an 
error will be reported and program execution will be stopped. 
Next, the program reads each line of the file and writes it to the monitor. The 
method readLine reads one line of text from the file and if there is no more 
data in the file, it returns null. The line 
(line !=null) 
Check for the end of file. Here, we continue reading new lines from the file 
until we reach the end of file. 
Now the stream BufferedReader also has a method called 
public int read(); 
Which reads a single character from an input stream. It reruns -1 if end of the 
stream is encountered. It returns an integer representation of the character. 
You need to cast it be able to treat it like a character. 
Procedural Programming in Java 154
Reading from a File 4 
Character processing is especially important when writing word processing and 
editing programs. Java has a rich set of tools to help the programmer with this. 
Most of the methods and functionality for character processing is available in 
the Wrapper class Character. Here are some of the most useful methods of 
this class: 
static boolean isDigit(char ch); 
//Determines if the specified character is a digit. 
static boolean isLetter(char ch) 
//Determines if the specified character is a letter. 
static boolean isLetterOrDigit(char ch) 
//Determines if the specified character is a letter or digit. 
static boolean isLowerCase(char ch) // or isUpperCase 
//Determines if the specified character is a lowercase character. 
static boolean isWhitespace(char ch) 
//Determines if the specified character is white space 
static boolean toLowerCase(char ch) //or toUpperCase 
//Converts the character argument to lowercase using 
Procedural Programming in Java 155
Exercises 
Ex.67) Using the information from slides (117-120), rewrite the program on 
slide 118 but this time the program will read from the file one character at a 
time. (Not line by line). 
Ex.68) Write a method that takes two file names as parameters and copies the 
contents of the first file into the second file. Test your program in Java 
program. 
Ex.69) Write a method that takes a file name as its only parameter. The 
method will search the file of numbers of type int and write the largest and 
smallest numbers to the screen. The file contains nothing but numbers of type 
int separated by blanks or line breaks or tabs. Test your method in a Java 
program. For this exercise, you may need to convert strings into integers: 
String str="123"; 
int x=Integer.parseInt(str);//convert 
Procedural Programming in Java 156
Exercises 
Ex.70) Write a program that reads text from one text file and writes an edited 
version of the same text to another file. The edited text is identical to the original 
version except that its text is all in upper case. 
Ex.71) Write a program that reads all the contents of a text file and writes 
everything except numbers into another file. It filters numbers from the file. 
Ex.72) Write a program to count the number of lines, the number of 
words and the number of non-whitespace characters in a file. It should then 
display this information on the screen. A word is any sequence of characters 
between any two of following characters: space, tab, new-line, comma, period. 
For this exercise only consider spaces and new-lines. 
Ex.73) Write a method that reads text from a file and writes each line 
preceded by a line number starting from 1. Follow the line number with a colon 
and a space for clarity. You may assume that the lines are short enough to fit 
within a line on the screen. 
Procedural Programming in Java 157
Exercises 
Ex.74) Write a method to strip or remove comments (//) from a Java 
source file. First write a method with the prototype/declaration 
public static void stripFile(String f1, String f2); 
Which simply reads lines from the input stream file f1 and then output them to 
the output stream file f2. 
Then test your method in a complete Java program. 
Be careful when this type of comment is used in the middle of a line of code. 
These comments do not have to start from the beginning of the line. 
Ex.75) Repeat exercise 72, but this time remove C-style comments, those 
which start with /* and end with */. 
Procedural Programming in Java 158
Classes 
You have seen several basic/primitive data types so far (int, double, char…) 
These basic data types can be used to represent single values. or atomic 
values, only. 
But many real-world applications require more complex data types. It is very 
difficult to do this using the primitive types. For example, a university student 
has a name, a date of birth, a year…. 
Here we need to have a data type which can represent a student. Not just the 
student name (string), not just student year (byte), not just date of birth of the 
student (?), but one data type representing the 'while' student. 
In Java, we can define a new data type using a class. In some other 
languages structs are used to define new data types. 
A class or a struct can be used to create a new data type which can be a 
compound data types consisting of several basic data types. 
Procedural Programming in Java 159
Classes 2 
In the following example we will create a new data type called Student and 
then declare variables of this type in a program: 
public class Students{ 
public static void main(String[] a){ 
Student s=new Student(); 
s.name="Karwan"; 
s.year=1; 
s.DOB="1 September 2003"; 
System.out.println("Name: " + s.name); 
System.out.println("Year: " + s.year); 
System.out.println("DOB: " + s.DOB); 
} 
} 
Procedural Programming in Java 160
Classes 3 
class Student{ 
String name; 
byte year; 
String DOB; 
} 
We have created a class called Student which has three member variables. 
The new data types Student is a compound data type. 
You can assign one class variable to another: 
Student s2=s; 
If you do this, s2 member variables will have the same values as member 
variables of s. 
But you should be careful when you compare class variables for equality. You 
should compare each member variable individually. 
Procedural Programming in Java 161
Classes 4 
Remember you can have arrays of any data type, including arrays of classes. 
For example, you could declare an arrays that can hold information about 30 
students: 
Student[] array=new Student[30]; 
An then to access array elements and their member variables: 
array[0].name="Karwan"; 
array[0].year=1; 
array[0].DOB="1 June 1983"; 
Array[0] refers to the first element of the array which is of type Student. 
Classes allow you to write more complex programs by letting you represent 
more real-world objects like students, books, cars, computers… 
Procedural Programming in Java 162
Classes 5 
In the next example, we use the same class Student and add a method to ask 
the user to provide data for 10 students: 
public class Students{ 
public static void main(String[] a){ 
Student[] array=new Student[10]; 
fill_array(array); 
} 
public static void fill_array(Student a[]){ 
Scanner input=new Scanner(System.in); 
for(int i=0; i<a.length; i++){ 
System.out.println("Enter name:"); 
a[i].name=input.nextLine(); 
System.out.println("Enter year:"); 
a[i].year=input.nextByte(); 
Procedural Programming in Java 163
Classes 6 
System.out.println("Enter Date of birth:"); 
a[i].DOB=input.nextLine(); 
} 
} 
} 
class Student{ 
String name; 
byte year; 
String DOB; 
} 
Look at this program carefully. The method fill_array is called to fill the 
10-element array with data from the user. 
Run this programs and enter data for 10 students. Once the array is filled, you 
could do anything with this data, e.g. you could save it to a file. 
Procedural Programming in Java 164
Exercises 
Ex.76) For the program on the previous slide, write another method called 
print_array, which will print all the students' information on the screen. 
Ex.77) Write another method which will save all the information from the array 
into a disk file. You could write each student's information on a separate 
line in the file like: 
Karwan 1 1 June 1981 
Kawa 1 3 May 1982 
…. 
Ex.78) Write a Java program that can maintain information about a 
personal bookshelf. The program asks for information about a new book 
such as the author, title, ISBN no., price, year published. Use a class to 
hold book information. 
Ex.79) Write a program that accepts a word from the user and outputs 
the number of vowels in that word. (Vowels include: A, E, I, O and U) 
Procedural Programming in Java 165
Recursion 
Recursion is a solution technique in which problems are solved by 
reducing them to smaller problems of the same form. We will start by 
looking at an example involving a recursive solution. 
Consider the factorial function below 
public static int Factorial(int n){ 
int product=1, i; 
for(i=1; i<=n; i++) 
product *=i; 
return product; 
} 
But this solution does not take advantage of an important property of 
factorials: each factorial is related to the factorial of the smaller number as in: 
n!=n*(n-1)! 
Procedural Programming in Java 166
Recursion 2 
So we can find a recursive solution for the method factorial because 
getting the factorial of one number involves also getting the factorial of a 
smaller number. This is the recursive definition of factorial: 
public static int factorial(int n) { 
if(n==0) 
return 1; //factorial of 0 is 1 
else 
return (n * factorial(n-1)); 
} 
Consider a call like: 
int x=factorial(4); 
The function performs the following operations: 
(4 * (3 *(2 *(1 *(1))))) which equals 24. 
Procedural Programming in Java 167
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++
Intro. to prog. c++

Mais conteúdo relacionado

Mais procurados

Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
Flowchart and algorithem
Flowchart and algorithemFlowchart and algorithem
Flowchart and algorithemehsanullah786
 
Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Adam Mukharil Bachtiar
 
Programming Fundamentals lecture 2
Programming Fundamentals lecture 2Programming Fundamentals lecture 2
Programming Fundamentals lecture 2REHAN IJAZ
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programmingmshellman
 
Basics Of C Programming For Beginners In Easiest Way
Basics Of C Programming For Beginners In Easiest WayBasics Of C Programming For Beginners In Easiest Way
Basics Of C Programming For Beginners In Easiest Wayakshay rajpure
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ programmatiur rahman
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingManoj Tyagi
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming TerminologyMichael Henson
 
Write programs to solve problems pascal programming
Write programs to solve problems   pascal programmingWrite programs to solve problems   pascal programming
Write programs to solve problems pascal programmingAnutthara Senanayake
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Akshay Nagpurkar
 
Introduction of c programming unit-ii ppt
Introduction of  c programming unit-ii pptIntroduction of  c programming unit-ii ppt
Introduction of c programming unit-ii pptJStalinAsstProfessor
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programmingChitrank Dixit
 

Mais procurados (20)

Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Flowchart and algorithem
Flowchart and algorithemFlowchart and algorithem
Flowchart and algorithem
 
Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)Algorithm and Programming (Introduction of Algorithms)
Algorithm and Programming (Introduction of Algorithms)
 
History of c++
History of c++ History of c++
History of c++
 
Programming Fundamentals lecture 2
Programming Fundamentals lecture 2Programming Fundamentals lecture 2
Programming Fundamentals lecture 2
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programming
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
 
Computer Programming- Lecture 3
Computer Programming- Lecture 3Computer Programming- Lecture 3
Computer Programming- Lecture 3
 
Basics Of C Programming For Beginners In Easiest Way
Basics Of C Programming For Beginners In Easiest WayBasics Of C Programming For Beginners In Easiest Way
Basics Of C Programming For Beginners In Easiest Way
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ program
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
Write programs to solve problems pascal programming
Write programs to solve problems   pascal programmingWrite programs to solve problems   pascal programming
Write programs to solve problems pascal programming
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Introduction of c programming unit-ii ppt
Introduction of  c programming unit-ii pptIntroduction of  c programming unit-ii ppt
Introduction of c programming unit-ii ppt
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 

Destaque (10)

Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
C++ programming
C++ programmingC++ programming
C++ programming
 
20130110 prs presentation ncim c++ 11
20130110 prs presentation ncim c++ 1120130110 prs presentation ncim c++ 11
20130110 prs presentation ncim c++ 11
 
presentation on C++ basics by prince kumar kushwaha
presentation on C++ basics by prince kumar kushwahapresentation on C++ basics by prince kumar kushwaha
presentation on C++ basics by prince kumar kushwaha
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
C++ language
C++ languageC++ language
C++ language
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Semelhante a Intro. to prog. c++

Semelhante a Intro. to prog. c++ (20)

Programming of c++
Programming of c++Programming of c++
Programming of c++
 
Contents Pre-requisites Approximate .docx
   Contents Pre-requisites  Approximate .docx   Contents Pre-requisites  Approximate .docx
Contents Pre-requisites Approximate .docx
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programming
 
C++ book
C++ bookC++ book
C++ book
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 
Comso c++
Comso c++Comso c++
Comso c++
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5
 
C++programing
C++programingC++programing
C++programing
 
C++programing
C++programingC++programing
C++programing
 
Notes
NotesNotes
Notes
 
C plus plus for hackers it security
C plus plus for hackers it securityC plus plus for hackers it security
C plus plus for hackers it security
 
Lecture 1-3.ppt
Lecture 1-3.pptLecture 1-3.ppt
Lecture 1-3.ppt
 
Unit 1
Unit 1Unit 1
Unit 1
 
JAVA
JAVAJAVA
JAVA
 
Beekman5 std ppt_13
Beekman5 std ppt_13Beekman5 std ppt_13
Beekman5 std ppt_13
 
Modern c
Modern cModern c
Modern c
 
PROBLEM SOLVING
PROBLEM SOLVINGPROBLEM SOLVING
PROBLEM SOLVING
 
6272 cnote
6272 cnote6272 cnote
6272 cnote
 
C progrmming
C progrmmingC progrmming
C progrmming
 
Programming in c
Programming in cProgramming in c
Programming in c
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

Intro. to prog. c++

  • 1. Introduction to Programming in C++ First Year Ishik University-Erbil Department of Information Technology 2011-2012
  • 2. About this course This course is an introduction to programming in C++. Fundamental concepts such as; variables, memory, data types and input/output will be explained. Functions, arrays will be covered later. Finally, pointers, addresses and dynamic arrays will be tackled. Although the examples will be in C++, the focus is more on the technique and skillset needed in program writing and problem solving. C++ is a popular and mature language. It is a successor of the famous C language that underlies many of the real time systems and operating systems. C++ is called to be a hybrid language which means you can write both procedural programs as well as object oriented programs. It is also said to be a low level language in which you can manipulate bits and variable addresses, allocate and free memory. These topics and others will be discussed throughout the course. Procedural Programming in C++ 2
  • 3. Goals There are two parts to this course: - programming principles - C++ programming language Programming principles are general to all languages and programs. We will begin the study of the language starting with the fundamentals of the language and simple programs; and as we explore more of the language, we will write increasingly larger programs. By the end of this year, every student: - should learn the essential programming concepts - should demonstrate a good familiarity with C++ syntax - should be able to write reasonably complex programs - should develop a consistent programming style - Have a good base for learning other programming languages such as Java and C sharp. Procedural Programming in C++ 3
  • 4. Course assessment You will have 2 hours theory and one lab session (2 hours) per week. You are advised to attend all lectures and lab sessions. They will NOT be repeated. The assessment for this course will be made up of: Quizzes 10% Mid-term Exam 25% Practice Exam 25% Final Exam 60% The pass mark for this course is 60%. But remember, the aim is to learn, it is not to get marks. Also note that quizzes are not expected. I may consider class participation for the 10% above. Procedural Programming in C++ 4
  • 5. Resources The recommended textbooks for this course: C++ How to Program, 3rd Edition, 2003, Deitel & Deitel Thinking in C++, 2nd Ed, Volumes I and II, Bruce Eckel For a reference book, you can consult the following: C++ The Complete Reference, 4th Edition, 2002, Schildt I will put the books on the main computer in the lab, so you will be able to copy the books and use them as refernces. I will not use any specific book to follow, but you can consult them if you need more explanation and examples on any particular topic. Bur remember: don't rely on lecture notes only. READ, PRACTICE and PRACTICE. Through writing programs you can learn how to program. Procedural Programming in C++ 5
  • 6. COURSE CONTENT Week Topic 1 Introduction. Classification of Programming Languages 2 Variables. Performing output and input. 3 Identifiers and Reserved words. Primitive data types. 4 Arithmetic operators. Predefined functions. 5 Increment and Decrement operators. Relational operators. 6 Boolean operators. Short circuiting. Precedence rules. 7 MIDTERM 8 Strings. Flow of control. 9 Branching (if-else) statements. 10 Multiway if-else statements. Switch statement. 11 Loops. While and Do-while loops. 12 Break and Continue statements. For loop. Goto statement. 13 Arrays. 14 FINAL
  • 7. Working in the Labs Working in the Labs is a very important part of your programming courses. All the software you need for your courses is installed on the computers in the Labs. The labs are considered as class presence and you should attend all of them. But the goal is to get you to work, not sit in the labs. Normally, you need to be in the lab even if the teacher is not there or late. You should have enough from the theory to practice and experiment with. But generally, I will be in the lab to help you with questions and difficulties. There will be guided sessions in the labs or just solving some problems from the slides of the theory lesson. In either case, you have access to me (teacher) and a lab assistant to help you in your practice. I am an Eclipse user, so I am using Eclipse CDT (C++ Development tooling, found at http://eclipse.org/cdt/ ). You are fee to use MS Visual Studio or any other IDE for your programming. Procedural Programming in C++ 7
  • 8. Programming Programming is about solving problems. Most often, a programmer, or a group of programmers, is presented with a problem and asked to produce a computerized solution for that problem. Almost anything that a computer can do, a human can also do. So why do we need computers and programs to solve our problems??? The basic reason is that humans are not good at doing repetitive asks while computers ARE. Humans can perform a few calculations but get tired especially if the calculations are long and complex).Computers don't get tired. In a perfect world, a computer could carry out endless repetitive and long calculations without stop. Another reason is that computers are much faster at performing calculations than humans. Modern computers can carry out millions of basic instructions per second. One important distinction is that computers carry out one step at a time, so when writing a program, you have to write every step no matter how trivial they are and in the sequence required for the solution to be produced by a computer. Procedural Programming in C++ 8
  • 9. Programming 2 A computer is a complex machine with many components. The part of the computer which does the real computing is called the Central Processing Unit or the CPU. It is the brain of the computer. Computers are capable of doing many interesting tasks. But computers need to be told what to do. You can tell a computer what to do by writing a program for the computer to execute. A program is a list of instructions for the computer to execute. The computer executes the instructions one after another, until it reaches the end of the list. Before a program is executed, it is stored in the computer's main memory or RAM. The CPU fetches the instructions one by one from the memory and executes them. This process -- fetch an instruction, execute it, fetch another instruction, execute it, and so on forever -- is called the fetch-and-execute cycle. Procedural Programming in C++ 9
  • 10. Good Programming Programming is a challenge. Often, programs are late, difficult to use, full of bugs, un-maintainable, and wrong. When someone writes a program, they should not only think about the people who will use it, but also about the people who will maintain it. Writing good programs comes only after a lot of practice and experience. Good programs are programs that are: • on time • user-friendly • reliable and stable • maintainable and extensible • correct (do what they were intended to do) • and above all, simple in a way that they don't make the task more difficult or convoluted than its manual counterpart. Procedural Programming in C++ 10
  • 11. Good Programming 2 To be able to write effective programs, one needs to know a few things: – mastery of the tools-of-the-trade (programming language, development environment etc.) – the ability to analyze a 'real world' problem and to construct a model for it suitable for programming – careful design of an algorithm and user-interface for the program at hand – knowing the techniques that have made other programmers more effective, and a reluctance to reinvent the wheel! – Practice and exercise Procedural Programming in C++ 11
  • 12. The syllabus The following topics will be covered in this course: – introduction – variables and assignment – basic input and output (I/O), formatting output – basic data types – a simple C++ program – arithmetic operators – arrays – pointers and references – strings – flow of control and loops – program style, comment and documentation. – methods, procedural abstraction – local/global variables, constants – creating libraries (.h) files. – structures – file I/O Procedural Programming in C++ 12
  • 13. Variables A variable is a placeholder used for storing data. The type of data may be numerical, string, character, boolean or any other type that the language supports. We will study all the basic data types in C++ later in the course. The data in a variable is called its value and it can be changed or deleted. In order to uniquely identify and keep track of a variable, we need to give each variable a name; this is called declaring a variable (variable declaration). It is a good idea to use meaningful names for variables. For example: int books; in this variable declaration, we declare a variable named "books" to be of type int (int is short for integer which refers to whole numbers like 1 , 5 , 192 , -8 …) Procedural Programming in C++ 13
  • 14. Variables 2 In the example on the previous page, we want the variable "books" to hold the number of books in a program. Also note that here, we used the data type int which represents whole numbers. We used this data type because the number of books is a whole number like 17 and not 3.6, for example. The data type of numerical values with decimals is called double. We will cover all data types later. For now keep it in mind that whole numbers are of type int and decimal numbers of type double. double myWeight; in this case, the variable myWeight is of type double because its value can be a number with a fraction like 1.3. Note that all variable declarations end with a semicolon(;). Procedural Programming in C++ 14
  • 15. Variables 3 To be more specific, a variable is a memory location which can contain a value of some type. A variable declaration like int books first maps a name (books) to a memory location in the computer's memory and tells the computer what type of data will be stored in this variable. A variable must be declared before it can be used. When the name of a variable appears in a program, its value is obtained. It's common to initialize variables upon declaration. If a variable is used in a program without being initialized, the results will be unpredictable and it usually is a logic error to use uninitialized variables. Variable initialization can be performed either during declaration using assignment statements (to be discussed shortly) as in int books=0; Procedural Programming in C++ 15
  • 16. Assignment Statement Values can be assigned or stored in variables with assignment statements: books=34; An assignment statement is an order, to the computer, to assign the value on the right-hand side of the equal sign to the variable on the left-hand side. The sign (=) is called the assignment operator. (C++ operators will be covered later in the course). Assignment statements end with a semicolon. In fact, every statement must end with a semicolon (;). The value on the right-hand side can also be another variable or expression: books1=books2; In an assignment statement, first the value on the right-hand side is evaluated and then its result is stored or assigned to the variable on the left-hand side. Procedural Programming in C++ 16
  • 17. Assignment Statement When using assignment, we have 2 sides of the operator, l-hand and r-hand, for left and right hands respectively, as in this example: books=200; The l-hand side must be something that can hold a value, i. e. a variable. The r-hand side can be an expression that produces a value. For example, literals 200, 500, -6 …etc. int firstSemister=70; int myAge=19; int temperature=-10; Or it could be another value producing expression, such as a variable or an operation: int yourAge=myAge; int hisAge=myAge+3; Procedural Programming in C++ 17
  • 18. Performing Output The values of variables, numerical values and strings of text ,may be output to the screen using the << operator, read c-out: int books=0; cout<<books<<endl; cout<<71<<endl; cout<<"This is a stringn"; in the first output statement, the value of variable books will be output on the screen, which is 0; in the second, the numerical value 71 will be output to the screen, and in the last statement, the string "This is the output" will be output to the screen. Note that we add <<endl; to produce a new line in the output. Equivalently, we put a n in the string to produce the same effect. If you miss these , output would follow on the same line. Procedural Programming in C++ 18
  • 19. Performing Output The code on previous slide produces the following output: If we omit the endl statements, as in: int books=0; cout<<books; cout<<71; cout<<"This is a string"; The output will be: Procedural Programming in C++ 19
  • 20. Performing Output Note the n in the string that causes the output to continue on the next line. C++ supports a number of other characters, called escape characters. The bellow table is taken from the textbook. How to program 7th ed. Procedural Programming in C++ 20
  • 21. Performing Input In C++, the input stream object, cin (read c-in) is used with stream extraction operator >> to read input from keyboard Performing input in Java is much more difficult than performing output: Procedural Programming in C++ 21
  • 22. Performing Input 2 We declare a variable called yourAge and initialize it to zero. Then the program uses the method >> to ask the user for input. The program waits for the user until input is provided at the keyboard. Once the user enters a number and presses the Enter key, the inputted value is saved (assigned) to the variable yourAge . The program finally outputs the value of the variable yourAge onto the screen with some other information. The screen capture on the previous slide shows the input in green font vs the output in normal black font. Procedural Programming in C++ 22
  • 23. Performing Input 4 And the output is: Procedural Programming in C++ 23
  • 24. Identifiers and Reserved Words An identifier is any symbolic name that refers to something in a Program. For example, variable names are identifiers. An identifier is a series of characters consisting of letters, digits and underscores that does not begin with a digit. C++ is case sensitive; which means lowercase and uppercase letters are different. So, a1 and A1 are two different identifiers. Identifiers can contain numbers but cannot begin with a number. In addition, they cannot contain any punctuation characters other than underscores. Also, you cannot use any of the keywords of the language such as: int, double, if, try, private, long, return, case, class, float, static, do, while, super… For a complete list of reserved words, see your textbook. Procedural Programming in C++ 24
  • 25. Primitive Data Types A variable is used to store a value in a computer's memory. The value could have one of several types. C++ supports a number of primitive data types: In C++, boolean and characters are represented as integers. The size of each type depends on the underlying implementation. That is one reason C++ programs are not portable. If you need to, you can use the Sizeof operator to get the size of any Variable. int x=90; cout<<sizeof(x); Outputs 4 on my machine. Procedural Programming in C++ 25
  • 26. Primitive Data Types 2 C++ has signed/unsigned types. The unsigned types don't allow storing negative numbers but use that extra sign bit to represent a larger positive value. Usually, they can represent numbers twice as big as the maximum their signed counterparts do. Characters are of type char; single quotes are used to denote char literals. C++ uses one byte for characters which can represent the ASCI characters. wchar_t however, uses 2 bytes and can represent Unicode. The bool type has two values: true and false. It is used with logical testing and in relational operators. 0 means false and anything else means true. You can declare a variable by specifying a data type followed by an identifier for the variable name as in: Procedural Programming in C++ 26
  • 27. Primitive Data Types 3 int aNumber; long aBigNumber; double aDecimalNumber; char myInitial; boolean myAnswer; After declaring a new variable, you should always initialize it using an assignment statement. C++ compiler does not force you to initialize your variables (like other strict languages such as Java), but using un-initialized variables is usually a programmer error: aNumber=250; aBigNumber=6965895; aDecimalNumber=256.3333; myInitial='K'; myAnswer=true; //could mean yes/positive Procedural Programming in C++ 27
  • 28. Primitive Data Types 4 When you assign a value of one type to a variable of different type, a cast (i.e. a conversion) occurs. C++ does not warn about possible data loss. In safe languages such as Java, the compiler does not allow you to assign a big value to a smaller variable. Procedural Programming in C++ 28
  • 29. Primitive Data Types 5 You can assign smaller data types to larger ones and they are safe. bool->short->int->long->float->double The reverse is not usually true and you have to have a good reason to do so. They usually represent logic errors in your programs and cause bugs that are hard to find. Above is the C-style casts and C++ has a more explicit casting syntax. See chapter three in the book (Thinking in C++) for a more in depth discussion. Unlike a variable, a constant's value cannot be changed. In C++, the keyword const is used to denote a constant: const double CM_PER_INCH=2.54; It's customary to name constants all in upper case. Constants are used to represent a value that does not change, for example if you wanted to use the PI value, which is 3.14, in a math program, you would not change the value. It is also good programming to use constants instead of literals. Can you think of a reason why this is the case? Procedural Programming in C++ 29
  • 30. Primitive Data Types 6 Contrary to constants are volatile variables. Normally, if you have a variables that does not change that much, the compiler may replace it with literals for optimization, but when marked as const other compiler never does any optimization. It is good for instances when the variable could be changed outside the scope of your program, such as a register coming from a hardware driver. Procedural Programming in C++ 30
  • 31. Your First Program The first program programmers of a new language learn is the "Hello World" program. We will keep with this tradition: As you see, the output is the just a line of text to the console. We will dissect the program in the following slides and create it in the lab. Procedural Programming in C++ 31
  • 32. Your First Program 2 The first two lines will be explained in greater detail later, but for a kick-start, they are: #include <iostream.h> makes available a library from C++ platform that contains all the input/output or i/o operators and objects, such as cin,cout,<< and >>. The second line contains the definitions of the names. Namespaces will be explained later in the course but for now, they are just a way of grouping a set of names together to prevent clashes with the same names used by other developers. The main method is where you put your statements to be executed by the system. Here we have only one statement that says, output the text "Hello World" to the screen follow it by a new line. Every statement must end with a semi colon (;) Every code block starts with an opening curly bracket and ends with a closing bracket. { } C++ is free form language, which means space is not counted and you can put as much space in your program as you like to increases readability. Procedural Programming in C++ 32
  • 33. Arithmetic Operators An expression is any combination of literals, variables, operators, and parentheses used to calculate a value. All the following are examples of expressions: 2 books (2 + 1) 1 – (Books + 10) As in mathematics, you can combine expressions using arithmetic operators. Usually, arithmetic operators come in between two expressions as in expression1 operator expression2 Or operand1 operator opreand2 Procedural Programming in C++ 33
  • 34. Arithmetic Operators 2 The operand can be either a single variable/number or a composite expression. The main arithmetic operators are the following: + for addition - for subtraction * for multiplication / for division % for division remainder - unary minus + unary plus-default not written All of these operators except the % can be used on floating point numbers and on integer numbers. However, the % operator is used on integral numbers. The operators behave differently when given different operands. For instance, / means "integer division" if both operands are integers, and means "floating point division" if one or both operands are floating point. Procedural Programming in C++ 34
  • 35. Arithmetic Operators 3 You should be careful when using the division operator /. When used with one or both operands of type double, the division operator behaves as you would expect. (Eg. 10/4.0=2.5) But when used with two operands of type int, the division operator / gives only the integer part of the division: 10/3 is 3 and not 3.333… Remainder Operator (%) The % operator can be used with operands of type int to recover the information lost when you use / to do division with operands of type int; for example: Procedural Programming in C++ 35
  • 36. Increment & Decrement Operators One of the most common operations with a numeric variable is to add or subtract 1. C++ has two operators for these common operations. To increment a variable: int x=0; x++; This would increment or increase the value of variable x to 1. Now to decrement a variable: int x=1; x--; This would decrement or decrease the value of variable x to 0. These operators cannot be applied to numbers themselves (literals). The following would be an illegal statement: 10++; You can only apply the operators to variables and the reason is obvious, you want to add one and store it back in its location. Literals are constants and are not variables. Procedural Programming in C++ 36
  • 37. Increment & Decrement Operators 2 There are two forms of these operators. The form you have seen is called the postfix form. The other form is the prefix form: ++x; --x; Both forms change the value of a variable by 1. The difference between the two only appears when they are used inside expressions. The prefix form does the evaluation first. The postfix form evaluates to the old value of the variable: Procedural Programming in C++ 37
  • 38. Relational Operators To test for equality of two variables or values, use the equality operator: (3==8); This expression evaluates to false. For inequality use the != operator: (2 != 7); Which evaluates to true. C++ also has the usual less than (<), greater than (>), less than or equal (<=) and greater than or equal (>=) operators. Here is the full list of relational operators and their equivalents in math: Procedural Programming in C++ 38
  • 39. Boolean Operators There is && for the logical "and" operator,|| for the logical "or" operator and ! for logical not operator. In evaluating Boolean expressions, uses Boolean Logic principles are used. You can combine two (or more) comparisons using the Boolean Logic "and" operator. For example, the expression (x>2) && (x <10) is true only if both (x>2) and (x<10) expressions are true. To remind you of the Boolean Logic truth tables: AND OR NOT X ! X true false false true Procedural Programming in C++ 39
  • 40. Short circuiting When dealing with logical operators, you run into a phenomenon called "short-circuiting." This means that the expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined. As a result, the latter parts of a logical expression might not be evaluated. Here's an example that demonstrates short-circuiting: As you can see from the output, the statement n++ did not et executed and that is why you see the value to be still 5. Procedural Programming in C++ 40
  • 41. Precedence Rules You can specify the order of operations using parentheses as illustrated in the following expressions: 1: (x + y) * z 2: x + (y * z) 1: the computer first adds x to y and then multiplies the result by z. 2: the computer first multiplies y by z and then adds the result to x. if you omit the parentheses, the computer will follow some rules of precedence. So, if you wrote x + y * z, the computer would multiply y by z and add the result to x. Because * has higher precedence than + (the same is true for / and %) It's always best to use parentheses as they remove any ambiguity and make the code much clearer to read and understand. Consult a textbook for a full listing of C++ precedence rules. Procedural Programming in C++ 41
  • 42. More Assignment Statements C++ has a shorthand notation that combines the assignment operator (=) and an arithmetic operator. For example: int hours=5; hours += 7; is equivalent to hours=hours + 7; That is, the new value of the variable hours is equal to its old value plus the number literal 7. We can use other arithmetic operators too: hours -=2; hours=hours-2; hours /=3; hours=hours/3; hours *=2; hours=hours*2; hours %=8; hours=hours%8; Procedural Programming in C++ 42
  • 43. Strings A string is a series of characters such as your name or telephone number. C used character arrays (more on arrays later) but they were very limited, error prone and difficult. C++ introduced the string class(data type) that makes life so much easy. We will talk more about string in later parts of this course, but their basic use if fairly easy. Just include string (or string.h) and you are good to Procedural Programming in C++ 43
  • 44. Strings 2 String is like any other data type we have seen (int, bool …etc), but it is not primitive which means, it is a class. Classes are created in Object Oriented languages. String objects, like s1, s2 and s3 on the previous slide have values, but they have behaviors'(methods) as well. We will see more on these concepts later, but for now, just look at this example: Procedural Programming in C++ 44
  • 45. Exercises Ex. 1) Write a program to ask the user for his/her name and then print out the name onto the screen. Ex. 2) Modify exercise 1 so that the program outputs the length of the user's name. Ex. 3) Write a program to ask the user for two names, first name and last name, and then concatenate the two names and output the full name. Ex. 4) Repeat exercise 3 but this time, have the user input his/her full name and you print fisrt name and last name separately. Ex. 5) What is the output of the following program: int x=0; cout<<x++<<endl; cout<<--x<<endl; Procedural Programming in C++ 45
  • 46. Flow of Control In the simple programs we have seen so far, the program consisted of a list of statements which were executed sequentially; one statement after another. There we did not specify any order for the program to follow. For bigger and more sophisticated programs, you will need some way to change the order in which statements are executed. The order in which statements are executed is called the flow of control. C++ has a number of mechanisms which let you control the flow of program execution. First, we will study a branching mechanism that allows you to choose between two alternative actions. Then we will discuss loops. Procedural Programming in C++ 46
  • 47. Branching (if-else statement) There is a statement that chooses between two alternative actions. it is called the if-else statement. in fact, there are two versions of this statement. We will discuss the first one as the second form is an extension of the first form. The general form of the if-else-statement is as follows: if (Boolean-expression) yes-statement else no-statement When program execution reaches the if-else-statement; only one of the two statements is executed, not both. if the Boolean-expression is true then the yes-statement is executed. if the Boolean-expression is false then the no-statement is executed. Procedural Programming in C++ 47
  • 48. Branching (if-else statement) 2 Suppose your program asks the user about the amount of time per week he/she spends on practicing programming. And you want the program to decide whether or not this is enough. Assume that 4 hours/week of practice is enough. Anything less is not good enough. Procedural Programming in C++ 48
  • 49. Branching (if-else statement) 3 Sometimes, your if statement does not have an else statement. In these cases, you are interested in conditionally executing a code based on truth/falsehood of a condition. Procedural Programming in C++ 49
  • 50. Branching (if-else statement) 4 In the previous slide, we only had one statement to execute, but if you had more than one statement, we had to put them in a set of curly braces { … } A list of statements enclosed inside brackets is called a compound statement. Procedural Programming in C++ 50
  • 51. Loops Sometimes you need to repeat an action several times, for example when you need to input names of a list of students. A section of a program that repeats a statement or group of statements is called a loop. C++ has a number of ways to create loops. One of them is called a while-loop. The following program shows how a while loop works: Procedural Programming in C++ 51
  • 52. Loops 2 In the example on the previous page, the section between the brackets { and } is called the body of the while-loop. This is the body (block of statements) that is repeated a number of times. Each repetition of the loop is called an iteration of the loop. If the user enters 0 at the keyboard, the loop body is executed zero times, that is, it is not executed at all. Because, the Boolean-expression is not satisfied and program execution proceeds with the following line after the while-loop. Note that you need some way to make sure that the loop ends at some point. Otherwise, the loop will run forever. It will be an infinite loop. In this example, we decrease a variable value after each iteration. We decrease it by 1 (decrement) after each iteration until the Boolean expression becomes false and the loop finishes. Procedural Programming in C++ 52
  • 53. Loops 3 As you know, a while-loop might execute its body zero times. If you know that under all circumstances your loop body should be executed at least once, then you can use a do-while loop. The do-while loop is similar to the while-loop, except that the loop body is executed at least once. Let's rewrite the previous example using the do-while loop note the semi colon after the while Same as before Different! Procedural Programming in C++ 53
  • 54. Infinite Loops A while-loop or do-while loop does not terminate as long as the boolean expression is true. This boolean expression normally contains a variable that will be changed by the loop body and the value of this variable eventually is changed in a way that makes the boolean expression false and therefore terminates the loop. However if you make a mistake and write your loop in a way that the boolean expression is always true, then the loop will run forever. (an infinite loop). On the next page we will write two loops, one that does terminate and one that does not terminate. Infinite loops are logic errors and does not get detected by compiler. The program just seems not responding and it never ends. Procedural Programming in C++ 54
  • 55. Infinite Loops 2 Write positive even numbers less than 12: int x=2; while ( x ! = 12) { cout<<x<<endl; x=x+2; } Write positive odd numbers less than 12: int x=1; while ( x ! = 12) { cout<<x<<endl; x=x+2; } Which is an infinite loop? Procedural Programming in C++ 55
  • 56. Programming Style All the variable names in our programs were chosen to suggest their use. We tried to use meaningful names for variable names. Also we laid out our programs in a particular format. For example, the declarations and statement were all indented the same amount. This is good programming as it makes our programs – easier to read – easier to correct, and – easier to change Indenting A program should be laid out so that elements that are naturally considered a group are made to look like a group. One way to do this is to skip a line between parts that are logically considered separate indenting can help to make the structure of the program clearer. A statement within a statement should be indented. Procedural Programming in C++ 56
  • 57. Programming Style 2 Also, the brackets {} determine a large part of the structure of a program. Placing each on a separate line by itself, as we have been doing, makes it easy to find the matching bracket. When one pair of brackets is embedded inside another pair, the inner pair should be indented more than the outer pair. Comments To make programs understandable, you should include some explanatory notes at important places in the program. Such notes are called comments. Most programming languages have this capability. In C family of languages, C, C++ and Java, the symbols // are used to indicate the start of a comment to the end of the line. These comments can be as long as a line only. If your comment spans more than one line, you can put them between an opening /* and closing */ symbols. Procedural Programming in C++ 57
  • 58. Programming Style 3 Unlike the // comments, which require an additional // on each new line, the /* to */ comments can span several lines. Your programs should always start with some comments like: //File name: hello.cpp //Author: Mr. Nice //Email: nice@yahoo.com //Description: Program to output Hello World //Last changed: 28 October 2000 Use comments sparingly; using two many comments is almost worse than no comments at all!. Spacing, indenting and comments are only for readability and not ready by the C++ compiler. They are not put in the compiled executable, so having more of them does not increase the size of the final program. They are only for human use. Procedural Programming in C++ 58
  • 59. Programming Style 4 If you are using some sort of IDE (and you should!), they have a way to format your code in a certain style. In Eclipse for example, you can format your code by pressing Ctrl+Shift+F to format your current file. If you have multiple files, you can select them in the left navigation view and click Source -> Format menu to format the selected files. You can comment or uncomment your code by selecting Toggle Comment sub-menu of the source menu. Also Eclipse provides a dictionary for auto-correcting your comments. So, if you misspell a word in your comment, eclipse can detect it and suggest a correction for you. Procedural Programming in C++ 59
  • 60. Exercises Ex. 6) What is the output of the following program fragment? int x=10; while (x > 0) { cout<<x<<endl; x=x-3; } Ex. 7) What output would be produced in the previous exercise if the > sign were replaced by <? Ex. 8) Write a program fragment to have the same output as Ex. 8 fragment but use a do-while loop this time. Procedural Programming in C++ 60
  • 62. Exercises Ex.12) The following if-else statement will compile and run without any Problems. However, it is not laid out in a way that is consistent with the other if-else statements we have used in our programs. Rewrite it so that the layout is clearer. if (x < 0) { x=7; cout<<"x is now positive.";} else { x =-7; cout<<"x is now negative.";} Ex.13) What is the output of the following program fragment? //this is not a comment /* cout<<"Hin"; does nothing cout<<"Hi againn"; */ cout<<"Hi againn"; //this is a comment /*this too is a comment*/ Procedural Programming in C++ 62
  • 63. Exercises Ex.14) Write a program fragment to display the numbers that are multiples of 4 between 0 and 20 inclusive. Ex.15) Write a program to ask the user for two whole numbers (int), calculate their addition, subtraction, multiplication, division, and molulus. Your program should display the results on the screen. Ex.16) Write a multiplication calculator program. This program will multiply numbers together and display the result on the screen. The program should keep asking the user for two numbers until the user enters the letter 's' for stop. Ex.17) Write a program fragment to check a student's grades for math and physics. If either the student's math grade is greater than 50 and the student's physics grade is greater than 60 then the program will output the word 'Passed' otherwise the word 'Failed'. Procedural Programming in C++ 63
  • 64. Exercises Ex.18) Write a program fragment that reads in a year (Ex. 1972) and checks whether or not this year is a leap year. Remember a leap year is a year that has 366 days. To be a leap year, one of the following conditions must hold: 1. The year is divisible by 4 but not by 100, or 2. The year is divisible by 400 Ex. 19) Write a program to add a list of numbers entered by the user. The user can stop the program by entering 0 when asked for the next number. Before it stops, it should print their addition and their average. Ex. 20) Rewrite Ex.21 program, but this time, the program should ignore even numbers. If the user enters an even number, your program will just ignore it; it will only accept odd numbers. Procedural Programming in C++ 64
  • 65. Multi-way if-else statements An if-else statement is a two-way branch. it allows a program to choose one of two possible actions. Sometimes, you will want to have a three- or four-way branch so that your program can choose between more than two alternative actions. You can do this by nesting if-else statements. For example: Procedural Programming in C++ 65
  • 66. Switch statement The if-else statement can be cumbersome when you have to deal with multiple selections. The switch-statement is another kind of statement that also implements multi-way branches. When a switch-statement is executed one of a number of different branches is executed. The choice of which branch is executed is determined by a control expression given in the parentheses after the keyword switch. The control expression must always evaluate to either a char or the integer types (byte, short, int). When the switch-statement is executed, this control expression is evaluated and the computer looks at the constant values given after the various occurrences of the identifiers case. if it finds a constant that equals the value of the controlling expression, it executes the code for that case. Let's look at an example involving a switch-statement: Procedural Programming in C++ 66
  • 67. Switch statement 2 Procedural Programming in C++ 67
  • 68. Switch statement 3 Notice that the constant is followed by a colon. Also note that you cannot have two occurrences of case with the same constant value after them since that would be an ambiguous instruction. A break-statement consists of the keyword break followed by a semicolon. When the computer executes the statements after a case label, it continues until it reaches a break-statement and this is when the switch-statement ends. Procedural Programming in C++ 68
  • 69. Switch statement if you omit the break-statement, then after executing the code for one case, it goes on to execute the code for the following case. The grades 50 and 30 cause the same branch to be taken. if the value of grade is anything other than 100, 80, , 60, 50, 30 then the output statement after the identifier default is executed. However, the default case is optional and can be omitted. When program execution reaches the break statement, the switch statement is exited and program execution follows the switch statement. The break statement has other uses, other than switch statement. It can be used to exit out of a loop before its exit condition is met. Say, for example, you want to break out of a loop when a special input is encountered. See an example on the next page: Procedural Programming in C++ 69
  • 70. The break statement Notice that we have used while(true) which is in itself an infinite loop, but in the body of the loop, we are checking for zero to quit the loop using a break statement. This program keeps accepting numbers from the keyboard till it gets zero. It then quits the loop and prints the result of the summation. Procedural Programming in C++ 70
  • 71. The continue statement While break statement terminates the loop, continue statement only terminates the current iteration of the loop. If the loop has more iterations, they will be executed. Let’s rewrite the previous example, but this time, we ignore any number that is a multiple of 3. Procedural Programming in C++ 71
  • 72. The continue statement Note that the sum does not take into account 3 and 9 in the first run of the program, and 12 and 15 in the second run. Procedural Programming in C++ 72
  • 73. For loop The while-statement and the do-while statement are all the loop mechanisms you need. In fact, the while-statement alone is enough. But there is one kind of loop that is so common in programming that we have a special syntax for it. In performing numerical calculations, it is common to do a calculation with a sequence of numbers. For example to add the numbers 1 through 10 you want the computer to perform the following statement ten times with the value of n equal to 1 the first time and with n increased by one each subsequent time. sum=sum + n You can do this with a while loop or even a do-while loop. But as you will see shortly, it becomes so much easier to do this operation with a for-loop. Basically, if the number of iterations is known before hand, for-loop is the most elegant way. It also makes a good choice for looping through array elements, as we will see later in the course. Procedural Programming in C++ 73
  • 74. For loop 2 The following is one way to accomplish this with a while statement: sum=0; n=1; while (n<=10) { sum=sum + n; n++; } Although a while-loop is OK here, this kind of situation is just what the for-loop was designed for. The following for-loop will neatly accomplish the same thing: sum=0; for (int n=1; n <= 10; n++) sum=sum + n; Procedural Programming in C++ 74
  • 75. For loop 3 An example involving a for-loop: int sum=0; initialization repeat the loop as long as this is true for ( int n=1; n <= 10; n++) { sum = sum + n; } done after each loop body iteration cout<<" The sum of the numbers 1 to 10 is : “; cout<< sum; Procedural Programming in C++ 75
  • 76. Goto statement Goto has been around from the beginning of programming languages. It a tool programmers have misused to create what we call "spaghetti code". It could create very unstructured code and flows of control that were extremely hard to follow and debug. In fact, what loop is doing can be done using if statement and goto. See the example and its output: Although goto is very much discouraged, it can be very useful to break out of deeply nested loops. As we know, break/continue only take the innermost loop into account. See example in the next slide: Procedural Programming in C++ 76
  • 77. Goto statement … And the output will be: Procedural Programming in C++ 77
  • 78. Exercises Ex.23) Write a multi-way if-else statement that classifies the value of an int variable n into one of the following categories and writes an appropriate message: n < 0 or 0 <= n <= 100 or n > 100 Ex.24) What is the output of the following fragment: int count=3; while (count-- > 0) cout<<count << " n"; Ex.25) What is the output of the following fragment: int count=3; while (--count > 0) cout<<count << " n"; Procedural Programming in C++ 78
  • 79. Exercises Ex.26) What is the output of the following fragment: int n=1; do cout<<n << " n"; while (n++ <= 3); Ex.27) What is the output of the following fragment: int n=1; do cout<<n << " n"; while (++n <= 3); Ex.28) What is the output of the following fragment: for (int count=1; count < 5; count++) cout<<(2 * count) <<" n"; Procedural Programming in C++ 79
  • 80. Exercises Ex.29) For each of the following situations, tell which type of loop would be better: a. summing a series, such as ½ + 1/3 + ¼ + … +1/10 b. inputting the list of exam marks for one student Ex.30) Rewrite the following code as a for-loop: int i=1; while ( i <= 10) { if (i < 5 && i !=2) cout<<'X'<<endl; i++; } Procedural Programming in C++ 80
  • 81. Exercises Ex.31) Rewrite the following code as a for-loop: int i=1; while ( i <= 10) { cout<<'X'<<endl; i = i + 3; } Ex.32) Rewrite the following code as a for-loop: long m=100; do { cout<<'X'<<endl; m = m + 100; }while ( m <= 1000); Procedural Programming in C++ 81
  • 82. Arrays An array is a collection of variables all of the same data type that are referred to by a common name. A specific element in an array is accessed by an index. Array elements are stored in contiguous memory locations. The lowest address refers to the first element and the highest address refers to the last element. Further, array sizes are fixed; once you create an array you cannot change its size. C++ supports dynamic arrays with pointers and it will be covered later. For example, to store a list of exam marks for students we can use an array like this: int marks[5]; This array is of type integer and it can hold 5 variables of type integer. 'mark' is the name of this array. Procedural Programming in C++ 82
  • 83. Arrays 2 The array declaration (similar to variable declaration) on the previous slide is equivalent to the following declarations: int mark1, mark2, mark3, mark4, mark5; You can see that the array notation is clearer and more elegant. The statement int mark[5; creates an array of type integer that can store 5 variables all of type integer. Array elements are numbered from 0. That is, the index of the first element in the array is 0 and the index of the last element is one less than the size of the array. ( in this example, first element has index 0 and last element has index 4) Now you can use array elements like any other variable: marks[0]=75; //puts 75 in the first location marks[4]=82; //puts 82 in the last location cout<<marks[4]; //prints the the last element which is 82 Procedural Programming in C++ 83
  • 84. Arrays 3 One way to create and initialize an array at the same time is like this: int mark[5] = { 87, 67, 90, 89, 100}; The size of this array is 5. The size of the array need not be declared if it can be inferred from the values in the initialization: int mark[ ] = { 87, 67, 90, 89, 100}; To access array elements we use the array name plus the index of the required element. For example to assign 64 to the fourth element: marks[3]=64; And to print the last element: System.out.println(mark[4]); Note that valid array index values are 0 to one minus the length. Accessing array elements outside the valid indexes is logic error. Procedural Programming in C++ 84
  • 85. Arrays 4 The following program creates a 5-element array and initializes the array elements using user input and shows the values afterwards: Note how natural it is to use for loop when working with array elements. Another thing you need to be aware of is lteral values for array size. Always use a a constant. See the next slide for an improvement in this program using a constant. Procedural Programming in C++ 85
  • 86. Arrays 5 The following program is exactly the same as the one on the previous slide, but it is far more readable and extensible just by using the constant instead of literal 5: Now if you decide to change the elements of the array from 5 to 10, only the declaration of the const int SIZE=5 has to change, but in the old version, you would have to change the value in 3 places. Procedural Programming in C++ 86
  • 87. Arrays 6 Array indexed variables are stored in memory in the same way as ordinary variables are stored. But with arrays, the locations of the array indexed variables are always placed next to one another in the computer's memory. For example consider the following array declaration: int marks[5]; When you declare this array, the computer reserves enough memory to hold 5 variables of type integer and the computer always places these variables one after the other in the memory. The computer then remembers the address of the indexed variable mark[0], but it does not remember the address of any other indexed variable. When your program needs the address of some other indexed element the computer calculates the address of this other element from the address of mark[0]. Procedural Programming in C++ 87
  • 88. Arrays 7 The most common programming error made when using arrays is attempting to reference a non-existent array index. For example consider the following array declaration: int marks[5]; For this array, every index must evaluate to one of the integers between 0 and 4. if you write: cout<<mark[i]; Then i must evaluate to one of: 0, 1, 2, 3, 4. If it evaluates to anything else it is an error. This is a logic error and can't be detected by C++ compiler. It even is not caught by the runtime and you will get whatever value is in that location. Errors like this produce bugs that are very hard to find and fix. You can calculate the length of an array by using the sizeof operator. Dividing the total bytes for the array by bytes of one of the elements gives you the length. Procedural Programming in C++ 88
  • 89. Exercises Ex.33) In the array declaration double score[6]; what is the a. the array name b. the base type c. the declared size of the array d. the range of indexes that are OK for accessing the elements e. one of the indexed variables (or elements) of this array Ex.34) What is the output of the following code fragment: char symbol[]= { 'a', 'b', 'c','d'}; for (int index =0; index<4; index++) cout<<symbol[index]; Procedural Programming in C++ 89
  • 90. Exercises Ex.35) What is the output of the following fragment: double a[] = { 1.1, 2.2, 3.3}; cout<<a[0] <<" " << a[1] << " " << a[2]; a[1]=a[2]; cout<<a[0] <<" " << a[1] << " " << a[2]; Ex.36) What is wrong with the following piece of code: int array1[10]; for (int index=1; index <= 10; index++) array1[index]=index; Ex.37) Write a program to fill an array with 5 values of type integer from the keyboard. The program should also output the square and square root of each array element next to it like a table. Procedural Programming in C++ 90
  • 91. Exercises Ex.38) Which of the following is NOT the name of a primitive data type? a. int b. float c. double d. string Ex.39) In which of the following answers does the number of bytes increase from fewest (on the left) to most (on the right)? a. byte long short int b. int byte short long c. byte short int long d. short byte long int Ex.40) Which one of the following is NOT a correct variable name? a. 2bad b. zero c. theLastValueButOne d. year2000 Procedural Programming in C++ 91
  • 92. Exercises Ex.41) Which one of the following declarations is NOT correct? a. double duty; b. float loan = 84.6; c. boole value = 12; d. int start = 34, end = 99; Ex.42) Which of the following shows the syntax of an assignment statement? a. variableName = expression; b. expression = expression; c. expression = variableName; d. dataType = variableName; Ex.43) What are the two steps that take place when an assignment statement is executed? a. (i) Evaluate the Expression, and (ii) Store the value in the variable. b. (i) Store the value in the variable, and (ii) Evaluate the Expression. c. (i) Reserve memory , and (ii) fill it with a number. d. (i) Evaluate the variable, and (ii) store the results. Procedural Programming in C++ 92
  • 93. Exercises Ex.44) Which of the following expressions is incorrect? a. (34 - 86) / 3 b. (34 - 86) / -3 c. 34 - 86) / (23 - 3 ) d. ( (34 - 86) / (23 + 3 ) ) Ex.45) . What is the result of evaluating the following expression? ( 1/2 + 3.5) * 2.0 a. 8.0 b. 8 c. 7.0 d. 0 Ex.46) How many choices are possible when using a single if-else statement? a. 1 b. 2 c. 3 d. 4 Ex.47) A sequence of statements contained within a pair of braces ("{" and "}") is called a: a. Block b. Blob c. branch d. brick Procedural Programming in C++ 93
  • 94. Exercises Ex.48 What three parts of a counting loop must be coordinated in order for the loop to work properly? a. initializing the counter, testing the counter, changing the counter b. initializing the condition, changing the condition, terminating the loop c. the while, the assignment, and the loop body d. the while statement, the if statement, and sequential execution. Ex.49) Which of the following situation most likely does NOT call for a counting loop? a. Adding up all the integers between zero and one hundred. b. Writing out a table of Fahrenheit and Celsius temperature equivalents. c. Prompting the user of a program until the user responds with correct information. d. Making the computer beep ten times. Procedural Programming in C++ 94
  • 95. Exercises Ex.50) What is the meaning of variable++ ? a. Add one to the variable. b. Add one to the variable after its current value has been used. c. Add one to the variable before using its value. d. Double the value in the variable. Ex.51) What does the following print on the monitor? for ( int j = 0; j < 5; j++ ){ for ( int k = 0; k < 10 ; k++ ) cout<< "*" ; cout<<endl; } Procedural Programming in C++ 95
  • 96. Exercises Ex.52) What is the output of the following code fragment: int[] arr = {2, 4, 6, 8 }; arr[0] = 23; arr[3] = ar[1]; cout<<arr[0] <<" "<< arr[3] ; Ex.53) What is the output of the following code fragment: int z[9]; z[0] = 7; z[1] = 3; z[2] = 4; cout<< z[0] <<" "<< z[1] << " " << z[5] ; a. 1 0 0 b. 7 3 0 c. 7 3 4 d. The program is defective and will not compile. Procedural Programming in C++ 96
  • 97. Methods A natural way to solve large problems is to break them down into a series of smaller sub-problems, which can be solved more-or-less independently and then combined to arrive at a complete solution. The programs we have written and seen so far have been too small to break them down into smaller units. When programs get bigger, you should break them down or divide them into smaller sub-programs. C++ lets programmers break down complex programs into smaller units. These units are called functions (but called methods at times). You have already seen method definitions. The most famous one is the main method which is required for any program to be run by the operating system. Consider a simple method that if you give it two numbers, it will give you the one that is bigger, so in other words, it will return the max of two numbers. Procedural Programming in C++ 97
  • 98. Methods You have already seen methods such as sqrt() to get the square root of a number. This method is from math.h library. There are many more functions from that library such as ceil() that rounds a number to the next larger integer and floor() that rounds down to the next smaller integer. For example: These are examples of pre-defined methods that we can use in our programs. Somebody else has defined them; we just use them and we even don't need to know how they are defined as long as we know how to use them. You can write your own method too. Let's write a method to return the max of two numbers: Procedural Programming in C++ 98
  • 99. Methods See how we use max just like ceil and floor methods from math.h. Also note that, we have to put the method definition above main so it is before its use inside main. We will get back to this issue later. Procedural Programming in C++ 99
  • 100. Methods The method body checks the 2 numbers and makes max equal to the one that is bigger. It then uses return statement to return the larger value. Now you can call this method from inside your program and from other methods you define. You can call this method as many times as you like. A few notes about method: • The structure of a method is similar to the structure of main, with its own list of variable declarations and statements. • A method may have a list of zero or more parameters inside its brackets, each of which has its own type. • Method declarations are a bit like variable declarations; they specify which type the function will return. • You can define as many functions as you require provided you declare them first. Procedural Programming in C++ 100
  • 101. Methods Breaking down functions makes programming easier to write and maintain. Now you can use that function many times in your main method. See in the following example how you can use max function to find the maximum of any number of integers, not just two. Procedural Programming in C++ 101
  • 102. Methods See how using the function made possible breaking down the problem of finding the maximum of 4 numbers by finding max of w,x first and then y,z. After that, the maximum of the results of the previous calls are used to find the maximum of all. The idea is very much similar to eliminating teams in sports tournaments. The method max is called from the main method to add find the maximum of w and x. When the method is called, two parameters are passed to this method w and x; the method is then executed and returns a value (6 as its bigger than 2). The result is then stored in the variable t1. Same thing for y, z and t2. After the method max returns, program execution continues on the line following the method-call line. Of course, for a simple program like this you would not write a method. This example was for demonstration only. Procedural Programming in C++ 102
  • 103. Methods Lets write another method to test if a number is even or not: Procedural Programming in C++ 103
  • 104. Methods And the output is: Procedural Programming in C++ 104
  • 105. Methods Although methods with return values are the most common, not all methods return a value. A method that does not return a value should have a return type of void. Void means nothing. In fact you have already seen such a method. (?) Her is an example: public void about(){ cout<<"My Simple Video Game"<<endl; cout<<"Version 2.2"<<endl; cout<<"Copyright 2008-2012 "<<endl; } In your porgram, you could have the method above and use it any time the user clicks (or selects) help->about menu. Without method, you would have this code repeated many times. Since void methods have no return values, you cannot use them on the right hand side of an assignment statement. Beware. Procedural Programming in C++ 105
  • 106. The Black Box A person who uses a program should not need to know the details of how the program is coded. That person should know how to use the program but not how the program works. A method is like a small program and should be viewed in a similar way. A programmer who uses a method needs to know how to use the function but not how the function does its job. This is what is meant when viewing a function as a black box. Writing methods so that they can be used as a black boxes is sometimes called information hiding or procedural abstraction. The word procedure is a general name for methods. The word abstraction is intended to convey the idea that when you use a method as a black box, you are abstracting away the details of the code in the method body. When we used the methods length() or round(), we did not know how they worked. We just used them. This is important. Details, although important, can be put aside for a later time. Procedural Programming in C++ 106
  • 107. Variable scope Variables declared inside a method exist only during the method call. Variables declared inside methods are called local variables. The scope of a local variable is the method inside which that variable is declared. It doesn't exist outside that method. As a general rule, the scope of any variable is the next closing brace } that comes after it. For example, if you declare a variable inside a loop, it is not visible after the loop's block is closed }. while(n-->0){ int x=n*n; cout<<x<<endl; } x=2;//this is a compiler error. Variable x is //not defined at this scope. Procedural Programming in C++ 107
  • 108. Variable shadowing Since variables are visible in their scopes, when a variable is defined in a schope and a variable with the same name exists in an outer scopes, the newly defined variable is said to shadow the outer schope variable. See this example: Procedural Programming in C++ 108
  • 109. Variable shadowing The output of the program on the prev slide is: As another example, see: Procedural Programming in C++ 109
  • 110. Exercises Ex.54) Write a method to find the smallest number in an array of type int. Declare the array size to be 7 and fill the array from the keyboard. The method should take the array as a parameter and return the smallest number as the return value. Test the method in a complete program. Ex.55) Write a method to find the index of the smallest number in an array of type int. Declare the array size to be 7 and fill the array from the keyboard. The method should take the array as a parameter and return the index of the smallest number as the return value. Test the method in a complete program. Note the difference between these two methods. One returns a number (value) and one returns an index of an array. This last exercise will be used as a basis for another exercise later. Procedural Programming in C++ 110
  • 111. Exercises Ex.56) Write a program that takes 2 dates and then calculates the number of days between those 2 dates. The program asks the user for two dates (day, month, year) and then passed this information to a method to calculate the number of days between them. Ex.57) From school you know that the standard quadratic equation ax2 + bx + c = 0 has two solutions given by formula Write a function that reads a, b and c and then calculates the two solutions. If the quantity under square root is negative it should display an appropriate message. You may assume that the value for a is nonzero. Procedural Programming in C++ 111
  • 112. Exercises Ex.58) Write a method that takes a string parameter and returns the reverse of that parameter string as its return value. Ex.59) Write a method that takes a string as a parameter and checks if the parameter string a palindrome or not. A palindrome string/word is a word that writing it in the reverse gives the same word; like the word "radar" or "noon". Ex.60) C++ does not have an operator for raising numbers to a power. Assume the method declaration like this: double power(double num1, double num2){ //your code goes here } This method raises num1 to the power of num2. Finish the method above and test it in main to make sure it works as required. Procedural Programming in C++ 112
  • 113. The & (address of) operator When your program is run, it is first loaded into memory; which means, it is placed somewhere in the computer's memeory which also means all the elements of your program (variables, functions …etc) will have an address. If you want to know the address of anything, just precede it with the & operator. For example, &i means the address of i. See the example: Procedural Programming in C++ 113
  • 114. The & (address of) operator Note that the variables i and j are placed next to each other but it is not predictable where these locations are. Also note that changing a variable does not change its location(address), only the value stored at that address. You may be rightfully wondering 'why do I need to know where a variable is located in memory?'. Well, in most cases you don't need to know, but sometimes, you do. See the example: Procedural Programming in C++ 114
  • 115. The & (address of) operator The problem we are facing is that: whenever we call a method (function), C++ makes a copy of the parameters we pass (i and j in our case) and the function works on these copies. Whatever the function does to these variables such as chaning them, swapping them …etc is not made to the actual variables we intented. In such situations, we need to modify our program so that it works on the actual variable not a copy of it. To rewrite our program with the & operator: Procedural Programming in C++ 115
  • 116. Pointers As you noted, changing the method swap to take address of integer void swap(int &x,int &y) changes the actual variables (i and j, swaps them). This is very important in some algorithms such as sorting when we want to swap to numbers when they are out of order. We will come back to sorting later. The address operator (&) is also called a references since it refers to a memory location. In the example above, we passed the address of a variable to a method, but is this all we can do with addresses? The answer is "NO". We can store the value in another variable. This variable has a special type called a pointer. To create a pointer that can point to an integer, we use int* p; Now, you can have p (a pointer to an integer) point to an actual integer, say a int a=25; p=&a; Now, you can manipulate the variable a via a as well as p. See the example on the next slide. Procedural Programming in C++ 116
  • 117. Pointers The output: Procedural Programming in C++ 117
  • 118. Pointers Now let's rewrite the swap function using pointers. As you note, the function takes pointers to integers and we pass it addresses of our integers (i and j) Procedural Programming in C++ 118
  • 119. Pointers A few notes about pointers: You can create them alternatively as int *p; You can create more than one pointer like: int *p1,*p2,*p3; You can assign addresses of a variable to an integer as in: int a=25,*p=&a; cout<<*p<<endl;//should output 25 You can create pointers that point to other data types such as long, bool, char …etc. double *d1; double d=3.5; d1=&d; Plus some relationship to arrays that will be explained in the next few slides. Procedural Programming in C++ 119
  • 120. Arrays and pointers As we said earlier, an array is just the address of the fist element. Since we can print addresses of variables, we can prove that: Outputs : The output is in hexadecimal, but you can see that both a and the address of a[0], the first element of the array, are the same. Remember, we said that when you create an array, the size is fixed and you can't change it. Also know that arrays are a read-only pointer and you can't change them. But with pointers, you can create dynamic arrays. int *p, size; cin>>size; //get the size from keyboard p=new int[size]; //use p like an ordinary array delete [] p; //you have to release the memory Procedural Programming in C++ 120
  • 121. Sorting So far, we have looked at quite a lot of topics. Variables, methods, arrays and pointers. It is time to look at making use of such topics to solve a problem. At the end of the day, we learn programming languages so that we can solve problems. The goal of the next few slides is walking you through the steps of solving a common problem. When presented with a problem, the first thing is to really understand what the problem is. After that, a systematic solution needs to be created so that a computer can perform the solution. It is usually easier (and a very essential problem solving skill) if one can divide a big problem into smaller sub-problems that can be solved more or less independently. This technique is called Divide and Conquer. In addition to that benefit, divide and conquer also supports team work by allowing programmers to solve parts of the problem and getting to the final solution by putting together these parts of the solution. Procedural Programming in C++ 121
  • 122. Sorting 2 One of the most common programming tasks is sorting a list of values from highest to lowest or vice versa or a list of words into alphabetical order. There are many sorting algorithms; some are easy to understand but not so efficient while some are efficient but hard to understand. One of the easiest sorting algorithms is called selection sort. The selection sort algorithm works as follows: for( int i=0; i<array_length; i++) Place the ith smallest element in a[i] Where a is an array and array_length is the declared size of the array. Algorithms are usually expressed in pseudo-code. Procedural Programming in C++ 122
  • 123. Sorting 3 The algorithm iterates through all the elements of the array one by one and at each iteration it places the smallest number of the array in the next suitable position. Now we will implement this algorithm description in C++. We need functionality/methods to do the following: To find the smallest number in the array(or the location of the smallest value in an array) To swap two values To sort the array We will now implement each of these methods separately and then write a main method to test the methods. For example, if I have the array [9,3,7,2,4], the selection sort routine would go through the following sequence of steps: Procedural Programming in C++ 123
  • 124. Sorting 4 9 3 7 2 4 2 3 7 9 4 Swap minimum of all five elements with first element 2 3 7 9 4 Swap minimum of last four elements with second element 2 3 4 9 7 Swap minimum of last three elements with third element 2 3 4 7 9 Swap minimum of last two elements with fourth element Here is the code for the method that sorts the array. Look, it uses two other methods to do its work. Procedural Programming in C++ 124
  • 125. Sorting 5 Now we will implement the function which will find the index of the next smallest element of the array (note how the array was passed to method index_of_min in the previous slide; you just give the array's name. Procedural Programming in C++ 125
  • 126. Sorting 6 Now, the last method that swaps two numbers in an array. We just give the two indices to the method and it will swap what is located at those locations. Note how we have commented the methods above this helps other programmers understand the intent of the method. It is essential that programmers don't have to understand a method to use it. Procedural Programming in C++ 126
  • 127. Sorting 7 Using these methods in a main method would look like this: In the lab, put all the methods we described above in one class and run it. Test it with a few different arrays and see if it works. Also not that we are using a method to_string that takes an array and returns a string representation of it. See next slide for that method too. Note that we did not have to know how it works to be able to use it. That is why we call method a black box. Procedural Programming in C++ 127
  • 128. Sorting 8 See this method and not how it uses string stream from sstream that must be included as #include <sstream> Procedural Programming in C++ 128
  • 129. Managing Separate Compilations If you have tried the sorting exercise in the lab (or at home), you probably have run into problems such as: In which order should I define my methods? For example, we defined swap first, then index_of_min, then sort and finally to_string. This was deliberate because in C++, you have to define a method before you can use it. So, the order at which we defined our method was crucial to get our code to compile successfully. Suppose now, if you wanted to call to_string inside the method sort! It gives you a compile error because to_string is defined after sort. So, what is the solution? The solution is separating the method declarations from method definitions. Method declaration is only the method signature: return type, method name and parameter list. Once we declare the methods, we can define them in any order and call any one of them from any other. This separation is very elegant as we will soon see and it will solve other problems not just the method ordering problem. Procedural Programming in C++ 129
  • 130. Managing Separate Compilations Another problem is often that we can not put all our code in one single file. A relatively small application may compose of a few thousand lines of code! Imagine having all of this code in a giant single file! It does not seem right as it is too big to be compiled, maintained, transmitted (or deployed) every time we make even the slightest change in the program. The problem is also that programs in practice often are developed by groups of developers and having everything in one monolithic file is by no means a solution. There have to be better ways; in fact there is: Separating compilation units(files). Code for useful and commonly used methods is put in files called libraries and included by different applications. For example, we could have created a library of our sort methods given them to two different groups of developers to use it in their applications just by including it very much the same way you include iostream or math libraries. In practice, there is no difference between system libraries such as iostream and libraries you create except for the location you put the libraries and also the way you include them. System libraries are included like <iostream> but user libraries are include like "sort-functions.h" Procedural Programming in C++ 130
  • 131. Managing Separate Compilations The common practice is to place all method declarations in a header file identified by a .h extension. The definition of those methods is put in a normal .cpp file with the .h file included. At runtime (or just before runtime), a special program called a linker links the method definitions to their implementations.: Now, let's re-write our sort code in this way and divide it into header file, source file and application file. First see the example in its old state, which everything in one file: Procedural Programming in C++ 131
  • 132. Managing Separate Compilations Let's see how converting the above project into a project with a few separate files can be achieved: Procedural Programming in C++ 132
  • 133. Managing Separate Compilations Procedural Programming in C++ 133
  • 134. Managing Separate Compilations Procedural Programming in C++ 134
  • 135. Managing Separate Compilations Procedural Programming in C++ 135
  • 136. Managing Separate Compilations Take special note the highlighted code: we have include the "sort-library.hi" (the function definitions header file) in both files. First in the implementation of the functions (we called them sort-impl.cpp ) and in the application that used the sort library to sort an array of integers in its main (sort.cpp) This this structure in place, we can have a groups of developers work on the same project, each on a sub-part of the bigger problem. This way, the compilation units are smaller and more manageable and can be developed more or less independently. If one developer needs to use another developer's methods, all he/she needs to have is the header function included. Procedural Programming in C++ 136
  • 137. Managing Separate Compilations Java also comes with several sorting tools for arrays which you can use without defining your own algorithms. You could use the following pre-defined Java sorting methods for sorting primitive data type arrays in ascending order: void sort(byte[] a); void sort(short[] a); void sort(char[] a); void sort(int[] a); void sort(float [] a); void sort(double[] a); To use these pre-defined methods, you must import the package to which they belong. All these and many more methods are defined in the class Arrays, in the package java.util. Procedural Programming in C++ 137
  • 138. Exercises Ex.61) Write a predicate function (whose return value is either true or false) that takes an int array as a parameter and returns true if the array is sorted in ascending order. Test your function in a program. Ex.62) You can sort an int array by following the following procedure: Start by going through the array, looking at adjacent pairs of values. If the values of a pair are correctly ordered, do nothing; if they are out of order, swap them. In either case move on to the next pair. The pairs overlap so that the second element of the a pair becomes the first of the next pair. Repeat this operation until you make a compl-ete pass in which you do not make an exchange or swap of values. This algorithm is called the bubble sort, because the values seem to bubble up to their eventual positions. Procedural Programming in C++ 138
  • 139. Multi-dimensional Arrays In Java, the elements of an array can be of any type. In particular, the elements of an array can themselves be arrays. Arrays of arrays are called multidimensional arrays. The most common form of a multidimensional array is a two-dimensional array which is similar to a rectangular structure divided into rows and columns. This type of two-dimensional array is called a matrix. You can have arrays of 3 or more dimensions. But they are less common. Consider the two-dimensional array as a mattrix: //two rows, three columns int[][] matrix=new int[][]{{2,2,2}, {2,2,2}}; This is an array (size 2) of two arrays (size 3). Procedural Programming in Java 139
  • 140. Multi-dimensional Arrays 2 When defining multi-dimensional arrays, like ordinary arrays, you can put the array size if you provide an initializer list. The following will be an error: int[][] matrix=new int[2][3]{{2,2,2}, //this will not {2,2,2}};//compile A couple of more examples defining two dimensional arrays: Procedural Programming in Java 140
  • 141. Multi-dimensional Arrays 3 We will now look at an example involving two-dimensional arrays; in this example we will write a method to add 2 matrixes. Procedural Programming in Java 141
  • 142. Multi-dimensional Arrays 4 Procedural Programming in Java 142
  • 143. Multi-dimensional Arrays 5 The output of the previous example is as follows: Procedural Programming in Java 143
  • 144. Multi-dimensional Arrays 6 For multi-dimensional array parameters and return types, as for arrays, dimension sizes should not be given. This makes sense if you think of a multi-dimensional array as an array of arrays. In this example we have an array each element of which is an int array. Remember that if you have an array parameter, you do not have to specify the array size in the square brackets. Multi-dimensional arrays are mainly used to perform matrix operations and numerical analysis calculations. The base type of a multi-dimensional array can be any type; but for numerical calculations the type is usually int or double. In the example on the previous page, we saw how to add two matrixes. You can also do other matrix operations like matrix multiplication, matrix transformations using two-dimensional arrays. Procedural Programming in Java 144
  • 145. Multi-dimensional Arrays 7 As with ordinary (1-dimensional arrays), the following two 2D-array declarations are equivalent: int[][] myArray = new int[3][5] ; and int[][] myArray = { {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} }; The length of a 2D-array is the number of rows it has. For example: int[][] uneven = { { 1, 9}, { 0, 2}, { 0, 1} }; System.out.println("Length is: " + uneven.length ); Procedural Programming in Java 145
  • 146. Exercises Ex.63) Write a method that has one parameter of type int array[][]. The function multiplies its parameter by the unit matrix and prints the result. Test your method in a Java program. Ex.64) Write a method that takes two parameters of type int[][] and then multiplies the two matrixes together and writes the result in a third matrix. Test you method in Java program. Note: You can multiply a matrix nXm only by a matrix that is mXn. Ex.65) Write a method that takes a parameter of type int a[5][5] and changes the value of every element above the diagonal to 0. Ex.66) Write a method that takes a parameter of type int[][] that is a square matrix mXm. and exchanges the elements above and below the diagonal together but leave the diagonal values unchanged. Procedural Programming in Java 146
  • 147. Writing to Files So far we have learnt how to input data from the keyboard and output data to the screen. But for many real problems we need to be able to input data from a file and output date into a file. I/O from and into files can be done using Java streams. Input streams for data input from a file/keyboard/network… and output streams for output to a file/screen/printer/network… You have already used some kinds of streams: System.in (an input stream) which is connected to the keyboard and System.out (an output stream) which is connected to the screen. The main reason behind using I/O streams is because keyboard input and screen output deal with temporary data. When the program ends the data typed in at the keyboard and the output data to the screen is lost. Files provide you with a way to store data permanently. Procedural Programming in Java 147
  • 148. Writing to Files 2 When your program takes input from a file it is said to be reading from the file and when your program sends output to a file it is said to be writing to the file. Usually when reading from a file, your program starts reading from the beginning of the file and when writing to a file it starts writing to the beginning of the file. A stream is a special kind of variable known as an object. Note that errors are very common when dealing with I/O operations, because the program has to deal with the external environment. In the following example, we will write a program that opens a specific file (if the file does not exist, it will create a new file) and then output a few lines of text to the file. Procedural Programming in Java 148
  • 149. Writing to Files 3 import java.io.*; public class WriteTextFile { public static void main ( String[] a) throws IOException { String fileName = "myFile.txt" ; //Following 2 line: open a text file called "myFile.txt FileWriter writer = new FileWriter( fileName, true); PrintWriter out=new PrintWriter(writer); out.println( "Line 1" ); out.println( "Line 2" ); out.println( "Line 3" ); out.println( "Line n" ); out.close(); } } Procedural Programming in Java 149
  • 150. Writing to Files 4 First we import the java.io package which contains definitions of input/output operations. The statement throws IOException is necessary for I/O operations. It deals with errors or exceptions. We will cover exceptions later; for now, just use this statement every time you use I/O streams. Then we create a string variable to represent a filename. The two bold lines open a text file called "myFile.txt" and if it does not exist, a new file with that name will be created in the current directory. You don't need to understand the details of these two statements. They will be explained later. The two lines can be combined into one line: PrintWriter out=new PrintWriter(new FileWriter(filename, true); If you leave out (or change it to 'false') the second parameter 'true' in the first bold statement, every time you run this program, your file will be overwritten. Procedural Programming in Java 150
  • 151. Writing to Files 5 Notice how the method println works with the variable out. Since out is an output stream like System.out, you can use this method the way you use it to output to the screen. The close() method should always be used when a program is done with a file. If a file is not closed, the program might end before the operating system has finished writing data to the file. The data written to the file might be lost! The method print or println can be used to output any data type to the output stream: void print(int i); Void print(char c); Void print(boolean b); Void print(double d); Void print(String s); and a few more… Procedural Programming in Java 151
  • 152. Reading from a File Now that we can output to a file, lets see how we can read or input from a file. Reading from a text file is as important as writing to a file. For this we first create an input stream and connect it to a file on the disk: BufferedReader in=new BufferedReader(new FileReader ("myFile.txt")); As we saw on page 115, the above step could be written in two lines: FileReader reader=new FileReader("myFile.txt"); BufferedReader in=new BufferedReader(reader); You can choose either. Again, don't worry if you don't understand the details of the above statements. We will cover them later. On the next page, we write a program that outputs all the contents of a file to the screen. Procedural Programming in Java 152
  • 153. Reading from a File 2 import java.io.*; class ReadTextFile{ public static void main(String[] args) throws IOException { String fileName = "reaper.txt" ; String line; BufferedReader in = new BufferedReader(new FileReader( fileName ) ); line = in.readLine();//read first line while ( line != null ){ //read all the file System.out.println( line ); line = in.readLine(); } in.close(); } } Procedural Programming in Java 153
  • 154. Reading from a File 3 The file "reaper.txt" is opened for reading when a FileReader stream is constructed. If the file does not exist in the current directory, an error will be reported and program execution will be stopped. Next, the program reads each line of the file and writes it to the monitor. The method readLine reads one line of text from the file and if there is no more data in the file, it returns null. The line (line !=null) Check for the end of file. Here, we continue reading new lines from the file until we reach the end of file. Now the stream BufferedReader also has a method called public int read(); Which reads a single character from an input stream. It reruns -1 if end of the stream is encountered. It returns an integer representation of the character. You need to cast it be able to treat it like a character. Procedural Programming in Java 154
  • 155. Reading from a File 4 Character processing is especially important when writing word processing and editing programs. Java has a rich set of tools to help the programmer with this. Most of the methods and functionality for character processing is available in the Wrapper class Character. Here are some of the most useful methods of this class: static boolean isDigit(char ch); //Determines if the specified character is a digit. static boolean isLetter(char ch) //Determines if the specified character is a letter. static boolean isLetterOrDigit(char ch) //Determines if the specified character is a letter or digit. static boolean isLowerCase(char ch) // or isUpperCase //Determines if the specified character is a lowercase character. static boolean isWhitespace(char ch) //Determines if the specified character is white space static boolean toLowerCase(char ch) //or toUpperCase //Converts the character argument to lowercase using Procedural Programming in Java 155
  • 156. Exercises Ex.67) Using the information from slides (117-120), rewrite the program on slide 118 but this time the program will read from the file one character at a time. (Not line by line). Ex.68) Write a method that takes two file names as parameters and copies the contents of the first file into the second file. Test your program in Java program. Ex.69) Write a method that takes a file name as its only parameter. The method will search the file of numbers of type int and write the largest and smallest numbers to the screen. The file contains nothing but numbers of type int separated by blanks or line breaks or tabs. Test your method in a Java program. For this exercise, you may need to convert strings into integers: String str="123"; int x=Integer.parseInt(str);//convert Procedural Programming in Java 156
  • 157. Exercises Ex.70) Write a program that reads text from one text file and writes an edited version of the same text to another file. The edited text is identical to the original version except that its text is all in upper case. Ex.71) Write a program that reads all the contents of a text file and writes everything except numbers into another file. It filters numbers from the file. Ex.72) Write a program to count the number of lines, the number of words and the number of non-whitespace characters in a file. It should then display this information on the screen. A word is any sequence of characters between any two of following characters: space, tab, new-line, comma, period. For this exercise only consider spaces and new-lines. Ex.73) Write a method that reads text from a file and writes each line preceded by a line number starting from 1. Follow the line number with a colon and a space for clarity. You may assume that the lines are short enough to fit within a line on the screen. Procedural Programming in Java 157
  • 158. Exercises Ex.74) Write a method to strip or remove comments (//) from a Java source file. First write a method with the prototype/declaration public static void stripFile(String f1, String f2); Which simply reads lines from the input stream file f1 and then output them to the output stream file f2. Then test your method in a complete Java program. Be careful when this type of comment is used in the middle of a line of code. These comments do not have to start from the beginning of the line. Ex.75) Repeat exercise 72, but this time remove C-style comments, those which start with /* and end with */. Procedural Programming in Java 158
  • 159. Classes You have seen several basic/primitive data types so far (int, double, char…) These basic data types can be used to represent single values. or atomic values, only. But many real-world applications require more complex data types. It is very difficult to do this using the primitive types. For example, a university student has a name, a date of birth, a year…. Here we need to have a data type which can represent a student. Not just the student name (string), not just student year (byte), not just date of birth of the student (?), but one data type representing the 'while' student. In Java, we can define a new data type using a class. In some other languages structs are used to define new data types. A class or a struct can be used to create a new data type which can be a compound data types consisting of several basic data types. Procedural Programming in Java 159
  • 160. Classes 2 In the following example we will create a new data type called Student and then declare variables of this type in a program: public class Students{ public static void main(String[] a){ Student s=new Student(); s.name="Karwan"; s.year=1; s.DOB="1 September 2003"; System.out.println("Name: " + s.name); System.out.println("Year: " + s.year); System.out.println("DOB: " + s.DOB); } } Procedural Programming in Java 160
  • 161. Classes 3 class Student{ String name; byte year; String DOB; } We have created a class called Student which has three member variables. The new data types Student is a compound data type. You can assign one class variable to another: Student s2=s; If you do this, s2 member variables will have the same values as member variables of s. But you should be careful when you compare class variables for equality. You should compare each member variable individually. Procedural Programming in Java 161
  • 162. Classes 4 Remember you can have arrays of any data type, including arrays of classes. For example, you could declare an arrays that can hold information about 30 students: Student[] array=new Student[30]; An then to access array elements and their member variables: array[0].name="Karwan"; array[0].year=1; array[0].DOB="1 June 1983"; Array[0] refers to the first element of the array which is of type Student. Classes allow you to write more complex programs by letting you represent more real-world objects like students, books, cars, computers… Procedural Programming in Java 162
  • 163. Classes 5 In the next example, we use the same class Student and add a method to ask the user to provide data for 10 students: public class Students{ public static void main(String[] a){ Student[] array=new Student[10]; fill_array(array); } public static void fill_array(Student a[]){ Scanner input=new Scanner(System.in); for(int i=0; i<a.length; i++){ System.out.println("Enter name:"); a[i].name=input.nextLine(); System.out.println("Enter year:"); a[i].year=input.nextByte(); Procedural Programming in Java 163
  • 164. Classes 6 System.out.println("Enter Date of birth:"); a[i].DOB=input.nextLine(); } } } class Student{ String name; byte year; String DOB; } Look at this program carefully. The method fill_array is called to fill the 10-element array with data from the user. Run this programs and enter data for 10 students. Once the array is filled, you could do anything with this data, e.g. you could save it to a file. Procedural Programming in Java 164
  • 165. Exercises Ex.76) For the program on the previous slide, write another method called print_array, which will print all the students' information on the screen. Ex.77) Write another method which will save all the information from the array into a disk file. You could write each student's information on a separate line in the file like: Karwan 1 1 June 1981 Kawa 1 3 May 1982 …. Ex.78) Write a Java program that can maintain information about a personal bookshelf. The program asks for information about a new book such as the author, title, ISBN no., price, year published. Use a class to hold book information. Ex.79) Write a program that accepts a word from the user and outputs the number of vowels in that word. (Vowels include: A, E, I, O and U) Procedural Programming in Java 165
  • 166. Recursion Recursion is a solution technique in which problems are solved by reducing them to smaller problems of the same form. We will start by looking at an example involving a recursive solution. Consider the factorial function below public static int Factorial(int n){ int product=1, i; for(i=1; i<=n; i++) product *=i; return product; } But this solution does not take advantage of an important property of factorials: each factorial is related to the factorial of the smaller number as in: n!=n*(n-1)! Procedural Programming in Java 166
  • 167. Recursion 2 So we can find a recursive solution for the method factorial because getting the factorial of one number involves also getting the factorial of a smaller number. This is the recursive definition of factorial: public static int factorial(int n) { if(n==0) return 1; //factorial of 0 is 1 else return (n * factorial(n-1)); } Consider a call like: int x=factorial(4); The function performs the following operations: (4 * (3 *(2 *(1 *(1))))) which equals 24. Procedural Programming in Java 167