Programming Course All Weeks
Programming Course All Weeks
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
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
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
1. Understand the
problem
2. Develop a solution
3. Write a program
4. Test the program
1. Understand the Problem
17
Structure chart
Hierarchy chart
Pseudocode:
Input a set of 4 marks
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
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
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
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
Print A
Example: 3(Continue…)
31
Algorith STAR
T
m Input W,L
Input
Step 1:
AL x W W, L
Step 2:
Print A
A LxW
Step 3:
Print
A
STOP
Example: 4
32
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 bb 4 a c
Step 3: x1sqrt
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
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
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
START
Input
VALUE1,VALUE
2
Y is N
VALUE1>VALUE2
Print
“The largest value is”,
MAX
STOP
NESTED IFS
42
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
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
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
Can’t you
see? Neo is
here.
Computer Programmin g(CSC-113) - Fall 2019
Language
Hierarchy of Programming
6
11
Structure of a C++ Program
11
Pre-compiler directive
Opening brace
Closing brace
Opening
brace
Closing brace
Hello World!
#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
i n t main()
The main body of the program.
Start of comment
End of comment
Start of comment
End of comment
Nested Block Comments are Invalid
17
Variables
18
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
In program
2 Bytes 4 Bytes
2 or 4 Bytes 8 Bytes
4 Bytes 10 Bytes
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
Assignment
Operators
Arithmetic operators
+ (Addition)
- (Subtraction
* (Multiplication)
/ (Division)
% (modulo)
34
C++ Expression Format
Operators
Operators
36
Sizeof
operator
Example
A=sizeof(b);
Compound Assignment
37
Example
s
Standard streams
38
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
#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 " ;
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)
COMPUTER
PROGRAMMIN
G
Decisions
/Selection
What will be discussed
2
Program begins
Do A
Do B
…
Do Z
Program ends
4
Flo
w be nice to be able to change which statements ran
It would
and when, depending on the circumstances.
Selection Statement
5
We need
comparisons!
Ex1) if the value in variable “num” is larger than 4, then execute
statement 1. Otherwise, execute statement 2.
8
Scal
e
In C++
If a value is zero, it can be used as the logical value false.
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”
In c++ : “&&”
Or
“true” or “false” “true”
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
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
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
How?
1. Cut and paste the codes 160 times?
2. cout << 1 + 2 + ……+100 << endl; ??
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++
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 ’ ;
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
•for(…;…;…) o r while(…)
•{
•…
break;
… Terminate the loop and
} execution jumps to here
…
break in Nested Loop
continue Statement
41
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)
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…)
ANY
QUERY ?
PROBLEMS# (43|44)
COMPUTER
PROGRAMMIN
G
Functions
I
ANY
QUERY ?
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
1
COMPUTER
PROGRAMMIN
G
Function
II
Different local
variables
Computer Programming(CS C-113) - Fall 2019 © Sept ember 2018 Shahid Khan
Calculate Quotient and
6
Remainder
Program 4-9
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)
COMPUTER
PROGRAMMIN
G
Recursio
n
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 ...
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.
ANY
QUERY ?
COMPUTER
PROGRAMMIN
G
String
s
#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;
}
#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:
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
ANY
QUERY ?
COMPUTER
PROGRAMMIN
G
Pointer
s
3
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
4
1
letter number amount
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;
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};
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
19
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Figure 9-
20
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];
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
23
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
24
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
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
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]
(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
36
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
Program continues
37
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.
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
// 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;
}
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
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.
ANY
QUERY ?
Computer Programming(CSC-113) - Fall 2019 © September 2018 Shahid Khan
1
COMPUTER
PROGRAMMIN
G
Pointers
(Cont. )
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;
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 ‘*’
a=
1000;
b=
2000;
c=
3000;
}
Operator ‘&’
cout << a;
1000 2000 3000
→ 1000
1004 1008 1012 1016
→ 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
Note:
Note:
sam
a e
& a[0]
‘a’ is a pointer only to the first element, not the whole array
a
constant to its first element
cout << a;
/ / → 1004
}
39
Dereference of array
40
name
ANY
QUERY ?
COMPUTER
PROGRAMMIN
G
Structure
s
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
(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
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)
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) {
}
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 };
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
PROGRAMMIN
G
File
Handling
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
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.
void main(void)
{
fstream dataFile("[Link]", ios::in
| ios::out);
cout << "The file [Link] was
opened.\n";
}
#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
Jones
Smith
Willis
Davis
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
123.456
123.46
123.5
124
7
,
1
6
2
3
, © September 2015 Shahid Khan
}
Contents of File [Link]
36
2897 5 837
34 7 1623
390 3456 12
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
Jones
Smith
Willis
Davis
Done.
if ([Link]())
[Link]();
//
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
Jones
Smith
Willis
Davis
Done.
ANY
QUERY ?
COMPUTER
PROGRAMMIN
G
File
Handling
[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.
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.
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
10
void main(void)
{
fstream nameFile;
char input[81];
[Link]("mu
[Link]",
ios::in);
if (!nameFile)
{
cout << "File open error!" << endl;
return;
}
JayneMurphy47JonesCircleAlmond,NC28702
#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;
}
19
Jayne Murphy
47 Jones Circle
Almond, NC
28702
#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]();
}
Jayne Murphy
47 Jones Circle
Almond, NC 28702
Bobbie Smith
217 Halifax Drive
Canton, NC 28716
Bill Hammet
PO Box 121
Springfield
, NC 28357
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;
}
void main(void)
{ fstream dataFile("[Link]", ios::out);
char ch;
void main(void)
{
ifstream inFile;
ofstream outFile("[Link]");
char fileName[81], ch, ch2;
ANY
QUERY ?
COMPUTER
PROGRAMMIN
G
File
Handling
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};
#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
// for toupper
#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;
17
[Link](3L, ios::cur);
[Link](ch);
cout << "Byte 3 from current: " << ch << endl;
[Link]();
}
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;
21
[Link](offset, ios::beg);
[Link](ch);
cout << "Character read: " << ch << endl;
cout << "Do it again? ";
cin >> again;
} while (toupper(again) == 'Y');
[Link]();
}
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]
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
void main(void)
{
fstream inventory("[Link]", ios::in | ios::binary);
Invtry record = { "", 0, 0.0 };
void
main(void)
{
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]();
}
ANY
QUERY ?