Your SlideShare is downloading. ×
  • Like
Introduction to Procedural Programming in C++
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Introduction to Procedural Programming in C++


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.

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.

Published in Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide
  • sss


  • 1. Introduction to Procedural Programming Department of Software Engineering College of Engineering University of Salahaddin Erbil 1
  • 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 2
  • 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 objectoriented 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 3
  • 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 calculations and get tired(especially if the calculations are long and complex). Computers hardly get tired. in a perfect world, a computer could carry out endless repetitive and long calculations without stop. Another reason is that computers are much faster at performing calculations than humans. Modern computers can carry out millions Of basic instructions per second. introduction to Procedural Programming 4
  • 5. Good Programming Programming is a challenge. Often, programs are late, difficult to use,full of bugs, un-maintainable, and wrong. When someone writes a program, they should not only think about the people who will use it, but also about the people who will maintain it. Writing good programs comes only after a lot of practice and experience. Good programs are programs that are:      on time ‘user-friendly’ reliable and stable maintainable and extensible correct (do what they were intended to do) introduction to Procedural Programming 5
  • 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 6
  • 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 7
  • 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++ later in the course. The data in a variable is called its value and it can be changed or deleted. in order to uniquely identify and keep track of a variable, we need to give each variable a name; this is called declaring a variable. 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 8
  • 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 data type of numerical values with decimals is called double. We will cover all data types later. For now keep it in mind that whole numbers are of type int and decimal numbers of type double. double myWeight; in this case, the variable myWeight is of type double because its value can be a number with a fraction like 1.3. Note that all variable declarations end with a semicolon(;). introduction to Procedural Programming 9
  • 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 will be unpredictable. Variable initialization can be performed either during declaration using assignment statements (to be discussed shortly) as in int books=0; Or using the input statement cin (input will be discussed later). introduction to Procedural Programming 10
  • 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 assign the value on the right-hand side of the equal sign to the variable on the left-hand side. The sign (=) is called the assignment operator. (C++ operators will be covered later in the course). Assignment statements end with a semicolon. The value on the right-hand side can also be another variable or expression: books1=books2; in an assignment statement, first the value on the right-hand side is evaluated and then its result is stored or assigned to the variable on the left-hand side. introduction to Procedural Programming 11
  • 12. Performing Output The values of variables, numerical values and strings of text ,may be output 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 be output 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 be output to the screen. introduction to Procedural Programming 12
  • 13. Performing output, cont Typically, you would want a new line to appear after some output to the screen; to force a new line the C++ keyword endl is appended at the end of the line. A second method for forcing a new line is using the escape character n as in: cout<<“Hello everyonen”; 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 either cout<<endl; or cout<<“n”; The double arrow signs (<<) are called the insertion operators. introduction to Procedural Programming 13
  • 14. Formatting Output When the computer outputs a value of type double, the format may not be what you would expect. Eg, if double price=78.5; might output: cout<<“The price is $”<<price<<endl; The price is $78.500000 or The price is $78.5 or The price is $7.850000e01 But, it is unlikely that the output will be The price is $78.50 which 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 14
  • 15. input using cin in C++, cin is used to input values into variables. After declaring a variable 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 user is asked to enter/type a value for price. This value is then input in the variable price using cin. A message is also output to the screen notifying 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 the Variable, the user must enter a new line. introduction to Procedural Programming 15
  • 16. input using cin, cont To have more than one input value entered at the keyboard, use more 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 must type a space or a tab or a new line to separate the two input values. The double arrows of cin statements are the same as for output statements (cout) except they are in the opposite direction. A cin statement sets the value of a variable equal to values typed at the keyboard. introduction to Procedural Programming 16
  • 17. Basic Data Types integer Numbers (int) As we have already mentioned the type int refers to whole numbers like 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 as 3.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 and 1.7E - 308. Here, the number 1.7E + 308 is equal to 1.7 multiplied by 10 to the power of 308. 1.7 x 10308. This is called the scientific notation. (8 bytes are used to store double numbers). Numbers of type double can have a precision of up to 15 digits. introduction to Procedural Programming 17
  • 18. Basic Data Types, cont We have seen two numeric types that the C++ supports: double and int types. These two are the main numeric types in C++. You can use these types for almost any situation. However, C++ includes Memory Used Size Range Precision other numeric types Type short or 2 bytes -32,767 to 32,767 N/A which are derived short int and based on these int 4 bytes -2,147,483,647 to N/A two types. These 2,147,483,647 types allow for difflong or 4 bytes -2,147,483,647 to N/A erent number sizes long int 2,147,483,647 and for more or less float 4 bytes Approximately 7 digits precision. 10-38 to 1038 Also can be used to make more efficient use of the memory. double 8 bytes Approximately 15 digits 10-308 to 10308 long double introduction to Procedural Programming 10 bytes Approximately 10-4932 to 104932 18 19 digits
  • 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 type char include letters of the alphabet, digits, symbols and punctuation marks. 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 is Placed inside double quotes as in: cout<<“This is string of text.”<<endl; So, in C++ the character ‘A’ is treated differently from “A” since the first is considered a character and the second a string. introduction to Procedural Programming 19
  • 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 a letter. After typing a letter and pressing the Enter key, the value is stored in the variable letter using cin statement. Then, the user is 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 20
  • 21. Basic Data Types, cont Boolean expressions (bool) The last basic data type we will look at is called bool. This type was recently added to the language. Values of type bool are called Boolean expressions and include only two values: true or false. Boolean expressions are used in branching And looping statement which we will cover later in the course. important note As a general rule, you cannot store values of one type in a variable of another type. This is a good rule to follow, even though some C++ compilers do not enforce this type checking. introduction to Procedural Programming 21
  • 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 22
  • 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. Without including 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 in sequence by the computer. (See next slide) introduction to Procedural Programming 23
  • 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 24
  • 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,11 Here, 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 25
  • 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 operating system and declare that the program has finished its execution. important Note The important thing to remember is that all C++ programs must have a function called main and that program execution begins and ends inside this function. introduction to Procedural Programming 26
  • 27. Arithmetic Operators in C++, you can combine expressions using the arithmetic operators. Usually, arithmetic operators come in between two expressions as in expression1 Or operand1 operator expression2 operator opreand2 The operand can be either a single variable/number or a composite expression. The main C++ arithmetic operator are the following: + for addition for subtraction * for multiplication / for division % for division remainder introduction to Procedural Programming 27
  • 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 28
  • 29. Arithmetic Operators, cont When used with one or both operands of type double, the division Operator, /, 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 3 with a remainder of 2 introduction to Procedural Programming 29
  • 30. Precedence Rules You can specify the order of operations in C++ using parentheses as illustrated in the following expressions: 1: (x + y) * z 2: x + (y * z) 1: the computer first adds x to y and then multiplies the result by z. 2: the computer first multiplies y by z and then adds the result to x. if you omit the parentheses, the computer will follow the C++ rules of precedence. So, if you wrote x + y * z, the computer would multiply y by z and add the result to x. Because * has higher precedence than + .(the same is true for / and %) it’s always best to use parentheses as they remove any ambiguity and make the code much clearer to read and understand. introduction to Procedural Programming 30
  • 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 value plus the number constant 7. We can use other arithmetic operators too: hours -=2; hours /=3; hours *=2; hours %=8; introduction to Procedural Programming hours=hours-2; hours=hours/3; hours=hours*2; hours=hours%8; 31
  • 32. Flow of Control in the simple C++ program we saw earlier, the program consisted of a list of program statements which were executed sequentially; one statement after another. There we did not specify any order for the program to follow. For bigger and more sophisticated programs, you will need some way to 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 choose between two alternative actions. Then we will discuss loops. introduction to Procedural Programming 32
  • 33. Branching (if-else statement) There is a C++ statement that chooses between two alternative actions. it is called the if-else statement. in fact, there are two versions of this statement. We will discuss the first one as the second form is an extension of the first form. The general form of the if-else-statement is as follows: if (Boolean-expression) yes-statement else no-statement When program execution reaches the if-else-statement only one of the two statements is executed, not both. if the Boolean-expression is true then the yes-statement is executed. if the the Boolean-expression is false then the no-statement is executed. introduction to Procedural Programming 33
  • 34. Branching (if-else statement), cont Example: Suppose your program asks the user about the amount of time per week he/she spends on practicing C++. And you want the program to decide whether or not this is enough. Assume that 4 hours/week of practice is enough. Anything less is not good enough. #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 34
  • 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 true or false by comparing the value of the variable and the constant 4. Here, we use C++ comparison operators. Here is the full list of comparison operators: Math Symbol C++ Notation Description = == Equal to ≠ != Not equal to < < Less than ≤ <= Less than or equal to > > Greater than ⋝ >= Greater than or equal to introduction to Procedural Programming 35
  • 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: X Y X || Y True True True True False True False True True False False False X Y X && Y True True True True False False False True False False False False Note: && is equivalent to “and” and || to “or”. introduction to Procedural Programming 36
  • 37. if-else-statement, cont Sometime, you want your program to test a condition and if the condition is satisfied the program does something, otherwise it does not do anything. You can do this by omitting the else part from the if-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 statement will 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 37
  • 38. if-else-statement, cont You may want to execute more than one statement inside an if-elsestatement. 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 compound statement. introduction to Procedural Programming 38
  • 39. Loops Most programs have some action that is repeated a number of times. A section of a program repeats a statement or group of statements is 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; } while (num_of_greetings > 0) { cout<<“Hello “; num_of_greetings=num_of_greetings-1; } return 0; introduction to Procedural Programming Boolean expression 39
  • 40. Loops, cont in the example on the previous page, the section between the brackets { and } is called the body of the while-loop. it is the action that is repeated a number of times. Each repetition of the loop is called an iteration of the loop. if the user enters 0 at the keyboard, the loop body is executed zero times, that is, it is not executed at all. Because, the Boolean-exp is not satisfied and program execution proceeds with the following line after the while-loop. Note that you need some way to make sure that the loop ends at some point. Otherwise, the loop will run for ever. in this example, we decrease a variable value after each iteration. We decrease it by one after each iteration. This is called decrementing. introduction to Procedural Programming 40
  • 41. increment and Decrement Operators 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 type int. 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; introduction to Procedural Programming 41
  • 42. Loops, cont 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 statement. The do-while loop statement is similar to the while-loop statement, except that the loop body is executed at least once. The syntax of 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. introduction to Procedural Programming 42
  • 43. Loops, cont An example involving a do-while loop statement: #include <iostream.h> main() { char answer=‘n’; do { cout<<“Hellon”; 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<<“Goodbyen”; } introduction to Procedural Programming 43
  • 44. infinite Loops (Be Careful) A while-loop or do-while loop does not terminate as long as the Boolean expression is true. This Boolean expression normally contains a variable that will be changed by the loop body and usually the value of this variable eventually is changed in a way that makes the Boolean expression false and therefore terminates the loop. However if you make a mistake and write your program so that the Boolean expression is always true, then the loop will run forever. (an infinite loop). On the next page we will write two loops, one that does terminate and one that does not terminate. introduction to Procedural Programming 44
  • 45. infinite Loops, cont 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. introduction to Procedural Programming 45
  • 46. Program Style All the variable names in our programs were chosen to suggest their use. We tried to use meaningful names for variable names. Also we laid out our programs in a particular format. For example, the declarations and statement were all indented the same amount. This is good programming as it makes our programs • easier to read easier to correct, and • easier to change • indenting A program should be laid out so that elements that are naturally Considered a group are made to look like a group. One way to do this is to skip a line between parts that are logically considered separate. introduction to Procedural Programming 46
  • 47. Program Style, cont indenting can help to make the structure of the program clearer. A statement 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 been doing, makes it easy to find the matching bracket. One one pair of brackets is embedded inside another pair, the inner pair should be indented more than the outer pair. Comments To make programs understandable, you should include some explanatory notes at important places in the program. Such notes are called comments. Most programming languages have this capability. in C++, the symbols // are used to indicate start of a comment to the end of the line. These comments can be as long as a line only. introduction to Procedural Programming 47
  • 48. Program Style There is another way to insert comments in a C++ program. Anything between /* and */ is considered a comment and ignored by the C++ compiler. Unlike the // comments, which require an additional // on each new line, the /* to */ comments can span several lines. Your programs should always start with some comments like: //File name: hello.cpp //Author: Mr. Nice //Email: //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!. introduction to Procedural Programming 48
  • 49. Constants 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 throughout the 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; else cout<<“Science Student”<<endl; This could be a large program and there could be many places where the 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. introduction to Procedural Programming 49
  • 50. Exercises 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. introduction to Procedural Programming 50
  • 51. Exercises, cont 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 the Value of variable score is greater than 100 and ‘Low’ if the value of score 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 finding A 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 equation has positive values. introduction to Procedural Programming 51
  • 52. Exercises, cont 7. The following if-else statement will compile and run without any Problems. However, it is not laid out in a way that is consistent with the other if-else statements we have used in our programs. Rewrite it so that the layout is clearer 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 nothing cout<<“Hi again”<<endl; */ cout<<“Hi again”<<endl; // this is a comment /*this too is a comment*/ introduction to Procedural Programming 52
  • 53. Exercises, cont 9. Write a program fragment to display the numbers that are multiples of 4 between 0 and 20 inclusive. 10. Write a program to 1. Ask the user for two whole numbers (int) 2. Calculate their addition, subtraction, multiplication, division and molulus 3. Display the results on the screen 10. Write a multiplication calculator program. This program will multiply numbers together and display the result on the screen. The program should keep asking the user for two numbers until the user enters the letter ‘s’ for stop. introduction to Procedural Programming 53
  • 54. Exercises, cont 2. 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’. 3. Write a program fragment that reads in a year (Ex. 1972) and checks 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 the following conditions must hold: 1. The year is divisible by 4 but not by 100, or 2. The year is divisible by 400 4. Write a program to add a list of numbers entered by the user. The user can stop the program by entering 0 when asked for the next number. Before it stops, it should print their addition & average. introduction to Procedural Programming 54
  • 55. Precedence Rules, cont e following list contains the precedence rules for some C++ erators: unary binary arithmetic binary arithmetic Boolean operators Boolean operators Boolean operator Boolean operator assignment (), [], ., ->, (postfix)++, (postfix)-+(unary), -(unary), ++(prefix), --(prefix), !, sizeof *, /, % +, <, >, <=, >= ==, != && || =,+=,-=,*=,/=,%= example, consider (x+1) > 2 || (x+1) < -3, s is equivalent to ((x+1) > 2) || ((x+1) < -3) because < and have higher precedence than ||. introduction to Procedural Programming 55
  • 56. Boolean Expressions 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 other than 0 was considered true. Although you can use integer values instead of values of type bool, you shouldn’t. The capability is left there for backward compatibility only. Use bool types instead. Example: if (1) cout<<“True”<<endl; else cout<<“False”<<endl; The point is that you should be aware of this feature of C++. Not that you should use it in your programs. introduction to Procedural Programming 56
  • 57. Multi-way if-else statements An if-else statement is a two-way branch. it allows a program to choose one of two possible actions. Sometimes, you will want to have a three- or four-way branch so that your program can choose between more than two alternative actions. You can do this by nesting if-else statements. For example, suppose we 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; introduction to Procedural Programming 57
  • 58. Multi-way Branches, cont The indenting used in the example on the previous slide was different from what we have been using. if we followed our indenting rules, we would produce something like the following: if (guess>number) cout<“No, too high”<<endl; else if (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 one above. This is because the format on the previous page is clearer and easier to understand than this one. Also, this way you save space. introduction to Procedural Programming 58
  • 59. Switch-statement You used if-else statements to construct multi-way branches. The switch-statement is another kind of C++ statement that also implements multi-way branches. When a switch-statement is executed one of a number of different branches is executed. The choice of which branch is executed is determined by a 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 the controlling expression, it executes the code for that case. introduction to Procedural Programming 59
  • 60. Switch-statement, cont 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; } introduction to Procedural Programming 60
  • 61. Switch-statement, cont Notice that the constant is followed by a colon. Also note that you cannot have two occurrences of case with the same constant value after them since that would be an ambiguous instruction. A break-statement consists of the keyword break followed by a semicolon. When the computer executes the statements after a case label, it continues until it reaches a break-statement and this is when the switch-statement ends. 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 the cout-statement after the identifier default is executed. introduction to Procedural Programming 61
  • 62. ++ and – Operators Revisited You use the increment operator (++) to increase the value of a variable By 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 can use ++ 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. introduction to Procedural Programming 62
  • 63. For-statement 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 you want the computer to perform the following statement ten times with the value of n equal to 1 the first time and with n increased by one each subsequent time. sum=sum + n introduction to Procedural Programming 63
  • 64. For-statement The following is one way to accomplish this with a while statement: sum=0; n=1; while (n<=10) { sum=sum + n; n++; } Although a while-loop is OK here, this kind of situation is just what the for-loop was designed for. The following for-loop will neatly accomplish the same thing: sum=0; for ( n=1; n <= 10; n++) sum=sum + n; introduction to Procedural Programming 64
  • 65. For-statement An example involving a for-loop: #include <iostream.h> initialization main() { int sum=0; for ( int n=1; n <= 10; n++) { sum = sum + n; } repeat the loop as long as this is true done after each loop body iteration cout<<“The sum of the numbers 1 to 10 is : “<<sum<<endl; return 0; } introduction to Procedural Programming 65
  • 66. break-statement You have already used the break-statement as a way of ending a switch-statement. This same break-statement can be used to exit a loop. 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 if some improper input is encountered then you may want to end the loop. To input a list of negative numbers and exit the loop if positive numbers are input: int count=0, sum=0, number=0; while (++count <= 10) //ten loop iterations { cin>>number; //input number if (number >= 0) break; //exit loop sum = sum + number; } introduction to Procedural Programming 66
  • 67. Continue statement 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 another control 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 example consider the following code fragment: while (true) { cin>>letter; if ( letter== ‘ ‘ ) continue; … } introduction to Procedural Programming 67
  • 68. Which Kind of Loop to Use We have seen three kinds of loops in C++ so far. That’s all there is on loops in C++. As we have shown, you can do everything with just the while-loop. The do-while loop is just an extension of the while oop. And you can also use a while-loop instead of a for-loop after ust a few changes. But in general: if the loop involves a numeric calculation using a variable That 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 calculations. n most other cases, you should use a while-loop or a do-while loop. t is quite easy to decide which of these to use. if you want the Loop body executed at least once use a do-while loop, otherwise use A while-loop. introduction to Procedural Programming 68
  • 69. Exercises 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<<“ “; introduction to Procedural Programming 69
  • 70. Exercises, cont 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) <<“ “<; introduction to Procedural Programming 70
  • 71. Exercises, cont 21. For each of the following situations, tell which type of loop would Be better: a. summing a series, such as ½ + 1/3 + ¼ + … +1/10 b. inputting the list of exam marks for one student 22. Rewrite the following code as a for-loop: int i=1; while ( i <= 10) { if (i < 5 && i !=2) cout<<‘X’; i++; } introduction to Procedural Programming 71
  • 72. Exercises, cont 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); introduction to Procedural Programming 72
  • 73. Arrays An array is a collection of variables all of the same data type that are referred to by a common name. A specific element in an array is accessed by an index. 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 use an array as in: int mark[5]; This array is of type integer and it can hold 5 variables of type integer. ‘mark’ is the name of this array. introduction to Procedural Programming 73
  • 74. Arrays, cont The array declaration (similar to variable declaration) on the previous slide 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 first Element in the array is 0 and the index of the last element is one less than the size of the array. ( in this example, first element has index 0 and last element has index 4) introduction to Procedural Programming 74
  • 75. Array initialization 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 element of this array: cout<< mark[1]<<endl; and the last element: cout<< mark[4]; introduction to Procedural Programming 75
  • 76. Arrays, cont #include <iostream.h> main() { int number[5]; for (int i=0; i<5; i++) { number[i]=i; //initialize the array cout<<i; cout<<"t"<<(number[i] * number[i])<<endl; } return 0; } introduction to Procedural Programming 76
  • 77. Arrays, cont 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 array and output that element on the screen. Then, we also output the result of squaring each array element on the screen. • The escape character ‘t’ is used to create a tab space between the array element and its square value. it is very common to use for-loops to step through array elements one by one. introduction to Procedural Programming 77
  • 78. Arrays in Memory Array indexed variables are stored in memory in the same way as ordinary variables are stored. But with arrays, the locations of the Array indexed variables are always placed next to one another in the computer’s memory. For example consider the following array declaration: int mark[5]; When you declare this array, the computer reserves enough memory To hold 5 variables of type integer and the computer always places These variables one after the other in the memory. The computer Then remembers the address of the indexed variable mark[0], but it Does not remember the address of any other indexed variable. When your program needs the address of some other indexed variable the computer calculates the address of this other variable from the address of mark[0]. introduction to Procedural Programming 78
  • 79. Arrays, cont The most common programming error made when using arrays is attempting to reference a non-existent array index. For example consider the following array declaration: int mark[5]; For this array, every index must evaluate to one of the integers between 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. introduction to Procedural Programming 79
  • 80. Exercises 26. Describe the difference in meaning of int x[5]; and the meaning Of x[4]; 27. in the array declaration double score[6]; what is the a. the array name b. the base type c. the declared size of the array d. the range of indexes that are OK for accessing the elements e. one of the indexed variables (or elements) of this array introduction to Procedural Programming 80
  • 81. Exercises, cont 28. identify any errors in the following array declarations. a. b. c. d. int x[4] = { 8, 7, 6, 4, 3}; int x[] = { 8, 7, 6, 4}; const int SiZE = 4; int x[SiZE]; 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]; introduction to Procedural Programming 81
  • 82. Exercises, cont 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 20 values of type integer from the keyboard. The program should also Output the square and square root of each array element next to it Like a table. introduction to Procedural Programming 82
  • 83. Structures So far, we have only seen basic data types which had single data items. Now we will look at a data type that is user defined and is a composite type. You can define your own composite data types using structures. For example, if you want to represent a point in the two-dimensional plane, 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 data type whose type is a structure consisting of two values of type int. struct point { int x; int y; }; introduction to Procedural Programming 83
  • 84. Structures, cont The structure ‘point’ which we defined on the previous slide, is a new user defined data type. You can declare variables of this type in your 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 structure variable followed by a dot and then the member name. For example to initialize the variable ‘point’ from last slide: firstPoint.x=0; firstPoint.y=0; introduction to Procedural Programming 84
  • 85. Structures, cont 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 structure type and at the end of initialization. Also, like other basic data types, you can assign one structure variable To 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) if ((firstPoint.x==secondPoint.x) && (firstPoint.y==secondPoint.y)) introduction to Procedural Programming //illegal //OK 85
  • 86. Structures, cont Let’s look at an example program in which we define and use a structure: #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; } introduction to Procedural Programming 86
  • 87. Strings C++ can manipulate text strings in two ways: using cstring values used in C language and with the new string type that was recently added to 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 storing a cstring value with 9 or fewer characters: char name[10]; This is because a cstring variable is used in a differernt way than an ordinary array of characters. A cstring variable places the special symbol ‘0’ in the array immediately after the last character of the cstring. introduction to Procedural Programming 87
  • 88. Strings, cont For example, consider the following cstring variable: char name[10] = “MR Nice”; name[0] M r N i c name[9] e 0 ? ? The character ‘0’ is used to mark the end of the cstring. Since the character ‘0’ always occupies one element of the array, the length of 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 and output with cstring variables as you do with other types of variables. introduction to Procedural Programming 88
  • 89. Strings, cont You cannot use a cstring variable in an assignment statement using =. Also, if you use == to test cstrings for equality, you will not get the result you expect. The reason is that cstrings and cstring variables are 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 you declare the cstring variable as in: char name[10]=“Mr Nice”; Technically, this is an initialization and not an assignment and is legal. introduction to Procedural Programming 89
  • 90. Strings, cont 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 array name. Also, you CANNOT use the operator == in an expression to test if two cstrings 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; introduction to Procedural Programming 90
  • 91. Strings, cont Note that the function strcmp works differently than you might expect. if the function returns a zero it means that the two cstrings 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 be able to use the functions. Another useful function in this library is called strlen which returns the 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 ? introduction to Procedural Programming 91
  • 92. Strings Input and Output 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, but there is one thing to be aware of. All spaces are skipped when cstrigs are 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 Nice Mr introduction to Procedural Programming 92
  • 93. Strings input and Output, cont So there is a problem with cstring input when input contains spaces or 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 variable a_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) introduction to Procedural Programming 93
  • 94. Exercises 33. Consider the following two statements and whether they are true 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. c. software_student? introduction to Procedural Programming 94
  • 95. Exercises, cont 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; introduction to Procedural Programming 95
  • 96. Exercises, cont 36. Define a structure called student with the following member variables: • • • • 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. introduction to Procedural Programming 96
  • 97. Exercises, cont 37. Write a C++ program that can maintain information about a personal bookshelf. The program asks for information about a new book such as the author, title, ISBN no., price, year published. Use a structure 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; introduction to Procedural Programming 97
  • 98. Exercises, cont 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 cstring variables. Test your program. 40. Based on the previous program, write another program in which the user enters their name such as XXX YYYYYY And then the program rearranges the first and last names into YYYYYY, XXX 41. Write a program that accepts a word from the user and outputs the number of vowels in that word. (Vowels include: A, E, I, O and U) introduction to Procedural Programming 98
  • 99. Functions and Procedural Abstraction A natural way to solve large problems is to break them down into a series of smaller sub-problems, which can be solved more-or-less independently and then combined to arrive at a complete solution. In programming too, you can follow a similar approach and divide large programs into smaller sub-programs; in C++ sub-programs are called functions. Most programs consist of 3 main sections: input, some calculations and output. We can perform each of these sections separately and combine 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 follows the old Roman philosophy of divide-and-conquer. introduction to Procedural Programming 99
  • 100. Functions, cont We have already seen functions such as sqrt(…) to get the square root of a number. Or the strcpy(s1, s2) which copies one string to 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’t need 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 the C++ library ‘math.h’. And the function strcpy(s1, s2) is defined in a file which we can access via the library ‘string.h’. You can have user-defined functions too. You can define your own functions to do specific tasks. introduction to Procedural Programming 100
  • 101. Functions, cont In the next few slides we will try to write our own functions. At first we will put these functions in the same file as “main”. Later we will see 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 call cout<<“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 } introduction to Procedural Programming 101
  • 102. Functions, cont 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 its brackets, 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; they specify which type the function will return. • You can define as many functions as you require provided you declare them first. introduction to Procedural Programming 102
  • 103. Functions, cont The function ‘area(…,…)’ returns a value of type int. And it takes two parameters. A parameter is variable; during a function call this parameter 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 uses its own local copies in its subsequent computation. introduction to Procedural Programming 103
  • 104. Exercises 42. What is the output of the following program? #include <iostream.h> bool is_even(int number); //function declaration main() { 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; else return false; } introduction to Procedural Programming 104
  • 105. Exercises, cont 43. Write a function that takes three parameters of type int. The function returns the sum of its three parameters. Test the function in 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 program and test it. int factorial(int n) { int product = 1; while ( n > 0) //n must be nonnegative { product = n * product; n--; } return product; } introduction to Procedural Programming 105
  • 106. Exercises, cont 45. Consider the declarations/prototypes of the following predefined mathematical functions: double double double double sqrt(double x); //returns square root of x pow(double x,double y); //returns x to the power of y ceil(double x); //returns ceiling of x 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; } introduction to Procedural Programming 106
  • 107. Type Casting 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 returns 4.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 operands in 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 predefined function. Another ex, double(2) evalutaes to 2.0. This is called type casting. introduction to Procedural Programming 107
  • 108. The Black Box A person who uses a program should not need to know the details of How the program is coded. That person should know how to use the Program but not how the program works. A function is like a small program and should be viewed in a similar way. A programmer who who uses a function needs to know how to use the function but not how the function does its job. This is what is meant when viewing a function as a black box. Writing 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 word abstraction 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. introduction to Procedural Programming 108
  • 109. The Black Box, cont 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 not need to look at the body of the function definition to see how the function works. The function prototype/declaration and the accompanying comment should be all the programmer needs to know to use the function. It’s very important to comment your functions. The comments should describe what the function does, not how. They should also mention any conditions that are required of the parameters to the function and describe the value that is returned by the function. Consider the Predefined function sqrt, we can use it without knowing how it works. introduction to Procedural Programming 109
  • 110. Local Variables As we have already seen in some of the functions that we have defined, you can have variables declared inside those functions. These variables exist only when you call the function to which they belong. Variables declared inside functions are called local variables. The scope of a local variable is the function inside which that variable is 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. introduction to Procedural Programming 110
  • 111. Global Constants and Global Variables In general, constants are declared outside any functions, even outside the main function. This is good programming as it is usually the case that 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. introduction to Procedural Programming 111
  • 112. Void Functions The functions that we have seen so far all returned a single value. In C++ a function must either return a single value or return no values at all. 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); retrun 0; } introduction to Procedural Programming //function call 112
  • 113. Call-by-Reference Parameters 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 by value. Copies of x1 and x2 are made and passed to swap and any changes to their values,inside the function, occur on the copies of the two variables. introduction to Procedural Programming 113
  • 114. Call-by-Reference Parameters, cont 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 or the actual variables are passed to the function. To correct the swap function we need to use reference parameters as in: void swap(int& num1, int& num2) { int temp=num1; num1=num2; num2=temp; } //call-by-reference parameters Notice that you need to append the ampersand sign & to the name. introduction to Procedural Programming 114
  • 115. Exercises 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; } introduction to Procedural Programming 115
  • 116. Exercises, cont 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; } introduction to Procedural Programming 116
  • 117. Exercises, cont 48. Write a function to find the smallest number in an array of type int. Declare the array size to be 7 and fill the array from the keyboard. The function should take the array as a parameter and return the smallest number as the return value. Test the function in 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 function as 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 data structure as Date to represent calendar dates. Use a function that takes two dates as parameters and calculates the number of days between them. introduction to Procedural Programming 117
  • 118. Exercises, cont 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 two solutions. If the quantity under square root is negative it should display an appropriate message. You may assume that the value for a is nonzero. Test the function in complete program. introduction to Procedural Programming 118
  • 119. Exercises, cont 52. You have seen the pre-defined math.h function pow which takes two double parameters and returns the power of first parameter raised to the second parameter. Write your own pow function and call it myPow. Test your program in a complete program. 53. Write a function that takes two int arrays as parameters and if 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 as parameters and if the two strings are equal it should return true otherwise false. Test your program in a complete program. introduction to Procedural Programming 119
  • 120. Sorting Arrays One of the most common programming tasks is sorting a list of values from highest to lowest or vice versa or a list of words into alphabetical order. There are many sorting algorithms; some are easy to understand but not so efficient while some are efficient but hard to understand. One of the easiest sorting algorithms is called selection sort. The selection sort algorithm works as follows: for( int 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. introduction to Procedural Programming 120
  • 121. Sorting Arrays, cont The algorithm iterates through all the elements of the array one by one and at each iteration it places the smallest number in the array in 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 then write a main function to test the functions. (We have already implemented the swap function, see slide 112) introduction to Procedural Programming 121
  • 122. Sorting Arrays, cont 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. introduction to Procedural Programming 122
  • 123. Sorting Arrays, cont Now we will implement the function which will find the index of the next 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 } introduction to Procedural Programming 123
  • 124. Exercises, cont 55. Write a predicate function (whose return value is either true or false) that takes an int array as a parameter and returns true if the array is sorted in ascending order. Test your function in a program. 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. The pairs overlap so that the second element of the a pair becomes the first of the next pair. Repeat this operation until you make a complete pass in which you do not make an exchange or swap of values. This algorithm is called the bubble sort, because the values seem to bubble up to their eventual positions. introduction to Procedural Programming 124
  • 125. I/O Streams 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 be able 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 stream for 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 ends the data typed in at the keyboard and the output data to the screen is lost. Files provide you with a way to store data permanently. introduction to Procedural Programming 125
  • 126. I/O Streams, cont When your program takes input from a file it is said to be reading From the file and when your program sends output to a file it is said To be writing to the file. 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 said Earlier there are both input and output streams. If you want a stream To connect to a file, you must declare it as with variables. The type for input file stream variables is ifstream and the type for Output file stream variables is ofstream. Both of these types are Defined in the library fstream.h. introduction to Procedural Programming 126
  • 127. I/O Streams, cont 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;“myInFile.txt”); //opening the file“myOutFile.txt”); //opening the file int num1, num2; input_file>>number1>>number2; //reading data output_file<<num1<<“ “<<num2<<endl; //writing data input_file.close(); output_file.close(); return 0; //close file //close file } introduction to Procedural Programming 127
  • 128. I/O Streams, cont In the previous example, one input stream and one output stream were declared and then two files were opened, open for to read from and 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 opening the 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 close a file may result in a corrupted file. introduction to Procedural Programming 128
  • 129. I/O Streams, cont 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 no file 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.txt”); if ( { 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. introduction to Procedural Programming 129
  • 130. I/O Streams, cont Let’s now look at a program that reads all the contents of a file, from beginning to end of the file: main() { ifstream input_file; int next, count=0; double sum=0;“myInFile.txt”); //opening the file while(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 file return 0; } introduction to Procedural Programming 130
  • 131. Character I/O Every input stream, whether it’s an input file stream or the stream cin has get as a member function. This function is used to read one character of input. Unlike the extraction operator >>, get reads the next character, no matter what that character is; it will even read blanks (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 and store it in the variable next_symbol. Remember that the function get can also be used with input file streams. introduction to Procedural Programming 131
  • 132. Character I/O, cont The member function put is analogous to the member function get except that it is used for output rather than input. Again as with get, the member function put is a member function of every output stream. Ex, cout.put(next_symbol); //output it to screen cout.put(‘b’); //output ‘b’ to screen This is some code to make a copy of one file (backup):“input_file.txt");"output_file.txt"); char next; in.get(next); while(next != 'X') //make sure ‘X’ is in the file { out.put(next); //write to output file in.get(next); // read next caharacter } // from input file introduction to Procedural Programming 132
  • 133. Character I/O, cont 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 for determining end of files. This method is more suitable for text files while the previous one is more suitable for files that consist of numeric data. This function is called eof which stands for end-of-file. Ex, ifstream input_file;“input.txt”); input_file.get(next); while( ! input_file.eof()) { cout.put(next); input_file.get(next); } introduction to Procedural Programming //or cout<<next; //read next character 133
  • 134. Character I/O Functions There are a number of useful character I/O functions that can be used to process text files. Among these functions are: (ctype.h) - toupper(char_var) returns uppercase version of char_var ex, toupper(‘a’) returns ‘A’ - tolower(char_var) returns lowercase version of char_var ex, tolower(‘H’) returns ‘h’ - isspace(char_var) returns true if char_var is either a space, tab or a new-line (‘n’), otherwise returns false ex, 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; introduction to Procedural Programming 134
  • 135. Exercises 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 onto the screen. First create a text file and type some text in the file and save it in the same directory. Test your function in a program. 58. Write a function that takes two file names as parameters and copies the contents of the first file into the second file. Test your Program 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 the largest and smallest numbers to the screen. The file contains nothing but numbers of type int separated by blanks or line breaks or tabs. Test your function in a C++ program. introduction to Procedural Programming 135
  • 136. Exercises, cont 60. Write a program that reads text from one text file and writes an edited version of the same text to another file. The edited text is identical to the original version except that its text is all in upper case. 61. Write a program that reads all the contents of a text file and writes everything except numbers into another file. It filters numbers from the file. 62. Write a function that takes three filenames as parameters. Two input 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 from the smallest to the largest. The output file will contain all the numbers from the two input files in one longer list in sorted order from smallest to largest. Test your function a C++ program. introduction to Procedural Programming 136
  • 137. Exercises, cont 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 name is enrolled on this course. The function takes a student’s name as Parameter and it then searches the file that contains student details to see if that student is on the course. If he/she is then it should print the students details on the screen. introduction to Procedural Programming 137
  • 138. Exercises, cont 64. Write a program to count the number of lines, the number of words and the number of non-blank characters in a file. It should then display this information on the screen. A word is any sequence of characters between any two of following characters: space, tab, new-line, comma, period. For this exercise only consider spaces and new-lines. 65. Write a function that reads text from a file and writes each line preceded by a line number starting from 1. Follow the line number with a colon and a space for clarity. You may assume that the lines are short enough to fit within a line on the screen. Test your function in a C++ program. introduction to Procedural Programming 138
  • 139. Exercises, cont 66. Write a function to strip or remove comments (//) from a C++ source file. Do this program in stages. First write a function with 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 file whose name is input from the keyboard. The program should also ask the user for the name of the output file. Test you function in a C++ program. introduction to Procedural Programming 139
  • 140. Multidimensional Arrays 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 arrays are called multidimensional arrays. The most common form of a multidimensional array is a twodimensional array which is similar to a rectangular structure divided into rows and columns. This type of two-dimensional array is called a matrix. You can have arrays of 3 or more dimensions. They are less common. Consider the two-dimensional array matrix: int matrix[2][3]={{2,2,2}, {2,2,2}}; //two rows, three columns This is an array (size 2) of two arrays (size 3). introduction to Procedural Programming 140
  • 141. Multidimensional Arrays, cont 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… introduction to Procedural Programming 141
  • 142. Multidimensional Arrays, cont 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]; } // to display the result on the screen for(i=0; i<4; i++) { for(j=0; j<2; j++) cout<<array1[i][j]<<" "; cout<<endl; } } introduction to Procedural Programming //adding 142
  • 143. Multidimensional Arrays, cont For multi-dimensional array parameters, all the dimension sizes except the first must be given. This makes sense if you think of a multi-dimensional array as an array of arrays. In this example we have an array each element of which is an int array 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 a multi-dimensional array can be any type; but for numerical calculations the type is usually int or double. In the example on the previous page, we saw how to add two matrixes. You can also do other matrix operations like matrix multiplication, matrix transformations using two-dimensional arrays. introduction to Procedural Programming 143
  • 144. Exercises 67. Write a function that has one parameter of type int array[][2] The function multiplies its parameter by the unit matrix and prints the 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. introduction to Procedural Programming 144
  • 145. Pointers 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 be declared 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 a variable and then assign that address to a pointer variable. introduction to Procedural Programming 145
  • 146. Pointers, cont Now we have two ways to refer to a variable: you can call it v1 or you can 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 is called the dereferencing operator. To clarify things, consider this piece 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 v1 then both *p1 and v1 refer to the same variable. So when you set *p1 to 32, you are also setting v1 to 32. introduction to Procedural Programming 146
  • 147. Pointers, cont 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 p2 so 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 names or identifiers. the operator new can be used to create variables that have no identifiers as their names. These nameless variables are referred to via pointers. introduction to Procedural Programming 147
  • 148. Pointers, cont 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 one creates an integer variable and sets p to point to this variable. This nameless 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 to it. Variables that are created using the new operator are called dynamic variables. They are created and destroyed while the program is running. introduction to Procedural Programming 148
  • 149. Pointers, cont am to demonstrate pointers and dynamic variables: *p1, *p2; //two pointers of type int new int; // dynamic int variable =32; p1; //assign p2 to p1 t<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl; =53; t<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl; new int; =88; t<<“*p1: “ <<*p1<<“ “<<“*p2: ”<<*p2<<endl; t<<“Hope you got the point of this example!!!”<<endl; urn 0; next slide for a pictorial explanation of this program. introduction to Procedural Programming 149
  • 150. Pointers, cont 1- int *p1, *p2; p1 ? p2 ? 2- p1=new int; p1 p2 ? ? 3- *p1=32; p1 p2 ? 32 (pictorial explanation of program) introduction to Procedural Programming 4- p2=p1; p1 p2 32 5- *p2=53; p1 p2 53 6- p1=new int; p1 ? p2 53 7- *p1=88; p1 p2 88 53 150
  • 151. Pointers, cont 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 consume all 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); } introduction to Procedural Programming 151
  • 152. Pointers, cont If your program no longer needs a dynamic memory, the memory consumed 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 variable some-statements delete 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 know what 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 to the same variable and if you delete one pointer the other pointer will be a dangling pointer since you have returned the memory it pointed to and don’t know what it points to now. introduction to Procedural Programming 152
  • 153. Dynamic Arrays The arrays you have seen so far had a basic limitation and that was that 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, you do not have to specify the array size as you write the program; you can 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 introduction to Procedural Programming 153
  • 154. Dynamic Arrays, cont 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,for example, how many array elements will be needed. You couldn’t do this with 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 operator as in: delete [] p; Notice the empty square brackets followed by the array’s name or pointer. (See next slide) introduction to Procedural Programming 154
  • 155. Dynamic Arrays, cont By now you should have noticed that array variables are memory addresses. 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 and it always points to the same location; but you can change p’s value. introduction to Procedural Programming 155
  • 156. Dynamic Arrays, cont 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; } introduction to Procedural Programming 156
  • 157. Exercise 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; introduction to Procedural Programming 157
  • 158. Pointers and Linked Lists 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 is it is a dynamic structure. A linked list is a list of nodes in which each node 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 a pointer which does not point to any object. This value is NULL which is defined in header file stddef.h. introduction to Procedural Programming 158
  • 159. Pointers and Linked Lists, cont 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 list head=new list; //create a new dynamic node(struct) head->value=12; //assign value to member variable head->next=NULL; //set node’s next pointer to NULL See next slide. introduction to Procedural Programming 159
  • 160. Pointers and Linked Lists, cont 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 pointer next to NULL because the list now has only one node and the node’s pointer 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. introduction to Procedural Programming 160
  • 161. Pointers and Linked Lists, cont 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; } introduction to Procedural Programming 161
  • 162. Pointers and Linked Lists, cont 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; } introduction to Procedural Programming 162
  • 163. Pointers and Linked Lists, cont 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 insert wo int numbers into the list. Each time we insert a new number into he list we need to obtain memory from the heap. Then we iterate hrough 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 lists uch as creating a new empty list, adding a new element to the list, heck if a list is empty and return the tail of a list. The funtion nil to create an empty list: listP nil() { return NULL; } introduction to Procedural Programming 163
  • 164. Pointers and Linked Lists, cont 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); } } introduction to Procedural Programming 164
  • 165. Pointers and Linked Lists, cont 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; you do not have to specify their size first, They can grow and shrink as your program is running. But you must take extra care with pointers. introduction to Procedural Programming 165
  • 166. Exercises 72. Write a program in which the user determines the size of an array 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 from an 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 remove insert 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. introduction to Procedural Programming 166
  • 167. Header Files Programming is hard. The programs we have seen and wrote were very small and not so complex. Most commercial programs that solve real world problems are very big and complex. As computers become more and more powerful and users expect more functionality from them programming becomes harder too. One way to simplify the process of programming is to break down the program into separate subprograms or functions with which we are already familiar. Another way is to group similar functions together in separate files called header files. You have already used header files such string.h, math.h,etc. These are part of the standard language. introduction to Procedural Programming 167
  • 168. Header Files, cont Modularity has several advantages including: 1. editing program code is simpler 2. the program can be better organized 3. several programmers can develop different parts of the program simultaneously. 4. the same group of functions can be reused in other programs 5. compilation time can be reduced But you should only try to group similar functions in the same file and each separate file or module should have a distinct purpose. For example, you could group all the list functions in one file. They are all related and only work on linked lists. Point 5 above is especially important when you have large programs. When making changes in a source file, only the modified files will be recompiled, not all the files. introduction to Procedural Programming 168
  • 169. Recursion Recursion is a solution technique in which problems are solved by reducing them to smaller problems of the same form. We will start by looking at an example involving a recursive solution. Consider the factorial function below int Factorial(int n) { int product=1, i; for(I=1; I<=n; I++) product *=I; return product; } But this solution does not take advantage of an important property of factorials: each factorial is related to the factorial of the smaller number as in: n!=n*(n-1)! introduction to Procedural Programming 169
  • 170. Recursion, cont So we can find a recursive solution for the function factorial because getting the factorial of one number involves also getting the factorial of a smaller number. This is the recursive definition of factorial: int factorial(int n) { if(n==0) return 1; //factorial of 0 is 1 else return (n * factorial(n-1)); } Consider a call like: int x=factorial(4); The function performs the following operations: (4 * (3 *(2 *(1 *(1))))) which equals 24. introduction to Procedural Programming 170
  • 171. Recursion, cont As another example of recursion consider the following function which 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 the computer’s resources and may run slower. But this is not always the case and recursion can sometimes make code easier to understand. introduction to Procedural Programming 171
  • 172. Exercises 77. Using header files, write the linked list functions and test your program using a separate main program. 78. Write a function to use a linked list to store a number of words or 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 a C++ 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. introduction to Procedural Programming 172
  • 173. introduction to Procedural Programming 173
  • 174. introduction to Procedural Programming 174