Arrays in C.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
Kernighan/Ritchie: Kelley/Pohl:
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Introduction to C programming
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Chapter 2 Array and String. Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
LINKED LISTS.
Computer Organization and Design Pointers, Arrays and Strings in C
Lesson #8 Structures Linked Lists Command Line Arguments.
User-Written Functions
Strings CSCI 112: Programming in C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
UNIT 5 C Pointers.
ECE Application Programming
Characters and Strings
Fundamentals of Characters and Strings
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Computer Programming BCT 1113
Lecture 8 String 1. Concept of strings String and pointers
Quiz 11/15/16 – C functions, arrays and strings
Lecture-5 Arrays.
Module 2 Arrays and strings – example programs.
Java Review: Reference Types
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Programming Languages and Paradigms
Computer Science 210 Computer Organization
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
C Stuff CS 2308.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Strings.
Week 9 – Lesson 1 Arrays – Character Strings
Chapter 2 - Introduction to C Programming
EKT150 : Computer Programming
Java Programming Arrays
Chapter 2 - Introduction to C Programming
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 2 Array and String Visit to more Learning Resources.
Chapter 16 Pointers and Arrays
Chapter 8 Character Arrays and Strings
CPS120: Introduction to Computer Science
Homework Starting K&R Chapter 5 Good tutorial on pointers
Arrays, Part 1 of 2 Topics Definition of a Data Structure
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
Chapter 2 - Introduction to C Programming
Exercise Arrays.
Strings #include <stdio.h>
CS31 Discussion 1H Fall18: week 6
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to Problem Solving and Programming
Presentation transcript:

Arrays in C

Topics Covered Arrays Declaring and initialising arrays what are they how are they used Declaring and initialising arrays Multiple dimension arrays Strings and string processing Internal representation of arrays Common array operations

Introduction to Arrays Single variables are ok for simple programs, if data requirements are small, and well known program always does the same thing, with the same data program is not expected to grow larger over time Most ‘real-world’ problems don’t meet these criteria Need some sort of large data storage facility to handle increased information needs Arrays are one way of accomplishing this! they are not the only way

What is an Array? An array is a mechanism whereby a single variable name refers to multiple pieces of data int a ; int ar[] ; 6 3 -1 7 14 ‘normal’ variable array

How are Arrays Used? Arrays are declared and accessed in C using the [] operator Declaration: int ar[10] ; Usage: ar[0] = 3 ; ar[5] = 7 ; size of array type of variable name of array element to be accessed

Array Sizes Arrays of any size can be declared up to limits of memory! The valid indices of an array run from 0 to size – 1 eg, an array declared as: int ar[10] valid indices are 0..9, NOT 10!

Initialising Arrays Arrays, like other variables, can be initialised when declared Syntax: int integer_array[10] = { 3, 5, 1, -1, 0, 7, 10, 2, 9, 2 }; OR int integer_array[] = { 3, 5, 1, -1, 0, 7, 10, 2, 9, 2 } ; size of array >= # of values size of array is determined by initialisation values, in this case 10

Array Example Simple program to read and store 10 numbers, then display them back to the screen int main ( void ){ int i, ar[10] ; for ( i = 0 ; i < 10 ; i++ ){ scanf ( “%d”, &ar[i] ) ; } printf ( “%d\n”, ar[i] ) ;

Size of Arrays There is no easy way to tell how big an array is unlike other languages, no size function, etc, to tell you If you pass an array to a function, you should always pass a second variable to let the function know how big the array is int process_array ( int ar[], int size ) ; Often, the total size of the array is of little interest, more important is how many values are actually in use

Size of Arrays int main ( void ){ int size = 0, num = 1, ar[50], i ; while ( size < 50 && num != 0 ){ printf ( “Please enter a number (0 to quit): “ ) ; scanf ( “%d”, &num ) ; if ( num != 0 ){ ar[size++] = num ; } printf ( “The user entered %d numbers before 0\n”, size ) ; for ( i = 0 ; i < size ; i++ ){ printf ( “%d: %d\n”, i+1, ar[i] ) ;

Strings C has no special type for strings, they are simply arrays of chars each character is one element of the array, with an extra character for the ‘end of string’ character ‘\0’ (or just 0) Declaring a string: char str[20] ; // 20 character long string Initialising is done somewhat differently than ‘normal’ arrays char str[] = “Hello world” ; note this allocates 12 bytes, not 11, as one is required for the “end of string” character

Manipulating Strings Strings are somewhat different to other variables cannot be directly assigned or compared do not require the & prefix with scanf special library functions are available <string.h> Individual characters can be accessed and modified like any other array, eg: str[5] = ‘a’ ; // set the 6th character to ‘a’ printf ( “The 1st character is %c\n”, str[0] ) ; The C compiler will recognise literal strings enclosed in double quotes (“ “) and store them accordingly

Manipulating Strings INCORRECT CORRECT #include <stdio.h> int main ( void ){ char str1[20], str2[20] ; str1 = “Hello world!” ; scanf ( “%s”, &str2 ) ; if ( str2 == “quit” ){ printf ( “all done!” ) ; } #include <stdio.h> #include <string.h> int main ( void ){ char str1[20], str2[20] ; strcpy(str1,“Hello World!”); scanf ( “%s”, str2 ) ; if (strcmp(str2,“quit”)==0){ printf ( “all done!” ) ; }

The ‘null’ Character Strings need to have a character so the computer knows where they end remember, there’s no way to tell the size of an array! This special character is known as the ‘null’ character, and can be written in a few ways ‘\0’ the backslash indicates an actual value 0 the actual value itself, in ASCII To get an idea of how this works, consider the following example..

The ‘null’ Character int main ( void ){ char string[10] ; strcpy ( string, “hello” ); printf ( “%s\n”, string ); // should print hello string[3] = 0 ; printf ( “%s\n”, string ) ; // what will it print now?! } Remember, printf() uses the null character as its cue to stop printing the string! strcpy, strcmp, do exactly the same thing.. ? ? ? ? ? ? ? ? ? ? ‘h’ ‘e’ ‘l’ ‘l’ ‘o’ ? ? ? ? ‘h’ ‘e’ ‘l’ ‘o’ ? ? ? ?

Common String Functions The following string functions are very commonly used, remember them! strcpy ( char dest[], char src[] ) ; copies the string src into dest, overwriting whatever is there. ASSUMES that dest is big enough! strcmp ( char str1[], char str2[] ) ; compares str1 and str2 which are null terminated strings of characters. Returns 0 if they are equal, otherwise a non-zero value strlen ( char str[] ) ; calculates the length of the null terminated string str and returns this value. strcat ( char dest[], char src[] ) ; appends the null terminated src to the end of dest There are many more functions in <string.h>, you might like to have a look…

Multidimensional Arrays C supports the use of higher dimensional arrays, which are declared with the syntax: int m_dim_array[10][20] ; // a 10x20 array of ints When initialising such arrays, only the size of the first dimension can be left blank! char names[][50] = { “Fred”, “Mary”, “Joe” } ; this is also true of functions that accept N-D arrays as arguments – all dimensions except the 1st MUST be supplied!

Multidimensional Arrays You can think of 2D arrays as being like a grid of values In reality, they are actually stored as a 1D array of size 3x4 = 12 ar[2][2] is the same as ar[0][10], is the same as ar[1][6], since 2*4+2 = 0*4+10 = 1*4+6 they are all at index 10 of the ‘equivalent’ 1D array int ar[3][4] ; Imagined layout ar[0][0] ar[0][1] ar[0][2] ar[0][3] ar[1][0] ar[1][1] ar[1][2] ar[1][3] ar[2][0] ar[2][1] ar[2][2] ar[2][3] Actual physical layout ar[0][0] ar[0][1] ar[0][2] ar[0][3] ar[1][0] ar[1][1] ar[1][2] ar[1][3] ar[2][0] ar[2][1] ar[2][2] ar[2][3]

Common Array Operations ‘for’ loops and arrays are almost inevitably linked, and are used when: reading values into arrays processing arrays displaying arrays The most common syntax is: for ( i = 0 ; i < size ; i++ ){ … where size is the number of elements in the array (not necessarily the total size!)

Examples Function to calculate the average of an array of floats: float avg ( float ar[], int size ){ // note the SIZE variable in the declaration! int i ; float total = 0 ; for ( i = 0 ; i < size ; i++ ){ total += ar[i] ; } return ( total / size ) ;

Examples Function to calculate the maximum of an array of ints: int max ( int ar[], int size ){ // note the SIZE variable in the declaration! int i, m = ar[0] ; // the FIRST value starts as the max for ( i = 1 ; i < size ; i++ ){ if ( ar[i] > m ){ m = ar[i] ; } return ( m ) ;

Examples Function to calculate the maximum of a 2D array of ints: int max ( int ar[][10], int size ){ // the size of the second dimension MUST be given! // the size variable refers to the first dimension only int i, j ; int m = ar[0][0] ; // the FIRST value starts as the max for ( i = 0 ; i < size ; i++ ){ for ( j = 0 ; j < 10 ; j++ ){ if ( ar[i][j] > m ){ m = ar[i][j] ; } return ( m ) ;

Examples An array of STRINGS is really a 2D array.. int main ( void ){ char names[][50] = { “Fred”, “Mary”, “John”, “Katherine” } ; // second dimension size MUST be supplied – first is automatically // set to 4 as four strings are given.. int longest = 0 ; // this is the INDEX of the longest name, // NOT the length, or the name itself! int i ; for ( i = 0 ; i < 4 ; i++ ){ printf ( “Name %d: %s\n”, i+1, names[i] ) ; if ( strlen ( names[i] ) > strlen ( names[longest] ){ longest = i ; } printf(“The longest name is (%d) %s\n”,longest+1,names[longest]);

Final Thoughts.. Arrays are actually addresses which are the location of the first element in memory when you access an element of the array it adds the index value to this address and accesses that piece of memory ar[2] really means: get the data at the address ar+2 when performing these calculations, the size of each element is taken into account, so for an integer array, ar[2] is actually ar+(2*4) This is why we don’t need the & (address) operator when reading strings – they array is ALREADY an address! This property of arrays can be used to do some pretty handy things..

Using Arrays as Addresses Consider: int main ( void ){ char str[20] = “Hello world!” ; printf ( “%s\n”, &str[3] ) ; } What will the output be!?!