0% found this document useful (0 votes)
7 views

Lecture 7 - Introduction To Data Structures

Programming notes

Uploaded by

mainabrian337
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture 7 - Introduction To Data Structures

Programming notes

Uploaded by

mainabrian337
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Introduction to Data Structures

Basic Concepts

G. Mariga: [email protected]

1
Data types
• The programmer has to tell the system before-hand, the type
of data such as numbers or characters the computer program

is to work on.

• This is referred to as declaration.

• You Declare the type of data to be used so that the amount of


memory in bytes is reserved for that type of data.

2
Data types
• For example in C,
– Integer requires 2 or 4 bytes (For 16 or 32-bit machine

– Float 4 bytes and double requires 8 bytes

– Char requires 1 byte (8 bits)

• Failure to do so results to type or variable declaration error


during the compile time. See the C code snippet below:
Data types

• Generally data types can be broadly classified as. :


– Primary/Primitive data types
– Structured data types

Figure below shows classification of data types in C


programming Language:

4
C Language Data types

5
Primary data types

• Primary data types also referred to as standard or primitive


or standard data types refers to a basic built in type for
which are supported by a programming language.
• These are data types that are defined without imposing any
structure on their values.
• The range of standard data types is dependent on the
programming language.

6
Primary data types
General examples are:

• Integer( int, integer, short, long, byte)-Integers are whole numbers with a

range of values, range of values are machine dependent. Generally an

integer occupies 2 or 4 bytes of memory space

• Floating point- The float data type is used to store fractional numbers

(real numbers)

• Boolean-True or false

• Characters (character, char)- Letters of the alphabet and special symbols

7
Structured data type

• A structured data type refers to a collection of several data


elements treated as a unit.
• A structure has a definition that imposes structure upon its
values.
• In many structured data types, there is an internal structural
relationship, or organization, that holds between the
components.
 Data structure usually refers to an organization for data in main
memory.
 File structure: an organization for data on peripheral storage, such as a
disk drive.

8
Data structures

• Array- is a collection of data items of the same type. This can


be of simple data types or structured type such as a record.

• Linked list is an implementation based on the concept of a


node. A node is made up of two pieces of information the
item that the user wants in the list, and
• a pointer to the next node in the list

• A stack is an abstract data type in which accesses are made at


only one end LIFO, which stands for Last In First Out

9
Data structures
• A Queue is an abstract data type in which items are entered
at one end and removed from the other end for First In First
Out (FIFO). Like a waiting line in a bank or supermarket.

• A tree As opposed to lists, stacks and queues, a tree is a non-


linear ADT. It is hierarchical data structure where nodes may
have more than one “next”

• Graph is data structure that consists of a set of nodes and a


set of edges that relate the nodes to each other.
Introduction to Arrays
• An array is a data structure consisting of items of the same data
type.
• Array is allocated a group of consecutive memory locations in
which data of the same name and type is stored. The Figure below
shows an array named scores.

50 65 78 90 80
Scores [5]
0 1 2 3 4

• Each element in an array is access using array name eg Scores and


subscript or index (Scores subscripts starts from 0 – 4).
• An array can be a:
– Single dimensional
– Multi-dimensional
Single dimensional arrays
• A single dimensional array is an ordered list. Assume we have score
for 5 students whose marks are 89, 57, 70, 45 and 65
• We can declare an array of 5 scores as:
int scores [5]
• In general to declare a single dimensional array use the syntax:
type arrayname[num_of_elements]
• To initialize the array with the five elements use:
int scores [5]={89, 57, 70, 45, 65}
#include <stdio.h>
int main()
{
//assign and initialize scores array with 5 scores
int scores[5]={30, 70, 89,34,70};
//display memory location of each element in the array
for (x=0;x<5;x++)
{
printf(“Score[%d] address is = %d\n",x,&score[x]);
}
//Display the five scores
for (x=0;x<5;x++)
{
printf("The score[%d] is = %d\n", x,scores[x]);
}
return 0;
}

13
Output

14
User input into an array

• You can use the for loop and scanf() function to capture input
from the user and the display the output
• Write a program requires the user to declare an array of as
much as 100 real numbers but choose how many to input.
• The program should calculates and display total and average
of the numbers entered.
Array of 100 elements
#include <stdio.h>
void main()
{
int i, count, number[100], sum;
double average;
sum =0;
printf ("How many numbers to enter?");
scanf("%d", &count);
for (i=0;i<count;i++)
{
printf ("Enter a number");
scanf("%d", &number[i]);
sum+=number[i];
}
Array of 100 integers Cont..
for (i=0;i<count;i++)
{
printf("Number %d is-> %d\n",i+1, number[i]);
}
average=(double)sum/count;
printf("Sum of %d numbers is %d\n ", count,sum);
printf("The Average is %2.3lf\n", average);
}
Output
Array of characters
• Unlike most programming languages, C does not provide a string as an
inbuilt data type. To manipulate text, we create an array of characters:
– char arrayname [elements] e.g. char Student_Name [20];
• Character arrays can be initialized using string literals. For example
– char City[20] = “Nairobi";
• City actually has 7 elements but the extra 8th space is used to store the
Null character '\0' that terminates the string.
• Since Array name is address of an array, & is not needed for scanf
(): scanf( "%s", name );. See sample program below

19
#include<stdio.h>
int main ()
{
char name[20];
char course [40]= "Data Structures & Algorithms";
printf("Enter name");
scanf("%s",name);
printf("Your name is %s \n",name);
printf("Taking a %s Bridging course\n",course);
return 0;
}
Array of Char output
Using string I/O functions
• When scanf () function is used, it reads characters until white space
encountered. This is why for the input James Kamureng’, only James is printed
on the console.
• Therefore we use string input function gets() and output function puts().
• To use the two complementary functions be sure to include the string.h
header file
#include <string.h>
…………………………………………
printf("Enter name");
gets(name);
• ………..
printf("Your name is");
puts(name);
#include<stdio.h>
#include <string.h>
int main ()
{
char name[20];int lettercount;
printf("Enter name");
gets(name);
printf("\n");
printf("Your name is");
puts(name);
lettercount=strlen(name);
printf("The name has %d ", lettercount);
return 0;
}

23
What Next ?
Pointers

24
What are Pointers?

• Pointers are variables that contain memory addresses as their


values.
• Whereas a variable name directly references a value, a
pointer indirectly references a value. Referencing a value
through a pointer is called indirection or dereferencing .
• A pointer variable must be declared before it can be used.
Declaring Pointers

We use an Asterisk to tell the compiler that the variable is a


pointer. Consider the statements:
float b ; /* Declare a float variable */
float *bptr ;/* Declare a pointer to an int */
…………………
The asterisk tells the compiler that the variable is to be a pointer, and
the type of data that the pointer points to, but NOT the name of the
variable pointed to.
Pointer to array of Integers
#include <stdio.h>
void main()
{
int i, count,sum;
int number[100];
int *numptr =number;
double average;
sum =0;
printf ("How many numbers to enter?");
scanf("%d", &count);
for (i=0;i<count;i++) //loop to get the
numbers i to count
{ printf ("Enter a number");
scanf("%d", (numptr+1));
sum+=*(numptr+1);
}
for (i=0;i<count;i++) // loop to display the list
{
printf ("Number %d is in address -> %d\n",i+1,
(numptr+i));
}
average=(double)sum/count; //average of numbers
printf("Sum for %d numbers is %d\n", count,sum);
printf("The Average is %7.3lf\n", average);
}
Relationship: Arrays and Pointers
• Arrays and pointers are related in C and may be used
interchangeably.
• An array name without a subscript is a constant pointer to the first
element in an array
• Assume an integer array:
– int scores[5]
• We can define an integer pointer to the array:
– int *scores_pointer =scores;
• This statement is equivalent to pointing to the first element:
– scores_pointer =&scores[0];
• Array element scores[3] can be referenced using a pointer as:
– *(scores_pointer+3)
Arrays and Pointers

• The program below shows how to declare a string (array of name).


• The array is then pointed to by a character pointer declared as
nameptr.

• The statement:
char *courseptr ="Data Structures & Algorithms";
• Creates an array named courseptr using a pointer. Char * points to the
base address of the memory block allocated Data Structures &
Algorithms
#include<stdio.h>
#include<string.h>
int main ()
{
char name[20];
char *nameptr = name; //pointer to name array
//creates an array of charactres using a pointer
char *courseptr = "Data Structures and Algorithms";
printf("Enter name");
gets(name);
printf("Your name is ");
puts(nameptr);
printf("Taking a %s Bridging course\n",courseptr);
return 0;
}
Call-by-Reference
• In the Lecture two, we used pass-by-value to pass a copy of the actual
parameter to a function [Modular Programming]
• Instead of passing a value, we can pass an address to a value using the
address of operator.
• Once the address is passed, we dereference the pointer to get the actual
value. For example:
num_cubed= cube(&number);
• Passes the address of the of number to the cube () function

• On receiving the address, *nptr dereferences the address to get the


actual value stored in the pointed address
Pointer to name array
#include<stdio.h>
int cube (int *nptr);//function signature
int main ()
{
int number, num_cubed;
printf("Enter a number");
scanf("%d",&number);
//call cube function by reference
num_cubed= cube(&number); //pass address
Cube by reference
printf("The number cubed
is%d\n",num_cubed);
return 0;
}
int cube (int *nptr)//dereference number
{
//multiply the numbers pointed to
return *nptr * *nptr * *nptr;
} //end function
Example 2: Pass-By-Ref

include<stdio.h>
void swapnumbers (int *num1, int *num2);
int main(){
int numb1, numb2;
printf("Enter the first number");
scanf("%d",&numb1);
printf("Enter the second number");
scanf("%d",&numb2);
Example 2
printf(“Before swapping Number1 is %d and
Number2 is %d \n ", numb1,numb2);
swapnumbers(&numb1,&numb2);
printf(“After swapping Number1 is %d Number %d
\n ", numb1,numb2);
return 0;}
void swapnumbers (int *num1, int *num2)
{
int temp;
temp= *num1;
*num1= *num2;
*num2=temp;
}
Passing an Arrays to a Function
• To pass an array to a function, you only need to
specify its name in the call statement.

• In the receiving function parameter list, you MUST


state the array type and include the brackets that
tells the function that this an array and NOT just a
simple data type.

• NB: You do not need to explicitly state the size of the


array in the receiving parameter.
Passing an Arrays to a Function
#include <stdio.h>
int maximum( int values [] ); //no size
int main() {
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
{
scanf("%d", &values[i] );
}
max = maximum( values );//Just the array
name
printf("\nMaximum value is %d\n", max );
return 0; }
Passing an Arrays to a Function
int maximum( int values[] )
{
int max_value, i;
max_value = values[0];
for( i = 0; i < 5; ++i )
{
if( values[i] > max_value )
max_value = values[i];
}
return max_value;
}
Explanation
• The declaration int maximum( int values[5] ) defines
the function name as maximum
• The values array in the main body are NOT PASSED
AS COPY, BUT AS REFERENCE.
• A local variable max_value is set to the first element
of array, and a for loop is executed through each
element and assigns the largest item to max_value.
• This number is then passed back by the return
statement, and assigned to max in the main function.
Introduction to records
• Whereas arrays are data structures whose elements are of the
same type, A record (known as Structure in C) is “a data
structure” in which the individual elements can differ in type.
• A structure is a data type that consists of a collection of
several variables stored together.
• The individual structure elements are known as elements.
Defining a structure
• A structure must be defined in terms of its individual
members. In general terms, a structure may be defined as:
struct tag{
member 1;
member 2;
member 3;
........
member m;
};
Structure members
• The individual members can be ordinary variables, pointers,
arrays or other structures.
• The member names within a particular structure must be distinct
from one another, though a member name can be the same as
the name of a variable that is defined outside the structure.
• Individual members cannot be initialized within a structure type
declaration.
• A storage class cannot be assigned to an individual member.
Declaring a structure
• Once the composition of the structure has been defined,
individual structure type variables can be declared as
follows:
storage_class struct tag variable1, variable2, variable n;
• Storage_class is an optional storage class specifier e.g. static,
external e.t.c.
• struct is a required keyword,
• tag is the name that appeared in the structure declaration
• variable1 to variable n are structure variables of type tag.
Example
struct account{
int acct_no;
char acct_type;
char *name;
float balance;
};
• We can now declare a structure variable customer follows:
• struct account customer;
• Thus, customer is a variable of type account whose
composition is identified by the tag account.
Processing a structure

• The members of a structure are usually processed individually using


the dot operator (.) or a structure pointer operator(->). Therefore,
we can access the individual members by writing:
• variable.member eg customer.acct_no
• Variable_pointer->member
• eg customerPtr->name;
• Where variable refers to the name of a structure type variable, and
member refers to the name of a member within the structure.
Sample program
#include<stdio.h>
struct Student {
char name[20];
int age;
};
int main ()
{
struct Student MyStudents;
printf("Enter student's full name");
gets(MyStudents.name)
printf("Enter his/her age");
scanf("%d",&MyStudents.age);
printf("The student name is " );
puts(MyStudents.name);
printf("His age is %d\n", MyStudents.age);
return 0;
}
Array of Structures
• Just like the primitive data types, you can also define
an array of structures and access the members using
the for loop.

#include <stdio.h>
#define SIZE 4
struct product {
int product_id;
int quantity;
};//end of record type definition
Array of structures
int main()
{
struct product item[SIZE];
int count;
for (count=0;count<SIZE;count++)
{
printf ("Enter the item number");
scanf("%d", &item[count].product_id);
printf ("Enter the quantity");
scanf("%d", &item[count].quantity);
}
Array of Structures
for (count=0;count<SIZE;count++)
{
printf("Product_id %d -->",
item[count].product_id);
printf("Quantity in stock %d \n",
item[count].quantity);
}
return 0;
}
Passing a structure as a parameter

• You can pass the entire structure as a


parameter or each an every element

• Unlike arrays, structures can be passed by


copy and by reference
• Program below illustrates pass by copy
Passing a structure by copy
#include <stdio.h>
#include<string.h>
struct students
{
char name[20];
int age;
float average;
};
struct students fillrecord(struct students
my_students);
void printlist(struct students my_students);
int main(){
Passing a structure by copy
struct students my_students;
my_students = fillrecord(my_students);
printlist (my_students);
return 0;
}
struct students fillrecord(struct students
my_students)
{
fflush(stdin);//clear buffer for next
input
printf("Student full name?");
gets(my_students.name);
Passing a structure by copy
printf("Enter age");scanf("%d",
&my_students.age);
printf("Enter average score");scanf("%f",
&my_students.average);
return my_students;
}
void printlist(struct students my_students)
{
printf("Student Name\t\tAge\t\tAverage\n");
printf("%s\t\t%d\t\t%.2f \n",
my_students.name, my_students.age,
my_students.average);
}
Pass structures by Reference
• If we want to access members of the structure. For example
we want to print out the name of the employee in our
example
• We declare a pointer that points to a structure declared using
struct tag.
– struct employees *st_ptr; eg
• We point it to employees structure with st_ptr:
– st_ptr = &my_employees
• To access a member of the structure, we use the arrow
operator ->
– st_ptr->age = 63;
Pass structures by Reference

• Let define a personnel record which look something


like:
struct employee {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* rate per hour */
};
Pass structures by Reference
#include <stdio.h>
#include <string.h>
struct employees{ /*
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* rate per hour */
};
struct employees my_struct;//global variable
void show_name(struct employees *p);
int main(void){
struct employees *st_ptr;
st_ptr = &my_struct;
Pass structures by Reference
strcpy(st_ptr->fname,"Jensen");
strcpy(st_ptr->lname,"Koka");
st_ptr->age=45;//assign 45 to integer
show_name(st_ptr); /* pass the pointer */
return 0;
}
void show_name(struct employees *p)
{
printf("\n%s ", p->fname); /* p points to a
structure */
printf("%s ", p->lname);
printf("%d\n", p->age);
}
Assignment
• A Lecturer keeps a record containing the following data for
each student; Name, Registration number, Course Unit , Exam
percentage score and Grade based on the university grading
system.

1. Using Arrays write a C program that stores the above details


in an array of records for an unspecified number of students.
The program should have at least three functions one input,
one processing and one for display.
2. Using pointer to a record write a C program that stores the
above details in an array of records for a number of students.
Point of Thought
Ever thought of Structures within
structures (Nested structures) –
Think of a student taking several
units – UnitCode + Unit Name

You might also like