174
1 Introduction to Procedural Programming Department of Software Engineering College of Engineering University of Salahaddin Erbil

Introduction to Procedural Programming in C++

Embed Size (px)

DESCRIPTION

This slide notes are more than 10 years old of my teacher Mr Karim Zebari. He uses a brilliant simple language to explain programming principles step by step.

Citation preview

Page 1: Introduction to Procedural Programming in C++

1

Introduction to Procedural Programming

Department of Software EngineeringCollege of Engineering

University of SalahaddinErbil

Page 2: Introduction to Procedural Programming in C++

2

About this Course

in this course, we will be learning to write procedural* programs.

The main tool needed for writing programs is a programming language.

Because of the popularity of C++ in the academic world and business, and its standardization, we will use C++ as our programming language.  C++ as a programming language is very powerful and feature-rich. it is a general-purpose programming language that can be used for many different situations. it can be used to write low-level system programs or high-level programs.

*This term will be explained later.

introduction to Procedural Programming

Page 3: Introduction to Procedural Programming in C++

3

About this Course, cont

C++ supports both procedural programming and object-oriented programming. in this course, this year, we will concentrate on procedural programming in C++. Next year, we will cover object-oriented aspects of the language.

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:• will learn about all the essential programming concepts• will demonstrate a good familiarity with C++ syntax• will be able to write reasonably complex procedural programs

introduction to Procedural Programming

Page 4: Introduction to Procedural Programming in C++

4

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 jobs while computers ARE. Humans can perform a few calculationsand get tired(especially if the calculations are long and complex).Computers hardly get tired. in a perfect world, a computer couldcarry out endless repetitive and long calculations without stop. Another reason is that computers are much faster at performingcalculations than humans. Modern computers can carry out millions Of basic instructions per second.

introduction to Procedural Programming

Page 5: Introduction to Procedural Programming in C++

5

Good Programming

Programming is a challenge. Often, programs are late, difficult to use,full of bugs, un-maintainable, and wrong. When someone writesa 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)

introduction to Procedural Programming

Page 6: Introduction to Procedural Programming in C++

6

Good Programming, cont

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

introduction to Procedural Programming

Page 7: Introduction to Procedural Programming in C++

7

The Syllabus

The following topics will be covered in this course:• introduction• variables and assignment• input, output (i/O), formatting output• basic data types• a simple C++ program• arithmetic operators• flow of control and loops• program style• procedures and functions• references• local and global variables, constants• procedural abstraction• file i/O• character i/O• structures and arrays• numerical analysis(Electrical Engineering only)• recursion

introduction to Procedural Programming

Page 8: Introduction to Procedural Programming in C++

8

Variables

A C++ variable is a placeholder used for storing data. The type of data may be numerical, string, character and any other type that the language supports. We will study all the data types in C++ laterin 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. 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 etc.)

introduction to Procedural Programming

Page 9: Introduction to Procedural Programming in C++

9

Variables, cont

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 datatype 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 itsvalue can be a number with a fraction like 1.3. Note that all variable declarations end with a semicolon(;).

introduction to Procedural Programming

Page 10: Introduction to Procedural Programming in C++

10

Variables, cont

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 willbe unpredictable. Variable initialization can be performed eitherduring declaration using assignment statements (to be discussedshortly) as in

int books=0;

Or using the input statement cin (input will be discussed later).

introduction to Procedural Programming

Page 11: Introduction to Procedural Programming in C++

11

Assignment Statements

Values can be assigned or stored in variables with assignment statements:

books=34;

An assignment statement is an order, to the computer, to assignthe 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.

The value on the right-hand side can also be another variable orexpression:

books1=books2;

in an assignment statement, first the value on the right-hand sideis evaluated and then its result is stored or assigned to the variableon the left-hand side.

introduction to Procedural Programming

Page 12: Introduction to Procedural Programming in C++

12

Performing Output

The values of variables, numerical values and strings of text ,may beoutput to the screen using cout as in

int books=0;cout<<books<<endl;cout<<72<<endl;cout<<“This is the output”<<endl;

in the first output statement, the value of variable books will beoutput on the screen, which is 0;

in the second, the numerical value 72 will be output to the screen, and in the last statement, the string “This is the output” will beoutput to the screen.

introduction to Procedural Programming

Page 13: Introduction to Procedural Programming in C++

13

Performing output, cont

Typically, you would want a new line to appear after some output tothe screen; to force a new line the C++ keyword endl is appended atthe end of the line. A second method for forcing a new line is usingthe escape character \n as in:

cout<<“Hello everyone\n”;

But this is only possible when the output is a text of string.

You can also combine a number of outputs in a single output statement as in

cout<<“i am “<<18<<“years old”<<endl;

To force a blank line on the screen use eithercout<<endl; or cout<<“\n”;

The double arrow signs (<<) are called the insertion operators.

introduction to Procedural Programming

Page 14: Introduction to Procedural Programming in C++

14

Formatting Output

When the computer outputs a value of type double, the format maynot be what you would expect. Eg, if double price=78.5;

cout<<“The price is $”<<price<<endl;

might output:The price is $78.500000

or The price is $78.5or The price is $7.850000e01But, it is unlikely that the output will be

The price is $78.50which is the format that is most common for currency.To specify the number of decimal point in values of type double we Use the following formula before the above statement:

cout.setf(ios::fixed);

cout.setf(ios::showpoint) (will output $78.50)cout.precision(2);

introduction to Procedural Programming

Page 15: Introduction to Procedural Programming in C++

15

input using cin

in C++, cin is used to input values into variables. After declaring avariable of type int,

int price;cout<<“Enter the price:”;cin>>price;cout<<“The price you entered is $“<<price<<endl;

in this program extract, first an integer is declared, then the useris asked to enter/type a value for price. This value is then input inthe variable price using cin. A message is also output to the screennotifying the user of the input value.

When the program reaches a cin statement, it waits for input to be entered from the keyboard and for this value to be input into theVariable, the user must enter a new line.

introduction to Procedural Programming

Page 16: Introduction to Procedural Programming in C++

16

input using cin, cont

To have more than one input value entered at the keyboard, usemore variables to store the inputted values as in

int price1,price2; (two variables of type int)cout<<“Enter two prices:”<<endl;cin>>price1>>price2;

Or you could have two separate cin statements. After each input,the computer waits for user to input some value. Then the user musttype a space or a tab or a new line to separate the twoinput values.

The double arrows of cin statements are the same as for outputstatements (cout) except they are in the opposite direction. A cinstatement sets the value of a variable equal to values typed atthe keyboard.

introduction to Procedural Programming

Page 17: Introduction to Procedural Programming in C++

17

Basic Data Types

integer Numbers (int)As we have already mentioned the type int refers to whole numberslike 37 and –45. The range of numbers of type int is usually between-2,147,483,647 and 2,147,483,647 (4 bytes are used to store the number) But this is system-dependent and some systems support bigger ranges.

Real Numbers(Double)And we also pointed out that numbers with fractional parts such as3.56 and 0.112 are of type double.(the real numbers in mathematics).For numbers of type double the range is between 1.7E + 308 and1.7E - 308. Here, the number 1.7E + 308 is equal to 1.7 multiplied by10 to the power of 308. 1.7 x 10308. This is called the scientificnotation. (8 bytes are used to store double numbers). Numbers oftype double can have a precision of up to 15 digits.

introduction to Procedural Programming

Page 18: Introduction to Procedural Programming in C++

18

Basic Data Types, cont

We have seen two numeric types that the C++ supports: double andint types. These two are the main numeric types in C++. You can use these types for almost any situation. However, C++ includes other numeric typeswhich are derived and based on thesetwo types. These types allow for diff-erent number sizesand for more or lessprecision.

Also can be used to make more efficientuse of the memory.

introduction to Procedural Programming

Type Memory Used

Size Range Precision

short or short int

2 bytes -32,767 to 32,767 N/A

int 4 bytes -2,147,483,647 to2,147,483,647

N/A

long or long int

4 bytes -2,147,483,647 to2,147,483,647

N/A

float 4 bytes Approximately10-38 to 1038

7 digits

double 8 bytes Approximately10-308 to 10308

15 digits

long double

10 bytes Approximately10-4932 to 104932

19 digits

Page 19: Introduction to Procedural Programming in C++

19

Basic Data Types, cont

Characters (char)

Computers and C++ not only use numerical values but they can also use non-numerical values like characters and strings. Values of typechar include letters of the alphabet, digits, symbols and punctuationmarks. For example:

char letter, symbol;letter=‘A’;symbol=‘#’;

Notice that character values are placed inside single quotes. We have already seen the string data type where the string of text isPlaced inside double quotes as in:

cout<<“This is string of text.”<<endl;So, in C++ the character ‘A’ is treated differently from “A” sincethe first is considered a character and the second a string.

introduction to Procedural Programming

Page 20: Introduction to Procedural Programming in C++

20

Basic Data Types, cont

String data types will be discussed later. For now, we just use values of Type string to output text onto the screen using C++cout statements. Let’s look at a small program extract using char and string types:

char letter;cout<<“Enter a letter: “;cin>>letter;cout<<“You typed the letter: “<<letter<<endl;

Here, we first declare a char variable and ask the user to type aletter. After typing a letter and pressing the Enter key, the valueis stored in the variable letter using cin statement. Then, the useris notified about the value that he/she typed.

The variable letter is of type char, while the text string Enter a Letter is of type string ( string or sequence of characters).

introduction to Procedural Programming

Page 21: Introduction to Procedural Programming in C++

21

Basic Data Types, cont

Boolean expressions (bool)

The last basic data type we will look at is called bool. This type wasrecently added to the language.

Values of type bool are called Boolean expressions and include onlytwo values: true or false. Boolean expressions are used in branchingAnd looping statement which we will cover later in the course.

important noteAs a general rule, you cannot store values of one type in a variable ofanother type. This is a good rule to follow, even though some C++compilers do not enforce this type checking.

introduction to Procedural Programming

Page 22: Introduction to Procedural Programming in C++

22

A simple C++ Program

Now, we will write our first complete C++ program.

#include <iostream.h>

main(){

int hours=0;cout<<“This is your first C++ program”<<endl;cout<<“Welcome to C++ Programming”<<endl;cout<<endl<<endl;cout<<“How many hours/week do you practice C++ ?”;cin>>hours;cout<<“You practice “<<hours<<“ per week.”<<endl;cout<<“OK, this is enough for now.”<<endl;return 0;

}in the next slide, we will dissect this program line by line.

introduction to Procedural Programming

Page 23: Introduction to Procedural Programming in C++

23

Program Dissection

Line 1:This include statement directs the C++ compiler to include the iostream.h library file with the program. This library contains input/output function definitions of the C++ language cin and cout. Withoutincluding this library file, you cannot use cin/cout for input/output.We will use other C++ libraries later.

You can even write your own libraries and include them in your C++programs. We will see this later.

Line 2:Every C++ program must have a function called main. This function has a body consisting of program statements to be executed insequence by the computer. (See next slide)

introduction to Procedural Programming

Page 24: Introduction to Procedural Programming in C++

24

Program Skeleton

The skeleton of a typical C++ program is as follows:#include library1#include library2

.

.

.function prototypes;

main(){

statement1;statement2; . .

.return 0;

}function definitions;

introduction to Procedural Programming

Page 25: Introduction to Procedural Programming in C++

25

Program Dissection, cont

Lines 3, 13:Every main function starts with an open bracket { and ends with a close bracket }.

Line 4:in this line we declare and initialize a variable of type int.

Lines 5,6,8,11Here, we are just outputting some text to the screen.

Line 7:We output two blank lines onto the screen for clarity.

Line 9:We capture the user input value and store it in a variable.

introduction to Procedural Programming

Page 26: Introduction to Procedural Programming in C++

26

Program Dissection, cont

Line 10:in this line, we output some text and a the value of the variable hours.

Line 12:Here, at the end of the program, we return control to the operatingsystem and declare that the program has finished its execution.

important NoteThe important thing to remember is that all C++ programs must havea function called main and that program execution begins and endsinside this function.

introduction to Procedural Programming

Page 27: Introduction to Procedural Programming in C++

27

Arithmetic Operators

in C++, you can combine expressions using the arithmetic operators.Usually, arithmetic operators come in between two expressions as in

expression1 operator expression2

Or operand1 operator opreand2

The operand can be either a single variable/number or a compositeexpression.

The main C++ arithmetic operator are the following:+ for addition- for subtraction* for multiplication/ for division% for division remainder

introduction to Procedural Programming

Page 28: Introduction to Procedural Programming in C++

28

Arithmetic Operators, cont

For example:int number_of_computers=10;int price_of_computer=7340;int total_price=price_of_computer * number_of_computers;

operand1 operator operand2

All of the arithmetic operators can be used with numbers of type int,numbers of type double and even with one number of each type.

Division Operator (/)However, if both operands are are of type int, the result is of type int. if one, or both operands are of type double, the result will be of type double.

introduction to Procedural Programming

Page 29: Introduction to Procedural Programming in C++

29

Arithmetic Operators, cont

When used with one or both operands of type double, the divisionOperator, /, behaves as you would expect: 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:

cout<<“11 divided by 3 is “<<11/3<<endl;cout<<“with a remainder of “<<11%3<<endl;

Output: 11 divided by 3 is 3with a remainder of 2

introduction to Procedural Programming

Page 30: Introduction to Procedural Programming in C++

30

Precedence Rules

You can specify the order of operations in C++ using parentheses asillustrated in the following expressions:

1: (x + y) * z2: 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 the C++ rulesof 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.

introduction to Procedural Programming

Page 31: Introduction to Procedural Programming in C++

31

More Assignment Statements

C++ has shorthand notation that combines the assignment operator(=) and an arithmetic operator. For example:

int hours=5;hours += 7; is equivalent to hours=hours + 7;

That is, the new value of the variable hours is equal to its old valueplus the number constant 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;

introduction to Procedural Programming

Page 32: Introduction to Procedural Programming in C++

32

Flow of Control

in the simple C++ program we saw earlier, the program consisted ofa list of program statements which were executed sequentially; onestatement after another. There we did not specify any order for the program to follow.

For bigger and more sophisticated programs, you will need some wayto vary 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 choosebetween two alternative actions. Then we will discuss loops.

introduction to Procedural Programming

Page 33: Introduction to Procedural Programming in C++

33

Branching (if-else statement)

There is a C++ statement that chooses between two alternativeactions. it is called the if-else statement. in fact, there are twoversions of this statement. We will discuss the first one as thesecond form is an extension of the first form.

The general form of the if-else-statement is as follows:

if (Boolean-expression)yes-statement

elseno-statement

When program execution reaches the if-else-statement only oneof the two statements is executed, not both. if the Boolean-exp-ression is true then the yes-statement is executed. if the theBoolean-expression is false then the no-statement is executed.

introduction to Procedural Programming

Page 34: Introduction to Procedural Programming in C++

34

Branching (if-else statement), cont

Example:Suppose your program asks the user about the amount of time perweek he/she spends on practicing C++. And you want the programto decide whether or not this is enough. Assume that 4 hours/weekof practice is enough. Anything less is not good enough.

#include <iostream.h>main(){

int hours_per_week=0;cout<<“How many hours/week do you practice C++? “<<endl;cin>> hours_per_week;if (hours_per_week>=4)

cout<<“That’s good ”<<endl;else

cout<<“That’s not good enough”<<endl;return 0;

}

introduction to Procedural Programming

Page 35: Introduction to Procedural Programming in C++

35

Branching (if-else statement), cont

The Boolean expression in the if-else-statement is: hours_per_week>=4

Remember that Boolean expressions or variables have only 2 values:true and false. C++ checks whether this Boolean expression is trueor false by comparing the value of the variable and the constant 4.Here, we use C++ comparison operators. Here is the full list ofcomparison operators:

introduction to Procedural Programming

Math Symbol C++ Notation Description

= == Equal to

≠ != Not equal to

< < Less than

≤ <= Less than or equal to

> > Greater than

⋝ >= Greater than or equal to

Page 36: Introduction to Procedural Programming in C++

36

Boolean Logic

in evaluating Boolean expressions, C++ uses Boolean Logic principles.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) Boolean expressions are true.

To remind you of the Boolean Logic truth tables:

Note: && is equivalent to “and” and || to “or”.

introduction to Procedural Programming

X Y X && Y

True True True

True False False

False True False

False False False

X Y X || Y

True True True

True False True

False True True

False False False

Page 37: Introduction to Procedural Programming in C++

37

if-else-statement, cont

Sometime, you want your program to test a condition and if thecondition is satisfied the program does something, otherwise it doesnot do anything. You can do this by omitting the else part from theif-else-statement. For example:

if (grade>=50)cout<<“The student has passed.”<<endl;

cout<<“……”<<endl;

So, if the Boolean expression is not satisfied, the cout statementwill not be executed and program execution will go to the second cout line.

This is called the if-statement, as opposed to if-else-statement.

introduction to Procedural Programming

Page 38: Introduction to Procedural Programming in C++

38

if-else-statement, cont

introduction to Procedural Programming

You may want to execute more than one statement inside an if-else-statement. To do this, enclose the statements inside brackets { }.For example:

if (grade >=50){

cout<<“ The student has passed”<<endl;passed-students +=1;

}else{

cout<<“Student has failed”<<endl;failed-students +=1;

}A list of statements enclosed inside brackets is called a compoundstatement.

Page 39: Introduction to Procedural Programming in C++

39

Loops

introduction to Procedural Programming

Most programs have some action that is repeated a number of times.A section of a program repeats a statement or group of statementsis called a loop. C++ has a number of ways to create loops. One of#include <iostream.h> them is called a main() while-statement or { while-loop.

int num_of_greetings=0; cout<<“How many greetings do you want? ” ; cin>>num_of_greetings;

Boolean expressionwhile (num_of_greetings > 0){

cout<<“Hello “;num_of_greetings=num_of_greetings-1;

}return 0;

}

Page 40: Introduction to Procedural Programming in C++

40

Loops, cont

introduction to Procedural Programming

in the example on the previous page, the section between the brackets { and } is called the body of the while-loop. it is the actionthat 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 zerotimes, that is, it is not executed at all. Because, the Boolean-expis 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 for ever. in this example,we decrease a variable value after each iteration. We decrease itby one after each iteration. This is called decrementing.

Page 41: Introduction to Procedural Programming in C++

41

increment and Decrement Operators

introduction to Procedural Programming

We have already seen a number of binary operators such as * and /.They were called binary because they take two operands, one on their left and one on their right.

Unary operators have only one operand. You know unary operators+ and –, in +8 and –9. The C++ language has two more unary operators++ and --. The ++ operator is called the increment operator and --the decrement operator. They are usually used in variables of typeint. The operator ++ increases a variable’s value by one and – decreases a variable’s value by one. Example:

int count=5;count++;cout<<“Count is changed to “<<count<<endl;count--;cout<<“Count is changed to “<<count<<endl;

Page 42: Introduction to Procedural Programming in C++

42

Loops, cont

introduction to Procedural Programming

As you know, a while-loop might execute its loop body zero times. if you know that under all circumstances your loop body should be executed at least one time, then you can use a do-while loop statem-ent. The do-while loop statement is similar to the while-loop statem-ent, except that the loop body is executed at least once. The syntaxof do-while loop statements is as follows:

do{

Statement_1;Statement_2;…Statement_n;

} while (Boolean-expression);

Loop body is executed once first, then the Boolean expression is checked for additional iterations of the loop body.

Page 43: Introduction to Procedural Programming in C++

43

Loops, cont

introduction to Procedural Programming

An example involving a do-while loop statement:#include <iostream.h>

main(){

char answer=‘n’;

do {

cout<<“Hello\n”;cout<<Do you want another greeting?\n” <<“Press y for yes, n for no,\n” <<“and then press Enter/Return: “;cin>>answer;

} while (answer ==‘y’ || answer == ‘n’);

cout<<“Goodbye\n”;}

Page 44: Introduction to Procedural Programming in C++

44

infinite Loops (Be Careful)

introduction to Procedural Programming

A while-loop or do-while loop does not terminate as long as the Bool-ean expression is true.

This Boolean expression normally containsa variable that will be changed by the loop body and usually the valueof this variable eventually is changed in a way that makes the Bool-ean expression false and therefore terminates the loop.

However if you make a mistake and write your program so that the Boolean expression is always true, then the loop will run forever. (aninfinite loop).

On the next page we will write two loops, one that does terminateand one that does not terminate.

Page 45: Introduction to Procedural Programming in C++

45

infinite Loops, cont

introduction to Procedural Programming

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?To terminate a program use control-C or Ctrl-C on the keyboard.

Page 46: Introduction to Procedural Programming in C++

46

Program Style

introduction to Procedural Programming

All the variable names in our programs were chosen to suggest theiruse. We tried to use meaningful names for variable names. Also welaid out our programs in a particular format. For example, thedeclarations 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

indentingA 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 thisis to skip a line between parts that are logically considered separate.

Page 47: Introduction to Procedural Programming in C++

47

Program Style, cont

introduction to Procedural Programming

indenting can help to make the structure of the program clearer. Astatement within a statement should be indented.

Also, the brackets {} determine a large part of the structure of a program. Placing each on a separate line by itself, as we have beendoing, makes it easy to find the matching bracket. One one pair of brackets is embedded inside another pair, the innerpair should be indented more than the outer pair.

CommentsTo make programs understandable, you should include some explanatorynotes at important places in the program. Such notes are calledcomments. Most programming languages have this capability. in C++,the symbols // are used to indicate start of a comment to the endof the line. These comments can be as long as a line only.

Page 48: Introduction to Procedural Programming in C++

48

Program Style

introduction to Procedural Programming

There is another way to insert comments in a C++ program. Anythingbetween /* and */ is considered a comment and ignored by the C++compiler. Unlike the // comments, which require an additional // oneach 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!.

Page 49: Introduction to Procedural Programming in C++

49

Constants

introduction to Procedural Programming

The word ‘variable’ means something that changes frequently. The value of a variable may change several times in the program.

Sometimes it is required to have some value unchanged throughoutthe program execution. Some value that does not change in a C++program is called a constant. For example:

const int ENGiNEERiNG_AVERAGE=90;

if (student_grade >= ENGiNEERiNG_AVERAGE)cout<<“Engineering Student”<<endl;

elsecout<<“Science Student”<<endl;

This could be a large program and there could be many places wherethe constant engineering_average is used. To change eng. average for next year, we only need to change the value at one place. it’s common to use capital letters for constants.

Page 50: Introduction to Procedural Programming in C++

50

Exercises

introduction to Procedural Programming

1. What is the output of the following program fragment?

int x=10;while (x > 0){

cout<<x<<endl;x=x-3;

}

2. What output would be produced in the previous exercise if the >sign were replaced by <?

3. Write a program fragment to have the same output as the exercise 1 fragment but use a do-while loop this time.

Page 51: Introduction to Procedural Programming in C++

51

Exercises, cont

introduction to Procedural Programming

4. What is the most important difference between a while-loop and a do-while loop statement?

5. Write an if-else statement that outputs the word ‘High’ if theValue of variable score is greater than 100 and ‘Low’ if the value ofscore is at most 100. The variable score is of type int.

6. Consider a quadric expression such as:x2 – x – 2

Describing where this quadratic is positive, involves findingA set of numbers that are either less than the smaller root(-1) or greater than the larger root (+2).Write a C++ Boolean expression that s true when this equationhas positive values.

Page 52: Introduction to Procedural Programming in C++

52

Exercises, cont

introduction to Procedural Programming

7. The following if-else statement will compile and run without anyProblems. However, it is not laid out in a way that is consistent withthe other if-else statements we have used in our programs. Rewriteit so that the layout is clearer and similar to how we have been doing.

if (x < 0) { x=7; cout<<“x is now positive.”;} else{ x =-7; cout<<“x is now negative.”;}

8. What is the output of the following program fragment?

//this is not a comment/* cout<<“Hi”<<endl; does nothingcout<<“Hi again”<<endl; */cout<<“Hi again”<<endl; // this is a comment/*this too is a comment*/

Page 53: Introduction to Procedural Programming in C++

53

Exercises, cont

introduction to Procedural Programming

9. Write a program fragment to display the numbers that are multiples of 4 between 0 and 20 inclusive.

10. Write a program to1. Ask the user for two whole numbers (int)2. Calculate their addition, subtraction, multiplication, division

and molulus3. Display the results on the screen

11. Write a multiplication calculator program. This program willmultiply 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.

Page 54: Introduction to Procedural Programming in C++

54

Exercises, cont

introduction to Procedural Programming

12. Write a program fragment to check the students grade and coursework. if either the student’s maths grade is greater than 50 or the students physics grade is greater than 60 then the program will output the word ‘Passed’ otherwise the word ‘Failed’.

13. Write a program fragment that reads in a year (Ex. 1972) andchecks whether or not this year is a leap year or not. Remember a leap year is a year that has 366 days. To be a leap year, one of thefollowing conditions must hold:

1. The year is divisible by 4 but not by 100, or2. The year is divisible by 400

14. 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 thenext number. Before it stops, it should print their addition & average.

Page 55: Introduction to Procedural Programming in C++

55

Precedence Rules, cont

introduction to Procedural Programming

The following list contains the precedence rules for some C++operators:

(), [], ., ->, (postfix)++, (postfix)-- unary +(unary), -(unary), ++(prefix), --(prefix), !, sizeof binary arithmetic *, /, %binary arithmetic +, -Boolean operators <, >, <=, >=Boolean operators ==, != Boolean operator &&Boolean operator ||assignment =,+=,-=,*=,/=,%=

For example, consider (x+1) > 2 || (x+1) < -3,this is equivalent to ((x+1) > 2) || ((x+1) < -3) because < and> have higher precedence than ||.

Page 56: Introduction to Procedural Programming in C++

56

Boolean Expressions

introduction to Procedural Programming

The C++ data type bool is new. it was added to C++ recently. C++ used the integers 1 and 0 for true and false. in fact, anything otherthan 0 was considered true. Although you can use integer values instead of values of type bool, you shouldn’t. The capability is leftthere for backward compatibility only. Use bool types instead.

Example:

if (1)cout<<“True”<<endl;

elsecout<<“False”<<endl;

The point is that you should be aware of this feature of C++. Not that you should use it in your programs.

Page 57: Introduction to Procedural Programming in C++

57

Multi-way if-else statements

introduction to Procedural Programming

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 havea 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, supposewe want to write a game-playing program in which the user must guess the value of some number.

cout<<“Guess the number: “;cin>>guess;if (guess >number)

cout<<“No, too high”;else if (guess==number)

cout<<“Correct!”<<endl;else

cout<<“No, too low”<<endl;

Page 58: Introduction to Procedural Programming in C++

58

Multi-way Branches, cont

introduction to Procedural Programming

The indenting used in the example on the previous slide was differentfrom what we have been using. if we followed our indenting rules, wewould produce something like the following:

if (guess>number)cout<“No, too high”<<endl;

elseif (guess == number)

cout<<“Correct”<<endl;else

cout<<“No, too low”<<endl;This is one of the rare cases where you should break the indenting rules and use the layout on the previous page rather than the oneabove. This is because the format on the previous page is clearerand easier to understand than this one. Also, this way you save space.

Page 59: Introduction to Procedural Programming in C++

59

Switch-statement

introduction to Procedural Programming

You used if-else statements to construct multi-way branches. Theswitch-statement is another kind of C++ statement that also imple-ments multi-way branches.

When a switch-statement is executed one of a number of differentbranches is executed. The choice of which branch is executed isdetermined by a controlling expression given in the parentheses after the keyword switch.

The controlling expression must always evaluate to either a bool, char, int or an enum type. When the switch-statement is executed,this controlling 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 thecontrolling expression, it executes the code for that case.

Page 60: Introduction to Procedural Programming in C++

60

Switch-statement, cont

introduction to Procedural Programming

Let’s look at an example involving a switch-statement:char grade;cout<<“Enter your grade: “;cin>>grade;switch (grade){

case ‘A’:cout<<“Excellent.”<<endl;break;

case ‘B’:cout<<“Very good.”<<endl;break;

case ‘C’:cout<<“Passing”<,endl;break;

case ‘D’:case ‘E’:

cout<<“Too bad, go study”<<endl;break;

default:cout<<“This is not a possible grade”<<endl;

}

Page 61: Introduction to Procedural Programming in C++

61

Switch-statement, cont

introduction to Procedural Programming

Notice that the constant is followed by a colon. Also note that youcannot have two occurrences of case with the same constant valueafter 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 iswhen the switch-statement ends. 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 ‘D’ and ‘F’ cause the same branch to be taken. if the value of grade is anything other than ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’ then thecout-statement after the identifier default is executed.

Page 62: Introduction to Procedural Programming in C++

62

++ and – Operators Revisited

introduction to Procedural Programming

You use the increment operator (++) to increase the value of a variableBy one. For example:

int number=2;int value_produced=2*(number++);cout<<value_produced<<endl;cout<<number<<endl;

The output will be 4 andf then 3.

The new value is assigned AFTER the increment operation. You canuse ++ before the variable name like:

int number= 2;int value_produced=2*(++number);cout<<value_produced<<endl;cout<<++number<<endl;

And this will output 6 and the 4. The increment operation is done BEFORE the variable is used.

Page 63: Introduction to Procedural Programming in C++

63

For-statement

introduction to Procedural Programming

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 that C++ includes a special statement for this kind of loop.

in performing numeric calculations, it is common to do a calculation with the number one, then with the number two and so forth until some last value is reached.

For example to add one through ten youwant the computer to perform the following statement ten times with the value of n equal to 1 the first time and with n increased byone each subsequent time.

sum=sum + n

Page 64: Introduction to Procedural Programming in C++

64

For-statement

introduction to Procedural Programming

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 whatthe for-loop was designed for. The following for-loop will neatly accomplish the same thing:

sum=0;for ( n=1; n <= 10; n++)

sum=sum + n;

Page 65: Introduction to Procedural Programming in C++

65

For-statement

introduction to Procedural Programming

An example involving a for-loop:

#include <iostream.h> initialization

main(){

int sum=0; repeat the loop as long as this is true

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

sum = sum + n; done after each} loop body iteration

cout<<“The sum of the numbers 1 to 10 is : “<<sum<<endl;return 0;

}

Page 66: Introduction to Procedural Programming in C++

66

break-statement

introduction to Procedural Programming

You have already used the break-statement as a way of ending a switch-statement. This same break-statement can be used to exit aloop. Sometimes you want to exit a loop before it ends in the normal way.For example, the loop might contain a check for improper input and ifsome improper input is encountered then you may want to end the loop. To input a list of negative numbers and exit the loop if positivenumbers are input:

int count=0, sum=0, number=0;while (++count <= 10) //ten loop iterations{

cin>>number; //input number if (number >= 0)

break; //exit loopsum = sum + number;

}

Page 67: Introduction to Procedural Programming in C++

67

Continue statement

introduction to Procedural Programming

We saw on the previous slide how to use the break-statement to exit from a loop or from a switch-statement case. There is anothercontrol statement that you can use in your programs: the continue statement.

The continue statement causes the current iteration of a loop to stop and the next iteration, if there is one, to begin. For exampleconsider the following code fragment:

while (true){

cin>>letter;if ( letter== ‘ ‘ ) continue;…

}

Page 68: Introduction to Procedural Programming in C++

68

Which Kind of Loop to Use

introduction to Procedural Programming

We have seen three kinds of loops in C++ so far. That’s all there ison loops in C++. As we have shown, you can do everything with justthe while-loop. The do-while loop is just an extension of the whileloop. And you can also use a while-loop instead of a for-loop afterjust a few changes.

But in general: if the loop involves a numeric calculation using a variableThat is changed by equal amounts each time through the loop, use a For-loop. it is the clearest and easiest loop to use for numeric calc-ulations.

in most other cases, you should use a while-loop or a do-while loop.it is quite easy to decide which of these to use. if you want theLoop body executed at least once use a do-while loop, otherwise use A while-loop.

Page 69: Introduction to Procedural Programming in C++

69

Exercises

introduction to Procedural Programming

15. 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

16. What is the output of the following fragment:

int count=3;while (count-- > 0)

cout<<count<<“ “;

17. What is the output of the following fragment:

int count=3;while (--count > 0)

cout<<count<<“ “;

Page 70: Introduction to Procedural Programming in C++

70

Exercises, cont

introduction to Procedural Programming

18. What is the output of the following fragment:int n=1;do

cout<< n << “ “;while (n++ <= 3);

19. What is the output of the following fragment:int n=1;do

cout<< n << “ “;while (++n <= 3);

20. What is the output of the following fragment:

for (int count=1; count < 5; count++)cout<< (2 * count) <<“ “<;

Page 71: Introduction to Procedural Programming in C++

71

Exercises, cont

introduction to Procedural Programming

21. For each of the following situations, tell which type of loop wouldBe better:

a. summing a series, such as ½ + 1/3 + ¼ + … +1/10b. inputting the list of exam marks for one student

22. Rewrite the following code as a for-loop:

int i=1;while ( i <= 10){

if (i < 5 && i !=2)cout<<‘X’;

i++;}

Page 72: Introduction to Procedural Programming in C++

72

Exercises, cont

introduction to Procedural Programming

23. Rewrite the following code as a for-loop:int i=1;while ( i <= 10){

cout<<‘X’;i = i + 3;

}

25. Rewrite the following code as a for-loop:long m=100;do{

cout<< ‘X’;m = m + 100;

}while ( m <= 1000);

Page 73: Introduction to Procedural Programming in C++

73

Arrays

introduction to Procedural Programming

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 isaccessed by an index.

in C++ the 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.

For example, to store a list of exam marks for students we can usean array as in:

int mark[5];

This array is of type integer and it can hold 5 variables of typeinteger. ‘mark’ is the name of this array.

Page 74: Introduction to Procedural Programming in C++

74

Arrays, cont

introduction to Procedural Programming

The array declaration (similar to variable declaration) on the previousslide is like the following declarations:

int mark1, mark2, …, mark5;

You can see that the array notation is clearer and more elegant.

The array int mark[5]; declares 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 firstElement 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 hasindex 0 and last element has index 4)

Page 75: Introduction to Procedural Programming in C++

75

Array initialization

introduction to Procedural Programming

You can initialize arrays in this way:

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 output the second elementof this array:

cout<< mark[1]<<endl;and the last element:

cout<< mark[4];

Page 76: Introduction to Procedural Programming in C++

76

Arrays, cont

introduction to Procedural Programming

#include <iostream.h>

main(){

int number[5];

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

number[i]=i; //initialize the arraycout<<i;cout<<"\t"<<(number[i] * number[i])<<endl;

}return 0;

}

Page 77: Introduction to Procedural Programming in C++

77

Arrays, cont

introduction to Procedural Programming

Let’s now look at the previous program more closely:

• because the array has five elements (its size is 5) we write a for-loop that iterates five times.

• During each iteration, we initialize the next element of the arrayand output that element on the screen. Then, we also outputthe result of squaring each array element on the screen.

• The escape character ‘\t’ is used to create a tab space betweenthe array element and its square value.

it is very common to use for-loops to step through array elements one by one.

Page 78: Introduction to Procedural Programming in C++

78

Arrays in Memory

introduction to Procedural Programming

Array indexed variables are stored in memory in the same way asordinary variables are stored. But with arrays, the locations of theArray indexed variables are always placed next to one another in thecomputer’s memory.

For example consider the following array declaration:int mark[5];

When you declare this array, the computer reserves enough memory To hold 5 variables of type integer and the computer always placesThese variables one after the other in the memory. The computerThen remembers the address of the indexed variable mark[0], but itDoes not remember the address of any other indexed variable. When your program needs the address of some other indexed variable the computer calculates the address of this other variablefrom the address of mark[0].

Page 79: Introduction to Procedural Programming in C++

79

Arrays, cont

introduction to Procedural Programming

The most common programming error made when using arrays isattempting to reference a non-existent array index. For exampleconsider the following array declaration:

int mark[5];

For this array, every index must evaluate to one of the integersbetween 0 and 4. if you write:

cout<<mark[i]<endl;

Then i must evaluate to one of: 0, 1, 2, 3, 4. if it evaluates to anything else it is an error. This is an out of range error.

Be especially careful when using for-loops to manipulate arrays.

Page 80: Introduction to Procedural Programming in C++

80

Exercises

introduction to Procedural Programming

26. Describe the difference in meaning of int x[5]; and the meaningOf x[4];

27. in the array declaration

double score[6];

what is the

a. the array nameb. the base typec. the declared size of the arrayd. the range of indexes that are OK for accessing the elementse. one of the indexed variables (or elements) of this array

Page 81: Introduction to Procedural Programming in C++

81

Exercises, cont

introduction to Procedural Programming

28. identify any errors in the following array declarations.

a. int x[4] = { 8, 7, 6, 4, 3};b. int x[] = { 8, 7, 6, 4};c. const int SiZE = 4; int x[SiZE];d. const int SiZE = 4; int x[SiZE – 4];

29. What is the output of the following code fragment:

char symbol[3]= { ‘a’, ‘b’, ‘c’};

for (int index =0; index < 3; index++)cout<<symbol[index];

Page 82: Introduction to Procedural Programming in C++

82

Exercises, cont

introduction to Procedural Programming

30. What is the output of the following fragment:

double a[3] = { 1.1, 2.2, 3.3};cout<< a[0]<<“ “<<a[1]<<“ “<<a[2]<<endl;a[1]=a[2];cout<< a[0]<<“ “<<a[1]<<“ “<<a[2]<<endl;

31. What is wrong with the following piece of code:

int array1[10];for (int index=1; index <= 10; index++)

array1[index]=3*index;32. Write a full complete C++ program to fill an array with 20values of type integer from the keyboard. The program should alsoOutput the square and square root of each array element next to itLike a table.

Page 83: Introduction to Procedural Programming in C++

83

Structures

introduction to Procedural Programming

So far, we have only seen basic data types which had single dataitems. Now we will look at a data type that is user defined and is acomposite type. You can define your own composite data types usingstructures.

For example, if you want to represent a point in the two-dimensionalplane, you would need two values: one for the x-axis and one for the y-axis ( the point coordinates) You can represent a point as a datatype whose type is a structure consisting of two values of type int.

struct point{

int x;int y;

};

Page 84: Introduction to Procedural Programming in C++

84

Structures, cont

introduction to Procedural Programming

The structure ‘point’ which we defined on the previous slide, is a newuser defined data type. You can declare variables of this type inyour programs which include its definition. To declare a variable of this new type, you follow the same method as we did for basic data types:

point firstPoint;

The variables inside the structure are called member variables and their values the structure’s member values.

Member variables are specified by giving the name of the structurevariable followed by a dot and then the member name. For exampleto initialize the variable ‘point’ from last slide:

firstPoint.x=0;firstPoint.y=0;

Page 85: Introduction to Procedural Programming in C++

85

Structures, cont

introduction to Procedural Programming

But it is more common to initialize structures as in

firstPoint = {0, 0};Do not forget the semicolon at the end of the definition of a structuretype and at the end of initialization.

Also, like other basic data types, you can assign one structure variableTo another variable of the same type as in

point firstPoint, secondPoint;firstPoint={1,2};secondPoint=firstPoint;

But you cannot compare structures with each other:if (firstPoint==secondPoint) //illegalif ((firstPoint.x==secondPoint.x) &&

(firstPoint.y==secondPoint.y)) //OK

Page 86: Introduction to Procedural Programming in C++

86

Structures, cont

introduction to Procedural Programming

Let’s look at an example program in which we define and use a struc-ture:#include <iostream.h>#include <math.h>struct point{

int x;int y;

};main(){

point firstPoint={4,9};point secondPoint={5,10};double distance=0.0;

distance = sqrt(((secondPoint.x – firstPoint.x)* (secondPoint.x – firstPoint.x)) + ((secondPoint.y – firstPoint.y)*

(secondPoint.x – firstPoint.x)))cout<<“the distance between points (4,9) and (5,10) is “<<distance<<endl;return 0;

}

Page 87: Introduction to Procedural Programming in C++

87

Strings

introduction to Procedural Programming

C++ can manipulate text strings in two ways: using cstring values usedin C language and with the new string type that was recently addedto the language. We will cover both methods in these slides.

A cstring variable is exactly the same thing as an array of characters.For example, the following array of characters is capable of storinga cstring value with 9 or fewer characters:

char name[10];

This is because a cstring variable is used in a differernt way thanan ordinary array of characters. A cstring variable places the specialsymbol ‘\0’ in the array immediately after the last character of thecstring.

Page 88: Introduction to Procedural Programming in C++

88

Strings, cont

introduction to Procedural Programming

For example, consider the following cstring variable:

char name[10] = “MR Nice”;name[0] name[9]

The character ‘\0’ is used to mark the end of the cstring. Since thecharacter ‘\0’ always occupies one element of the array, the lengthof the longest cstring that the array can hold is one less than the size of the array.

The character ‘\0’ is called the null character. You can do input andoutput with cstring variables as you do with other types of variables.

M r N i c e \0 ? ?

Page 89: Introduction to Procedural Programming in C++

89

Strings, cont

introduction to Procedural Programming

You cannot use a cstring variable in an assignment statement using =.Also, if you use == to test cstrings for equality, you will not get theresult you expect. The reason is that cstrings and cstring variablesare arrays rather than simple variables and values.

So you CANNOT do the following:char name[10];name=“Mr Nice”;

This is illegal in the homeland of C++!. You can only do this when youdeclare the cstring variable as in:

char name[10]=“Mr Nice”;

Technically, this is an initialization and not an assignment and is legal.

Page 90: Introduction to Procedural Programming in C++

90

Strings, cont

introduction to Procedural Programming

There are a number of ways to assign a value to a cstring variable.The easiest way is to use the predefined function strcpy as in:

strcpy(name, “Mr Nice”);This will assign (assignment) the value “Mr Nice” to character arrayname.

Also, you CANNOT use the operator == in an expression to test if twocstrings are equal. You can use the function strcmp as in:

char name1[]=“Mr A”, name2[]=“Mr B”;

if (strcmp(name1, name2)cout<<“The two names are NOT the same”<<endl;

else cout<<“The two names are the same”<<endl;

Page 91: Introduction to Procedural Programming in C++

91

Strings, cont

introduction to Procedural Programming

Note that the function strcmp works differently than you might expect. if the function returns a zero it means that the twocstrings are the same (equal).

The functions strcpy and strcmp are defined in the library file string.h so you must include this library in your C++ programs to beable to use the functions.

Another useful function in this library is called strlen which returnsthe length of the specified cstring. (‘\0’ is not counted) For example:

int length=0;char name[]=“Software Engineering”;length=strlen(name);cout<<length<<endl; //will output ?

Page 92: Introduction to Procedural Programming in C++

92

Strings Input and Output

introduction to Procedural Programming

As we have already seen, cstring output is easy; we just use the insertion operator << to do output.

Also you can use the input operator >> to fill a cstring variable, butthere is one thing to be aware of. All spaces are skipped when cstrigsare read this way. For eg.

char a_cstring[20];cout<<“Enter some input:\n”;cin>>a_cstring;cout<<a_string<<endl;

The output:Enter some input:Mr NiceMr

Page 93: Introduction to Procedural Programming in C++

93

Strings input and Output, cont

introduction to Procedural Programming

So there is a problem with cstring input when input contains spacesor tabs. The solution to this problem is to use the predefined function getline which is also defined in the string.h library.

Let’s see an example:

char a_cstring[30];cout<<“Enter some text:\n”;cin.getline(a_cstring, 30);cout<<a_cstring<<endl;

Here, the inputted text or string is copied into the cstring variablea_cstring. The number 30 specifies the number of characters to be copied into the variable a_cstring. (we will discuss functions after finishing this topic)

Page 94: Introduction to Procedural Programming in C++

94

Exercises

introduction to Procedural Programming

33. Consider the following two statements and whether they aretrue or false:

a. the types of an array elements must all be the same?b. the types of a structure’s members must all be the same?

34. Consider the following code:struct student{

char name[20];int year;bool male;

};student software_student;

What is the type of a. student.male?b. student.name?c. software_student?

Page 95: Introduction to Procedural Programming in C++

95

Exercises, cont

introduction to Procedural Programming

35. What is the output of the following code:(if included in a complete program)

struct student{

char name[20];int year;

};student software_students[30];for(int i=0; i<30; i++){ cout<<“Enter student’s name:”

cin.getline(software_student[i].name, 20);cout<<“Enter student’s year:”;cin>>software_students[i].year;cin.ignore(1, ‘\n’); //don’t worry about this now

}cout<<“Software students are the following:”;for(int j=0; j<30; j++) cout<<software_students[i].name<<“ “<<

software_students[i].year<<endl;

Page 96: Introduction to Procedural Programming in C++

96

Exercises, cont

introduction to Procedural Programming

36. Define a structure called student with the following membervariables:

• Student’s name• Male/Female• Date of Birth• Students Exam Marks

Note:1. You should define another structure which can represent a calendar date. 2. You should also define a structure to represent the marks that each student has obtained in each subject. 3. Number of subjects is pre-determined.

Page 97: Introduction to Procedural Programming in C++

97

Exercises, cont

introduction to Procedural Programming

37. Write a C++ program that can maintain information about a personal bookshelf. The program asks for information about a newbook such as the author, title, ISBN no., price, year published. Use astructure to hold book information.

38. Find as many errors as you can find in the following piece of C++code:

struct employee{

char name[];char address[30];bool married;double salary;

}employee college_employees[100];for (int i=0; i<=100; i++)

college_employees[i].salary *=1.2;

Page 98: Introduction to Procedural Programming in C++

98

Exercises, cont

introduction to Procedural Programming

39. Write a program in which the user can input their full name (consisting of exactly two words separated by a space). Store the complete name, including the space, into a single cstring variable.

Then separate the two words and store them in two separate cstringvariables. Test your program.

40. Based on the previous program, write another program in whichthe user enters their name such as

XXX YYYYYYAnd then the program rearranges the first and last names into

YYYYYY, XXX 41. Write a program that accepts a word from the user and outputsthe number of vowels in that word. (Vowels include: A, E, I, O and U)

Page 99: Introduction to Procedural Programming in C++

99

Functions and Procedural Abstraction

introduction to Procedural Programming

A natural way to solve large problems is to break them down into aseries of smaller sub-problems, which can be solved more-or-less independently and then combined to arrive at a complete solution.

In programming too, you can follow a similar approach and divide largeprograms into smaller sub-programs; in C++ sub-programs are calledfunctions.

Most programs consist of 3 main sections: input, some calculationsand output. We can perform each of these sections separately andcombine the results to produce the final complete program.

In larger programs, it’s almost impossible or very difficult to do anything without dividing the program using functions. This followsthe old Roman philosophy of divide-and-conquer.

Page 100: Introduction to Procedural Programming in C++

100

Functions, cont

introduction to Procedural Programming

We have already seen functions such as sqrt(…) to get the squareroot of a number. Or the strcpy(s1, s2) which copies one stringto another.

These are pre-defined functions that we can use in our programs. Somebody else has defined them; we just use them and we even don’tneed to know how the are defined as long as we know how to use them.

The function sqrt(…) is defined in a file that we can access via theC++ library ‘math.h’. And the function strcpy(s1, s2) is definedin a file which we can access via the library ‘string.h’.

You can have user-defined functions too. You can define your ownfunctions to do specific tasks.

Page 101: Introduction to Procedural Programming in C++

101

Functions, cont

introduction to Procedural Programming

In the next few slides we will try to write our own functions. At firstwe will put these functions in the same file as “main”. Later we willsee how to put them in separate files. Example:#include <iostream.h>int area(int length, int width); //function declaration

main(){

int this_length, this_width, rectangle_area;cout<<“Enter the length followed by width:”;cin>>this_length>>this_width;rectangle_area=area(this_length, this_width); //function callcout<<“The rectangle area is “<<rectangle_area”<<andl;return 0;

}int area(int length, int width) //start of function definition{

int number;number= length * width;return number; //function returning a value

}

Page 102: Introduction to Procedural Programming in C++

102

Functions, cont

introduction to Procedural Programming

We will now look at this program closely to see how functions work:• The structure of a function is similar to the structure of “main”

with its own list of variable declarations and statements

• A function may have a list of zero or more parameters inside itsbrackets, each of which has a separate type.

• A function must be declared before it can be used or called. Functions are declared just before the ‘main’ function begins.

• Function declarations are a bit like variable declarations; theyspecify which type the function will return.

• You can define as many functions as you require provided youdeclare them first.

Page 103: Introduction to Procedural Programming in C++

103

Functions, cont

introduction to Procedural Programming

The function ‘area(…,…)’ returns a value of type int. And it takestwo parameters. A parameter is variable; during a function call thisparameter is replaced with a value.

In the this function, we have two parameters, both of type int. When we call the function area(…,…) we pass two variables, this-length and this-width, to the function. The function area(…,…)then does some action on these variables and at the end, returns some value of type int.

The parameters in the above function are called value parameters.When the function is called in the main function, it is passed the current values of the variables this_length and this_width. The function then stores these values in its own local variables and usesits own local copies in its subsequent computation.

Page 104: Introduction to Procedural Programming in C++

104

Exercises

introduction to Procedural Programming

42. What is the output of the following program?#include <iostream.h>

bool is_even(int number); //function declarationmain(){

int i=0;cout<<“enter a number: “;cin>>i;if (is_even(i))

cout<<i<<“ is even”<<endl;else

cout<<i<<“ is odd”<<endl;return 0;

}bool is_even(int num){

if (num % 2 == 0)return true;

elsereturn false;

}

Page 105: Introduction to Procedural Programming in C++

105

Exercises, cont

introduction to Procedural Programming

43. Write a function that takes three parameters of type int. Thefunction returns the sum of its three parameters. Test the functionin a complete C++ program that asks the user for 3 numbers to be added.

44. What does the following function do? Embed it in a full programand test it.

int factorial(int n){

int product = 1;while ( n > 0) //n must be nonnegative{

product = n * product;n--;

}return product;

}

Page 106: Introduction to Procedural Programming in C++

106

Exercises, cont

introduction to Procedural Programming

45. Consider the declarations/prototypes of the following pre-defined mathematical functions:

double sqrt(double x); //returns square root of xdouble pow(double x,double y); //returns x to the power of ydouble ceil(double x); //returns ceiling of xdouble floor(double x); //returns floor of x

What would be the value of the 4 local variables if the following function was called with num1=2.0 and num2=2:

int myFunction(double num1, double num2){

double localVar1, localVar2, localVar3, localVar4;localVar1 = sqrt(num1);localVar2 = pow(num2, 3.0);localVar3=ceil(localVar1);localVar4=floor(localVar1);return 0;

}

Page 107: Introduction to Procedural Programming in C++

107

Type Casting

introduction to Procedural Programming

Remember that 9/2 is integer division, and evaluates to 4 , not 4.5.If you want division to produce an answer of type double, then at least of the two numbers must be of type double. Ex, 9/2.0 returns4.5. We can do this because we had constants and we added a decimal point and a zero to one or both numbers. BUT if both the operandsin the division are variables, not constants, then we would have a problem.

In C++ you can tell the computer to convert a value of one type to a value of another type:

double(9)/2 produces 4.5 because the type double can also be used as a pre-defined function. Another ex, double(2) evalutaes to 2.0.This is called type casting.

Page 108: Introduction to Procedural Programming in C++

108

The Black Box

introduction to Procedural Programming

A person who uses a program should not need to know the details ofHow the program is coded. That person should know how to use theProgram but not how the program works.

A function is like a small program and should be viewed in a similarway. A programmer who who uses a function needs to know how touse the function but not how the function does its job. This is whatis meant when viewing a function as a black box.

Writing functions 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 functions. The wordabstraction is intended to convey the idea that when you use a function as a black box, you are abstracting away the details of the code in the function body.

Page 109: Introduction to Procedural Programming in C++

109

The Black Box, cont

introduction to Procedural Programming

The term black box, information hiding and procedural abstraction all refer to the same principle. They all mean the same thing.

The basic idea is that the programmer who uses a function should notneed to look at the body of the function definition to see how thefunction works.

The function prototype/declaration and the accompanying commentshould be all the programmer needs to know to use the function.

It’s very important to comment your functions. The comments shoulddescribe what the function does, not how. They should also mentionany conditions that are required of the parameters to the function and describe the value that is returned by the function. Consider thePredefined function sqrt, we can use it without knowing how it works.

Page 110: Introduction to Procedural Programming in C++

110

Local Variables

introduction to Procedural Programming

As we have already seen in some of the functions that we havedefined, you can have variables declared inside those functions.

These variables exist only when you call the function to which theybelong. Variables declared inside functions are called local variables.

The scope of a local variable is the function inside which that variableis declared. It doesn’t exist outside that function.

If you have a local variable in a function, you can have another variable with the same name that is declared in the main function or in another function and these will be different variables.

Remember that main is also a function; but a special one. Every C++program must have the main function.

Page 111: Introduction to Procedural Programming in C++

111

Global Constants and Global Variables

introduction to Procedural Programming

In general, constants are declared outside any functions, even outsidethe main function. This is good programming as it is usually the casethat more than one function uses the same constant.

Constants are therefore usually declared as a group and just after any #include directives. Hence the name global constant.

Also, you can declare variables outside any function definitions. These are called global variables. The scope of global variables is the entire program, unlike local variables whose scope is limited to a particular function.

However, there is seldom any need to use global variables. Also, global variables make a program harder to understand and maintain.So we will not use global variables unless in exceptional cases.

Page 112: Introduction to Procedural Programming in C++

112

Void Functions

introduction to Procedural Programming

The functions that we have seen so far all returned a single value. InC++ a function must either return a single value or return no values atall. A function that returns no value is called a void function. Ex.

void myFunction(int num);{

num++;cout<<“ one plus your number is “<<num<<endl;

}

As you can see, this function returns no values; it has no return statements. You call void functions like other C++ statements as in:

main(){

int x=0;myFunction(x); //function callretrun 0;

}

Page 113: Introduction to Procedural Programming in C++

113

Call-by-Reference Parameters

introduction to Procedural Programming

Will the function in the following program swap values of x1 and x2?main(){

int x1=5, x2=10;swap(x1, x2);cout<<“now x1 is “<<x1<<“ and x2 is “<<x2<<endl;return 0;

}void swap(int num1, int num2){

int temp=num1;num1=num2;num2=temp;

}

No, it will not. Because here, x1 and x2 have been passed to swap byvalue. Copies of x1 and x2 are made and passed to swap and any changes to their values,inside the function, occur on the copies ofthe two variables.

Page 114: Introduction to Procedural Programming in C++

114

Call-by-Reference Parameters, cont

introduction to Procedural Programming

The parameters x1 and x2 are call-by-value parameters. The value of the parameters is passed to the function not the variables themselves.

To ensure that the actual variables are passed to the function C++ supports call-by-reference parameters. This way, the address orthe actual variables are passed to the function. To correct the swapfunction we need to use reference parameters as in:

void swap(int& num1, int& num2) //call-by-reference parameters{

int temp=num1;num1=num2;num2=temp;

}

Notice that you need to append the ampersand sign & to the name.

Page 115: Introduction to Procedural Programming in C++

115

Exercises

introduction to Procedural Programming

46. What is the output of the following program?

#include <iostream.h>void average(int& x, int& y, int&z);main(){

cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);int num1=0, num2=0, num3=0;cout<<“Enter 3 numbers:”;cin>>num1>>num2>>num3;cout<<“The average is “<<average(x, y, z)<<endl;return 0;

}void average(int& x, int& y, int& z){

return double(x + y + z))/3;}

Page 116: Introduction to Procedural Programming in C++

116

Exercises, cont

introduction to Procedural Programming

47. What is the output of the following program?#include <iostream.h>bool isInArray(int a[],int num);main(){

int x, a[]={2,3,4,5};cout<<"enter a number:"<<endl;cin>>x;if (isInArray(a, x))

cout<<"yes"<<endl;return 0;

}bool isInArray(int a[], int num){

for (int i=0; i<4; i++)if (num==a[i])

return true;return false;

}

Page 117: Introduction to Procedural Programming in C++

117

Exercises, cont

introduction to Procedural Programming

48. Write a function 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 function should take the array as a parameter and return the smallest number as the return value. Test the functionin a complete program.

49. Rewrite the above function as a void function and get the function to change the value of a variable passed on to the functionas a parameter.

50. Write a program that takes 2 dates and then calculates the number of days between those 2 dates. You can create a new datastructure as Date to represent calendar dates. Use a function thattakes two dates as parameters and calculates the number of days between them.

Page 118: Introduction to Procedural Programming in C++

118

Exercises, cont

introduction to Procedural Programming

51. From school you know that the standard quadratic equation ax2 + bx + c = 0

has two solutions given by formula

-b + b2 – 4ac

2a

Write a function that reads a, b and c and then calculates the twosolutions. If the quantity under square root is negative it should display an appropriate message. You may assume that the value fora is nonzero. Test the function in complete program.

Page 119: Introduction to Procedural Programming in C++

119

Exercises, cont

introduction to Procedural Programming

52. You have seen the pre-defined math.h function pow which takestwo double parameters and returns the power of first parameterraised to the second parameter. Write your own pow function andcall it myPow. Test your program in a complete program.

53. Write a function that takes two int arrays as parameters andif the two arrays are equal, ie have the same elements, it should return true otherwise false. Test your program in a complete program.

54. Write a function that takes two character array strings asparameters and if the two strings are equal it should returntrue otherwise false. Test your program in a complete program.

Page 120: Introduction to Procedural Programming in C++

120

Sorting Arrays

introduction to Procedural Programming

One of the most common programming tasks is sorting a list of valuesfrom highest to lowest or vice versa or a list of words into alphabetical order.

There are many sorting algorithms; some are easy to understand butnot 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 index=0; index<ARRAY_SIZE; index++)Place the indexth smallest element in a[index]

Where a is an array and array-size is the declared size of the array.algorithms are usually expressed in pseudo-language.

Page 121: Introduction to Procedural Programming in C++

121

Sorting Arrays, cont

introduction to Procedural Programming

The algorithm iterates through all the elements of the array one byone and at each iteration it places the smallest number in the arrayin the next suitable position.

Now we will implement this algorithm description in C++. We need functions to do the following:

• To find the smallest number in the array• To swap two values• To sort the array

We will now implement each of these functions separately and thenwrite a main function to test the functions.(We have already implemented the swap function, see slide 112)

Page 122: Introduction to Procedural Programming in C++

122

Sorting Arrays, cont

introduction to Procedural Programming

The sort function can be implemented as follows:

void sort(int array[]){

int index_of_next_smallest = 0;for(int index=0; index<ARRAY_SIZE-1; index++){

index_of_next_smallest=index_of_smallest(array, index);swap_values(array[index], array[index_of_next_smallest]);

}}

Notice that the last iteration is redundant (ARRAY_SIZE - 1 iterations)

We call another function to find the index of the next smallest value,and then call yet another function to swap that value with the value of the current position in the array.

Page 123: Introduction to Procedural Programming in C++

123

Sorting Arrays, cont

introduction to Procedural Programming

Now we will implement the function which will find the index of thenext smallest element of the array:

int index_of_smallest((int array[], int start_index){

int min=a[start_index];int index_of_min=start_index;

for (int index=start_index; index<ARRAY_SIZE; index++)if (array[index] < min){

min=array[index];index_of_min=index;

}

return index_of_min; //return index of smallest number}

Page 124: Introduction to Procedural Programming in C++

124

Exercises, cont

introduction to Procedural Programming

55. Write a predicate function (whose return value is either true orfalse) that takes an int array as a parameter and returns true if thearray is sorted in ascending order. Test your function in a program.

56. 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. Thepairs overlap so that the second element of the a pair becomes thefirst 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 tobubble up to their eventual positions.

Page 125: Introduction to Procedural Programming in C++

125

I/O Streams

introduction to Procedural Programming

So far we have learnt how to input data from the keyboard and output data to the screen. But for many real problem we need to beable to input data from a file and out date into a file.

I/O from and into files can be done using C++ streams. Input streamfor data input from a file and output stream for output to a file.

You have already used some kinds of streams: cin (an input stream) which is connected to the keyboard and cout (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 endsthe data typed in at the keyboard and the output data to the screenis lost. Files provide you with a way to store data permanently.

Page 126: Introduction to Procedural Programming in C++

126

I/O Streams, cont

introduction to Procedural Programming

When your program takes input from a file it is said to be readingFrom the file and when your program sends output to a file it is saidTo be writing to the file.

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 beginning of the file.

A streams is a special kind of variable known as an object. As we saidEarlier there are both input and output streams. If you want a streamTo connect to a file, you must declare it as with variables.

The type for input file stream variables is ifstream and the type forOutput file stream variables is ofstream. Both of these types areDefined in the library fstream.h.

Page 127: Introduction to Procedural Programming in C++

127

I/O Streams, cont

introduction to Procedural Programming

Once you declare a stream variable of type ifstream or ofstream you then must connect it to a file. This is called opening the file. Ex,main(){

ifstream input_file;ofstream output_file;

input_file.open(“myInFile.txt”); //opening the fileoutput_file.open(“myOutFile.txt”); //opening the fileint num1, num2;input_file>>number1>>number2; //reading dataoutput_file<<num1<<“ “<<num2<<endl; //writing data

input_file.close(); //close fileoutput_file.close(); //close filereturn 0;

}

Page 128: Introduction to Procedural Programming in C++

128

I/O Streams, cont

introduction to Procedural Programming

In the previous example, one input stream and one output stream were declared and then two files were opened, open for to read fromand one to write to.

Two numbers were read from the input file and these values were then wrote to the output file using the output stream connected to the output file.

Note that we only refer to the real name of a file once, when openingthe file. After a file is opened, the file is always referred to by naming the stream that is connected to the file.

Also remember that every file should be closed when your program is finished reading from a file or writing to a file. Forgetting to closea file may result in a corrupted file.

Page 129: Introduction to Procedural Programming in C++

129

I/O Streams, cont

introduction to Procedural Programming

Always check that a file was opened successfully. Trying to open a file may fail for a number of reasons; for example, if there is nofile with such a name the call to open will fail.

You can use an input stream function called fail to test whether a stream operation has failed. Ex,

input_file.open(“input.txt”);if (inout_file.fail()){

cout<<“Input file opening failed.\n”;exit(1); //end the program

}

The exit statement causes your program to terminate immediately. By convention, pass 1 for errors and 0 for success in. Exit(n) is defined in library stdlib.h.

Page 130: Introduction to Procedural Programming in C++

130

I/O Streams, cont

introduction to Procedural Programming

Let’s now look at a program that reads all the contents of a file, frombeginning to end of the file:main(){

ifstream input_file; int next, count=0;double sum=0;input_file.open(“myInFile.txt”); //opening the filewhile(input_file>>next) //also acts as a Boolean exp.{

sum=sum + next;count++;

}cout<<“the average of numbers: “<<(sum/count)<<endl;input_file.close(); //close filereturn 0;

}

Page 131: Introduction to Procedural Programming in C++

131

Character I/O

introduction to Procedural Programming

Every input stream, whether it’s an input file stream or the streamcin has get as a member function. This function is used to read onecharacter of input. Unlike the extraction operator >>, get reads thenext character, no matter what that character is; it will even readblanks (spaces), tabs, new-lines etc.

This function has one parameter which must be a variable of type char. Ex,

char next_symbol;cin.get(next_symbol);

This code will get the next character input from the keyboard andstore it in the variable next_symbol. Remember that the functionget can also be used with input file streams.

Page 132: Introduction to Procedural Programming in C++

132

Character I/O, cont

introduction to Procedural Programming

The member function put is analogous to the member function getexcept that it is used for output rather than input. Again as with get, the member function put is a member function of every outputstream. Ex,

cout.put(next_symbol); //output it to screencout.put(‘b’); //output ‘b’ to screen

This is some code to make a copy of one file (backup):in.open(“input_file.txt");out.open("output_file.txt");char next;in.get(next);while(next != 'X') //make sure ‘X’ is in the file{

out.put(next); //write to output filein.get(next); // read next caharacter

} // from input file

Page 133: Introduction to Procedural Programming in C++

133

Character I/O, cont

introduction to Procedural Programming

The input file stream has a useful function which can be used to determine when all of a file has been read and there is no more input left to be read. This is the second technique we have seen fordetermining end of files. This method is more suitable for text fileswhile the previous one is more suitable for files that consist ofnumeric data. This function is called eof which stands for end-of-file. Ex,

ifstream input_file;input_file.open(“input.txt”);

input_file.get(next);while( ! input_file.eof()){

cout.put(next); //or cout<<next;input_file.get(next); //read next character

}

Page 134: Introduction to Procedural Programming in C++

134

Character I/O Functions

introduction to Procedural Programming

There are a number of useful character I/O functions that can beused to process text files. Among these functions are: (ctype.h)

- toupper(char_var) returns uppercase version of char_varex, toupper(‘a’) returns ‘A’

- tolower(char_var) returns lowercase version of char_varex, tolower(‘H’) returns ‘h’

- isspace(char_var) returns true if char_var is either a space, tab or a new-line (‘\n’), otherwise returns falseex, isspace(‘ ‘) returns true

- isupper(char_var) returns true if char_var is uppercase letter,ex, isupper(‘L’) retruns true

- islower(char_var) returns true if is char_var is a lowercase letter, ex, islower(‘r’) retruns true- isalpha(char_var) returns true if char_var is a letter of the

alphabet ex, isalpha(‘$’) returns false- isdigit(char_var) returns true if char_var is one of the digits

0,1….9. Ex isdigit(‘5’) returns true;

Page 135: Introduction to Procedural Programming in C++

135

Exercises

introduction to Procedural Programming

57. Write a function that takes as parameter the name of a file,then it opens the file and outputs all the contents of the file ontothe screen. First create a text file and type some text in the fileand save it in the same directory. Test your function in a program.

58. Write a function that takes two file names as parameters andcopies the contents of the first file into the second file. Test yourProgram in C++ program.

59. Write a function takes a file name as its only parameter. The function will search the file of numbers of type int and write thelargest and smallest numbers to the screen. The file containsnothing but numbers of type int separated by blanks or line breaksor tabs. Test your function in a C++ program.

Page 136: Introduction to Procedural Programming in C++

136

Exercises, cont

introduction to Procedural Programming

60. Write a program that reads text from one text file and writesan edited version of the same text to another file. The editedtext is identical to the original version except that its text is all inupper case.

61. Write a program that reads all the contents of a text file andwrites everything except numbers into another file. It filtersnumbers from the file.

62. Write a function that takes three filenames as parameters. Twoinput files and one output file. The input files consist of numbers of type int only. The numbers in the two files are in sorted order fromthe smallest to the largest. The output file will contain all the numbers from the two input files in one longer list in sorted orderfrom smallest to largest. Test your function a C++ program.

Page 137: Introduction to Procedural Programming in C++

137

Exercises, cont

introduction to Procedural Programming

63. This is a programming mini-project.

Write a program that defines a new structure called student and asks the user to enter information on first year Software Engineering students. The structure has name, year, grade as structure member variables.

The program should write or save this information to an output file.

Then define a function to check whether a particular student nameis enrolled on this course. The function takes a student’s name asParameter and it then searches the file that contains student detailsto see if that student is on the course. If he/she is then it shouldprint the students details on the screen.

Page 138: Introduction to Procedural Programming in C++

138

Exercises, cont

introduction to Procedural Programming

64. Write a program to count the number of lines, the number of words and the number of non-blank characters in a file. Itshould 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.

65. Write a function that reads text from a file and writes each linepreceded by a line number starting from 1. Follow the line numberwith a colon and a space for clarity. You may assume that the linesare short enough to fit within a line on the screen. Test your function in a C++ program.

Page 139: Introduction to Procedural Programming in C++

139

Exercises, cont

introduction to Procedural Programming

66. Write a function to strip or remove comments (//) from a C++source file. Do this program in stages. First write a functionwith the prototype/declaration

void stripFile(ifstream &inFile, ofstream &outFile);Which simply reads lines from the input stream inFile to a character array and then output them to the output stream outFile.

You need to store new-line characters explicitly as they do not get stored in the character array automatically.

Then change your function to remove the comments from a filewhose name is input from the keyboard. The program should alsoask the user for the name of the output file. Test you function in aC++ program.

Page 140: Introduction to Procedural Programming in C++

140

Multidimensional Arrays

introduction to Procedural Programming

In C++, the elements of an array can be of any type. In particular,the elements of an array can themselves be arrays. Arrays of arraysare called multidimensional arrays.

The most common form of a multidimensional array is a two-dimensional array which is similar to a rectangular structure dividedinto rows and columns. This type of two-dimensional array is called amatrix.

You can have arrays of 3 or more dimensions. They are less common.

Consider the two-dimensional array matrix:int matrix[2][3]={{2,2,2}, //two rows, three columns

{2,2,2}};This is an array (size 2) of two arrays (size 3).

Page 141: Introduction to Procedural Programming in C++

141

Multidimensional Arrays, cont

introduction to Procedural Programming

We will now look at an example involving two-dimensional arrays; in this example we will write a function to add to matrixes.

main(){

int array1[4][2]={ 0,1, 0,1, 0,1, 0,1};

int array2[4][2]={ 1,1,1,1,

2,2, 2,2};

addMatrixes(array1, array2);

return 0;}

cont…

Page 142: Introduction to Procedural Programming in C++

142

Multidimensional Arrays, cont

introduction to Procedural Programming

The function takes two two-dimensional arrays as parameters. It adds the two matrixes and puts the result into the first array. It then prints the result matrix on the screen.

void addMatrixes(int a[][2], int b[][2]){

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

for(int j=0; j<2; j++)a[i][j]=a[i][j]+ b[i][j]; //adding

}// to display the result on the screenfor(i=0; i<4; i++){

for(j=0; j<2; j++)cout<<array1[i][j]<<" ";

cout<<endl;}

}

Page 143: Introduction to Procedural Programming in C++

143

Multidimensional Arrays, cont

introduction to Procedural Programming

For multi-dimensional array parameters, all the dimension sizesexcept the first must be given. This makes sense if you think ofa multi-dimensional array as an array of arrays. In this example we have an array each element of which is an int array of size 4. Remember that if you have an array parameter, you do not have to specify the 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 amulti-dimensional array can be any type; but for numerical calculationsthe 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.

Page 144: Introduction to Procedural Programming in C++

144

Exercises

introduction to Procedural Programming

67. Write a function that has one parameter of type int array[][2]The function multiplies its parameter by the unit matrix and printsthe result. Test your function in a C++ program.

68. Write a function that takes two parameters one of type int a[2][5] and the other of type int b[5][2] and then multiplies the two matrixes together and writes the result in a third matrix. Test you function in C++ program.

69. Write a function that takes a parameter of type int a[5][5]and changes the value of every element above the diagonal to 0 and

70. Write a function that takes a parameter of type int [4][4] and exchanges the elements above and below the diagonal together. Leave the diagonal values unchanged.

Page 145: Introduction to Procedural Programming in C++

145

Pointers

introduction to Procedural Programming

A pointer is the memory address of a variable and can be stored in a variable. But even though a pointer is a memory address and a memory addresses are numbers, you cannot store a pointer in a variable of type int or double. A variable to hold a pointer must bedeclared to have a type. Ex.

double *p1, *p2, v1, v2;p1 = &v1;

The variables p1 and p2 can hold pointers to variables of type double.Also notice that you need to add an asterisk before the pointer variable name.

Pointer variables can point to variables like v1 and v2 since they are of type double. You can use the operator & to get the address of avariable and then assign that address to a pointer variable.

Page 146: Introduction to Procedural Programming in C++

146

Pointers, cont

introduction to Procedural Programming

Now we have two ways to refer to a variable: you can call it v1 or youcan call it “the variable pointed to by p1. In C++ you use *p1 to say“the variable pointed to by p1”. This use of the asterisk operator iscalled the dereferencing operator. To clarify things, consider thispiece of C++ code:

int v1, *p1;v1=0;p1=&v1;*p=32;cout<<v1<<“ “<<*p1<<endl;

What will this code produce? Because p1 is a pointer pointing to v1then both *p1 and v1 refer to the same variable. So when you set *p1to 32, you are also setting v1 to 32.

Page 147: Introduction to Procedural Programming in C++

147

Pointers, cont

introduction to Procedural Programming

You can assign the value of one pointer to another pointer variable.For example, if p1 is still pointing to v1, then the following will set p2so that it also points to v1:

p2=p1;and if we write

cout<<*p2;

this will also output 32.

Using pointers, you can use variables even if variables have no namesor identifiers. the operator new can be used to create variables thathave no identifiers as their names. These nameless variables arereferred to via pointers.

Page 148: Introduction to Procedural Programming in C++

148

Pointers, cont

introduction to Procedural Programming

Consider the following piece of C++ code:

int *p;p=new int;cin>>*p;*p=*p+1;cout<<*p1;

the first statement creates a pointer of type int and the second onecreates an integer variable and sets p to point to this variable. Thisnameless variable can be referred to as *p. Here we have an integer variable but without a name; but we can use the pointer p to refer toit.Variables that are created using the new operator are called dynamic variables. They are created and destroyed while the program is running.

Page 149: Introduction to Procedural Programming in C++

149

Pointers, cont

introduction to Procedural Programming

A program to demonstrate pointers and dynamic variables:main(){

int *p1, *p2; //two pointers of type intp1=new int; // dynamic int variable*p1=32;p2=p1; //assign p2 to p1cout<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl;*p2=53;cout<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl;p1=new int;*p1=88;cout<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl;cout<<“Hope you got the point of this example!!!”<<endl;return 0;

}See the next slide for a pictorial explanation of this program.

Page 150: Introduction to Procedural Programming in C++

150

Pointers, cont

introduction to Procedural Programming

1- int *p1, *p2;p1 ? 4- p2=p1;p2 ? p1

p2 322- p1=new int;

p1 5- *p2=53;p2 ? ? p1

p2 533- *p1=32; 6- p1=new int;

p1 p1 ?p2 ? 32 p2 53

7- *p1=88;(pictorial explanation of program) p1 88

p2 53

Page 151: Introduction to Procedural Programming in C++

151

Pointers, cont

introduction to Procedural Programming

There is a special area of memory reserved for dynamic variable. This is called the heap. When you create a dynamic variable, the variable consumes some of this memory.

If your program creates too many dynamic variables it will consumeall of the memory in the heap and any further calls to new will fail.For this reason your program should always check to see if new successfully created the dynamic variable. new returns a special pointer called NULL when memory in heap has finished:

int *p;p=new int;if(p==NULL) //NULL defined in stddef.h library{

cout<<“Insufficient memory.\n”;exit(1);

}

Page 152: Introduction to Procedural Programming in C++

152

Pointers, cont

introduction to Procedural Programming

If your program no longer needs a dynamic memory, the memoryconsumed by that variable can be released or returned to the heap.The operator delete destroys a dynamic variable and returns the memory to the heap. Ex,

int *p;p=new int; //create a dynamic variablesome-statementsdelete p; //destroy dynamic variable/return memory

Note that delete destroys the dynamic variable, not the pointer which points to that variable. When this happens you don’t knowwhat the pointer is pointing to. It could point to any part of memory. These undefined pointers are called dangling pointers. Another example of a dangling pointer is when two pointers point tothe same variable and if you delete one pointer the other pointerwill be a dangling pointer since you have returned the memory it pointed to and don’t know what it points to now.

Page 153: Introduction to Procedural Programming in C++

153

Dynamic Arrays

introduction to Procedural Programming

The arrays you have seen so far had a basic limitation and that wasthat you must specify the array size when you write the program. But sometimes you don’t know how big the array size will be.

If you specify the array size to be too big then if you do not make use of all the array you are wasting memory. On the other hand, if you specify an array’s size to be too small then your program will not work in all situations.

Dynamic arrays avoid these problems. With dynamic arrays, youdo not have to specify the array size as you write the program; youcan do this when your program is running. You create a dynamic array as you create a dynamic variable:

double *p;p=new double[array-size]; //array-size is a variable

Page 154: Introduction to Procedural Programming in C++

154

Dynamic Arrays, cont

introduction to Procedural Programming

In the example on the previous slide, the value of the variable array-size can be determined at run time. You could ask the user,forexample, how many array elements will be needed. You couldn’t do thiswith ordinary arrays.

As with dynamic variables, you should always try to release the memory used by the array when your program no longer needs the array. You return a dynamic array’s memory using the delete operatoras in:

delete [] p;

Notice the empty square brackets followed by the array’s name orpointer. (See next slide)

Page 155: Introduction to Procedural Programming in C++

155

Dynamic Arrays, cont

introduction to Procedural Programming

By now you should have noticed that array variables are memoryaddresses. You didn’t use & for array parameters in functions. Now we know that memory addresses are pointers. So, in C++ an array variable is a pointer variable that points to the first indexed variable of the array.

Consider the program on the next slide: Since a is a memory address and a memory address is a pointer you can assign the value of a to the pointer p as in p=a; After this assignment, p points to the same memory location as a points to. So, p[0], p[1], …, p[9] refer to the indexed variables a[0], a[1],…, [9]. The square bracket notation applies to pointer variables only if the pointer variable points to an array in memory. So p and a seem to behave the same, except that you cannot change the value of a. Its value is fixed andit always points to the same location; but you can change p’s value.

Page 156: Introduction to Procedural Programming in C++

156

Dynamic Arrays, cont

introduction to Procedural Programming

mian(){

int *p, index; int a[10]; for(index=0; index<10; index++)

a[index]=index; p=a; for(index=0; index<10; index++)

cout<<p[index]<<“ “; cout<<“\n”;

for(index=0; index<10; index++)p[index]=p[index]+1;

for(index=0; index<10; index++)cout<<a[index]<<“ “; return 0;

}

Page 157: Introduction to Procedural Programming in C++

157

Exercise

introduction to Procedural Programming

71. What is the output of the following code:

int *p, *q;p=new int [10];q=new int [10];

for(int i=0; i<10; i++)p[i]=i;

q=p;for(i=0; i<10; i++)

q[i]=i+1;for(i=0; i<10; i++)

cout<<p[i]<<‘ ‘;delete [] p;cout<<q[0]<<endl;

Page 158: Introduction to Procedural Programming in C++

158

Pointers and Linked Lists

introduction to Procedural Programming

A linked list is constructed using pointers. A linked list is not fixed in size but can grow and shrink while your program is running, that isit is a dynamic structure. A linked list is a list of nodes in which eachnode has a member variable that is a pointer that points to the next node in the list. The first node in the list is called the head.

A non-empty list comprises a head and a tail (the rest of the list, which is itself a list) so to represent a list of numbers dynamically:

struct list{

int value;list *next;

};And to be able to represent the end of the list we need a value for apointer which does not point to any object. This value is NULL whichis defined in header file stddef.h.

Page 159: Introduction to Procedural Programming in C++

159

Pointers and Linked Lists, cont

introduction to Procedural Programming

Let’s now see how we can insert the first number into the linked list defined below:

struct list{

int value;list *next;

};

list *head; //pointer pointing to head of listhead=new list; //create a new dynamic node(struct)

head->value=12; //assign value to member variablehead->next=NULL; //set node’s next pointer to NULL

See next slide.

Page 160: Introduction to Procedural Programming in C++

160

Pointers and Linked Lists, cont

introduction to Procedural Programming

head 12 NULL

As you can see, we now have a linked list which has a single node.In this example, we started from the beginning with an empty list.We set the value of member variable value to 12 and set the pointernext to NULL because the list now has only one node and the node’spointer pointing to the next node should indicate the end of the list. Also note how the pointer operator -> is used. Since the pointer is pointing to a struct, we use -> operator to get to the struct members.

Now we will see how we can insert nodes in a linked list that already has some nodes.

Page 161: Introduction to Procedural Programming in C++

161

Pointers and Linked Lists, cont

introduction to Procedural Programming

struct node{

int val;node *next;

};typedef struct node *listP; //define an alias

listP insert(listP l,int num){

listP tempP;tempP=new node;

tempP->val =num;tempP->next =l;return tempP;

}

Page 162: Introduction to Procedural Programming in C++

162

Pointers and Linked Lists, cont

introduction to Procedural Programming

main(){

listP head;head=new node;head->val=12; head->next=NULL;

head=insert(head, 8);head=insert(head, 9);while( head!=NULL){

cout<<head->val<<endl;head=head->next ;

}delete head;return 0;

}

Page 163: Introduction to Procedural Programming in C++

163

Pointers and Linked Lists, cont

introduction to Procedural Programming

In the program on previous page, we first added a node to the head of the list in main. Then we called the function insert twice to inserttwo int numbers into the list. Each time we insert a new number intothe list we need to obtain memory from the heap. Then we iterate through the list to output the elements of the list one by one.

Now we will write a few functions that are usually used on linked listssuch as creating a new empty list, adding a new element to the list,check if a list is empty and return the tail of a list.

The funtion nil to create an empty list:listP nil(){

return NULL;}

Page 164: Introduction to Procedural Programming in C++

164

Pointers and Linked Lists, cont

introduction to Procedural Programming

Function empty to check if a list is empty:bool empty(listP l){

return (l==NULL);}The function head to return the first element of a list:int head(listP l){

if(empty(l)){

cout<<“List is empty”;exit(1);

}else

return (l->val);}

}

Page 165: Introduction to Procedural Programming in C++

165

Pointers and Linked Lists, cont

introduction to Procedural Programming

The function tail which returns the tail of a list:

listP tail(listP &l){

if(empty(l)){

cout<<“List is empty”;exit(1);

}else

return (l->next);}Remember that we have already defined the function insert to add an element into a list. Linked lists are more flexible than arrays; youdo not have to specify their size first, They can grow and shrink asyour program is running. But you must take extra care with pointers.

Page 166: Introduction to Procedural Programming in C++

166

Exercises

introduction to Procedural Programming

72. Write a program in which the user determines the size of anarray at runtime. Then the user will fill the array with that many numbers. The program should output the array in the reverse order.

73. Rewrite the program 72 but this time it should get its input froman input strean file.

74. Type the program and the functions defined on slides 161-165 and execute the program.

75. Using the list functions we defined, write a program to removeinsert 5 elements into a list. The user should provide the numbers.

76. Write a function that reverses the elements of a linked list.Test this function in the program 75.

Page 167: Introduction to Procedural Programming in C++

167

Header Files

introduction to Procedural Programming

Programming is hard. The programs we have seen and wrote werevery small and not so complex. Most commercial programs that solve real world problems are very big and complex. As computersbecome more and more powerful and users expect more functionalityfrom them programming becomes harder too.

One way to simplify the process of programming is to break down theprogram into separate subprograms or functions with which we arealready familiar.

Another way is to group similar functions togetherin separate files called header files. You have already used header files such string.h, math.h,etc. These are part of the standard language.

Page 168: Introduction to Procedural Programming in C++

168

Header Files, cont

introduction to Procedural Programming

Modularity has several advantages including:

1. editing program code is simpler2. the program can be better organized3. several programmers can develop different parts of the program

simultaneously.4. the same group of functions can be reused in other programs5. compilation time can be reduced

But you should only try to group similar functions in the same file andeach separate file or module should have a distinct purpose. Forexample, you could group all the list functions in one file. They are allrelated and only work on linked lists. Point 5 above is especiallyimportant when you have large programs. When making changes in asource file, only the modified files will be recompiled, not all the files.

Page 169: Introduction to Procedural Programming in C++

169

Recursion

introduction to Procedural Programming

Recursion is a solution technique in which problems are solved by reducing them to smaller problems of the same form. We will startby looking at an example involving a recursive solution.

Consider the factorial function belowint 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 propertyof factorials: each factorial is related to the factorial of the smallernumber as in:

n!=n*(n-1)!

Page 170: Introduction to Procedural Programming in C++

170

Recursion, cont

introduction to Procedural Programming

So we can find a recursive solution for the function factorial becausegetting the factorial of one number involves also getting the factorialof a smaller number. This is the recursive definition of factorial:

int factorial(int n){

if(n==0)return 1; //factorial of 0 is 1

elsereturn (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.

Page 171: Introduction to Procedural Programming in C++

171

Recursion, cont

introduction to Procedural Programming

As another example of recursion consider the following functionwhich does a similar task to pow function defined in math.h:

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 in C++. Every function defined recursively can also be defined iteratively using ‘for’, ‘while’ and ‘do…while’ loops.Also, recursive calls, function calls in general, are expensive on thecomputer’s resources and may run slower. But this is not always thecase and recursion can sometimes make code easier to understand.

Page 172: Introduction to Procedural Programming in C++

172

Exercises

introduction to Procedural Programming

77. Using header files, write the linked list functions and test yourprogram using a separate main program.

78. Write a function to use a linked list to store a number of wordsor strings. Define your linked list so that one of its member variables is a char array. The user can type the words at keyboards and could indicate end of list if ‘.’ is entered. Test your function in aC++ program.

79. Using the function from exercise 78, write two recursively defined functions print_list_forward(…) and print_list_backward(…) which will respectively display the elements of a linked list forward and backward. Test the two functions in a program.

Page 173: Introduction to Procedural Programming in C++

173introduction to Procedural Programming

Page 174: Introduction to Procedural Programming in C++

174introduction to Procedural Programming