intro. to prog. c++

193
Introduction to Programming in C++ First Year Ishik University-Erbil Department of Information Technology 2011-2012

Upload: kurdgul

Post on 09-Jul-2015

1.522 views

Category:

Technology


1 download

DESCRIPTION

C++ programming

TRANSCRIPT

Page 1: Intro. to prog. c++

Introduction to Programmingin

C++

First Year

Ishik University-Erbil

Department of Information Technology

2011-2012

Page 2: Intro. to prog. c++

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

Page 3: Intro. to prog. c++

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

Page 4: Intro. to prog. c++

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

Page 5: Intro. to prog. c++

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

Page 6: Intro. to prog. c++

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

Page 7: Intro. to prog. c++

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

Page 8: Intro. to prog. c++

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

Page 9: Intro. to prog. c++

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

Page 10: Intro. to prog. c++

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

Page 11: Intro. to prog. c++

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

Page 12: Intro. to prog. c++

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

Page 13: Intro. to prog. c++

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

Page 14: Intro. to prog. c++

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

Page 15: Intro. to prog. c++

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

Page 16: Intro. to prog. c++

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

Page 17: Intro. to prog. c++

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

Page 18: Intro. to prog. c++

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 string\n";

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

Page 19: Intro. to prog. c++

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

Page 20: Intro. to prog. c++

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

Page 21: Intro. to prog. c++

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

Page 22: Intro. to prog. c++

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

Page 23: Intro. to prog. c++

Performing Input 4

And the output is:

Procedural Programming in C++ 23

Page 24: Intro. to prog. c++

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

Page 25: Intro. to prog. c++

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

Page 26: Intro. to prog. c++

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

Page 27: Intro. to prog. c++

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

Page 28: Intro. to prog. c++

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

Page 29: Intro. to prog. c++

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

Page 30: Intro. to prog. c++

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

Page 31: Intro. to prog. c++

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

Page 32: Intro. to prog. c++

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

Page 33: Intro. to prog. c++

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

Page 34: Intro. to prog. c++

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

Page 35: Intro. to prog. c++

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

Page 36: Intro. to prog. c++

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

Page 37: Intro. to prog. c++

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

Page 38: Intro. to prog. c++

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

Page 39: Intro. to prog. c++

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

Procedural Programming in C++ 39

X ! X

true false

false true

Page 40: Intro. to prog. c++

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

Page 41: Intro. to prog. c++

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

Page 42: Intro. to prog. c++

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 tohours=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

Page 43: Intro. to prog. c++

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

Page 44: Intro. to prog. c++

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

Page 45: Intro. to prog. c++

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

Page 46: Intro. to prog. c++

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

Page 47: Intro. to prog. c++

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

Page 48: Intro. to prog. c++

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

Page 49: Intro. to prog. c++

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

Page 50: Intro. to prog. c++

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

Page 51: Intro. to prog. c++

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

Page 52: Intro. to prog. c++

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

Page 53: Intro. to prog. c++

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

Page 54: Intro. to prog. c++

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

Page 55: Intro. to prog. c++

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

Page 56: Intro. to prog. c++

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

Page 57: Intro. to prog. c++

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

Page 58: Intro. to prog. c++

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: [email protected]

//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

Page 59: Intro. to prog. c++

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

Page 60: Intro. to prog. c++

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

Page 61: Intro. to prog. c++

Exercises

Procedural Programming in C++ 61

Page 62: Intro. to prog. c++

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<<"Hi\n"; does nothing

cout<<"Hi again\n"; */

cout<<"Hi again\n"; //this is a comment

/*this too is a comment*/

Procedural Programming in C++ 62

Page 63: Intro. to prog. c++

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

Page 64: Intro. to prog. c++

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

Page 65: Intro. to prog. c++

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

Page 66: Intro. to prog. c++

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

Page 67: Intro. to prog. c++

Switch statement 2

Procedural Programming in C++ 67

Page 68: Intro. to prog. c++

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

Page 69: Intro. to prog. c++

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

Page 70: Intro. to prog. c++

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

Page 71: Intro. to prog. c++

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

Page 72: Intro. to prog. c++

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

Page 73: Intro. to prog. c++

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

Page 74: Intro. to prog. c++

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

Page 75: Intro. to prog. c++

For loop 3

An example involving a for-loop:

int sum=0;

for ( int n=1; n <= 10; n++) {

sum = sum + n;

}

cout<<" The sum of the numbers 1 to 10 is : “;

cout<< sum;

Procedural Programming in C++ 75

initialization

repeat the loop

as long as this is

true

done after each

loop body iteration

Page 76: Intro. to prog. c++

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

Page 77: Intro. to prog. c++

Goto statement …

And the output will be:

Procedural Programming in C++ 77

Page 78: Intro. to prog. c++

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

Page 79: Intro. to prog. c++

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

Page 80: Intro. to prog. c++

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

Page 81: Intro. to prog. c++

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

Page 82: Intro. to prog. c++

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

Page 83: Intro. to prog. c++

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

Page 84: Intro. to prog. c++

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

Page 85: Intro. to prog. c++

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

Page 86: Intro. to prog. c++

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

Page 87: Intro. to prog. c++

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

Page 88: Intro. to prog. c++

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

Page 89: Intro. to prog. c++

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

Page 90: Intro. to prog. c++

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

Page 91: Intro. to prog. c++

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

Page 92: Intro. to prog. c++

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

Page 93: Intro. to prog. c++

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

Page 94: Intro. to prog. c++

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

Page 95: Intro. to prog. c++

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

Page 96: Intro. to prog. c++

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

Page 97: Intro. to prog. c++

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

Page 98: Intro. to prog. c++

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

Page 99: Intro. to prog. c++

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

Page 100: Intro. to prog. c++

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

Page 101: Intro. to prog. c++

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

Page 102: Intro. to prog. c++

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

Page 103: Intro. to prog. c++

Methods

Lets write another method to test if a number is even or not:

Procedural Programming in C++ 103

Page 104: Intro. to prog. c++

Methods

And the output is:

Procedural Programming in C++ 104

Page 105: Intro. to prog. c++

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

Page 106: Intro. to prog. c++

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

Page 107: Intro. to prog. c++

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

Page 108: Intro. to prog. c++

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

Page 109: Intro. to prog. c++

Variable shadowing

The output of the program on the prev slide is:

As another example, see:

Procedural Programming in C++ 109

Page 110: Intro. to prog. c++

Exercises

Ex.54) Write a method to find the smallest number in an array of typeint. 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

Page 111: Intro. to prog. c++

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

Page 112: Intro. to prog. c++

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

Page 113: Intro. to prog. c++

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

Page 114: Intro. to prog. c++

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

Page 115: Intro. to prog. c++

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

Page 116: Intro. to prog. c++

Pointers

As you noted, changing the method swap to take address of integervoid 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 useint* p;

Now, you can have p (a pointer to an integer) point to an actual integer, say aint 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

Page 117: Intro. to prog. c++

Pointers

The output:

Procedural Programming in C++ 117

Page 118: Intro. to prog. c++

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

Page 119: Intro. to prog. c++

Pointers

A few notes about pointers:

You can create them alternatively asint *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

Page 120: Intro. to prog. c++

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

Page 121: Intro. to prog. c++

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

Page 122: Intro. to prog. c++

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

Page 123: Intro. to prog. c++

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

Page 124: Intro. to prog. c++

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

Page 125: Intro. to prog. c++

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

Page 126: Intro. to prog. c++

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

Page 127: Intro. to prog. c++

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

Page 128: Intro. to prog. c++

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

Page 129: Intro. to prog. c++

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

Page 130: Intro. to prog. c++

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

Page 131: Intro. to prog. c++

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

Page 132: Intro. to prog. c++

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

Page 133: Intro. to prog. c++

Managing Separate Compilations

Procedural Programming in C++ 133

Page 134: Intro. to prog. c++

Managing Separate Compilations

Procedural Programming in C++ 134

Page 135: Intro. to prog. c++

Managing Separate Compilations

Procedural Programming in C++ 135

Page 136: Intro. to prog. c++

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

Page 137: Intro. to prog. c++

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

Page 138: Intro. to prog. c++

Exercises

Ex.61) Write a predicate function (whose return value is either true orfalse) 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

Page 139: Intro. to prog. c++

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

Page 140: Intro. to prog. c++

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

Page 141: Intro. to prog. c++

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

Page 142: Intro. to prog. c++

Multi-dimensional Arrays 4

Procedural Programming in Java 142

Page 143: Intro. to prog. c++

Multi-dimensional Arrays 5

The output of the previous example is as follows:

Procedural Programming in Java 143

Page 144: Intro. to prog. c++

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

Page 145: Intro. to prog. c++

Multi-dimensional Arrays 7

As with ordinary (1-dimensional arrays), the following two 2D-array

declarations are equivalent:

int[][] myArray = new int[3][5] ;

andint[][] 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

Page 146: Intro. to prog. c++

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

Page 147: Intro. to prog. c++

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

Page 148: Intro. to prog. c++

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

Page 149: Intro. to prog. c++

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

Page 150: Intro. to prog. c++

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

Page 151: Intro. to prog. c++

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

Page 152: Intro. to prog. c++

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

Page 153: Intro. to prog. c++

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

Page 154: Intro. to prog. c++

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

Page 155: Intro. to prog. c++

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 spacestatic boolean toLowerCase(char ch) //or toUpperCase

//Converts the character argument to lowercase using

Procedural Programming in Java 155

Page 156: Intro. to prog. c++

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

Page 157: Intro. to prog. c++

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

Page 158: Intro. to prog. c++

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

Page 159: Intro. to prog. c++

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

Page 160: Intro. to prog. c++

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

Page 161: Intro. to prog. c++

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

Page 162: Intro. to prog. c++

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

Page 163: Intro. to prog. c++

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

Page 164: Intro. to prog. c++

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

Page 165: Intro. to prog. c++

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

Page 166: Intro. to prog. c++

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 belowpublic 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

Page 167: Intro. to prog. c++

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

Page 168: Intro. to prog. c++

Recursion 3

As another example of recursion consider the following method which does a similar task to pow method defined in the Java class Math (see slide 99):

double raise_to_power(double num, int power){

if(power==0)

return 1.0;

else

return (num * raise_to_power(num, power-1);

}

Recursion is not essential. Every method defined recursively can also be

defined iteratively using 'for', 'while' and 'do…while' loops. Also, recursive calls,

method calls in general, are expensive on the computer's resources and may

run slower. But this is not always the case and recursion can sometimes make

code easier to understand.

Procedural Programming in Java 168

Page 169: Intro. to prog. c++

About Time

Many real-world computer applications make extensive use of time and time-

related operations. Consider a banking system which has to calculate interest

for its customers, or issue account statements every month. Or consider a

flight reservation system which checks for dates and times of flights and their

schedule. There are many more examples like these.

The following program will obtain the system time and print the time and the

date of the host computer.

See next slide for the program and its output as it is run.

Procedural Programming in Java 169

Page 170: Intro. to prog. c++

About Time 2

Procedural Programming in Java 170

Page 171: Intro. to prog. c++

About Time 3

Hours are between 0-23; minutes between 0-59; days between 1-31, months

between 0-11 and days of the week between 1-7.

The program first creates a variable/object of type GregorianCalendar

which represents a date calendar. This date is initialized to the current host

computer time.

You can create a new Gregorianalendar variable and set it to a new date:

GregorianCalendar d=new GregorianCalendar();

d.set(2000,2,29);

Or provide time as well as date:d.set(2000,2,29, 22,10,5);

Procedural Programming in Java 171

Page 172: Intro. to prog. c++

About Time 4

If you mistakenly provide incorrect parameters for the above methods, for

example if you set d to:d.set(2000,2,33);

Java will automatically readjust the date. In this case, d will be set to

2 3 2000

You could prevent users from giving inconsistent date fields by a user-defined

method. Or you could use the following method:d2.setLenient(false);

To check if date d1 is before date d2:d1.before(d2);

Or to check if d1 is after date d2:d1.after(d2);

To check two dates for equality:d1.equals(d2);

Date&time has many useful applications. For example; you could measure how

long a program takes! See next slide for an example:

Procedural Programming in Java 172

Page 173: Intro. to prog. c++

About Time 5

import java.util.*; //needed for date operations

public class RunningTime{

public static void main(String[] a){

GregorianCalendar d1 = GregorianCalendar();

long l1=d1.getTimeInMillis();

for (int i=0; i<1000000; i++){

int x=0;

x++;

}

GregorianCalendar d2=GregorianCalendar();

long l2=d2.getTimeInMillis();

System.out.println(l2-l1);

}

}

Procedural Programming in Java 173

Page 174: Intro. to prog. c++

About Time 6

The System class has some methods that can be used to get the current time

in milliseconds and nanoseconds since the epoch.( Jan 1st, 1970) public class RunningTime{

public static void main(String[] a){

long l1=System.currentTimeMillis();

for (int i=0; i<1000000; i++){

int x=0;

x++;

}

long l2=System.currentTimeMillis();

//could also have used System.nanoTime() for

//getting time in nanosecond precision.

System.out.println(l2-l1);//

}

}

Procedural Programming in Java 174

Page 175: Intro. to prog. c++

About Time 7

The programs in the prevous 2 slides did exactly the same thing. First used the

Calendar API and the second used the more straightforward System class without the need to include anything from java.util library.

Procedural Programming in Java 175

Page 176: Intro. to prog. c++

About Time 7

On slides 134/5 we used the get method of the GregorianCalendar class

to obtain individual fields of a date such year, month, day and so on.

The GregorianCalendar class has another method called set which can be

used to set the individual fields of a date:

Calendar c=Calendar.getInstance();

c.set(Calendar.YEAR, 9999);

c.set(Calendar.MONTH,12);

c.set(Calendar.DAY,31);

There are many more date related methods in the Calendar class which you

can use if you need them .

The Java Documentation is the best source of reference material on all Java

classes and methods. It is available on the department's soft-eng intranet.

Procedural Programming in Java 176

Page 177: Intro. to prog. c++

About Time 8

Here is some more GregorianCalendar class methods:

System.out.println(gc.get(Calendar.DAY_OF_MONTH));

System.out.println(gc.get(Calendar.DAY_OF_WEEK));

System.out.println(gc.get(Calendar.ERA));//BC/AC 0/1

System.out.println(gc.get(Calendar.AM_PM));//AM/PM 0/1

System.out.println(gc.get(Calendar.HOUR_OF_DAY));//0-23

System.out.println(gc.get(Calendar.MILLISECOND));

System.out.println(gc.getTimeInMillis());

GregorianCalendar gc2=new GregorianCalendar();

gc2.set(Calendar.YEAR,2000);

gc2.set(Calendar.MONTH,1);

gc2.set(Calendar.DATE,30);

gc2.add(Calendar.YEAR, 1000);

gc2.add(Calendar.DAY_OF_MONTH, 20);

Procedural Programming in Java 177

Page 178: Intro. to prog. c++

Formatting Numbers

Look at the following statements:x=100.0/3; yields the value 3333.3333333333336

To control the output, for example to specify 2 digits after the decimal point,

separate groups of 1000s with commas, show trailing 0s, and don't show leading 0s: (import java.text.DecimalFormat)

double d=10000/3.0;

DecimalFormat dm=new DecimalFormat(",##0.00");

System.out.println(dm.format(d)); //33.33

To format the number with leading zeros, use the following pattern",000.00" 033.00 with 2 leading 0s

"$,##0,00" $33.00 with no leading 0s

"000" 033 2 leading 0s and no

decimal points

Procedural Programming in Java 178

Page 179: Intro. to prog. c++

Formatting Dates

Java let's you format dates and times as this programs demonstrates:

And the output was the following on my machine:

Procedural Programming in Java 179

Page 180: Intro. to prog. c++

Formatting Dates 2

The output will be different on your machine because it get the time of your computer. So, it will be different each time you run it.

This program first creates a GregorianCalendar object and then uses its

getTime method to assign its value to a Date object. Then a

SimpleDateFormat object is created for formatting dates.

A string pattern is

provided which will

determine how the

date will be

displayed.

There are more

formatting patterns

you can use:

Procedural Programming in Java 180

Page 181: Intro. to prog. c++

Formatting Dates 3

To get familiar to DateFormat API and any other API for that mattere, you have

to hunt through the documentation for that class and packages to see what

methods they have and see some sample code.

This screen shows the API

documentation for the

DateFormat object. You

should be able to browse

the java documentation

online or download a copy

for offline use.

I will put a downloaded

copy on the shared folder

so you can use and take a

copy home.

Procedural Programming in Java 181

Page 182: Intro. to prog. c++

Method Overloading

In Java it's possible to have more than one method with the same name

provided the functions have different parameter types or different number of

parameters. This is known as method overloading or function overloading.

(Having only a different return type is not enough) The signature of a method

is: Its name and the number and types of its parameters.

Method overloading should be used in situations where we have several

methods that do similar tasks. For example, to find the average of some

numbers as in:public static int average(int a, int b);

public static int average(int a, int b, int c);

public static double average(double a,double b);

Here we have overloaded three methods. When we call one of the three

methods, the compiler knows which method to call. This can make large

programs easier to read and reduces complexity.

Procedural Programming in Java 182

Page 183: Intro. to prog. c++

More on Strings

A string variable/object is immutable which means that once a string is created,

it cannot be changed. Each time a string is modified, a new string is created.

The following example illustrates:

String str="Yes";

str

str="No"; str

Procedural Programming in Java 183

Yes

Yes

No

Page 184: Intro. to prog. c++

More on Strings 2

Java also provides a StringBuilder class which is mutable and can be

more efficient for code that does a lot of string manipulation. A string builder

implements a mutable sequence of characters.

The output:

Procedural Programming in Java 184

Page 185: Intro. to prog. c++

More on Strings

You couldn't do this with a string object. There is also another useful class

called StrignTokenizer which can be used to break strings into smaller

strings:

Which outputs:

As you can see from the output, the string is broken into

smaller pieces delimited by a space. i. e. each word.

Procedural Programming in Java 185

Page 186: Intro. to prog. c++

More on Strings 3

The default delimiter is a space but you can specify any other character as a

delimiter (or even specify multiple delimiter characters in a string):

StringTokenizer st=new StringTokenizer(line," ,.\n");

This class can be useful when retrieving data from delimited text files. It

relieves the programmer from having to do the extraction process manually.

For more information on these clases, String, StringBuilder and

StringTokenizer see their API documentation pages.

Procedural Programming in Java 186

Page 187: Intro. to prog. c++

Bitwise operators

The Java programming language also provides operators that perform bitwise

and bit shift operations on integral types. The operators discussed in this

section are less commonly used. Therefore, their coverage is brief; the intent is

to simply make you aware that these operators exist.

Bitwise operators work on the bit level, and so depend on the internal

implementation of the numeric types by the java virtual machine. You can

always call Ingeger.toBinaryString(int x) to get a binary representation of any

given integer.

The following screenshots, show an example of using that method to display

the binary form of an integer.

Procedural Programming in Java 187

Taken p

artly

form

the J

ava T

uto

rial

Page 188: Intro. to prog. c++

Bitwise operators 2

And the output will be:

Just FYI, the output is not precisely correct because the

Zeros on the right of each number is not shown. If we

Pad them with zeros, the will be something like:

00000000000000000000000000000000

00000000000000000000000000000001

00000000000000000000000000000010

And so on.

So, if we ever want to work on the bits an integer has,

We can use these operators.

Procedural Programming in Java 188

Page 189: Intro. to prog. c++

Bitwise operators 3

Let’s think about inverting every bit, that is making every

1 a 0 and vice versa. We use ~ operator. See the following example:

The output:

This is he previous example with every bit inverted 0 to 1 and 1 to 0

Procedural Programming in Java 189

Taken fo

rm th

e J

ava T

uto

rial

Page 190: Intro. to prog. c++

Bitwise operators 4

The ~ operator works on one operand, that is, it is unary operator.

We have a similar unary operator that works on boolean values and inverts

their values. It is the ! operator, called NOT operator.

The following example explains this operator:

And the output is:

Procedural Programming in Java 190

X NOT x (Math) !x (Java)

true false false

false true true

Page 191: Intro. to prog. c++

Bitwise operators 5

We have bitwise binary operators that work on two operands. They are AND,

OR and XOR (or exclusive or) in logic. The following in the table of input and

output combinations:

As you see, the value of OR ( | ), is only zero when both operands are zero, but

it is 1 otherwise. The AND (&) is opposite which is only 1 when both operands

are one and zero otherwise.

The behavior of XOR is unique in a way that it only gives 1 when the operands

are different and it gives zero when they are the same. This has some very

interesting applications in checking data correctness.

Procedural Programming in Java 191

x y x|y x&y x^y

0 0 0 0 0

0 1 1 0 1

1 0 1 0 1

1 1 1 1 0

Page 192: Intro. to prog. c++

Bitwise operators 6

The following example puts all these three operators to work:

And the output is :

Procedural Programming in Java 192

Page 193: Intro. to prog. c++

Bitwise operators 7

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed

right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given

by the left-hand operand, and the number of positions to shift by the right-hand

operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost

position, while the leftmost position after ">>" depends on sign extension.

A live example will be shown in the class to explain the effects of these

operators.

See page 89-98 for a good coverage of the

Operators in java including bitwise ops.

For a few tricks and uses of bitwise operators, see also:

http://www.vipan.com/htdocs/bitwisehelp.html

Procedural Programming in Java 193