data structure and algorithm chapter 1
data structure and algorithm chapter 1
1
Content
▪ Functions
▪ Arrays
▪ Pointers
▪ dynamic memory allocation
▪ Structure
4/19/2021 2
1.Function
4/19/2021 3
Functions in C++
4/19/2021 4
Why functions?
4/19/2021 5
Types of Functions
4/19/2021 6
Components of Function
4/19/2021 7
Function Prototype/Declaration
4/19/2021 8
Syntax for function declaration
▪ We declare a function as follows
return_type function_name ( parameters ) ;
– return_type: any valid data type or void (A function with void as return type don’t return
any value. )
– function_name: any valid cpp identifier
– parameters: zero or more input to the function(separated by comma if more than 1)
▪ Examples:
– float average( int num1, int num2 ); /*function name = average, receives two integers as
argument and returns float*/
– int product(int,int); /*function name = product, receives two integers as argument and
returns an integer*/
▪ Note:
– A function declaration doesn’t require name of arguments to be provided, only type of the arguments
can be specified.
4/19/2021 9
Function Definition
4/19/2021 10
Syntax for function definition
4/19/2021 11
Example
– Let's see the average function that we defined earlier.
4/19/2021 14
Call by value
4/19/2021 15
Example: call bay value
4/19/2021 16
Call by reference
4/19/2021 17
Example: call by reference
#include <iostream>
void swap(int &x, int &y) // function definition
Using namespace std;
void swap(int &, int &); // function prototype
{
int temp;
int main() {
temp = x;
int a,b; x = y;
cout<<"Enter two numbers: "; y = temp;
cin>>a>>b; }
cout<<"Before swapping”;; Sample Output:
cout<<"a =“<<a<<endl; Enter two numbers: 12 35
cout<<"b =“<<b<<endl; Before swapping
a = 12
swap(a,b); // function call by reference b = 35
cout<<"After swapping\n"; After swapping
cout<<"a =“<<a<<endl; a = 35
b = 12
cout<<"b =“<<b<<endl; return 0; } 4/19/2021 18
Variable Scope
▪ Variable Scope is a region in a program where a variable is declared
and used.
▪ Depending on the region where variables are declared and used,
there are two types of variables
– Local variables
▪ Variables that are declared inside a function or a block are called local variables and
are said to have local scope.
▪ These local variables can only be used within the function or block in which these are
declared.
▪ Example: variables in the previous example programs
– Global variables
▪ Variables that are defined outside of all the functions and are accessible throughout
the program are global variables and are said to have global scope.
▪ Once declared, these can be accessed by any function in the program.
4/19/2021 19
4/19/2021 20
Example:
#include <iostream>
using namespace std;
int g = 10; Here, g is a global variable , since we declared 'g' outside of
all the functions and gave it a value in the function.
void func1(){
g = 20;
cout << g << endl; What is the output?
}
int main(){
func1();
g = 30;
cout << g << endl;
return 0;
}
4/19/2021 21
What if there exists a local variable with the same
name as that of global variable inside a function?
// C++ program to show that we can access a global • We use the scope resolution operator
// variable using scope resolution operator :: when (::) to access global variable in the
// there is a local variable with same name
presence of local variable having same
#include<iostream> Output: name with the global variable
using namespace std; Value of global x is 0
Value of local x is 10
int x = 0; // Global x • In C++, scope resolution operator is ::.
4/19/2021 25
Arrays
▪ 1-dimensional array.
4/19/2021 27
Array Declaration
▪ Syntax:
<type> <arrayName>[<array_size>]
Ex. int Ar[9];
▪ The array elements are all values of the type <type>.
▪ The size of the array is indicated by <array_size>, the number of
elements in the array.
▪ <array_size> must be an int constant or a constant expression.
▪ Note that an array can have multiple dimensions.
4/19/2021 28
Multi-dimensional array declaration
▪ Syntax:
<type> <arrayName>[<num_rows>] >[<num_columns>]
Ex. int Ar[9][9];
4/19/2021 29
Accessing Array Elements
▪ Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
▪ Subscript(indexing):
– To access an individual element we must apply a subscript to array named Ar.
– A subscript is a bracketed expression.
▪ The expression in the brackets is known as the index.
– First element of array has index 0. Ar[0]
– Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
– Last element has an index one less than the size of the array. Ar[9]
▪ Caution: Incorrect indexing is a common error.
4/19/2021 30
Subscripting
Ar[3] = 1; --
int x = Ar[3];
1 --
-- -- --
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
4/19/2021 31
Array Element Manipulation
▪ Consider
int Ar[10], i = 7, j = 2, k = 4;
Ar[0] = 1;
Ar[i] = 5;
Ar[j] = Ar[i] + 3;
Ar[j+1] = Ar[i] + Ar[0];
Ar[Ar[j]] = 12;
cin >> Ar[k]; // where the next input value is 3
0 1 2 3 4 5 6 7 8 9
Ar 1 -- 8 6 3 -- -- 5 12 --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
4/19/2021 32
Array Initialization Ex.
int Ar[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 -1 5 4 3 2 1 0
4/19/2021 33
Example: Printing arrays
4/19/2021 34
Fill array from keyboard
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
} 4/19/2021 35
Copying Arrays
▪ This is not allowed in C++. You have to copy individual elements from one array
to the other as follows:
4/19/2021 36
Summing All Elements
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
} 4/19/2021 37
Finding the Largest Element
4/19/2021 41
Example
void display(int m[5]) {
cout << "Student " << i + 1 << ": " << m[i] << endl;
int main() {
// call display function and pass array as argument with no size and [ ] operator
display(marks);
return 0;
4/19/2021 42
}
Exercise 1: What is the output?
4/19/2021 43
Exercises
4/19/2021 44
3.Pointers
4/19/2021 45
Computer Memory
… … 100 … 1024 …
a
Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024
4/19/2021 46
Pointers
… … 100 … 1024 …
integer
pointer
4/19/2021 47
Pointer Types
▪ Pointer
– C++ has pointer types for each type of object
▪ Pointers to int objects
▪ Pointers to char objects
▪ Pointers to user-defined objects
– Struct type(e.g., Student)
– Class type
– Even pointers to pointers
▪ Pointers to pointers that points to int objects
4/19/2021 48
Pointer Variable
Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
4/19/2021 49
Address Operator &
▪ The "address of " operator (&) gives the memory address of the
variable
– Usage: &variable_name
Memory address: 1020 1024
… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
4/19/2021 50
Address Operator &
… 88 100 … … …
a b
#include <iostream>
Result is:
using namespace std;
The address of a is: 1020
void main(){
The address of b is: 1024
int a, b;
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
} 4/19/2021 51
Pointer Variables
Memory address: 1020 1024 1032
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a;
cout << a << " " << &a <<endl;
cout << p << " " << &p <<endl; Result is:
100 1024
1024 1032
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
4/19/2021 53
Pointer to Pointer
58 58 58
4/19/2021 54
Don’t get confused
▪ Declaring a pointer means only that it is a pointer:
– int *p;
▪ Don’t be confused with the dereferencing operator, which is also written with an
asterisk (*).
– They are simply two different tasks represented with the same sign
p2 = &b; // p2 points to b
Result is:
p2 = p1; // p2 points to a 888
b = *p3; //assign c to b
4/19/2021 56
Another Pointer Example
#include <iostream>
Result is
using namespace std;
value1==10 / value2==20
int main (){
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
} 4/19/2021 57
Reference Variables
A reference is an additional name to
an existing memory location
Pointer: Reference:
x 9 x
9
ref
ref
int x = 9;
int x=9;
int &ref = x;
int *ref;
ref = &x;
4/19/2021 58
Reference Variables
int m = 10;
int &j = m; // j is a reference variable
cout << “value of m = “ << m << endl;
value of m = 10
//print 10
value of m = 18
j = 18;
cout << “value of m = “ << m << endl;
// print 18 4/19/2021 59
Reference Variables
4/19/2021 62
NULL pointer
4/19/2021 65
Memory Management
4/19/2021 66
Static vs. Dynamic Objects
new
delete
{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
4/19/2021 68
Object (variable) creation: New
Syntax
ptr = new SomeType;
where ptr is a pointer of type SomeType
Example
int* p = new int;
4/19/2021 69
Object (variable) destruction: Delete
Syntax
delete p;
storage pointed to by p is returned to free store and p is now undefined
Example
int* p = new int;
*p = 10;
delete p;
p 10
4/19/2021 70
Array of New: dynamic arrays
▪ Syntax
SomeType *P = new SomeType[Expression];
– Where
▪ P is a pointer of type SomeType
▪ Expression is the number of objects to be constructed -- we are making an array
4/19/2021 71
Example
Dynamic Memory Allocation
Request for “unnamed” memory from the Operating System
p = new int; p
p = new int[100];
new
p
new
p = new int[n]; p
4/19/2021 72
Memory Allocation Example
4/19/2021 74
Caution 1: Memory Leak Problem
int *A = new int [5];
for(int i=0; i<5; i++)
A[i] = i; 2
A 0 1 2 3 4
A 0 1 2 3 4
— — — — —
4/19/2021 75
Caution 2; Dangling Pointer Problem
B[0] = 1; // illegal! ?
B
4/19/2021 76
5. Structures
4/19/2021 77
Structure
4/19/2021 78
When we may use structures ?
4/19/2021 79
How to create a structure?
Example struct declaration
▪ The ‘struct’ keyword is used to create a
structure. struct Student
▪ The general syntax to create a structure is: {
char name[30];
float cgpa;
struct structureName{
int age;
member1; }s1;
member2;
. In the above example, Student is a structure
with three members. And an instance(variable)
. of the Student structure s1
.
memberN; Note;
• Memory is only allocated after a
} [zero or more structure variables]; variable is added to the struct.
4/19/2021 80
How to declare structure variables?
4/19/2021 82
How to access structure elements?
4/19/2021 83
Pointers to Structure
▪ It's possible to create a pointer that points to a structure.
▪ It is similar to how pointers pointing to native data types like int, float,
double, etc.
▪ Example • The ‘.’ operator can also be used with
struct pointer, but can look clumsy;
int main(){
student s1 = {“Abebe Kebede”, 3.75, 20}; • Example:
cout<<(*sp).cgpa ;
Student *sp=&s1; • Note:
• () is required due to operator
sp->cgpa=3.89; precedence
cout<<“cgpa of “<<sp->name<<“is”<<sp->cpga;
}
4/19/2021 84
Another Example: structure pointers
4/19/2021 85
Exercise: What is the output ?
4/19/2021 86
Array of Structures
4/19/2021 87
Array of Structures
▪ struct student
{
int roll_no;
string name;
int phone_number;
};
int main()
{
student stud[100];
…
return 0;
}
4/19/2021 88
Example: read and display details of 5
students
4/19/2021 89
Nested structures
▪ We can nest structures inside structures.
(P.x, P.y)
▪ Examples:
struct point{ (L.p2.x, L.p2.y)
double x, y;
}; (L.p1.x, L.p1.y)
point P;
struct triangle{
point p1, p2, p3; (T.p3.x, T.p3.y)
};
triangle T;
(T.p1.x, T.p1.y)
90
Nested structures
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;
(2, 0)
T.p3.y = 3; 91
C++ Structure and Function
▪ Structures variables can be passed to a function and
returned in a similar way as normal arguments.
Example:
struct_type func_name(struct_type){
.
.
.
return struct_type;
}
92
struct Person
Person getData(Person); // Function declaration cout << "Enter Full name: ";
cin.get(p.name, 50);
void displayData(Person);
cout << "Enter age: ";
int main() cin >> p.age;
{ cout << "Enter salary: ";
cin >> p.salary;
Person p;
return p;
// Function call with structure variable as an argument }
p = getData(p); void displayData(Person p)
{
displayData(p);
cout << "\nDisplaying Information." << endl;
return 0; cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
}
cout << "Salary: " << p.salary;
93
}
Next Time!
Ch2: Complexity Analysis
4/19/2021 94