Algorithms & Arrays.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Matrices CSE, POSTECH.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
C ARRAYS -a collection of same type data, 1D, 2D- © 1/25.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
ARRAYS, RECORDS AND POINTER
Lecture DS & Algorithms:09 Abstract Data Types. Lecture DS & Algorithms:09 2 Abstract Data Types Data Type: A data type is a collection of values and.
Chapter 8 Arrays and Strings
Chapter 2 ARRAYS.
Course Teacher: Moona Kanwal
Data Strcutures.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Lecture -3 on Data structures Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Array Data structures are classified as either linear or nonlinear.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
1 Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character Handling Library 8.4String Conversion.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
26/06/ :14:35 CSC Alliance — 1 Kimera Richard Phone: INSTITUTE OF COMPUTER SCIENCE DEPARTMENT.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
EGR 2261 Unit 10 Two-dimensional Arrays
INC 161 , CPE 100 Computer Programming
C Characters and Strings
Fundamentals of Characters and Strings
Characters and Strings
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
© 2016 Pearson Education, Ltd. All rights reserved.
Operation performed by Linear Structure
Arrays.
A First Book of ANSI C Fourth Edition
Module 2 Arrays and strings – example programs.
Arrays in C.
Chapter 8 - Characters and Strings
Arrays, For loop While loop Do while loop
7 Arrays.
Pointers and Pointer-Based Strings
C Characters and Strings – Review Lab assignments
ARRAYS, RECORDS AND POINTER
7 Arrays.
Programming Logic and Design Fifth Edition, Comprehensive
C++ Programming Lecture 20 Strings
Lecture 19: Working with strings
Characters and Strings Functions
C Characters and Strings
Presentation transcript:

Algorithms & Arrays

Informal definition of an algorithm used in a computer

Finding the largest integer among five integers

Defining actions in FindLargest algorithm

FindLargest refined

Generalization of FindLargest

Characteristics of algorithm Precision – the steps are precisely stated(defined). Uniqueness – results of each step are uniquely defined and only depend on the input and the result of the preceding steps. Finiteness – the algorithm stops after a finite number of instructions are executed. Input – the algorithm receives input. Output – the algorithm produces output. Generality – the algorithm applies to a set of inputs.

Three constructs

Write an algorithm to find the largest of 1000 numbers. Solution See Algorithm on the next slide.

Algorithm : Find largest of 1000 numbers FindLargest Input: 1000 positive integers Set Largest to 0 Set Counter to 0 while (Counter less than 1000) 3.1 if (the integer is greater than Largest) then 3.1.1 Set Largest to the value of the integer End if 3.2 Increment Counter End while Return Largest End

ARRAYS An array is a collection of elements of the same type that are referenced by a common name. Compared to the basic data type (int, float & char) it is an aggregate or derived data type. All the elements of an array occupy a set of contiguous memory locations.

int studMark0, studMark1, studMark2, ..., studMark999; Why ARRAYS? "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int  studMark0, studMark1, studMark2, ..., studMark999; Can you imagine how long we have to write the declaration part by using normal variable declaration? int main() { int studMark1, studMark2, studMark3,…………studMark1000; ………… return 0; }

ARRAYS By using an array, we just declare like this, int  studMark[1000]; This will reserve 1000 contiguous memory locations for storing the students’ marks. Graphically, this can be depicted as in the following figure.

Arrays in Memory Assuming integer takes 2 bytes of storage

Arrays One Dimensional Array: Declaration A single or one dimensional array declaration has the following form, array_data_type  array_name[array_size]; Here, array_data_type define the base type of the array, which is the type of each element in the array. array_name is any valid C / C++ identifier name that obeys the same rule for the identifier naming. array_size defines how many elements the array will hold.

Arrays For example, to declare an array of 30 characters, that construct a people name, we could declare, char   cName[30]; Which can be depicted as follows, In this statement, the array character can store up to 30 characters with the first character occupying location cName[0] and the last character occupying cName[29].  Note that the index runs from 0 to 29.  In C, an index always starts from 0 and ends with array's (size-1).

Arrays An array may be initialized at the time of declaration. Array Initialization An array may be initialized at the time of declaration. Initialization of an array may take the following form, type  array_name[size] = {a_list_of_value}; For example: int    idNum[7] = {1, 2, 3, 4, 5, 6, 7}; float  fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively. The second line assigns the values 5.6 to fFloatNum[0], 5.7  to  fFloatNum[1], and so on.

1-D Array Homogeneous data: a) Elements are represented through indexes. b) Elements are saved in sequential in memory locations. Number of elements, N –> length or size of an array. If: UB : upper bound ( the largest index) LB : lower bound (the smallest index) Then: N = UB – LB + 1 Length = N = UB when LB = 1 Department of CSE

Address Calculation in 1-D Array The process to determine the address in a memory: a) First address –> base address. b) Relative address to base address through index function. Example: char X[100]; Let char uses 1 location storage. If the base address is 1200 then the next element is in 1201. Index Function is written as: Loc (X[i]) = Loc(X[0]) + i , i is subscript and LB = 0 1200 1201 1202 1203 X[0] X[1] X[2]

Address Calculation in 1-D Array(..contd) In general, index function: Loc (X[i]) = Loc(X[LB]) + w*(i-LB); where w is length of memory location required. For real number: 4 byte, integer: 4 byte and character: 1 byte. Example: If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ? Loc(X[8])= Loc(X[5]) + 4*(8 – 5) = 1212

2-D Array Imagine now we want to keep 10 test scores for 30 students. How would we represent this in a program with what we’ve learned? Answer: You would need either 30 10-element arrays or 10 30-element arrays. What we have been working with so far are considered one dimensional arrays, because they only extend along one dimension (one set of data). “C” allows for higher dimensional arrays, for example, two dimensional arrays. Two dimensional arrays can be though of having a table of rows and columns in memory. So, a better solution to the above question is what? Answer: Have a 30 x 10 or a 10 x 30 two dimensional array! Department of CSE

Storage Order Row-major order: the array is stored as a sequence of arrays consisting of rows (0,0) (0,1) (0,2) 1 2 3 5 4 6

Storage Order Column-major order: The array is stored as a sequence of arrays consisting of columns instead of rows (0,0) (1,0) (0,1) 1 2 3 5 4 6

Address Calculation in 2-D Array When lower bound is not given. The computer keeps track of Base (BA),:-  the address of the first element A[0][0] of A[M][N],  and computes address i.e. Loc (A[I][J]) of A[M][N] using the formula Loc(A[I][J])=Base (BA)+W[M*J + I] [Column Major] Loc(A[I][J])=Base (BA)+W[N*I + J] {Row- Major} W denotes the size, i.e; number of bytes per data element of the array A, M is total numbers of rows, and N is total number of columns in the array. Department of CSE

Address Calculation in 2-D Array(..contd) When lower bound is given Loc(A[I][J])=Base (BA)+W[M*(J-LBC) + (I-LBR)] [Column Major] Loc(A[I][J])=Base (BA)+W[N*(I-LBR) + (J-LBC)] {Row- Major} In case of ‘C’ LBR=0 (Lower Bound Row) LBC=0 (Lower Bound Column) Department of CSE

Example Suppose element of array A[4][5] occupies 4 bytes, and the address of the 1st element is 49.  Find the address of the element A(4,3) when the storage is row major. = BA + [N * (I - LBR) + (J - LBC)] * W  = 49 + [5 * (4 – 0) + (3 - 0)] * 4  = 49 + [23] * 4  = 49 + 92  = 141 Department of CSE

Special Matrices A square matrix has the same number of rows and columns. Some special forms of square matrices are Diagonal: M(i,j) = 0 for i ≠ j Tridiagonal: M(i,j) = 0 for |i-j| < =1 Lower triangular: M(i,j) = 0 for i < j Upper triangular: M(i,j) = 0 for i > j Symmetric M(i,j) = M(j,i) for all i and j

Fig. 1 Special Matrices

Special Matrices Why are we interested in these “special” matrices? We can provide more efficient implementations for specific special matrices. Rather than having a space complexity of O(n2), we can find an implementation that is O(n). We need to be clever about the “store” and “retrieve” operations to reduce time.

Distance Matrix

Diagonal Matrix Naive way to represent n x n diagonal matrix T d[n][n] d[i-1][j-1] for D(i,j) requires n2 x sizeof(T) bytes of memory Better way T d[n] d[i-1] for D(i,j) where i = j 0 for D(i,j) where i ≠ j requires n x sizeof(T) bytes of memory

Tridiagonal Matrix Nonzero elements lie on one of three diagonals: main diagonal: i = j diagonal below main diagonal: i = j+1 diagonal above main diagonal: i = j-1 3n-2 elements on these three diagonals: T t[3n-2] Mappings of Figure 1(b) by row [2,1,3,1,3,5,2,7,9,0] by column [2,3,1,1,5,3,2,9,7,0] by diagonal [3,5,9,2,1,2,0,1,3,7]

Triangular Matrix Nonzero elements lie in the region marked “nonzero” in the figure below 1+2+…+n = Σ(i=1..n) = n(n+1)/2 elements in the nonzero region

Triangular Matrix Both triangular matrices may be represented using 1-D array  T t[n(n+1)/2] Mappings by row?  [2,5,1,0,3,1,4,2,7,0] by column?  [2,5,0,4,1,3,2,1,7,0]

Symmetric Matrix An n x n matrix can be represented using 1-D array of size n(n+1)/2 by storing either the lower or upper triangle of the matrix Use one of the methods for a triangular matrix The elements that are not explicitly stored may be computed from those that are stored How do we compute this?

Sparse Matrix A matrix is sparse if many of its elements are zero A matrix that is not sparse is dense Two possible representations array linked list

Array Representation of Sparse Matrix The nonzero entries may be mapped into a 1D array in row-major order To reconstruct the matrix structure, need to record the row and column each nonzero comes from

Input and print array in C int main() {     int i, arr[50], num;     printf("\nEnter no of elements :");    scanf("%d", &num);     //Reading values into Array    printf("\nEnter the values :");    for (i = 0; i < num; i++)        scanf("%d", &arr[i]);    }  //Printing of all elements of array    for (i = 0; i < num; i++)        printf("\narr[%d] = %d", i, arr[i]);    }     return (0); }

Input and print array in C++ //For loop to fill & print a 10-int array 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 "; cout << ar[index] << " "; return 0; }

Basic Operations Following are the basic operations supported by an array. Traverse − print all the array elements one by one. Insertion − Adds an element at the given index. Deletion − Deletes an element at the given index. Search − Searches an element using the given index or by the value.

Traversal Description: Here A  is a linear array with lower bound  LB  and upper bound  UB. This algorithm traverses array A and applies the operation PROCESS to each element of the array. 1.  Repeat For I = LB to UB 2.    Apply PROCESS to A[I]        [End of For Loop] 3.  Exit

Deletion algorithm DELETE (LA, N, K, ITEM)  Here LA is a Linear Array with N elements and K is the positive integer such that K<=N. This algorithm deletes the Kth element from LA. 1. Set ITEM: = LA [k]. 2. Repeat for J = K to N – 1. [Move J + 1st element upward] Set LA [J]: = LA [J +1]. [End of loop] 3. [Reset the number N of elements in LA] Set N: = N-1 4. EXIT

Insertion algorithm INSERT (LA, N, K, ITEM) 1. [Initialize counter] Set J: = N. 2. Repeat Steps 3 and 4 while j >= k; 3. [Move jth element downward.] Set LA [J + 1]: =LA [J]. 4. [Decrease counter] Set J: = J-1 [End of step 2 loop] 5. [Insert element] Set LA [K]:=ITEM. 6. [Reset N] Set N:=N+1 7. EXIT.

Linear Search Linear Search ( Array A, Value x) Step 1: Set i to 1 Step 2: if i > n then go to step 7 Step 3: if A[i] = x then go to step 6 Step 4: Set i to i + 1 Step 5: Go to Step 2 Step 6: Print Element x Found at index i and go to step 8 Step 7: Print element not found Step 8: Exit

Binary Search

Bubble Sort BUBBLE-SORT(a) Time complexity is O(n2). for i = 0 to n-1 for j =0 to n-2 if key[j] > key[j+1] then swap if no elements swapped in this pass through array, done otherwise, continue Time complexity is O(n2). for j =0 to n-2 if key[j] > key[j+1] then swap

Example

Strings Characters Strings Building blocks of programs Every program is a sequence of meaningfully grouped characters Strings Series of characters treated as a single unit Can include letters, digits and special characters (*, /, $) String literal (string constant) - written in double quotes "Hello" Strings are arrays of characters

Contd.. String declarations Inputting strings Declare as a character array or a variable of type char * char color[] = "blue"; char *colorPtr = "blue"; Remember that strings represented as character arrays end with '\0' color has 5 elements Inputting strings Use scanf scanf("%s", word); Copies input into word[] Do not need & (because a string is a pointer) Remember to leave room in the array for '\0'

String Conversion Functions In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point values

Standard Input/output Library Functions Functions in <stdio.h> Used to manipulate character and string data

Example #include <stdio.h> int main() { char str[20]; sprintf(str, “Data Structure"); puts(str); return(0); }

Example #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int day, year; char weekday[20], month[20], dtm[100]; strcpy( dtm, "Friday Jan 13 2017" ); sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year ); printf("%s %d, %d = %s\n", month, day, year, weekday ); }

String Manipulation Functions String handling library has functions to Manipulate string data Search strings Tokenize strings Determine string length

#include <stdio.h> #include <string.h> int main() { char s1[ 20 ] = "Happy "; char s2[] = "New Year "; char s3[ 40 ] = ""; printf( "s1 = %s\ns2 = %s\n", s1, s2 ); printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) ); printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) ); printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) ); return 0; } s1 = Happy s2 = New Year strcat( s1, s2 ) = Happy New Year strncat( s3, s1, 6 ) = Happy strcat( s3, s1 ) = Happy Happy New Year

Comparison Functions Comparing strings Computer compares numeric ASCII codes of characters in string int strcmp( const char *s1, const char *s2 ); Compares string s1 to s2 Returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2 int strncmp( const char *s1, const char *s2, size_t n ); Compares up to n characters of string s1 to s2 Returns values as above

Example #include<stdio.h> #include<string.h> int main() { char str1[]="hello"; char str2[]="NESTLE MAGGI"; int i; i=strcmp(str1,str2); printf("%d",i); return 0; }