0% found this document useful (0 votes)
2 views540 pages

Programming Course All Weeks

This document serves as a lecture note for a 'Computer Programming Basics' course, covering essential topics such as computational thinking, binary number systems, and the program development process. It outlines key concepts including algorithms, pseudo-code, and flowcharts, providing examples and exercises for practical understanding. The content is based on materials from a textbook and aims to equip students with foundational programming knowledge and skills.

Uploaded by

SHAHMEER
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views540 pages

Programming Course All Weeks

This document serves as a lecture note for a 'Computer Programming Basics' course, covering essential topics such as computational thinking, binary number systems, and the program development process. It outlines key concepts including algorithms, pseudo-code, and flowcharts, providing examples and exercises for practical understanding. The content is based on materials from a textbook and aims to equip students with foundational programming knowledge and skills.

Uploaded by

SHAHMEER
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

COMPUTER
PROGRAMMIN
G
Introduction
What will be discussed
2

 Computational Thinking
 How computer see the world
 Review binary number system
 About Computer
 Program, Programmer &
Programming
 Program development process
 Pseudo-code, Algorithms & Flow chart
About The Lecture Note
3

 This lecture note is intended to be used by students in


“Computer Programming Basics” course at the Kyung Hee
University.

 Large portion of the materials is based on the lecture note


supplied by the authors of the textbook “Computer Science : A
Structured Approach Using C++, 2nd Edition.”
What is computational thinking?
4

 Computational thinking allows usto take a complex problem, understand what


the problem is and develop possible solutions. We can then present these solutions
in a way that a computer, a human, or both, can understand.
 Computational thinking involves looking at a problem and working out a way a
computer might be able to help you solve it. Todo this, you need to understand
how a computer processes information.
Four Cornerstones
5

 There are four key techniques (cornerstones) to computational


thinking:
 decomposition - breaking down a complex problem or system
into
smaller, more manageable parts
 pattern recognition – looking for similarities among and
within problems
 abstraction – focusing on the important information only,
ignoring
irrelevant detail
 algorithms - developing a step-by-step solution to the
problem, or the rules to follow to solve the problem
Continue…
How computers see the world
7

 Computers use electrical signals that are on or off,


so they have to see everything as a series of binary
numbers. This data is represented as a sequence
of 1s and 0s (on and off). All data that we want a
computer to process needs to be converted into this
binary format.
What is binary?
8

 Binary is a number system that only uses two digits: 1 and 0. All information that
is processed by a computer is in the form of a sequence of 1s and 0s. Therefore,
all data that we want a computer to process needs to be converted into binary.
Continue…
9

 The binary system is known as a ‘base 2’ system.


This is because:
 there are only two digits to select from (1 and 0)
 when using the binary system, data is converted using
the power of two.
What is computers?
10

 Wikipedia says
 “A computer is a general purpose device that can be
programmed to carry out a finite set of arithmetic
or logical operations.”

 Device? Hardware!
 Programmed? Software!
 Arithmetic or logical? Digital!
Nintendo DS

Hardware Software
Apple iPod/iPhone

Hardware Software
Internet

Hardware Software
Program and Programming
14

 Computer program  Software

 Computer programming  “Making


software”

 Computer programmer = A person who


develops
software
Programming Language
15

Human Language Programming


Language
Naturally created, e.g., Artificially developed,
Chinese, Korean, English, e.g., C, Basic, C#,
… Fortran,…
Interpreted mostly Interpreted by human
by human and computer
Ambiguities and Clear and precise syntax
exceptions in syntax
and grammar
Program Development Process
16

1. Understand the
problem
2. Develop a solution
3. Write a program
4. Test the program
1. Understand the Problem
17

Calculate the square meters of your


house.

What is the definition of square meter?


How is the square meter going to be
used?
-for insurance purposes?
-to paint ?

Is the garage included?
-…
2. Develop a Solution
18

 Structure chart
 Hierarchy chart

 Each step will be a separate module.


2. Develop a Solution(Continue…)
19

 First produce a general algorithm (one can use


pseudo-code)
 Refine the algorithm successively to get step by step
detailed algorithm that is very close to a computer
language.
 Pseudo-code is an artificial and informal language
that helps programmers develop algorithms. Pseudo-
code is very similar to everyday English.
2.1 Steps in Problem Solving
20

 First produce a general algorithm (one can use


pseudocode)
 Refine the algorithm successively to get step by step
detailed algorithm that is very close to a computer
language.
 Pseudocode is an artificial and informal language that
helps programmers develop algorithms. Pseudocode
is very similar to everyday English.
Pseudo-code & Algorithm
21

 Example 1: Write an algorithm to determine a


student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as
the average of four marks.
Pseudo-code & Algorithm
22

Pseudocode:
 Input a set of 4 marks

 Calculate their average by summing and dividing by

4
 if average is below 50

Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm
23

 Detailed
 Algorithm
Step 1: Input M1,M2,M3,M4
Step GRADE  (M1+M2+M3+M4)/4
2: if (GRADE < 50) then
Step Print “FAIL”
3: else
Print “PASS”
endif
2.2 The Flowchart
24

 (Dictionary) A schematic representation of a sequence of


operations, as in a manufacturing process or computer
program.

 (Technical) A graphical representation of the sequence of


operations in an information system or program. Information
system flowcharts show how data flows from source documents
through the computer to final distribution to users. Program
flowcharts show the sequence of instructions in a single
program or subroutine. Different symbols are used to draw
each type of flowchart.
The Flowchart
25

A Flowchart
 shows logic of an algorithm
 emphasizes individual steps and their interconnections
 e.g. control flow from one action to the next
Flowchart Symbols
26
Name S ym bol U s e in Flowchart

O val De not es the beginning or e n d of the pr og r am

Parallelogram De not es a n input operation

R e c t a n g le De not es a process to b e carried out


e.g. addition, subtraction, division etc.

D ia m o n d D e n o t e s a decision (or branch) to b e m a d e .


T h e pr og r am should continue along o n e of
t w o routes. (e.g. I F / T H E N / E L S E )

H y b r id Denotes an output operation

F l o w line D e n o t e s the direction of logic flow in the p r o g r a m


Example: 1
27

START
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Input
M1,M2,M3,M4
Step 3: if (GRADE <50) then
Print “FAIL”
else
GRADE(M1+M2+M3+M4)/4 Print “PASS”
endif
N IS Y
GRADE<5
0

PRINT PRINT
“PASS
” “FAIL

STOP
Example: 2
28

 Write an algorithm and draw a flowchart to


convert the length in feet to centimeter.
Pseudocode:
 Input the length in feet (Lft)

 Calculate the length in cm (Lcm) by multiplying LFT

with 30
 Print length in cm (LCM)
Example: 2 (Continue…)
29

Algorithm Flowchart
 Step 1: Input START

Lft
 Step Lcm  Lft x 30 Input
2: Print Lcm
Lft

 Step
Lcm  Lft x 30
3:
Print

Lcm

STOP
Example: 3
30

Write an algorithm and draw a


flowchart that will read the two sides
of a rectangle and calculate its area.
Pseudocode
 Input the width (W) and Length (L) of a rectangle

 Calculate the area (A) by multiplying L with W

 Print A
Example: 3(Continue…)
31

Algorith STAR
T
m Input W,L
Input
 Step 1:
AL x W W, L

 Step 2:
Print A
A LxW
 Step 3:

Print
A

STOP
Example: 4
32

 Write an algorithm and draw a flowchart that will


calculate the roots of a quadratic equation
ax2  bx  c  0
 Hint: d = sqrt b 2
 4ac), and the roots are:
( x1
= (–b + d)/2a and x2 = (–b – d)/2a
Example: 4(Continue…)
33

Pseudocode:
 Input the coefficients (a, b, c) of the quadratic

equation
 Calculate d

 Calculate x1
 Calculate x2

 Print x1 and x2
Example: 4(Continue…)
34

STAR
T
 Algorith
 m:
Step 1: Input a, b,
Input
a, b,
 Step 2: c bb  4 a c

 Step 3: x1sqrt
d (–b(+ 
d) c/ )(2 x d  sqrt(b x b – 4 x a x c)

 Step 4: a)
x1 (–b + d) / (2 x a)
 Step 5: x2  (–b – d) / (2 x
a) Print x1, x2 X2  (–b – d) / (2 x a)

Print
x1 ,x2

STOP
DECISION STRUCTURES
35

 The expression A>B is a logical expression


 it describes a condition we want to test
 if A>B is true (if A is greater than B) we take the action
on left
 print the value of A
 if A>B is false (if A is not greater than B) we take the
action on right
 print the value of B
DECISION STRUCTURES
36

Y N
is
A>B

Print Print
A B
IF–THEN–ELSE STRUCTURE
37

 The structure is as
follows
If condition then
true alternative
else
false alternative
endif
IF–THEN–ELSE STRUCTURE
38

 The algorithm for the flowchart is as


follows:
If A>B then
elseprint A
Y N
is
print B A>B
endif
Print Print
A B
Relational Operators
39

Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
 Greater than or equal to
 Less than or equal to
 Not equal to
Example: 5
40

 Write an algorithm that reads two values, determines the


largest value and prints the largest value with an identifying
message.
ALGORITHM
Step Input VALUE1, VALUE2
1: if (VALUE1 > VALUE2) then
Step MAX  VALUE1
2: else
MAX  VALUE2
endif
Step Print “The largest value is”,
3: MAX
Example: 5(Cotinue…)
41

START

Input
VALUE1,VALUE
2

Y is N
VALUE1>VALUE2

MAX  VALUE1 MAX  VALUE2

Print
“The largest value is”,
MAX

STOP
NESTED IFS
42

 One of the alternatives within an IF–THEN–ELSE


statement
 may involve further IF–THEN–ELSE statement
3. Write a Program
43

 Writing and editing


programs
 Text editor

 Source file

 Compiling programs
 Compiler:
preprocessor/translator

 Linking programs
 The linker assembles
all of functions
(source and system’s)
into final
43/37
executable- Fall 2019
Computer Programming(CSC-113) © September 2018 Shahid Khan
3. Writing a Program (Executing)
44

 Getting the program into memory is the function of


an operating system (OS) program known as the
loader.
4. Test the Program
45

 Specification errors
 When the problem definition is either incorrectly stated or

misinterpreted.
 They should be caught during blackbox testing.

 Code errors
 Compiler error message

 Logic errors
 They can be corrected only by thorough whitebox testing.
Conclusion
46

In this lecture …
 Computation thinking
 Binary numbers
 How can we differentiate Program, Programmer & Programming?
 What is program development process?
 What is the role of Pseudo-code, Algorithms & Flowchart?
 How to translate Pseudo-Code into Algorithm
 How to translate Algorithm into Flow char
 Some example

ANY
Practice Questions
47

 Review
 Binary to Decimal
 Decimal to Binary
 Octal, Hex-Decimal
 Addition & Subtraction
 1’s & 2’s Complements
Practice Questions
48

Write down algorithm and draw the flowchart for


following question
 Q1. Find the average of two numbers

 Q2. Find the sum of 5 numbers

 Q3. Print Hello World 10 times

 Q4. To log in to Facebook account

 Q5. Reads three numbers and prints the value of

the largest number.


 PROBLEMS# (32-34) from “A structures
approach using C++”
1

COMPUTER
PROGRAMMIN
G
Programming
Basics
What will be discussed
2

 Structures of C++
program
 Variable and identifier
 Standard Data Types
 Standard Streams
 Constants and Operators
 Standard Streams
About The Lecture Note
3

 Large portion of the materials is based on the lecture note


supplied by the authors of the textbook “Computer Science : A
Structured Approach Using C++, 2nd Edition.”
4
Languagof Programming
Hierarchy
e
Languag
Hierarchy
e of Programming
5

The movie “Matrix”

Can’t you
see? Neo is
here.
Computer Programmin g(CSC-113) - Fall 2019
Language
Hierarchy of Programming
6

The movie “Matrix”

Now you can


pick Neo,
but not
clearly.
Computer Programmin g(CSC-113) - Fall 2019
7
Languagof Programming
Hierarchy
e The movie “Matrix”
Examples of Programming
Language
- HTML (Hyper Text Markup
Language)
<html>
<head>
<meta http-equiv="content-type" content="text/html;
charset=euc-kr">
<title>▒ 경희대학교 전자정보대학▒ </title>
</head>
<frameset rows="1*" cols="100%" border="0">
<frame name="electronic" scrolling="auto"
marginwidth="0" marginheight="0"
src="electronic/[Link]">
<noframes>
<body bgcolor="#FFFFFF"
text="#000000"
link="#0000FF" vlink="#800080"
alink="#FF0000">
<p>&nbsp;</p>
</body>
</noframes>
</frameset>
</html>
Examples of Programming Language
- COBOL (COmmon Business-Oriented
Language)
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
PROGRAM-ID. Multiplier.
AUTHOR. Michael Coughlan.
* Example program using
ACCEPT, DISPLAY and
MULTIPLY to
* get two single digit numbers
from the user and multiply
them together

01 Num1 PIC 9 VALUE ZEROS.


DATA DIVISION.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
WORKING-STORAGE
SECTION.
PROCEDURE DIVISION.
DISPLAY "Enter first number (1 digit) : " WITH NO ADVANCING.
ACCEPT Num1.
DISPLAY "Enter second number (1 digit) : " WITH NO ADVANCING.
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
STOP RUN.
Brief History of C++

11
Structure of a C++ Program
11

Pre-compiler directive

Opening brace

Closing brace

Opening

brace
Closing brace
Hello World!

Namespace std contains Without namespace


all the classes, objects and
functions of the standard #include <iostream>
C++ library. int main () {
std::cout << "Hello
world!\n";
return 0;
}
Preprocessor Directives

#include <iostream>
“I want to use a predefined library called iostream”
Always start with a ‘#’
iostream: a library for inputs (from e.g., a user) and
outputs
(to e.g., the monitor)
“using” Directives
14

using namespace s t d ;
 “I want to use objects in a name group

‘std’ ”
Tells the compiler where to look for names

in the library
Can deal with the situation where two or

more objects in different libraries share


a same name (naming confliction).
 Read Appendix N for more about
namespace
main function
15

i n t main()
 The main body of the program.

Compiler first tries to locate

“main()” to find where to begin the


program
 In the form of a function

 I will cover “function” soon


Comment
16

 Internal program document


 Not considered as a program
code

Start of comment

End of comment
Start of comment

End of comment
Nested Block Comments are Invalid
17
Variables
18

 Named memory locations that have a


type
 Named: identifier
 Type: needs declaration

 What you can do with variables


 Storing data
 Modifying data
 Reading data
Variables and Identifiers
19

Memory

Address of memory:

Hard to remember

Identifier: name of
address
Variables and Identifiers
20

Memory
Identifiers

studentID
studentGrade1

studentGrade2
Variables and Identifiers

Memory

studentID

studentGrade

studentName

Compiler keeps track


of [identifier-address]
table
Variables and Identifiers
22

In program

stu dent I D_Tot a l _Gr ade = s t udentG rade1


+ studentGrade2
Naming Identifiers
23

 Allowed characters: A-Z, a-z, 0-9, _


(underscore)
 Not allowed to start with a digit. E.g., 3class (x),
class3(o)
 The identifier cannot duplicate a reserved word.
e.g., if, case, while…
 Good names  descriptive but short
 C++ is case sensitive; PI, Pi and pi are
different.
Standard Data Types
Integer and Floating Point Types
25

2 Bytes 4 Bytes

2 or 4 Bytes 8 Bytes

4 Bytes 10 Bytes

Size of value type depends on computer architecture


Maximum/Minimum of Integer

26
Value Type
Type Sign Byte Minimum value Maximum value
signed -32,768 32,767
short int/short 2
unsigned 0 65,535
signed -32,768 32,767
int (PC) 2
unsigned 0 65,535
signed -2,147,483,648 2,147,483,647
int (Mainframe) 4
unsigned 0 4,294,967,295
signed -2,147,483,648 2,147,483,647
long int/long 4
unsigned 0 4,294,967,295
27
Variables Declaration
28
Variable Initialization
29

 Variable declaration ≠ variable initialization


 Should be initialized by a programmer before it is
used
e.g.,
int count;  declaration (o),
initialization(x)
char grade = ‘ d ’ ;  declaration (o),
initialization(o)
Constants
30

 Data values that cannot be changed during


program execution
 E.g.,
 3.141592
 ‘d’
 “Hello word”
 ‘\0’
To Remember
32

 A character constant is enclosed by the single


quotes. (e.g. ‘a’)

 Use double quotes for string constants. (e.g. “Jeon,


Seokhee”)

 bool types are treated as a number. True: non-zero.


False: zero.
Operators
33

 Assignment
Operators
 Arithmetic operators

+ (Addition)
 - (Subtraction
 * (Multiplication)
 / (Division)
 % (modulo)
34
C++ Expression Format
Operators
Operators
36

 Increment and decrement


operators
 Pre/ post increment
 Pre / post decrement

 Sizeof
operator
 Example
 A=sizeof(b);
Compound Assignment
37

 Shorthand notation for a simple


assignment

 Example
s
Standard streams
38

 A mapping between data and input/output


device
Using iostream.h
39

 Include iostream.h instead of stdio.h


 Standard iostream objects:
cout - object providing a connection to the monitor
cin - object providing a connection to the keyboard
cerr - object providing a connection to error
streem
 To perform input and output we send messages to one
of these objects (or one that is connected to a file)
The Insertion Operator (<<)
40

 To send output to the screen we use the insertion


operator on the object cout
 Format: cout << Expression;
 The compiler figures out the type of the object and
prints it out appropriately
cout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “String”; // Outputs String
cout << ‘\n’; // Outputs a newline
The Extraction Operator (>>)
41

 To get input from the keyboard we use the extraction


operator and the object cin
 Format: cin >> Variable;
 No need for & in front of variable
 The compiler figures out the type of the variable and
reads in the appropriate type
int X;
float Y;
cin >> X; // Reads in an integer
cin >> Y; // Reads in a float
More about cout
42

 w i d t h ( i n t ) function sets the width for printing


a value
 Only works until the next insertion command comes

int x = 42;
cou t. w idth (5 ) ;
cout << x << ‘ \ n ’ ; // Outputs 42
cout << x << ‘ \ n ’ ; // Outputs
42
44 More about cout
 f i l l ( c h a r ) function sets the fill character.
 The character remains as the fill character until
set again.

i n t x = 42;
[Link](5);
cou t. f i l l ( ‘ * ’ ) ;
cou t << x << ‘ \ / / Ou tput s * * * 42
n’ ;
More about cout
47

 Output Manipulators (not a function)


endl - outputs a new line character, flushes
output
dec - sets int output to decimal
hex - sets int output to hexadecimal
oc t - sets int output to octal

#include
i n t x = 42; <iomanip.h>
cout << oc t << x << e n d l ; / / Outputs 52\n
cout << hex << x << e n d l ; / / Outputs 2a\n
cout << dec << x << e n d l ; / / Outputs 42\n
Example codes reading (Program 2-2)

 #include <iostream>
 using namespace s t d ;
Welcome. This program adds
 int main (void)
three numbers. Enter three numbers
 { in the form: nnn nnn nnn <return>
 int a;
11 22 33
 int b; The total is: 66
 int c;
 int sum; Thank you. Have a good day.
 cout << "Welcome. This program adds\ n";
 cout << " t h r e e numbers. Enter three numbers\n";
 cout << " i n the form : nnn nnn nnn < r e t u r n > \ n " ;

 c i n >> a >> b >> c ;

 / / Numbers are now stored i n a , b , and c . Add them.


 sum = a + b + c ;

 cout << "\nThe t o t a l i s : " << sum << " \ n " ;


 cout << "\nThank you. Have a good d a y. \ n " ;
 return 0;
 } / / main
Example
Example
51
Conclusion
52

In this lecture …
 What is structure of C++?
 What is variable and Identifier?
 What Is Standard Data Types?
 What are operators in the language?
 What are strems?

ANY
QUERY ?
Practice Questions
53

 PROBLEMS# (24-32)
 PROBLEMS# (33-37)

 From “A structures approach using C+


+” Page (72-73)
1

COMPUTER
PROGRAMMIN
G
Decisions
/Selection
What will be discussed
2

 Serial Execution of program


 Selection statement
 Arithmetic usage and logical
operator
 Decision logic
 If statement and its uses
 Switch statement and its uses
Serial execution of code
3

Program begins

Do A

Do B


Do Z

Program ends

 boring! inefficient! not very useful!


e.g., movie vs. computer game
Conditionally Changing Program

4
Flo
w be nice to be able to change which statements ran
It would
and when, depending on the circumstances.
Selection Statement
5

Provide a means to conditionally execute


sections of code.
Selection
statements
Conditional Change  Selection
6

We need
comparisons!
Ex1) if the value in variable “num” is larger than 4, then execute
statement 1. Otherwise, execute statement 2.

Ex2) if the value in variable “num1” is same as that in variable


“num2”, then execute statement 1. Otherwise, execute statement
2.

Ex3) if the value in variable “num1” is either 1 or 2, then execute


statement 1. Otherwise, execute statement 2.
How to Select?
7

Simple yes/no decision can do everything!


In computer science, we use true/false

How to determine true/false?


Logical data and logical operator
If logical data satisfies something, we
consider it’s true. Otherwise,
it’s false.
True and False for the Arithmetic

8
Scal
e

In C++
If a value is zero, it can be used as the logical value false.

If a value is not zero, it can be used as the logical value true.

Zero <===> False


Nonzero <===> True
Arithmetic Scale Example
9

 int a = 4;  true
 char name = 3  true
 int b = 0;  false
 bool isRunning = false; false
 4  true
 0  false
Logical Operator
10

 And
 “true” and “true”  “true”

 “true” and “false”  “false”

 In c++ : “&&”
 Or
 “true” or “false”  “true”

 “false” or “false”  “false”

 In c++  “ | | ”
 Not
 “not” “true”  “false”

 In c++  “!”
Usage
11

i n t a = 4, b = 0;
a && b //false
a || b //true
!a //false
!b //true
(a+b) //true
(a- //false
4)
Logical Operators Truth Table
12
Short-Circuit Methods for “and”

13
and
“or”
Relational Operators
15
Logical operator complements
16
Two-way decision logic
18
Two-way decision logic : “if...else”

19
logic
flow
A simple if...else statement
20
Compound statements in an if...else
21
Complemented if...then statements
A null else statement
23
A null if statement
24
Nested if statements
26

else is always paired with the most recent,


unpaired if
The ? Alternative
28

 You can use the ? operator to replace if-else statements of the general
form:
 if(condition) expression;

• else expression;
 The ? is called a ternary operator because it requires three operands. It
takes the general form
 Exp1 ? Exp2 : Exp3

• The value of a ? expression is determined as follows: Exp1 is evaluated. If it is


true, Exp2 is evaluated and becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of
the expression.
Dangling else
29
Dangling else solution
30
Conditional expression
31
switch decision logic
32
switch statement
33
switch flow
34
switch results
35
A switch with break statements
36
The else…if for Program 5-9
37
Comparison between if and switch
39
Conclusion

In this week …
 What is serial execution ?
 How Arithmetic and logical operator are used in program?
 How decision works?
 What is ‘if’ statement and ‘switch’ statement?

ANY
QUERY ?
Practice Questions
41

 PROBLEMS# (15-34)
 PROBLEMS# (35-50)
 PROBLEMS# (35-50)
 PROBLEMS# (51|52|53|54|55 )
 From “A structures approach using C+
+” Page (221-223)
1

COMPUTER
PROGRAMMIN
G
Repetitio
n
What will be discussed
2

 Repetition and its need in programming


 Concept of loop
 Loop in C++
 While, for and do-While loops
Why Do We Need Repetition?
3

 Sometimes we want to do things more than


once.
 E.g., Calculate the grades of 160 students
 E.g., Calculate the sum of 1~100

 How?
1. Cut and paste the codes 160 times?
2. cout << 1 + 2 + ……+100 << endl; ??

3. Then, what about summing up 1~10000?


Concept of Loop
4

Loop: The real power of computers!


Stopping the Loop
Question: When to Check Loop-End

6
Condition
?
Two Different Strategies for

7
Starting
Exercise
Minimum Number of Iterations in

8
Two
Loops
Loop Initialization and Updating
9
Initialization and Updating for

10
Exercis
e
Question: When to Stop a Loop?
11

 Counter-Controlled Loop
 Know how many times to loop when a loop begins
 E.g., do the summing calculation 100 times.

 Event-Controlled Loop
 Don’t know how many times, but knows how world will
be when done
 E.g., end the exercise when energy runs out
Event-Controlled Loop Concept
12
Counter-Controlled Loop Concept
13
Loops in C++

Usually used Usually used Usually used


for event- for counter- for event-
controlled controlled controlled
loop loop loop
The while Statement
The Compound while Statement
16
Examples of while Loop
Heating System Control Example
19
Enter an integer:
12345 Your number
is:
12345
The number of digits is: 5
The sum of the digits is: 15
The for Statement
24

A for loop is used when your loop is to be


executed a known number of times. You can
do the same thing with a while loop, but the
for loop is easier to read and more natural for
counting loops.
The Compound for Statement
25
Comparing for and while Loops
26
Conversion from while to for Loop
27
int
i n t main() main()
{ {
int j ; int j ;
j = -4; j = -4;
while(j for( ;
<= 0 ) j <=
{ 0; )
cout << j << {
endl; j = j + 1; cout << j <<
} endl; j = j + 1;
return 0; }
} return 0;
}
int
i n t main()
main()
{
{
i n t j = -4; int j ;
f o r ( ; j <= 0 ; ) f o r ( j = - 4 ; j <= 0 ; )
{ {
cout << j << cout << j <<
endl; j = j + 1; endl; j = j + 1;
} }
return 0; return 0;
} }
Step by Step Trace

i n t main()
{
int j ;
f o r ( j = - 4 ; j <= 0 ; j = j + 1)
{
cout << j << e n d l ;
}
return 0;
}
Examples!

f o r ( i = 2 ; i <= 6 ; i = i + 2)
cout << i+1 << ‘ \ t ’ ;

f o r ( i = 2 ; i ! = 11; i = i + 3)
cout << i+1 << ‘ \ t ’ ;

cout << "\nPlease enter a l i m i t : " ; Please enter the limit: 3


c i n >> l i m i t ; 1
f o r ( i = 1 ; i <= l i m i t ; i + + ) 2
cout << " \ t " << i << e n d l ; 3

0 10
1 9
f o r (n=0,i=10;n!=I;n++,i--) 2 8
cout << n < < " \ t " << i << e n d l ; 3 7
4 6
Compound Interest
Nested for Loop
Sun Mon Tue Wed Thu Fri
Sat
--- --- --- --- --- --- ---
1 2 3 4 5
6 7 8 9 10 11
12
13 14 15 16 17
18 19
20 21 22 23 24
25 26
Format of the do…while Statement
36
while vs. do … while

Print nothing because the i<0 is


checked prior to the cout

Print 1. cout is executed at least once


Before checking the i<0
Loopin
Other Statements Related to
38 g
break Statement
39

• Unconditional loop exit

•for(…;…;…) o r while(…)
•{
•…
break;
… Terminate the loop and
} execution jumps to here


break in Nested Loop
continue Statement
41

Skip the rest of the loop body without


exiting the loop
break vs. continue
42

Result:
Adam

Result:
Adam
Adam
Adam
Adam
Adam
break and continue Examples
43
continue Statement Example
44
Conclusion
45

In this week …
 What is the concept of Repetition in programming?
 How C++ implements loops in programming?
 How while, do-while and for loop work in
programming?

ANY
QUERY ?
Practice Questions
46

 PROBLEMS# (16-34)
 PROBLEMS# (35-45)

 PROBLEMS# (53|54|55|56|57|58)

 From “A structures approach using C+


+” Page (292-297)
1

COMPUTER
PROGRAMMIN
G
Array
s
What will be
2
discussed
 Introduction of an Array
 Declaration and Initialization of an
Array
 Utilization of an Array
Derived
Types
3
Ten
4
Variables
Processing Ten
5
Variables
An Array of
6
Scores
The Scores
7
Array
Loop for Ten
8
Scores
Declaring and defining
9
arrays
Initializing
arrays
Exchanging scores-the wrong
11
way
Exchanging scores with
temporary
12
variabl
e
Squares
13
Array
Print Input
14
Reversed
Passing individual
elements to
15
functio
n
Passing arrays—
16
average

Prevent x
from being
changed.
Use x just
for refering
Changing values in
17
arrays
Permutatio
Random Number
n
18
Conclusio
n
In this week …
 What is Array?
 How can we declare and Initialize an
Array ?
 How can we Utilize the Array?

ANY
QUERY ?
1

COMPUTER
PROGRAMMIN
G
Arrays
(Continue…)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Two dimensional Array
 Declaration and Initialization
 Utilization of Two dimensional Array

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Two-dimensional
3
array

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Array of
4
arrays

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Memory
5
layout

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Passing a
6
row

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Calculate average of integers
7
in
arra
y

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Fill
8
Matrix

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


A three-dimensional array (3 x 5
9
x
4
)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


C++ view of three-
10
dimensional
arra
y

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Initializing a three-
11
dimensional
arra
y

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
12
n
In this week …
 What is the Multi dime national Array?
 How can we use multi dimensional Array?

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Practice
13
Questions
 PROBLEMS# (16-18)
 PROBLEMS# (28-31)

 PROBLEMS# (43|44)

 From “A structures approach using C+


+” Page (406-410)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
Functions
I

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Overview of function
 Function in C++
 Declaration & Definition of
Function
 Some Examples

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Designing Structured
3
Programs

In top-down design, a program is divided into a main


module and its related modules. Each module is in
turn divided into submodules until the resulting
modules are intrinsic; that is, until they are implicitly
understood without further division.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Structure
4
Chart

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions in C+
5
+

In C++, a program is made of one or more functions,


one and only one of which must be named main. The
execution of the program always starts with main, but it
can call other functions to do some part of the job.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Structure Chart for a C++
6
Program

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions in C+
7
+
 A function in C++ can have a value, a side effect,
or both.
 The side effect occurs before the value is returned.
 The function’s value is the value of the expression in the
return statement.
 A function can be called for its value, its side effect, or
both.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions in C+
8
+

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


User-Defined
9
-Functions
Declaring, Calling, and
Defining

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions without Return
10
Value Have Side
(Only
Effect)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions without Return
11
Value
(Only Have Side
Effect)

void functions cannot be used in an expression;


they must be a separate statement.
Functions that return a value may be used in
an expression or as a separate statement.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions with Return
12
Value

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Function
13
Definition

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Function Return
14
Statements

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Function Local
15
Variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Notes on
16
Parameters
•Formal parameters are variables that are declared in
the header of the function definition.
•Actual parameters are the expressions in the calling
statement.
•The formal and actual parameters must match
exactly in type, order, and number. Their names,
however, do not need to be the same.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Part of a Function
17
Call

The type of the expression in the return


statement must match the return type in the
function header.
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Examples of Function
18
Calls

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-
19
1

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-2
20

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-3
21

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-4
22

Computer Programming(CSC-11 3) - Fall 2019 © September 2018 Shahid Khan


Program 4-5
23

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-6
24

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
25
n
In this week …
 What are the Functions?
 How C++ implements function in
programming?

ANY
QUERY ?
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
1

COMPUTER
PROGRAMMIN
G
Function
II

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Value passing to Function
 Built in function /Library
Function
 Linker in C++

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pass by Value
3

Different local
variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pass by
4
Reference

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


A Bad
5
Exchange

Computer Programming(CS C-113) - Fall 2019 © Sept ember 2018 Shahid Khan
Calculate Quotient and
6
Remainder

Computer Program ming(CSC-113) - Fall 2019 © Septembe r 2018 Shahid Khan


Program 4-8
7

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Default Parameter
8
Arguments
 Default values for parameters can be defined in
function declaration

Program 4-9

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Library Functions and the
9
Linker

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahi d Khan


Standard Library
10
Functions

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Floor and Ceiling
11
Functions

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


abs(), pow(), and
12
sqrt()
 abs(3)  returns 3
 fabs(-3.4)  returns 3.4

 pow(3.0, 4.0)  returns 81 (3^4)


 pow(3.4, 2.3)  returns 16.687893

 sqrt(25.0)  returns 5.0

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-10 Random
number generation
13

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-11,
Random number
14
generation

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Scope for Global and Block
15
Areas

Computer Programming(CS C-113) - Fall 2019 © Se ptember 2018 Shahid Khan


Scope for Global and Block
16
Areas
Variables are in scope from their point of
definition until the end of their function or block.

It is poor programming style to reuse identifiers


within the same scope.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-12
17

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 4-13
18

Computer Programming(C SC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
19
n
In this week …
 How the values pass to a Functions?
 What are built-in function and role of
linker?

ANY
QUERY ?
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Practice
20
Questions
 PROBLEMS# (13-24)
 PROBLEMS# (25-36)

 PROBLEMS# (37|38|39|40|41)

 From “A structures approach using C+


+” Page (169-173)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
Recursio
n

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


What will be
2
discussed
 What are Recursion?
 Stack and Function
Call

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Overview of
3
Recursion
 Recursion is present when a function is defined in
terms of itself.
 The factorial of an integer can be expressed using
a recursive definition. For example, 5 factorial
(5!) may be expressed as:
5! = 5 * 4 * 3 * 2 * 1
However, a more concise definition involving recursion would
be
5! = 5 * 4!
Now, in order to find the definition of 5! We must first find
the definition of 4!, then 3!, then 2! And finally 1!.

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Overview of
4
Recursion
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1 (basis case or
stopping
state) would
 A more generic recursive factorial definition

be: N! = N * (N-1)!
 This assumes that N >= 0 and that the factorial of 0
is 1 and the factorial of 1 is also 1 (a non-recursive
definition).
Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan
Factorial
5 Example
 Converting the mathematical definition to an
equivalent software algorithm we have ...

unsigned int factorial(unsigned long number) {


if (number <= 1)
return 1; / / basis case or stopping state
else
return number * factorial(number - 1); //
direct recursive call
}

 Notice how the last statement conforms to the


expression N * (N-1)!
Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan
Overview of
6 Recursion
 As discussed earlier, control structures may be
categorized as either sequential structures, selection
structures or repetition structures.
 Recursion is a technique by which to achieve
repetition.
 Iterative loops such as while, do while and for are
the other technique.
 Any algorithm that can be expressed iteratively
can also be expressed recursively, and visa
versa.
Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan
Overview of
7
Recursion
 In many cases an algorithm expressed recursively is
more concise than when expressed iteratively.
 In general, recursive algorithms run slower and
require more memory than do iterative algorithms.
 This often leads to a trade-off between efficiency and
simplicity of expression.
 There are two types of recursion
 Direct recursion is when a function contains a call to itself
within its own body.
 The factorial function is an example of direct recursion.

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Overview of
8
Recursion
 Indirect recursion is when a function calls a second
function which in turn calls the first function.
void g( ) {
f ( ); / / indirect recursive call
}
void f ( ) {
g ( );
}
void main ( ) {
f ( );
}
Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan
Stacks and Function
9 Calls
 A stack is a last-in-first-out data structure used by program
translators in the implementation of function calls, both
recursive and non-recursive.
 A stack is is operated on by two functions - push and pop.
 Push adds a new data element to the top of the stack.

 Pop removes an existing data element from the top of the

stack.
 Whenever a program translator encounters a function call it
generates the code to push a return address and any function
arguments that need to be passed to the called function onto the
stack.

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Stacks and Function
10 Calls
 Whenever a program translator encounters a return statement it
generates the code to pop a return address from the top of the
stack (and into the instruction pointer) as well as any parameters
that might have been previously pushed.
 The pops must be in the opposite order of the corresponding
pushes.
 In this way a program can find its way back from any number of
nested function calls.
 Understanding the relationship between stacks and function calls
can help in walking through complex recursive algorithms.

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Recursion
11
Examples
 Available in Word file

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


Conclusio
12
n
In this lecture …
 Role of recursion technique in
programming

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2018 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
String
s

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


What will be
2
discussed
 What are string
 What cstring
 String library in c++
 Sample code
 Class practice
 Conclusion

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Stri
3
ng
 C++ provides following two types of string
representations:

 The C-style character string.


 The string class type introduced with Standard
C++.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


The C-Style Character
4
String:
 The C-style character string originated within the C language and
continues to be supported within C++. This string is actually a one-
dimensional array of characters which is terminated by a null character
'\0'. Thus a null- terminated string contains the characters that comprise
the string followed by a null.

 The following declaration and initialization create a string consisting of


the word "Hello". To hold the null character at the end of the array, the
size of the character array containing the string is one more than the
number of characters in the word "Hello.“

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


5

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\


0'};
If you follow the rule of array initialization then you can write the above statement as follows:

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C+


+:

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Note
6
:
 Actually, you do not place the null character at the
end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string
when it initializes the array. Let us try to print
above mentioned string:

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


7

#include <iostream>
When the above code is compiled
using namespace and executed, it produces result
something as follows:
std; int main ()
Greeting message: Hello
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\
0'}; cout << "Greeting message: ";
cout << greeting <<
endl; return 0;
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


C++ supports a wide range of functions that
manipulate null-terminated strings:
8

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Following example makes use of few of the
above mentioned functions:
9

 #include <iostream>
 #include <cstring>
 using namespace std;
 int main ()
 {
 char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ;
 / / copy str1 into str3
 strcpy( str3, str1);
 cout << "strcpy( str3, str1) : " << str3 << endl;
 / / concatenates str1 and str2
 strcat( str1, str2);
 cout << "strcat( str1, str2): " << str1 << endl;
 / / total lenghth of str1 after concatenation
 len = strlen(str1);
 cout << "strlen(str1) : " << len << endl;
 return 0;
 }
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
When the previous code is compiled and
executed, it produces result something as
10
follows:

Strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


The String Class in
11
C++:
 The standard C++ library provides a string class type that supports all
the operations mentioned above, additionally much more functionality. We
will study this class in C++ Standard Library but for now let us check
following example:

 At this point you may not understand this example because so far we
have not discussed Classes and Objects. So can have a look and proceed
until you have understanding on Object Oriented Concepts

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Conclusio
13
n
In this lecture …
 Stings and C-Style Character
String

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
Pointer
s

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Introduction to
pointers
 Use of pointers
 Pointers and Arrays
 Pointers and
Arithmetic
 Pointers and Functions
 Pointers To Structures

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Getting the address of a
3
Variable
 The address operator (&) returns the
memory address of a variable.

3
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
4
1
letter number amount

1200 1201 1203

4
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
5
Program 9-
// 1
// This program uses the & operator to determine a variable’s
address and the sizeof operator to determine its size.

#include <iostream.h>

void main(void)
{
int x = 25;
cout << "The
address of x is "
<< &x << endl;
cout << "The size of x is " << sizeof(x) << " bytes\n";
cout << "The value in x is " << x << endl;
}

5
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
6 Output
The address of x is 0x8f05
The size of x is 2 bytes
The value in x is 25

6
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Pointer
7
Variables
 Pointer variables, which are often just called
pointers, are designed to hold memory
addresses. With pointer variables you can
indirectly manipulate data stored in other
variables.

7
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Pointers are useful for the
8
following:
 Working with memory locations that regular
variables don’t give you access to
 Working with strings and arrays
 Creating new variables in memory while the
program is running
 Creating arbitrarily-sized lists of values in
memory

8
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
// 2
9 This program stores the address of a variable in a pointer.
#include <iostream.h>

void main(void)
{
int x = 25;
int *ptr;

ptr = &x; // Store the address of x in


ptr cout << "The value in x is " << x <<
endl; cout << "The address of x is " << ptr
<< endl;
}

9
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
10 Output
The value in x is 25
The address of x is 0x7e00

10
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
11
2
x
25
ptr

0x7e00

Address of x: 0x7e00

11
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
3 operator.
12 // This program demonstrates the use of the indirection
//
#include <iostream.h>

void main(void)
{
int x = 25;
int *ptr;

ptr = &x;

// Store
the address
of x in ptr
cout << "Here is the value in x, printed twice:\n";
cout << x << " " << *ptr << endl;
*ptr = 100; 12
cout << "Once
Computer Programming(CSC-113) again, here is the value in x:\n";
- Fall 2019 © September 2018 Shahid Khan
Program
13 Output
Here is the value in x, printed twice:
25 25
Once again, here is the value in x:
100 100

13
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
14
4 #include <iostream>

void main(void)
{
int x = 25, y = 50, z = 75;
int *ptr;
cout << "Here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *= 2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
cout << "Once again, here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
}

14
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
15 Output
Here are the values of x, y, and z:
25 50 75
Once again, here are the values
of x, y , and z:
50 100 150

15
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
9.3 Relationship Between
16
Arrays
and
Pointers
array names can be used as pointers, and vice-
versa.

16
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
1 5
/ / This program shows an array name being
7

dereferenced
// with the * operator.

#include <iostream.h>

void main(void)
{
short numbers[] =
{10, 20, 30, 40,
50};

cout << "The first element of the array is ";


cout << *numbers << endl;
}

17
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
18 Output
The first element in the array is 10

18
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
19
3

numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

numbers

19
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
20
4

numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

numbers (numbers+1) (numbers+2) (numbers+3) (numbers+4)

20
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
// 6
// This program processes the contents of an array. Pointer
21 notation is used.
#include <iostream.h>

void main(void)
{
int numbers[5];

cout << "Enter five numbers: ";


for (int count = 0; count < 5; count++)
cin >> *(numbers + count);
cout << "Here are the numbers you entered:\n";
for (int count = 0; count < 5; count++)
cout << *(numbers + count)<< " ";
cout << endl;
}

21
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Output with Example
22 Input
Enter five numbers: 5 10 15 20 25 [Enter]
Here are the numbers you entered:
5 10 15 20 25

22
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
7// pointer notation with an array name.
// This program uses subscript notation with a pointer and
23

#include <iostream.h>

void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index

floatPtr = coins; // floatPtr now points to coins array


[Link](2);
cout << "Here are the values in the coins array:\n";

23
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
24

for (count = 0; count < 5; count++)


cout << floatPtr[count] << "
";
cout << "\nAnd here they are
again:\n";
for (count = 0; count < 5; count++)
cout << *(coins + count) << " ";
cout << endl;
}

24
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
25 Output
Here are the values in the coins array:
0.05 0.1 0.25 0.5 1
And here they are again:
0.05 0.1 0.25 0.5 1

25
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
8
26
// This program uses the address of each element in
the array.

#include <iostream.h>
#include <iomanip.h>

void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index
[Link](2);
cout << "Here are the values in the
coins array:\n";

26
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
27

for (count = 0; count < 5; count++)


{
floatPtr = &coins[count];
cout << *floatPtr << "
";
}
cout << endl;
}

27
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
28 Output
Here are the values in the coins array:
0.05 0.1 0.25 0.5 1

28
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
9.4 Pointer
29
Arithmetic
 Some mathematical operations may be performed
on pointers.
 The ++ and – operators may be used to increment or
decrement a pointer variable.
 An integer may be added to or subtracted from a
pointer variable. This may be performed with
the +, -
+=, or -= operators.
 A pointer may be subtracted from another pointer.

29
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
// This program uses a pointer to display the contents
// 9
30
of an integer array.
#include <iostream.h>

void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums, index;
nums = set;
cout << "The
numbers in set
are:\n";
for (index = 0;
index < 8; index+
+)
{
cout << *nums << " ";
nums++; 30
Computer }
Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues

31

cout << "\nThe numbers in set backwards are:\n";


for (index = 0; index < 8; index++)
{
nums--;
cout << *nums << " ";
}
}

31
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
32 Output
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5

32
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
9.5 Initializing
33
Pointers
 Pointers may be initialized with the address of an
existing object.

33
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
9.6 Comparing
34
Pointers
 If one address comes before another address in
memory, the first address is considered “less than”
the second. C++’s relational operators maybe
used to compare pointer values.

34
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
35
5
An array of five integers
array[0] array[1] array[2] array[3] array[4]

0x5A00 0x5A04 0x5A08 0x5A0C 0x5A0F

(Addresses)

35
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
36
10
// This program uses a pointer to display the contents
// of an integer array.
#include <iostream.h>

void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums = set; // Make nums point to set

cout << "The numbers in set are:\n";


cout << *nums << " "; // Display first element
while (nums < &set[7])
{
nums++;
cout << *nums << " ";
}

36
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues

37

cout << "\nThe numbers in set backwards are:\n";


cout << *nums << " "; // Display last element
while (nums > set)
{
nums--;
cout << *nums << " ";
}
}

37
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
38 Output
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5

38
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
9.7 Pointers as Function
39
Parameters
 A pointer can be used as a function parameter. It
gives the function access to the original argument,
much like a reference parameter does.

39
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-11
// This program uses two functions that accept addresses of
40 // variables as arguments.
#include <iostream.h>

// Function prototypes
void getNumber(int *);
void doubleValue(int *);

void main(void)
{
int number;
getNumber(&number) // Pass address of number to getNumber
doubleValue(&number); // and doubleValue.
cout << "That value doubled is " << number << endl;
}

40
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
continues
// Definition of getNumber. The parameter, Input, is a pointer.
41
// This function asks the user for a number. The value entered
// is stored in the variable pointed to by Input.

void getNumber(int *input)


{
cout << "Enter an integer number: ";
cin >> *input;
}

// Definition of doubleValue. The parameter, val, is a pointer.


// This function multiplies the variable pointed to by val by
// two.

void doubleValue(int *val)


{
*val *= 2;
}
41
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Output with Example
42 Input
Enter an integer number: 10
[Enter]
That value doubled is 20

42
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9-
12
// This program demonstrates that a pointer may be used as a
43

// parameter to accept the address of an array. Either subscript


// or pointer notation may be used.
#include <iostream.h>
#include <iomanip.h>

// Function prototypes
void getSales(float *);
float totalSales(float *);

void main(void)
{
float sales[4];

getSales(sales);
[Link](2);

43
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
[Link](ios::fixed | ios::showpoint);
cout << "The total sales for the year are $";
44 cout << totalSales(sales) << endl;
}

// Definition of getSales. This function uses a pointer to accept


// the address of an array of four floats. The function asks the
// user to enter the sales figures for four quarters, and stores
// those figures in the array. (The function uses subscript
// notation.)

void getSales(float *array)


{
for (int count = 0; count < 4; count++)
{
cout << "Enter the sales figure for quarter ";
cout << (count + 1) << ": ";
cin >> array[count];
}
}
44
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
45
// continues
Definition
of totalSales. This function uses a pointer to
// accept the address of an array of four floats. The function
// gets the total of the elements in the array and returns that
// value. (Pointer notation is used in this function.)

float totalSales(float *array)


{
float sum = 0.0;

for (int count = 0; count < 4; count++)


{
sum += *array;
array++;
}
return sum;
}

45
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Output with Example
46 Input
Enter the sales figure for quarter 1: 10263.98 [Enter]
Enter the sales figure for quarter 2: 12369.69
[Enter] Enter the sales figure for quarter 3:
11542.13 [Enter] Enter the sales figure for quarter
4: 14792.06 [Enter]
The total sales for the year are $48967.86

46
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Dynamic Memory
47
Allocation
 Variables may be created and destroyed while a
program is running.
 A pointer than contains the address 0 is called a
null pointer.
 Use the new operator to dynamically allocate
memory.
 Use delete to dynamically deallocate
memory.

47
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 9 -
// This program totals and averages the sales figures for any
48
13
// number of days. The figures are stored in a dynamically
// allocated array.

#include <iostream.h>
#include <iomanip.h>

void main(void)
{
float *sales,
total = 0,
average;
int numDays;

cout << "How many days of sales figures do you wish ";
cout << "to process? ";
cin >> numDays;
sales = new float[numDays]; // Allocate memory

48
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
49 if (sales == NULL) // Test for null pointer
{
cout << "Error allocating memory!\n";
return;
}
// Get the sales figures from the user
cout << "Enter the sales figures below.\n";
for (int count = 0; count < numDays; count++)
{
cout << "Day " << (count + 1) << ": ";
cin >> sales[count];
}
// Calculate the total sales
for (count = 0; count < numDays; count++)
{
total += sales[count];
}

49
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues

50

// Calculate the average sales per day


average = total / numDays;

// Display the results


[Link](2);
[Link](ios::fixed | ios::showpoint);
cout << "\n\nTotal sales: $" << total << endl;
cout << "average sales: $" << average <<
endl;
// Free dynamically allocated memory
delete [] sales;
}

50
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Output with Example
51 Input
How many days of sales figures do you wish to process? 5
[Enter]
Enter the sales figures below.
Day 1: 898.63 [Enter]
Day 2: 652.32 [Enter]
Day 3: 741.85 [Enter]
Day 4: 852.96 [Enter]
Day 5: 921.37 [Enter]
total sales: $4067.13
average sales: $813.43

51
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Returning Pointers from
52
Functions
 Functions can return pointers, but you must be sure
the object the pointer references still exists.
 You should only return a pointer from a function if it
is:
 A pointer to an object that was passed into the function
as an argument.
 A pointer to a dynamically allocated object.

52
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Pointers to
53
Structure
#include <iostream>
using namespace
std;

struct Distance {
int feet;
float inch;
};
53
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
54

int main()
{ Distance *ptr,
d; ptr = &d;
cout << "Enter feet:
"; cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;
cout << "Displaying
information." <<
endl;
cout << "Distance =
" << (*ptr).feet << "
feet " << (*ptr).inch
<< " 54
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
55

Enter feet: 4
Enter inch: 3.5
Displaying
Distance
information.
= 4 feet 3.5 inches
Note: Since pointer ptr is pointing to variable d in this program, (*ptr).inch
and [Link] is exact same cell. Similarly, (*ptr).feet and [Link] is exact same
cell.
The syntax to access member function using pointer is ugly and there is
alternative notation -> which is more common.

ptr->feet is same as (*ptr).feet


ptr->inch is same as
(*ptr).inch
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Conclusio
56
n
In this lecture …
 What is pointer?
 How to use pointers?
 What is dynamic memory allocaton?

ANY
QUERY ?
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
1

COMPUTER
PROGRAMMIN
G
Pointers
(Cont. )

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Pointers
 Pointers to
array

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Variable and
3
memory
identifier

int main ()
{ int a int b int c
int a;
int 1000 2000 3000
b;
int c;
value
a=
1000
;
b=
2000
;
c=
3000
;
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Variable and
4
memory
int main ()
{ int a int b int c
int a;
int b;
1000 2000 3000
int
c;
1004 1008 1012 1016
a=
c100
= 3000; address
0;
}
b=
200
0;

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointe
r
int main () int a int b int c
{
int a; 1000 2000 3000
int
b;
1004 1008 1012 1016
int c;

int* ptr
int*
ptr;
NUL
a=
100 3004 3008
}
0;
b=
200
0;
c=
Pointe
r
int main () int a int b int c
{
int a; 1000 2000 3000
int
b;
1004 1008 1012 1016
int c;
int* memory int* ptr
ptr; address of ‘a’

a= 1004
100
0; 3004 3008
}
b=
200
0;
c=
300
Pointe
r‘Pointer’ is
a variable
that contains a memory address of other variable
(does not contain a actual data).
This is why we call it “Pointer”
since it is used to POINT other variable.
Operator ‘*’

When * is used as a prefix to a variable name,


it means “value” of a pointer.
When it is used as a suffix to a type, it means
a pointer of that type.
Operator ‘*’ as “value of”
int a int b int c

1000 2000 3000


cout << ptr; its
value
→ 1004 1004 1008 1012 1016

pointed int* ptr


address
cout <<
1004
*ptr;
→ 1000 3004 3008

Copyright(c) 2009 Kyung Hee University. All Rights 9


Reserved.
Operator ‘*’ as “pointer
type
definition”
int main ()
{
int a;
int b;
int c;
int* ptr;

a=
1000;
b=
2000;
c=
3000;
}
Operator ‘&’

When the ampersand (&) is used as a prefix to a


variable name, it means “address” of variable.
When it is used as a suffix to a type, it means
reference parameter.
Operator ‘&’ as “address of”

int a int b int c

cout << a;
1000 2000 3000
→ 1000
1004 1008 1012 1016

cout << &a; address

→ 1004
Operator ‘&’ as
“reference
parameter”
void exchange(int & num1, int & num2);
int main ()
{
int a;
int
b;

a=
100
0;
b=
200
0;
Pointer and
data int* ptr

1004
ptr = &a;
int a

1000

1004 1008
Character constants and
15
variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer
16
constants

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Print character
17
addresses

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Integer constants and
18
variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


19

Note:

The address of a variable is the


address of the first byte occupied by
that variable.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer
20
variable

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Multiple pointers to a
21
variable

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Accessing variables
22
through
pointer
s

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Address and indirection
23
operators

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer variable
24
declaration

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Declaring pointer
25
variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Uninitialized
26
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Initializing pointer
27
variables

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer
28
flexibility

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Using one variable with
29
many
pointer
s

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Exchanging
30
values

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Exchanging values
31
(continued)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Exchanging values
32
(continued)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Functions returning
33
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


34

Note:

It is a serious error to return a pointer


to a local variable.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointers to
35
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer
36
compatibility

Computer Programming(C SC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer types must
37
match

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointers to
38
arrays

sam
a e
& a[0]
‘a’ is a pointer only to the first element, not the whole array

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Array name as a pointer
a[0] a[1] a[2]

int main () 1000 2000 3000


{
int a[3];
1004 1008 1012 1016
cout << &a[0];
The name of an array is a pointer
/ / → 1004

a
constant to its first element

cout << a;
/ / → 1004
}

39
Dereference of array
40
name

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Array names as
41
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


42
Note:

To access an array, any pointer to the


first element can be used instead of the
name of the array.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Multiple array
43
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer Arithmetic and
44
Arrays
Given pointer, p, p ± n is a pointer to the
value n elements away.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Pointer arithmetic and
45
different
type
s

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Dereferencing array
46
pointers

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
47
n
In this lecture …
 Pointer in
programming

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
Structure
s

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 What is Structure?
 How to declare Structures?
 What are nested
Structures?
 Structures And Arrays
 Structures And Fucntions

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


 A Structure is a collection of related
data items, possibly of different types.
 A structure type in C++ is called struct.
 A struct is heterogeneous in that it
can be composed of data of
different types.
 In contrast, array is homogeneous
since it can contain only data of the
same type.
3
 Structures hold data that belong
together.
 Examples:
 Student record: student id, name,
major, gender, start year, …
 Bank account: account number,
name, currency, balance, …
 Address book: name, address,
telephone number, …
 In database applications, structures are
called records.
4
 Individual components of a struct
type are called members (or fields).
 Members can be of different types
(simple, array or struct).
 A struct is named as a whole while
individual members are named
using field identifiers.
 Complex data structures can be
formed by defining arrays of
structs. 5
 Definition of a
structure:
struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;

 Example:
struct Date { The “Date” structure
int day; has 3 members,
int month;
int year; day, month & year.
} ;
6

Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age;
char Gender; structure has 4 members
double CGA; of different types.
};

 Example:
struct StudentGrade{
char Name[15];
char Course[9]; The “StudentGrade”
int Lab[5]; structure has 5
int Homework[3];
int Exam[2]; members of
}; different array types.
7

Example:
struct BankAccount{
char Name[15]; The “BankAcount”
int AcountNo[10]; structure has simple,
double balance; array and structure
Date Birthday;
};
types as members.

 Example:
struct StudentRecord{
char Name[15]; The “StudentRecord”
int Id; structure has 4
char Dept[5]; members.
char Gender;
};

8
 Declaration of a variable of struct
type:
<struct-type> <identifier_list>;
 Example:
StudentRecord Student1, Student2;

Name Name
Student1 Id Gender Id Gender Student2

Dept Dept

Student1 and Student2 are variables


of
StudentRecord type. 9
 The members of a struct type variable are accessed
with the dot (.) operator:
<struct-variable>.<member_name>; Student1
 Example:
strcpy([Link], "Chan Tai Man"); Name
[Link] = 12345; Id Gender
strcpy([Link], "COMP");
[Link] = 'M'; Dept
cout << "The student is ";
switch ([Link]){
case 'F': cout << "Ms. Chan Tai Man
"; break; 12345
case 'M': cout << "Mr.
"; break; M COMP
}
cout << [Link] << 10
11
 The values contained in one struct type
assigned
variable can to
beanother variable of the same
struct type.
Student1
 Example:
strcpy([Link],
"Chan Tai Man");
[Link] = 12345; Chan Tai Man
strcpy([Link], "COMP");
[Link] = 'M';
12345 M
Student2 = Student1;
COMP

Chan Tai Man


12345 M
Student2 COMP
12
13
 We can nest structures inside
structures.
 Examples:
struct
point{ doub (P.x, P.y)
le x, y;
};
point P;
(L.p2.x, L.p2.y)
struct
line{ point (L.p1.x, L.p1.y)
p1, p2;
};
line L; (T.p2.x, T.p2.y)
struct
triangle{ point
p1, p2, p3;
};
triangle T;
(T.p3.x, T.p3.y)

(T.p1.x, T.p1.y)
14
 We can nest structures inside
structures.
 struct line{
point p1, p2;
}; (L.p2.x, L.p2.y)
line L;
(L.p1.x, L.p1.y)

line
p1 p2
x y x y

15
 Assign values to the variables P, L,
using
and T the
(4, 11)
picture:
point P;
line L; (10, 9)
triangle T;
(2, 7)

(6, 5)
Ex. 3: Graph a point
Ex. 4: Graph a line
Ex. 5: Graph a (8, 3)
triangle
(2, 0)
16
point P;
line L;
triangle T;
(4, 11)
P.x = 4;
P.y = 11; (10, 9)
L.p1.x = 2;
L.p1.y = 7; (2, 7)
L.p2.x = 10;
L.p2.y = 9;
(6, 5)
T.p1.x = 2;
T.p1.y = 0;
T.p2.x = 6; (8, 3)
T.p2.y = 5;
T.p3.x = 8;
T.p3.y = 3;
(2, 0)
17
 An ordinary array: One type of
data

0 1 2 … 98 99

 An array of structs: Multiple types of


data in each array element.

0 1 2 … 98 99
18
 We often use arrays of
Example:
structures.

StudentRecord Class[100];
strcpy(Class[98].Name, "Chan Tai Man");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP");
Class[98].gender = 'M';
Class[0] = Class[98]; Chan Tai Man
12345 M
COMP

...

0 1 2 … 98 99
19
 We can use arrays inside
structures.
 Example: (4, 3) (10, 3)
struct square{
point vertex[4];
};
square Sq; (4, 1) (10, 1)

 Assign values to Sq using the given


square
x y x y x y x y

20
 A structure variable can be passed to a
function in similar way as normal
argument. Consider this
 Example:

#include
<iostream> using
namespace std;
struct person
{
char
name[50];
int age;
float salary;
int main()
{
person p;
cout << "Enter Full name: "; [Link]([Link], 50);
cout << "Enter
age: "; cin >>
[Link];
cout << "Enter
salary: ";
cin >> [Link];
displayData(p); / / Function call with structure variable as
arugment return 0;
}
void displayData(person p1) {

cout << "\nDisplaying Information."


<< endl; cout << "Name: " <<
[Link] << endl;
cout <<"Age: " << [Link] << endl;
cout << "Salary: " << [Link];

}
OUT PUT:
Enter Full name: Bill
Jobs Enter age: 55
Enter salary: 34233.4
Displaying
Information. Name:
Bill Jobs
Age: 55
Salary: 34233.4
 Example:
#include
<iostream> using
namespace std;
struct person
{
char
name[50];
int age;
float salary;
};

person
getData(person); void
int main()
{
person p;
p =
getData(p);
displayData(
p); return 0;
}
person
getData(pers
on p1)
{
cout
<<
"Enter
Full
name:
";
[Link]([Link],
void displayData(person p1)
{
cout << "\nDisplaying Information."
<< endl; cout << "Name: " <<
[Link] << endl;
cout <<"Age: " << [Link] << endl;
cout << "Salary: " << [Link];
}
 An enumeration is a user-defined type whose
value is restricted to one of several explicitly
named constants(enumerators). Enumeration
are defined using keyword: enum.
enum seasons { spring, summer, autumn,
winter };

 This code is a enum declaration. After


declaration, you can define variable of type
seasons. And this variable of type seasons can
only have one of those 4 values. For example:
C++ program to define enumeration type
and assign value to variable of that type.
 Exmple 1:
#include <iostream>
using namespace std;
enum seasons { spring, summer, autumn, winter };
int main() {
seasons s;
s = autumn; // Correct
s = rainy; // Error
return 0;
}
 In this program, an enum type seasons is
declared with 4 enumerators (spring, summer,
autumn, winter).
Then, inside main() function, a variable s of
type seasons is defined. This variables can
only store any one of four values (spring,
summer, autumn, winter).

 By default, the value of first enumerator is 0,


second is 1 and so in. In this program, spring
is equal to 0, summer is equal to 1 and
autumn is 2 and winter is 3.

 One very important thing to remember is that,


spring, summer etc are not variables. They
are treated as integers by compiler. Hence,
#include <iostream>

using namespace std;

enum seasons { spring, summer, autumn, winter };

int main()
{

seasons s;
s=
spring;
cout >>
"spring = "
>> s >>
endl;
s=
summer;
cout >> "summer = " >> s >> endl;
s = autumn;
cout >> "autumn = " >> s >> endl;
s = winter;
cout >> "winter = " >> s >> endl;

return 0;
}
OUT PUT:
spring =
0
summer =
1
autumn =
2
winter =
3
 You can change the default value during
enumeration declaration(after
declaration, you cannot change it) and
give them another value. Consider this
example:
#include <iostream>
using namespace std;
enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main()
{

seasons s;
s = summer;
cout <<
"summer = "
<< s <<
endl;

return 0;
}

OUT
Conclusio
34
n
In this lecture …
 Role of recursion technique in
programming

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


What will be
2
discussed
 Introduction to File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.1 What is a
3
File?
 A file is a collection on information, usually stored
on a computer’s disk. Information can be saved to
files and then later reused.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.2 File
4
Names
 All files are assigned a name that is used for
identification purposes by the operating system and
the user.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Table 12-1
5

File Name and Extension File Contents

[Link] BASIC program


[Link] DOS Batch File
[Link] Documentation File
[Link] Executable File
[Link] HTML (Hypertext Markup Language) File
[Link] Java program or applet
A [Link] Object File
[Link] Borland C++ Project File
[Link] System Device Driver
[Link] Text File

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.3 The Process of Using a
6
File
 Using a file in a program is a simple three-step
process
 The file must be opened. If the file does not yet
exits, opening it means creating it.
 Information is then saved to the file, read from the file,
or both.
 When the program is finished using the file, the file
must be closed.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Figure 12-
7
1

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Figure 12-
8
2

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.4 Setting Up a Program for
9
File
Input/
Output
 Before file I/O can be performed, a C++
program must be set up properly.
 File access requires the inclusion of fstream.h

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.5 Opening a
10
File
 Before data can be written to or read from a
file, the file must be opened.
ifstream inputFile;
[Link](“[Link]”
);

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
11
1
// This program demonstrates the declaration of an
fstream
// object and the opening of a file.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile; // Declare file stream
object char fileName[81];
cout << "Enter the name of a file you wish to
open\n";
cout << "or create: ";
[Link](fileName, 81);
[Link](fileName, ios::out);
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
Program Output with Example Input
12

Enter the name of a file you wish to open


or create: [Link] [Enter]
The file [Link] was opened.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Table 12-3
13

File Type Default Open Mode


ofstrea The file is opened for output only. (Information may be
m written to the file, but not read from the file.) If the file
does not exist, it is created. If the file already exists, its
contents are deleted (the file is truncated).
ifstream The file is opened for input only. (Information may be
read from the file, but not written to it.) The file’s
contents will be read from its beginning. If the file does
not exist, the open function fails.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Table 12-4
14
File Mode Flag
Meaning
ios::ap Append mode. If the file already exists, its
p contents are preserved and all output is
written to the end of the file. By default, this
flag causes the file to be created if it does
not exist.
ios::at If the file already exists, the program goes
e directly to the end of it. Output may be
written anywhere in the file.
ios::binary Binary mode. When a file is opened in
binary mode, information is written to or
read from it in pure binary format. (The
default mode is text.)
ios::i Input mode. Information will be read from
n the file. If the file does not exist, it will
not be created and the open function
will fail.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Table 12-4 continued
15

File Mode
Meaning Flag
ios::nocreate If the file does not already exist, this flag
will cause the open function to fail. (The
file will not be created.)
ios::noreplac If the file already exists, this flag will cause
e the open function to fail. (The existing file
will not be opened.)
ios::out Output mode. Information will be written to
the file. By default, the file’s contents will
be deleted if it already exists.
ios::trunc If the file already exists, its contents will
be deleted (truncated). This is the default
mode used by ios::out.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Opening a File at
16
Declaration
fstream dataFile(“[Link]”, ios::in |
ios::out);

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
17
2
// This program demonstrates the opening of a file at
the
// time the file stream object is declared.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile("[Link]", ios::in
| ios::out);
cout << "The file [Link] was
opened.\n";
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program Output with Example Input
18

The file [Link] was opened.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Testing for Open
19
Errors
[Link](“[Link]”, ios::in);
if (!dataFile)
{
cout << “Error opening file.\
n”;
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Another way to Test for Open
20
Error
[Link](“[Link]”, ios::in);
if ([Link]())
{
cout << “Error opening file.\
n”;
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.6 Closing a
21
File
 A file should be closed when a program is finished
using it.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


22
Program 12-
/3
/ This program demonstrates the close
function.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
[Link]("[Link]", ios::out);
if (!dataFile)
{
cout << "File open error!" <<
endl; return;
}
cout << "File was created
successfully.\n";
cout << "Now closing the file.\n"; © September 2015 Shahid Khan
Program
Output
23

File was created successfully.


Now closing the file.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.7 Using << to
24
Write
Information to a
File
 The stream insertion operator (<<) may be used
to write information to a file.
outputFile << “I love C++ programming !”

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
// This program uses the << operator to write information to a file.
4
25

#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile;
char line[81];

[Link]("[Link]", ios::out);
if (!dataFile)
{
cout << "File open error!" <<
endl; return;
}
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
Program continues
26

cout << "File opened successfully.\n";


cout << "Now writing information to the file.\
n"; dataFile << "Jones\n";
dataFile << "Smith\n";
dataFile << "Willis\n";
dataFile << "Davis\n";
[Link]();
cout << "Done.\n";
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program Screen
Output
27

File opened successfully.


Now writing information to the file.
Done.

Output to File [Link]


Jone
s
Smit
h
Willi
s
Davi
s

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Figure 12-
28
3

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
/5
29

/ This program writes information to a file, closes the


file,
/ / then reopens it and appends more
information. #include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
[Link]("[Link]", ios::out);
dataFile << "Jones\n";
dataFile << "Smith\
n"; [Link]();
[Link]("demofil
[Link]", ios::app);
dataFile << "Willis\
n";
dataFile << "Davis\n";
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
Output to File [Link]
30

Jones

Smith
Willis
Davis

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.8 File Output
31
Formatting
 File output may be formatted the same way as
screen output.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
6
32
// This program uses the precision member function of
a
// file stream object to format file output.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile;
float num = 123.456;
[Link]("numf
[Link]", ios::out);
if (!dataFile)
{
cout << "File open error!" <<
endl; return;
}
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
Program continues

33

dataFile << num << endl;


[Link](5);
dataFile << num << endl;
[Link](4);
dataFile << num << endl;
[Link](3);
dataFile << num << endl;
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Contents of File [Link]
34

123.456
123.46
123.5
124

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
35
7
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
void main(void)
{ fstream
outFile("[Link]",
ios::out);
int nums[3][3] =
{ 2897, 5, 837,
3
4
,

7
,

1
6
2
3
, © September 2015 Shahid Khan
}
Contents of File [Link]
36

2897 5 837
34 7 1623
390 3456 12

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Figure 12-
37
6

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.9 Using >> to
38
Read
Information from a
File
 The stream extraction operator (>>) may be
used to read information from a file.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
39
8// This program uses the >> operator to read information from a file.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile;
char name[81];
[Link]("[Link]", ios::in);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
cout << "File opened successfully.\n";
cout << "Now reading information from
the file.\n\n";
Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan
Program continues

40

for (int count = 0; count < 4; count+


+)
{
dataFile >> name;
cout << name << endl;
}
[Link]();
cout << "\nDone.\n";
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program Screen
Output
41

File opened successfully.


Now reading information from the file.

Jones

Smith
Willis

Davis

Done.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


12.10 Detecting the End of a
42
File
 The eof() member function reports when the
end of a file has been encountered.

if ([Link]())
[Link]();

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program 12-
// This program uses the file stream object's eof() member
9function to detect the end of the
43

//
file. #include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
char name[81];
[Link]("d
[Link]",
ios::in);
if (!dataFile)
{
cout <<
"File open
error!" <<
endl; - Fall 2019
Computer Programming(CSC-113) © September 2015 Shahid Khan
Program continues

44

dataFile >> name; // Read first name from the


file while (![Link]())
{
cout << name << endl;
dataFile >> name;
}
[Link]();
cout << "\nDone.\n";
}

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Program Screen
Output
45

File opened successfully.


Now reading information from the file.

Jones

Smith
Willis

Davis
Done.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Note on
46
eof()
 In C++, “end of file” doesn’t mean the program is
at the last piece of information in the file, but
beyond it. The eof() function returns true
when there is no more information to be read.

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


Conclusio
47
n
In this lecture …
 What is Filing?

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2015 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Introduction to File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.11 Passing File Stream
3
Objects
to
Functions
 File stream objects may be passed by reference to
functions.
bool openFileIn(fstream &file, char name[51])
{
bool status;

[Link](name, ios::in);
if ([Link]())
status = false;
else
status = true;
return status;
}
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
12.12 More Detailed Error
4
Testing
 All stream objects have error state bits that indicate
the condition of the stream.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Table 12-5
5

Bit Description
ios::eofb Set when the end of an input stream is
it encountered.
ios::failbit Set when an attempted operation has
ios::hardfa failed.
il Set when an unrecoverable error has
ios::badbit occurred.
ios::goodb Set when an invalid operation has been
it attempted.
Set when all the flags above are not set.
Indicates the stream is in good condition.
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
6
Table 12-6
Function Description
eof( Returns true (non-zero) if the eofbit flag is set,
) otherwise returns false.
fail( Returns true (non-zero) if the failbit or hardfail
) flags are set, otherwise returns false.
bad( Returns true (non-zero) if the badbit flag is set,
) otherwise returns false.
good( Returns true (non-zero) if the goodbit flag is
) set, otherwise returns false.
clear( When called with no arguments, clears all the
) flags listed above. Can also be called with a
specific flag as an argument.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


7
Program 12-11
// This program demonstrates the return value of the
stream
// object error testing member
functions. #include <iostream.h>
#include <fstream.h>
// Function prototype
void showState(fstream &);

void main(void)
{
fstream testFile("[Link]", ios::out);
if ([Link]())
{
cout << "cannot open the file.\n";
return;
}
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
8

int num = 10;


cout << "Writing to the file.\n";
testFile << num; // Write the integer to testFile
showState(testFile);
[Link](); // Close the file
[Link]("[Link]", ios::in); // Open for input
if ([Link]())
{
cout << "cannot open the file.\n";
return;
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues
9
cout << "Reading from the file.\n";
testFile >> num; // Read the only number in the
file
showState(testFile);
cout << "Forcing a bad read operation.\n";
testFile >> num; // Force an invalid read operation
showState(testFile);
[Link](); // Close the file
}

// Definition of function ShowState. This function uses


// an fstream reference as its parameter. The return values
of
// the eof(), fail(), bad(), and good() member functions are
// displayed. The clear() function is called before the function
// returns.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues

10

void showState(fstream &file)


{
cout << "File Status:\n";
cout << " eof bit: " << [Link]() << endl;
cout << " fail bit: " << [Link]() << endl;
cout << " bad bit: " << [Link]() <<
endl; cout << " good bit: " << [Link]()
<< endl; [Link](); // Clear any bad
bits
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program
11
Outputto the file.
Writing
File Status:
eof bit: 0
fail bit: 0
bad bit: 0
good bit: 1
Reading from the file.
File Status:
eof bit: 0
fail bit: 0
bad bit: 0
good bit: 1
Forcing a bad read operation.
File Status:
eof bit: 1
fail bit: 2
bad bit: 0
good bit: 0
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
12.13 Member Functions
12
for
Reading and Writing
Files
 File stream objects have member functions for more
specialized file reading and writing.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Figure 12-
13
8

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
12
14 // This program uses the file stream object's eof() member
// function to detect the end of the file.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream nameFile;
char input[81];

[Link]("mu
[Link]",
ios::in);
if (!nameFile)
{
cout << "File open error!" << endl;
return;
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-12
15
(continued)
nameFile >> input;
while (![Link]())
{
cout << input;
nameFile >> input;
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen
Output
16

JayneMurphy47JonesCircleAlmond,NC28702

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


The getline Member
17
Function
 [Link](str, 81, ‘\n’);
str – This is the name of a character array, or a pointer to a section of
memory. The information read from the file will be stored
here.
81 – This number is one greater than the maximum number of
characters to be read. In this example, a maximum of 80
characters will be read.
‘\n’ – This is a delimiter character of your choice. If this
delimiter is encountered, it will cause the function to stop reading
before it has read the maximum number of characters. (This
argument is optional. If it’s left our, ‘\n’ is the default.)

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
13
18 // This program uses the file stream object's getline member
// function to read a line of information from the file.

#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream nameFile;
char input[81];

[Link]("[Link]", ios::in);
if (!nameFile)
{
cout << "File open error!" <<
endl;
return;
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues

19

[Link](input, 81); // use \n as a delimiter


while (![Link]())
{
cout << input << endl;
[Link](input, 81); // use \n as a delimiter
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen
Output
20

Jayne Murphy
47 Jones Circle
Almond, NC
28702

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
14
21 // This file shows the getline function with a user-
// specified delimiter.

#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile("[Link]", ios::in);
char input[81];
[Link](input, 81, '$');
while (![Link]())
{
cout << input << endl;
[Link](input, 81, '$');
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program
Output
22

Jayne Murphy
47 Jones Circle
Almond, NC 28702

Bobbie Smith
217 Halifax Drive
Canton, NC 28716

Bill Hammet
PO Box 121
Springfield
, NC 28357

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


The get Member
23
Function
[Link](ch);

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
// This program asks the user for a file name. The file is
// 15
opened and its contents are displayed on the screen.
24 #include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream file;
char ch, fileName[51];
cout << "Enter a file name: ";
cin >> fileName;
[Link](fileName, ios::in);
if (!file)
{
cout << fileName << “
could not be opened.\n";
return;
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues
25

[Link](ch); // Get a character


while (![Link]())
{
cout << ch;
[Link](ch); // Get another character
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


The put Member
26
Function
 [Link](ch);

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
27
16 <iostream.h>
// This program demonstrates the put member function.
#include
#include <fstream.h>

void main(void)
{ fstream dataFile("[Link]", ios::out);
char ch;

cout << "Type a sentence and be sure to end it with a ";


cout << "period.\n";
while (1)
{
[Link](ch);
[Link](ch);
if (ch == '.')
break;
}
[Link]();
}
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Screen Output with Example Input
28

Type a sentence and be sure to end it with a


period.
I am on my way to becoming a great programmer. [Enter]

Resulting Contents of the File [Link]:


I am on my way to becoming a great programmer.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.14 Focus on
Engineering: Working with Multiple
Software
29
Files
 It’s possible to have more than one file open at once
in a program.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
// 17
// This program demonstrates reading from one file and writing
to a second file.
30
#include <iostream.h>
#include <fstream.h>
#include <ctype.h> // Needed for the toupper function

void main(void)
{
ifstream inFile;
ofstream outFile("[Link]");
char fileName[81], ch, ch2;

cout << "Enter a file name: ";


cin >> fileName;
[Link](fileName);
if (!inFile)
{
cout << "Cannot open " <<
fileName << endl;
return;
Computer}Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
[Link](ch); // Get a characer from file 1
31
while (![Link]()) // Test for end of file
{
ch2 = toupper(ch); // Convert to uppercase
[Link](ch2); // Write to file2
[Link](ch); // Get another character from file 1
}
[Link]();
[Link]();
cout << "File
conversion
done.\n";
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen Output with Example Input
32

Enter a file name: [Link] [Enter]


File conversion done.
Contents of [Link]:
how now brown cow.
How Now?
Resulting Contents of
[Link]: HOW NOW BROWN
COW. HOW NOW?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
33
n
In this lecture …
 What is Filing?

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


1

COMPUTER
PROGRAMMIN
G
File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


What will be
2
discussed
 Introduction to File
Handling

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.15 Binary
3
Files
 Binary files contain data that is unformatted, and
not necessarily stored as ASCII text.
[Link](“[Link]”, ios::out | ios::binary);

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Figure 12-
4
9

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Figure 12-
5
10

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
// This program uses the write and read functions.

6
18
#include <iostream.h>
#i nclude <fstream.h>

void main(void)
{
fstream file(“[Link]", ios::out | ios::binary);
int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

cout << "Now writing the data to the file.\n";


[Link]((char*)buffer, sizeof(buffer));
[Link]();
[Link]("[Link]", ios::in); // Reopen
the file.
cout << "Now reading the data back into memory.\n";
[Link]((char*)buffer, sizeof(buffer));
for (int count = 0; count < 10; count++)
cout << buffer[count] << " ";
[Link]();
}
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Screen
Output
7

Now writing the data to the file.


Now reading the data back into memory.
1 2 3 4 5 6 7 8 9 10

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.16 Creating Records
8 with
Structures
 Structures may be used to store fixed-length
records to a file.
struct Info
{
char name[51];
int age;
char
address1[51];
char address2[51];
char phone[14];
};
 Since structures can contain a mixture of data
types, you should always use the ios::binary mode
when opening a file to store them.
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 12-
// This program demonstrates the use of a structure variable to
9 19 a record of information to a file.
// store

#include <iostream.h>
#include <fstream.h>
#include <ctype.h>

// for toupper

// Declare a structure for the record.


struct Info
{
char name[51];
int age;
char
address1[51];
char address2[51];
char phone[14];
};
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program
voidcontinues
main(void)
{
10
fstream people("[Link]", ios::out | ios::binary);
Info person;
char again;
if (!
people)
{
cout << "Error opening file. Program aborting.\n";
return;
}
do
{
cout << "Enter the following information about a ”
<< "person:\n";
cout << "Name: ";

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues
[Link]([Link], 51);
cout << "Age: ";
11 cin >> [Link];
[Link](); // skip over remaining newline.
cout << "Address line 1: ";
[Link](person.address1, 51);
cout << "Address line 2: ";
[Link](person.address2, 51);
cout << "Phone: ";
[Link]([Link], 14);
[Link]((char *)&person,
sizeof(person));
cout << "Do you want to enter another record? ";
cin >> again;
[Link]();
} while (toupper(again) == 'Y');
[Link]();
}
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program Screen Output with
12 Example
Enter the Input
following information about a person:
Name: Charlie Baxter [Enter]
Age: 42 [Enter]
Address line 1: 67 Kennedy Bvd. [Enter]
Address line 2: Perth, SC 38754 [Enter]
Phone: (803)555-1234 [Enter]
Do you want to enter another record? Y [Enter]
Enter the following information about a person:
Name: Merideth Murney [Enter]
Age: 22 [Enter]
Address line 1: 487 Lindsay Lane [Enter]
Address line 2: Hazelwood, NC 28737 [Enter]
Phone: (704)453-9999 [Enter]
Do you want to enter another record? N [Enter]

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.17 Random Access
13
Files
 Random Access means non-sequentially
accessing informaiton in a file.
Figure 12-11

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Table 12-7
14

Mode Flag Description

ios::be The offset is calculated from


g the beginning of the file.
ios::en The offset is calculated from
d the end of the file.
ios::cur The offset is calculated from
the current position.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Table 12-8
15
Statement How it Affects the Read/Write Position
[Link](32L, ios::beg); Sets the write position to the 33rd byte
(byte 32) from the beginning of the file.
[Link](-10L, ios::end); Sets the write position to the 11th byte
(byte 10) from the end of the file.
[Link](120L, ios::cur); Sets the write position to the 121st byte
(byte 120) from the current position.
[Link](2L, ios::beg); Sets the read position to the 3rd byte
(byte 2) from the beginning of the file.
[Link](-100L, ios::end); Sets the read position to the 101st byte
(byte 100) from the end of the file.
[Link](40L, ios::cur); Sets the read position to the 41st byte
(byte 40) from the current position.
[Link](0L, ios::end); Sets the read position to the end of the
file.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
16
21
// This program demonstrates the seekg function.

#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream file("[Link]", ios::in);
char ch;

[Link](5L, ios::beg);
[Link](ch);
cout << "Byte 5 from beginning: " << ch << endl;
[Link](-10L, ios::end);
[Link](ch);
cout << "Byte 10 from end: " << ch << endl;

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues

17

[Link](3L, ios::cur);
[Link](ch);
cout << "Byte 3 from current: " << ch << endl;
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen
Output
18

Byte 5 from beginning: f


Byte 10 from end: q
Byte 3 from current: u

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


The tellp and tellg
19
Member
Function
s tellp returns a long integer that is the

current byte number of the file’s write position.


 tellg returns a long integer that is the
current byte number of the file’s read position.

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
20
23
// This program demonstrates the tellg function.
#include <iostream.h>
#include <fstream.h>
#include <ctype.h> // For toupper

void main(void)
{
fstream file("[Link]", ios::in);
long offset;
char ch, again;

do
{
cout << "Currently at position " << [Link]() << endl;
cout << "Enter an offset from the beginning of the file: ";
cin >> offset;

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues

21

[Link](offset, ios::beg);
[Link](ch);
cout << "Character read: " << ch << endl;
cout << "Do it again? ";
cin >> again;
} while (toupper(again) == 'Y');
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Output with
Example Input
22

Currently at position 0
Enter an offset from the beginning of the file: 5
[Enter]
Character read: f
Do it again? y [Enter]
Currently at position 6
Enter an offset from the beginning of the file: 0
[Enter]
Character read: a
Do it again? y [Enter]
Currently at position 1
Enter an offset from the beginning of the file: 20
[Enter]
Character read: u
Do it again? n [Enter]

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


12.18 Opening a File for
23
Both and
Input
Output
 You may perform input and output on an fstream file
without closing it and reopening it.

fstream file(“[Link]”, ios::in |


ios::out);

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
// This program sets up a file of blank inventory records.
24 24 <iostream.h>
#include
#include <fstream.h>

// Declaration of Invtry structure


struct Invtry
{
char desc[31];
int qty;
float price;
};

void main(void)
{
fstream
inventory("inv
[Link]",
ios::out |
ios::binary);
ComputerInvtry record- Fall 2019
Programming(CSC-113) © September 2018 Shahid Khan
Program
continues
25

// Now write the blank records


for (int count = 0; count < 5; count++)
{
cout << "Now writing record " << count << endl;
[Link]((char *)&record, sizeof(record));
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen
Output
26

Now writing record 0


Now writing record 1
Now writing record 2
Now writing record 3
Now writing record 4

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program 12-
// This program displays the contents of the inventory file.
27 25 <iostream.h>
#include
#include <fstream.h>

// Declaration of Invtry structure


struct Invtry
{
char desc[31];
int qty;
float price;
};

void main(void)
{
fstream inventory("[Link]", ios::in | ios::binary);
Invtry record = { "", 0, 0.0 };

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues
// Now read and display the records
28 [Link]((char *)&record, sizeof(record));
while (![Link]())
{
cout << "Description: ";
cout << [Link] << endl;
cout << "Quantity: ";
cout << [Link] << endl;
cout << "Price: ";
cout << [Link] << endl << endl;
[Link]((char *)&record, sizeof(record));
}
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Here is the screen output of Program 12-25 if it is
run immediately after Program 12-24 sets
29 records.
up the file of blank
Program Screen
Output
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program 12-
// This program allows the user to edit a specific record in
// 26
the inventory file.
30
#include <iostream.h>
#include <fstream.h>

// Declaration of Invtry structure


struct Invtry
{
char desc[31];
int qty;
float price;
};

void
main(void)
{

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues
fstream inventory("[Link]", ios::in | ios::out | ios::binary);
31 Invtry record;
long recNum;
cout << "Which record do you want to edit?";
cin >> recNum;
[Link](recNum * sizeof(record), ios::beg);
[Link]((char *)&record, sizeof(record));
cout << "Description: ";
cout << [Link] << endl;
cout << "Quantity: ";
<< [Link] << endl;
cout
cout << "Price: ";
cout << [Link] << endl;
cout << "Enter the new data:\n";
cout << "Description: ";

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program continues

32

[Link]();
[Link]([Link], 31);
cout << "Quantity: ";
cin >> [Link];
cout << "Price: ";
cin >> [Link];
[Link](recN
um * sizeof(record),
ios::beg);
[Link]((char *)&record, sizeof(record));
[Link]();
}

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Program Screen Output with
Example Input
33

Which record do you ant to edit? 2 [Enter]


Description:
Quantity: 0
Price: 0.0
Enter the new data:
Description: Wrench [Enter]
Quantity: 10 [Enter]
Price: 4.67 [Enter]

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan


Conclusio
34
n
In this lecture …
 What is Filing?

ANY
QUERY ?

Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan

You might also like