The C Programming Language

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
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.
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.
C Strings. The char Data Type for Storing Characters The char data type can is used to declare a variable that can hold a single character. Examples:
Chapter 10.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 9: Arrays and Strings
Strings String - a string is a series of characters treated as a unit. A C string is a variable-length array of characters that is delimited by the null.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
Week 7 – String. Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
CHAPTER 8 CHARACTER AND STRINGS
1 IPC144 Session 11 The C Programming Language. 2 Objectives To format a #define statement correctly To use a #define statement in a C program To construct.
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.
 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 Arrays and Strings
Array with base type char One character per indexed variable One extra character: '\0' Called ‘null character’ Delimiter of the string To declare a string,
Introduction to Computer Programming Using C Session 23 - Review.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
 Integers and Characters  Character Strings  Input and Output.
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.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Pointers *, &, array similarities, functions, sizeof.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and 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.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Strings, Pointers and Tools
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
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.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
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.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Strings CSCI 112: Programming in C.
© 2016 Pearson Education, Ltd. All rights reserved.
C Programming Tutorial – Part I
Chapter 18 I/O in C.
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Computer Science 210 Computer Organization
Chapter 16 Pointers and Arrays
CS1100 Computational Engineering
Presentation transcript:

The C Programming Language IPC144 Session 15 The C Programming Language 1

To define arrays within the C language To use arrays in a C program Objectives To define arrays within the C language To use arrays in a C program To pass arrays between functions Define what a string is List the three methods strings can be stored in a computer. Use arrays to store strings List the standard C functions for manipulating strings List the parameters for the C string functions, and their restrictions Use the C string functions to manipulate strings 2

The C Language Arrays Recall from or earlier discussions of Arrays, that we will be dealing with one-dimensional arrays (like a column of an Excel spreadsheet). A one-dimensional array is also called a list or a vector. Each element is numbered uniquely For C we will use the same notation we used in flowcharts: tableName[index] the tableName is a variable, and therefore you apply the variable naming standards when declaring a table. the index is the element number In C, the index always start at zero 3

The C Language Arrays, continued One dimensional tables If a table called myTab contained: element# element 0 Red 1 Orange 2 Yellow 3 Green 4 Blue 5 Violet myTab[0] contains Red myTab[4] contains ?? 4

The C Language Arrays, continued What is the data type of a table? The data type can be any of the types we discussed- the compiler uses this information so that it knows how to interpret the data once it gets there How are arrays stored inside the computer? Arrays are stored in contiguous memory locations, where the first location is pointed to by a variable that knows how to get to the start of the list of elements How are arrays declared? 5

The C Language Arrays, continued Anatomy of an array declaration: int myTab[5]; The maximum number of elements in the array (numbered 0 to n - 1)‏ The name of the table- following the variable naming standards Data type of the array This is an implicit declaration of a pointer (myTab) that points to a fixed block of memory that will contain the elements of the array. This means that when you use the array name by itself, you are using a pointer variable! 6

The C Language Arrays, continued Write a program that reads 10 floats from the user and stores them into an array. 7

The C Language Arrays, continued Something new: #include <stdio.h> #define ARRAY_SIZE 10 int main(void)‏ { int counter, ch; float theArray[ARRAY_SIZE]; for (counter = 0; counter < 10; counter = counter + 1)‏ scanf("%f", &theArray[counter]); while((ch = getc(stdin)) != EOF && ch != '\n'); } for (counter = 0; counter < ARRAY_SIZE; counter = counter + 1)‏ printf("theArray[%d] = %1.2f\n", counter, theArray[counter]); Something new: This causes the computer to discard anything that happens to have been left in the keyboard buffer after the last read - essentially this cleans up in preparation of another keyboard read. 8

The C Language Arrays, continued What is the most efficient method to pass an array to a function, in order that the function may change the contents of one of the elements (or many elements) of the array? Pass-by-reference. There are two possible syntax rules for declaring a pointer to an array in a function prototype or a function declaration (shown below): myFunc(int mytab[])‏ { } or myFunc(int *myTab)‏ The following is a program written to use a function to print a table: 9

The C Language Arrays, continued #include <stdio.h> #define TAB_SIZE 10 void printFunction(int tbl[]); int main(void)‏ { int i; int table[TAB_SIZE]; for (i = 0; i < 10; i = i + 1)‏ table[i] = i * 2; } printFunction(table); void printFunction(int tbl[])‏ for (i = 0; i < TAB_SIZE; i= i + 1)‏ printf("table[%d] = %d\n", i, tbl[i]); 10

The C Language Arrays, continued Write a program that reads 5 numbers from the user and stores them into a 5 element array. Create a function that flips the array upside down. The first element becomes the last, the last becomes the first. The second element becomes the second last, the second last element becomes the second and so on. 11

Strings 12

The C Language Strings What is a string? Strings are a collection of characters treated as a unit A word, sentence, paragraph or book can all be considered strings Even a single character can be considered a string- we shall see why shortly There is also an allowance for an empty string- that is a string containing no characters 13

The C Language Strings Variable length Fixed Length controlled Strings, continued How are strings defined to the computer? Strings Variable length Fixed Length controlled Delimited 14

The C Language Strings Variable length Fixed Length controlled Strings, continued Fixed Length Strings Variable length Fixed Length controlled Delimited Non character data A R I S T O T L E 15

The C Language Strings Variable length Fixed Length controlled Strings, continued Length Controlled Strings Variable length Fixed Length controlled Delimited Length 9 A R I S T O T L E 16

The C Language Strings Variable length Fixed Length controlled Strings, continued Delimited Strings Variable length Fixed Length controlled Delimited Delimiter A R I S T O T L E \0 17

The C Language A R I S T O T L E \0 Strings, continued Delimiter We have used the '\n' in our programs. C identifies this as the new-line character. The ‘\0’ is another ‘special’ character in C- it represents the ‘null’ character It is one of those strange things about computers - they need to have something that represents nothing- null The null character, as far as the computer is considered, is a legitimate, normal character Delimiter A R I S T O T L E \0 18

The C Language Strings, continued If we remember the char data-type, it can contain ‘letters’ of the ASCII alphabet zero, in the ASCII alphabet, is the null character When programming in C there is a difference between how strings are represented and how single characters are represented 19

The C Language Strings, continued Character Data The data type for character data is char We can assign any of the 256 ‘letters’ of the ASCII alphabet to a char We can assign the ‘letter’ by using its numeric representation: char myChar; myChar = 65; We can assign the ‘letter’ by enclosing it in single quotes: myChar = ‘A’; The above assignments perform the same action 20

The C Language Strings, continued String Data The data type for each character of the string is char The string is really an array of char data types We represent a string by enclosing it in double quotes: "this is a string" "" The second example is an empty string, or null string In both cases there is an IMPLICIT null character terminating the string 21

The C Language Strings, continued What does the string look like in memory? Based on these definitions being found in your program: ... char myString[20]; strcpy(myString, “this is a string”); The strcpy() is a predefined function that performs a STRingCoPY - it is like saying, in pseudocode: myString = "this is a string" ... t h i s i s a s t r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 22

The C Language Strings, continued When deciding on how much memory to reserve for a string be sure to include one position for the null-terminator What would be the result of: myString[8] = '1'; On the following string in memory: ... t h i s i s a s t r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 23

The C Language Strings, continued When deciding on how much memory to reserve for a string be sure to include one position for the null-terminator What would be the result of: myString[8] = 0; On the following string in memory: ... t h i s i s 1 s t r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 24

The C Language Strings, continued Formatted output of strings - printf()‏ A new conversion code is used: %s This tells the compiler to treat the array as a string of characters The function will print the string up to but not including the null-terminating character '\0' The flags and minimum width attributes can still be used Based on what you already know, what does the following mean? (assuming txnDesc has been declared a string)‏ printf(“%-64s\n”, txnDesc); 25

The C Language Strings, continued Unformatted output of strings - puts()‏ The function prototype of puts() is: int puts(char *ptrString); If the function was successful, it returns a value >= 0 (a non-negative integer)‏ If the function failed, it returns EOF EOF is a value defined by the compiler through a #define statement it is a value < 0 This function will AUTOMATICALLY output a new-line character after outputting all of the characters of the string 26

The C Language Strings, continued Formatted input of strings - scanf()‏ Again, the %s conversion code is used The following statement will read a string of data up to the first white-space character: scanf("%s", myString); The function stores the new-line character (if encountered)‏ 27

The C Language Strings, continued Consider the following code: #include <stdio.h> void main(void)‏ { char strData[10]; scanf(“%s”, strData); printf(“Read: %s\n”, strData); } What would happen if the user typed in: a_very_long_and_arduous_journey,_is_this_course_on_C! 28

The C Language Strings, continued A better solution would be: #include <stdio.h> void main(void)‏ { char strData[10]; scanf(“%9s”, strData); /* remember to leave a spot for the null */ printf(“Read: %s\n”, strData); } Now what would happen if the user typed in: a_very_long_and_arduous_journey,_is_this_course_on_C! 29

The C Language Strings, continued Unformatted input of strings - gets()‏ The function prototype of gets() is: char *gets(char *ptrString); This function will AUTOMATICALLY replace the new-line character with a null-terminator If the function was successful, it returns a pointer to the same input string If the function was unsuccessful, it returns NULL NULL is a value defined by the compiler through a #define statement it is a pointer to nothing THIS IS A DANGEROUS FUNCTION AS YOU CAN EASILY CORRUPT MEMORY WITH AN UNCONTAINED READ – a better function is fgets() which will be introduced with file processing. 30

The C Language Strings, continued Predefined string manipulation commands: They all have the same basic format strxxx( parameters )‏ When working with strings, the computer will do NO checking on lengths It your responsibility to ensure that when you manipulate a string you do not overrun memory There is a specific header file associated with the predefined string functions: #include <string.h> 31

The C Language Strings, continued String Copy: char *strcpy(char *stringTo, char *stringFrom); This function takes a string pointed to by stringFrom and copies it to the location pointed to by stringTo (including the null-terminator)‏ The function returns a pointer to stringTo The following is an example of memory overrun: #include <stdio.h> #include <string.h> void main(void)‏ { char strTo[5]; char strFrom[15]; strcpy(strFrom, “This fails”); strcpy(strTo, strFrom); } 32

The C Language Strings, continued String-Number Copy: char *strncpy(char *stringTo, char *stringFrom, int size); This function copies no more than size characters If stringFrom is less than size, then stringTo will be padded to size characters using nulls If stringFrom is greater than size, then only size characters will be copied - NO null-terminator will be placed in stringTo 33

The C Language Strings, continued String Length: int strlen(char *string); This function returns the number of characters in the string (not including the null-terminator)‏ 34

The C Language Strings, continued String Compare: int strcmp(char *string1, char *string2); This function will compare two strings character-by-character If the two strings are identical, the function returns zero Otherwise, it returns a value < 0 if string1 < string2, or a value > 0 if string1 > string2 You need to reference an ASCII table to determine the order, or collating sequence, of the 'letters' For example 'a' > 'A' according to the ASCII table 35

The C Language Strings, continued String-Number Compare: int strncmp(char *string1, char *string2, int size); This function will compare two strings character-by-character The test will stop when a null-terminator is encountered, OR size characters of string1 have been tested - whichever occurs first 36

The C Language Strings, continued String Concatenate: char *strcat(char *stringTo, char *stringFrom); This function will concatenate stringFrom to the end of stringTo Remember that there must be enough memory set aside to contain both the contents of stringTo and stringFrom The function returns a pointer to stringTo The null-terminator in stringTo is replaced by the first character of stringFrom All of stringFrom is copied to the end of stringTo until reaching the null-terminator of stringFrom 37

The C Language Strings, continued String-Number Concatenate: char *strncat(char *stringTo, char *stringFrom, int size); If the length of stringFrom is less than size, then the function will behave as if the strcat() function was used If the length of stringFrom is greater than size, then size characters are appended to stringTo followed by a null-terminator 38

The C Language Strings, continued What would be the output of the following program: #include <stdio.h> #include <string.h> void main(void)‏ { char str1[10]; char str2[10]; strcpy(str1, “Testing”); printf(“Length is %d\n”, strlen(str1)); strcpy(str2, str1); printf(“String2 = %s\n”, str2); if (strcmp(str1, str2) == 0)‏ printf(“Both strings are the same\n”); str1[4] = ‘\0’; strncat(str1, str2, 3); printf(“String1 is now: %s\n”); if (strncmp(str1, str2, 4) == 0)‏ printf(“The strings are still equal\n”); } 39