Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Advertisements

Strings.
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.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
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.
Chapter 10.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
C++ for Engineers and Scientists Third Edition
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Arrays in C.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
1 This chapter covers both string constants (or literals, as they're called in the C standard) and string variables, which can change during the execution.
Spring 2005, Gülcihan Özdemir Dağ Lecture 8, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 8 Outline 8.1 Declaring.
Review of Lectures 12, 13, 14 -Functions -Arrays -Strings.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
COIT29222-Structured Programming Lecture Week 08  Reading: Textbook (4 th Ed.), Chapter 4 Textbook (6 th Ed.), Chapter 7 Study Guide Book 2, Module 11.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
General comments [1]  array is a fixed sized group in which the elements are of the same type  The general form of array's definition is as follows:
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
Computer Programming for Engineers
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
© 2016 Pearson Education, Ltd. All rights reserved.
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
A First Book of ANSI C Fourth Edition
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Arrays in C.
CS111 Computer Programming
Lecture 10 Arrays.
Lecture 11 Strings.
Chapter 8 Character Arrays and Strings
C++ Programming Lecture 20 Strings
Introduction to Problem Solving and Programming
Presentation transcript:

Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 2 Outline Array String

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 3 Array Generic declaration: typename variablename[size]; – typename is any type – variablename is any legal variable name – size is a number the compiler can figure out int a[10]; – For example : int a[10]; – Defines an array of ints with subscripts ranging from 0 to 9 – There are 10*sizeof(int) bytes of memory reserved for this array. – You can use a[0]=10; x=a[2]; a[3]=a[2]; etc. – You can use scanf("%d",&a[3]); a

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 4 Array Representation int A[3]; A[2] 0x1008 A[1] 0x1004 A[0] 0x1000 A[-1] All elements of same type – homogenous First element (index 0) Last element (index size - 1) array[0] = 3; array[2] = 4; array[10] = 5; array[-1] = 6; sizeof(A)? sizeof(A[0]) = sizeof(A[1]) = sizeof(A[2])? No bounds checking! 3 * 4 = 12 4

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 5 Array-Bounds Checking C, unlike many languages, does NOT check array bounds subscripts during: – Compilation (some C compilers will check literals) – Runtime (bounds are never checked) It is the programmer’s responsibility to ensure that their programs are correctly written and debugged! – This does have some advantages but it does give you all the rope you need to hang yourself!

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 6 Using Constants to Define Arrays It is useful to define arrays using constants: #define MONTHS 12 float a [MONTHS]; However, in ANSI C, you cannot int n; scanf(“%d”, &n); float a[n]; In GNU C, the variable length array is allowed.

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 7 Initializing Arrays Initialization of arrays can be done by a comma separated list following its definition For example: int array [4] = { 100, 200, 300, 400 }; – This is equivalent to: int array [4]; array[0] = 100; array[1] = 200; array[2] = 300; array[3] = 400; You can also let the compiler figure out the array size for you: int array[] = { 100, 200, 300, 400};

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 8 Initializing Arrays For example: int array [4] = { 100, 200 }; Also can be done by int array [4] = { 100, 200, 0, 0 }; – This is equivalent to int array [4]; array[0] = 100; array[1] = 200; array[2] = 0; array[3] = 0;

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 9 A Simple Example #include #define COUNT 10 int main() { float number_Array[COUNT]; float sum = 0, max = 0; for(int i = 0; i < COUNT; i++) // loop for get numbers, calculating sum, and selecting max { printf("Enter number %d = ", i + 1); scanf("%f", &number_Array[i]); // get a number and store in array sum += number_Array[i]; // sum of numbers if(max < number_Array[i]) // selecting max max = number_Array[i]; } printf("AVG of entered number (%d) is %f", COUNT, sum / COUNT); return 0; }

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 10 Multidimensional Arrays Arrays in C can have virtually as many dimensions as you want Definition is accomplished by adding additional subscripts when it is defined For example: – int a [4] [3] ; 2-dimensional array 4 * 3 * sizeof(int) – int a[4][3][2] 3-dimention array 4 * 3 * 2 * sizeof(int)

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 11 Multidimensional Arrays Representation Row 0 Row 1 Row 2 Column 0Column 1Column 2Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] int a[n][m] ; &a[i][j] = [(m * i) + j] * (sizeof(int)) + &a[0]

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 12 Initializing Multidimensional Arrays The following initializes a[4][3]: int a[4] [3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Also can be done by: int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; – is equivalent to a[0][0] = 1; a[0][1] = 2; a[0][2] = 3; a[1][0] = 4;... a[3][2] = 12;

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 13 Examples Initialization – Example: short b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; – If not enough, unspecified elements set to zero short b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 14 An Example #include int main () { int random1[10][8]; int a, b; for (a = 0; a < 10; a++) for (b = 0; b < 8; b++) random1[a][b] = rand() % 2; for (a = 0; a < 10; a++) { for (b = 0; b < 8; b++) printf ("%c ", random1[a][b] ? 'x' : 'o'); printf("\n"); } return 0; }

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 15 Examples int a[10]; // Ok int a[2.5]; // Syntax error int a[-5]; // Syntax error int a[0]; // Logical error a[3.6] = 10; // Syntax error or a[3] = 10; a[3.2] = 10; // Syntax error or a[3] = 10; int b[2][3] = { {1, 2}, {3, 4}, {5, 6} }; // Syntax error

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 16 Strings are Character Arrays Strings in C are simply arrays of characters – Example:char s [10]; This is a ten (10) element array that can hold a character string consisting of  9 characters This is because C does not know where the end of an array is at run time – By convention, C uses a NULL character '\0' to terminate all strings in its library functions For example: char str [10] = {'u', 'n', 'I', 'x', '\0'}; It’s the string terminator (not the size of the array) that determines the length of the string

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 17 Accessing Individual Characters The first element of any array in C is at index 0. The second is at index 1, and so on... char s[10]; s[0] = 'h'; s[1] = 'i’; s[2] = '!'; s[3] = '\0'; This notation can be used in all kinds of statements and expressions in C: – For example: c = s[1]; if (s[0] == '-') … switch (s[1])... ??????\0!ih [9][8][7][6][5][4][3][2][1][0]s

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 18 String Literals String literals are given as a string quoted by double quotes – printf("Long long ago."); Initializing char array... – char s[10] = "unix"; /* s[4] is '\0'; */ five elements – char s[ ] = "unix"; /* s has five elements */

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 19 Printing with printf ( ) Example: char str[ ] = "A message to display"; printf ("%s\n", str); printf knows how much to print out because of the NULL character at the end of all strings – When it finds a \0, it knows to stop

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 20 Example char str[11]="unix and c"; printf("%s", str); printf("\n"); str[6]='\0'; printf("%s", str); printf("\n"); printf(str); printf("\n"); str[2]='I'; printf(str); printf("\n"); \0c dna xinu [10][9][8][7][6][5][4][3][2][1][0]str \0c d a xinu [10][9][8][7][6][5][4][3][2][1][0]str \0c d a xInu [10][9][8][7][6][5][4][3][2][1][0]str

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 21 Printing with puts( ) The puts function is a much simpler output function than printf for string printing Prototype of puts is defined in stdio.h int puts(const char * str) – This is more efficient than printf : because your program doesn't need to analyze the format string at run-time. – For example: char sentence[] = "The quick brown fox"; \n puts(sentence); // printf("The quick brown fox\n");

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 22 Inputting Strings with scanf ( ) To read a string include: – %s scans up to but not including the “next” white space character – %ns scans the next n characters or up to the next white space character, whichever comes first Example: scanf ("%s%s", s1, s2); // fundamental of programming scanf ("%2s%2s", s1, s2); // fundamental of programming – Note:ampersand(&) – Note: No ampersand(&) when inputting strings into character arrays! (We’ll explain why later …) s1s2 s1s2

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 23 Inputting Strings with scanf ( ) char line[80]; scanf("%[ ABCDF]s", line); // AB F G scanf("%[ A-Za-z]s", line); // AB F g scanf("%[ ^\n]s", line);

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 24 Inputting Strings with gets( ) gets( ) gets a line from the standard input char * gets(char *str) The prototype is defined in stdio.h : char * gets(char *str) – str is a pointer to the space where gets will store the line to, or a character array – Returns NULL upon failure. Otherwise, it returns str – Example: char your_line[100]; printf("Enter a line:\n"); gets(your_line); puts("Your input follows:\n"); puts(your_line);

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 25 Difference between gets and scanf gets( ) read a line scanf("%s",…) read up to the next space char line[80]; gets(line);scanf("%[ ^\n]s", line); puts(line); printf(“%s\n", line);

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 26 The C String Library String functions are provided in an ANSI standard string library – Access this through the include file: #include – Includes functions such as: Computing length of string Copying strings Concatenating strings

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 27 strlen strlen returns the length of a NULL terminated character string: size_t strlen (char * str) ;

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 28 strcpy Copying a string comes in the form: char *strcpy (char * destination, char * source); A copy of source is made at destination – source should be NULL terminated – destination should have enough room (its length should be at least the size of source) The return value also points at the destination

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 29 strcat Concatenating two stings: char * strcat (char * str1, char * str2); – Appends a copy of str2 to the end of str1 – A pointer equal to str1 is returned Ensure that str1 has sufficient space for the concatenated string! – Array index out of range will be the most popular bug in your C programming career

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 30 Example #include int main() { char str1[10] = "abc"; char str2[100]; printf("%d\n", strlen(str1)); strcpy(str2, str1); puts(str2); puts("\n"); // printf("\n\n"); strcat(str2, str1); puts(str2); }

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 31 Comparing Strings C strings can be compared for equality or inequality If they are equal - they are ASCII identical If they are unequal the comparison function will return an int that is interpreted as: < 0 : str1 is less than str2 0 : str1 is equal to str2 > 0 : str1 is greater than str2

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 32 strcmp Four basic comparison functions: int strcmp (char *str1, char *str2) ; – Does an ASCII comparison one char at a time until a difference is found between two chars Return value is as stated before – If both strings reach a '\0' at the same time, they are considered equal. int strncmp (char *str1, char * str2, size_t n); – Compares n chars of str1 and str2 Continues until n chars are compared or The end of str1or str2 is encountered – Also have strcasecmp() and strncasecmp() which do the same as above, but ignore case in letters.

Array and String – Lecture 6 Sharif University of Technology Department of Computer Engineering 33 Example char str1[] = "The first string."; char str2[] = "The second string."; printf("%d\n", strcmp(str1,str2) ); // -1 printf("%d\n", strncmp(str1,str2,4) ); // 0 // 'f' - 's' = -13 printf("%d\n", strncmp(str1,str2,5) ); // -13 If(str1 == str2) … // Syntax error in many c complier!