Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Similar documents
Chapter 8 - Characters and Strings

C: How to Program. Week /May/28

Chapter 8: Character & String. In this chapter, you ll learn about;

Fundamental Data Types

Do not start the test until instructed to do so!

Data Representation and Binary Arithmetic. Lecture 2

Introduction to string

Chapter 8. Characters and Strings

Fundamentals of Programming (C)

Characters and Strings

Do not start the test until instructed to do so!

Fundamentals of Programming. Lecture 11: C Characters and Strings

Do not start the test until instructed to do so!

Chapter 8 C Characters and Strings

CMPSC 311- Introduction to Systems Programming Module: Strings

Chapter 2 Bits, Data Types, and Operations

by Pearson Education, Inc. All Rights Reserved.

C Characters and Strings

BITG 1113: Array (Part 2) LECTURE 9

Chapter 2 Bits, Data Types, and Operations

Chapter 2 Bits, Data Types, and Operations

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

CPS 104 Computer Organization and Programming Lecture-2 : Data representations,

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Number Systems for Computers. Outline of Introduction. Binary, Octal and Hexadecimal numbers. Issues for Binary Representation of Numbers

ASSIGNMENT 5 TIPS AND TRICKS

1.1. INTRODUCTION 1.2. NUMBER SYSTEMS

CS341 *** TURN OFF ALL CELLPHONES *** Practice NAME

Computers Programming Course 11. Iulian Năstac

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Binary Numbers. The Basics. Base 10 Number. What is a Number? = Binary Number Example. Binary Number Example

Experiment 3. TITLE Optional: Write here the Title of your program.model SMALL This directive defines the memory model used in the program.

Fundamentals of Programming

Chapter 2 Bits, Data Types, and Operations

Characters Lesson Outline

Appendix A Developing a C Program on the UNIX system

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras

Chapter 2 Bits, Data Types, and Operations

Computer Programming

Week 1 / Lecture 2 8 March 2017 NWEN 241 C Fundamentals. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

Lecture (09) x86 programming 8

Number System (Different Ways To Say How Many) Fall 2016

Chapter 2 Number System

Bits and Bytes. Data Representation. A binary digit or bit has a value of either 0 or 1; these are the values we can store in hardware devices.

ENCM 339 Fall 2017 Lecture Section 01 Lab 3 for the Week of October 2

EXPERIMENT 8: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

Chapter 3. Information Representation

Exercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014

Number Representations

EXPERIMENT 7: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

Oberon Data Types. Matteo Corti. December 5, 2001

EE 109 Unit 2. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

Introduction to Decision Structures. Boolean & If Statements. Different Types of Decisions. Boolean Logic. Relational Operators

ONE DIMENSIONAL ARRAYS

Reminder. Sign up for ee209 mailing list. Precept. If you haven t received any from ee209 yet Follow the link from our class homepage

CSE 30 Fall 2013 Final Exam

Chapter 8 Character Arrays and Strings

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

5/17/2009. Digitizing Discrete Information. Ordering Symbols. Analog vs. Digital

PureScan - ML1. Configuration Guide. Wireless Linear Imager Wireless Laser scanner - 1 -

The Binary Number System

Outline. Computer Programming. Structure of a function. Functions. Function prototype. Structure of a function. Functions

Number Systems Base r

Simple Data Types in C. Alan L. Cox

String can be represented as a single-dimensional character type array. Declaration of strings

Midterm CSE 131 Winter 2012

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

CMSC 313 Lecture 03 Multiple-byte data big-endian vs little-endian sign extension Multiplication and division Floating point formats Character Codes

Midterm Exam, Fall 2015 Date: October 29th, 2015

Unit 3. Analog vs. Digital. Analog vs. Digital ANALOG VS. DIGITAL. Binary Representation

Midterm CSE 131 Winter 2013

CSE 30 Spring 2007 Final Exam

Final CSE 131 Winter 2010

CSE 30 Winter 2014 Final Exam

CSE 30 Fall 2012 Final Exam

Intermediate Programming, Spring 2017*

C PROGRAMMING. Characters and Strings File Processing Exercise

CSE 30 Fall 2007 Final Exam

DATA REPRESENTATION. Data Types. Complements. Fixed Point Representations. Floating Point Representations. Other Binary Codes. Error Detection Codes

Pointers, Arrays, and Strings. CS449 Spring 2016

1. Character/String Data, Expressions & Intrinsic Functions. Numeric Representation of Non-numeric Values. (CHARACTER Data Type), Part 1

VARIABLES AND CONSTANTS

Chapter 9 Strings. With this array declaration: char s[10];

Midterm CSE 131 Winter 2014

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

System Design and Programming II

Universal Asynchronous Receiver Transmitter Communication

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

Course organization. Course introduction ( Week 1)

Introduction to C/C++ Lecture 5 - String & its Manipulation

Fundamental of Programming (C)

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Transcription:

Lecture 10 Arrays (2) and Strings UniMAP SEM II - 11/12 DKT121 1

Outline 8.1 Passing Arrays to Function 8.2 Displaying Array in a Function 8.3 How Arrays are passed in a function call 8.4 Introduction to Strings 8.5 Strings Type 8.6 Character Array 8.7 Declaration of Strings 8.8 Fundamentals of Strings & Characters 8.9 Initialization of Strings 8.10 Assigning Values to Strings 8.11 Calculation of Strings Size 8.12 Strings Conversion Functions 8.13 Comparison Functions of the Strings 8.14 ASCII Table 2

Passing Arrays to Function void fninitialize (int ailist [ ]) { int icount; } for (icount = 0; icount < 5; icount ++) ailist [icount] = 0; Initializes int array of size 5 to 0. 3

Array as Parameter in Function If size changes (lets say 10 or 20), need to write another function. not practical and inflexible. Therefore, introduce another variable, isize. void fninitialize (int ailist [ ], int isize) { int icount; } for (icount = 0; icount < isize; icount ++) ailist [icount] = 0; 4

Constant Arrays Prevent the function from changing the values in array. Use word const in declaration. Function can modify array aix but not array aiy. void fnexample (int aix[ ], const int aiy[ ], int isizex[ ],int isizey[ ]) {...... } 5

Initialize an array to 0 void fninitializearray (int aix[ ], int isizex) { int icounter; } for (icounter = 0; icounter < isizex; icounter ++) aix [icounter] = 0; 6

Read data and store it in an array void fnfillarray (int aix[ ], int isizex) { int icounter; } for (icounter = 0; icounter < isizex; icounter++) scanf ( %d, &aix [icounter]); 7

Displaying array in a function void fnprintarray (const int aix[ ], int isizex) { int icounter; } for (icounter = 0; icounter < isizex; icounter ++) printf ( %d, aix [icounter]); 8

Find and return the sum of an array int fnsumarray (const int aix[ ], int isizex) { int icounter; int isum = 0; for (icounter = 0; icounter < isizex; icounter ++) isum = isum + aix[icounter]; } return (isum); 9

Find and return index of largest element of an array int fnindexlargestelement (const int aix[ ], int isizex) { int icounter; int imaxindex = 0; for (icounter = 0; icounter < isizex; icounter ++) if ( aix[imaxindex] < aix[icounter] ) imaxindex = icounter; } return (imaxindex); 10

Copy an array into another array void fncopyarray (const int aix[ ], int aiy[ ], int ilength) { int icounter; } for (icounter = 0; icounter < ilength; icounter ++) aiy[icounter] = aix[icounter]; 11

How arrays are passed in a function call #include <stdio.h> const int iarraysize = 10; void fninitializearray (int aix[], int isizex); void fnfillarray (int aix[], int isizex); void fnprintarray (const int aix[], int isizex); int fnsumarray (const int aix[], int isizex); int fnindexlargestelement (const int aix[], int isizex); void fncopyarray (const int aix[], int aiy[], int ilength); 12

How arrays are passed in a function call int main() { int ailista [iarraysize] = {0}; int ailistb [iarraysize]; fnprintarray (ailista, iarraysize); fninitializearray (ailistb, iarraysize); fnprintarray (ailistb, iarraysize); fnfillarray (ailista, iarraysize); fnprintarray (ailista, iarraysize); fnsumarray (ailista, iarraysize); fncopyarray (ailista, ailistb, iarraysize); fnprintarray (ailistb, iarraysize); } return 0; 13

Sample Program #include <stdio.h> void fnprintarray (const int aia[][3]); // function prototype //function main begins program execution int main() { //initialize array1, array2, array3 int aiarray1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int aiarray2 [2][3] = { 1, 2, 3, 4, 5 }; int aiarray3 [2][3] = { {1, 2 }, { 4 } }; printf ( Values in array1 by row are : \n); fnprintarray (aiarray1); printf ("Values in array2 by row are : \n"); fnprintarray (aiarray2); printf ("Values in array3 by row are : \n"); fnprintarray (aiarray3); return 0; } // end of main 14

Sample Program (cont ) //function to display array with two rows and three columns void fnprintarray (const int aia[][3]) { int irow; //row counter int icolumn; //column counter //loop through row for (irow = 0; irow <= 1; irow++) { //output column values for (icolumn = 0; icolumn <= 2; icolumn++) { printf ("%d ", aia[irow][icolumn]); } //end inner for printf ("\n"); //start new line of output } //end outer for } //end function fnprintarray 15

Sample Program (cont ) Output Values in array1 by row are : 1 2 3 4 5 6 Values in array2 by row are : 1 2 3 4 5 0 Values in array3 by row are : 1 2 0 4 0 0 16

What is a String? A string is a series of characters treated as a single unit. Strings can be treated as array of type char used to store names of people, places, or anything that involves a combination of letters. A string may include letters, digits and various special characters such as +, -, *,? and $. String literals, or string constants, in C are written in double quotation marks ( ) as follows: John Doe (a name) 99999 Main Street (a street address) Kangar, Perlis (a city and a state) (012) 123-8755 (a telephone number) 17

What is a String? The data type string is a programmer-defined and is not part of the C language. The C standard library supplies it. A string with no characters is called a null or empty string. is the empty string. Every character in a string has a relative position in the string. The position of the first character is 0, position of the second is 1, and so on. The length of a string is the number of character in it. A string is accessed via a pointer to the first character in the string. The value of a string is the address of its first character. 18

Example String Position of a Character Length of the String in the String William Jacob Position of W is 0 13 Position of the first i is 1 Position of (the space) is 7 Position of J is 8 Position of b is 12 Mickey Position of M is 0 6 Position of i is 1 Position of c is 2 Position of k is 3 Position of e is 4 Position of y is 5 19

String Type To use the data type string, the program must include the header file string. #include <string.h> The statement string acinfo = Welcome ; declares acinfo to be string variable and also initializes info to Welcome. The position of the first character, W, in the info is 0, the position of the second character, e, is 1, and so on. The variable acinfo is capable of storing (just about) any size string. 20

Character Array (string of characters) char acinfo [10]; Can store Welcome, Good Bye. char acname [50]; Able to store shorter strings than total length. The last value in the string will be a null character ( \0 ). 21

Declaration of Strings An example of declaration of an array (or string of characters): acinfo char acinfo [10]; can store a string up to 10 characters long, and may visualize it as below It is not necessary that this max size of 10 characters should at all the times be fully used. acinfo could store at any part of the program either the string of characters Welcome or the string Good Bye. 22

Declaration of Strings (cont..) A null character, constant 0 or \0 can be written at the end of the valid content of a string if the characters to be stored is shorter than its total length (10 in this case). acinfo is an array of 10 elements of type char, could be represented by storing the strings of characters Welcome and Good Bye in the following way: 23

Declaration of Strings (cont..) acinfo W e l c o m e \0 to indicate end of string indefinite values G O o d B y e \0 24

Fundamentals of Strings and Characters String declarations Declare as a character array or a variable of type char * char acinfo[] = Welcome"; char *pcinfo = Welcome"; Remember that strings represented as character arrays end with '\0' acinfo has 8 elements Inputting strings Use scanf scanf("%s", acword); Copies input into acword[] Does not need & (because a string is a pointer (slide 18)) Remember to leave room in the array for the null character ('\0 ) 25

Initialization of string Similar to array, but each character is enclosed in or. Example: char acnewstring[]={ W, e, l, c, o, m, e, \0 }; char acnewstring[]= Welcome ; \0 is automatically inserted. The difference is that single quotes ( ) are used to specify single character constants and null character must be added at the end of the sentence. 26

Initialization of string (cont ) On the other hand, double quotes ( ) are constant that specify sequence of characters and always have a null character ( \0 ) automatically inserted at the end. char acnewstring[]= { W, e, l, c, o, m, e, \0 }; char acnewstring[] = Welcome ; Single quotes null char must be added Double quotes null char automatically inserted 27

Initialization of string (cont ) The examples below are not valid for string of characters (array). newstring = Welcome ; //no [] and data type newstring [] = Welcome ; //no data type newstring = { W, e, l, c, o, m, e, \0 }; //no [] and data type 28

Assigning values to string The left hand side value of an assignation can only be array items and not the entire array, a possible way to assign a string of characters to an array of char can be shown as: acnewstring[0] = W ; acnewstring [1] = e ; acnewstring [2] = l ; acnewstring [3] = c ; acnewstring [4] = o ; acnewstring [5] = m ; acnewstring [6] = e ; acnewstring [7] = \0 ; 29

Calculation of string size char is 1 byte, the total number of alphabets plus a null would be the size of the string. Example program: #include <stdio.h> #include <string.h> char acnewstring[] = {'W','e','l','c','o','m','e','\0'}; char acmystring[] = "Good Bye"; int main() { printf ("Size of acnewstring is %d", sizeof (acnewstring)); //size of string Welcome printf ("\nsize of acmystring is %d", sizeof (acmystring));// size of string Good Bye return 0; } What is the output? 30

Character and string manipulation Examples: a program may need to verify that an ID number of first year students starts with 09. determine whether last three characters in a part number are valid. Built-in functions available makes it easier. 31

Controlling the case of a character K is not equal to k. You use: if (cchoice == K cchoice == k ) while (cchoice == Y cchoice == y ) Can use a function that temporarily converts the letter to uppercase or lowercase before comparing it. strupr(charvariable) strlwr(charvariable) 32

Controlling the case of a character (Example) char cchoice; printf ( Continue? (Y or N) : ); scanf ( %c, &cchoice); while (strupr(cchoice) == Y ) {...... } 33

Controlling the case of a character (Example) char acname[]; printf ( Enter a name : ); scanf ( %s, acname); strupr(acname); printf("the name in uppercase is %s", acname ); 34

Sample Program To convert a string to uppercase #include <stdio.h> #include <string.h> void main() { char acname[20]; /* declare an array of characters 0-79 */ } printf("enter in a name in lowercase\n"); scanf( "%s", acname ); strupr(acname); printf("the name in uppercase is %s", acname ); Output Enter in a name in lowercase john The name in uppercase is JOHN 35

Controlling the case of a character Real value does not changed. The functions only affect characters of letters or alphabets. Does not affect numbers and special characters such as $ and %. If the character is already lowercase or uppercase, the function will not affect the real value. It will return the original value. char crepeat = Y ; cletter = strupr(crepeat); cletter =? 36

Strings Conversion Functions Conversion functions In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point values Prototype double atof( const char *nptr ) int atoi( const char *nptr ) long atol( const char *nptr ) double strtod( const char *nptr, char **endptr ) long strtol( const char *nptr, char **endptr, int base ) unsigned long strtoul( const char *nptr, char **endptr, int base ) Description Converts the string nptr to double. Converts the string nptr to int. Converts the string nptr to long int. Converts the string nptr to double. Converts the string nptr to long. Converts the string nptr to unsigned long. 37

Strings 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 38

ASCII Table ASCII Character Set 0 1 2 3 4 5 6 7 8 9 0 nul soh stx etx eot enq ack bel bs ht 1 If vt ff cr so si dle dc1 dc2 dc3 2 dc4 nak syn etb can em sub esc fs gs 3 rs us sp! # $ % & ` 4 ( ) * +, -. / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 < = >? @ A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z [ \ ] ^ _ a b C 10 d e f g h i j k l M 11 n o p q r s t U v W 12 x y z { } ~ del 39

Sample Program 1 #include <stdio.h> #include <string.h> int main() { char acstring1[ 20 ], acstring2[ 20 ]; int iresult; //declaration of acstring1 and acstring2 printf( "Enter two strings: " ); scanf( "%s %s", acstring1, acstring2 ); iresult = strcmp( acstring1, acstring2 ); //compare between acstring1 and acstring2 } if ( iresult > 0 ) printf( "\"%s\" is greater than \"%s\"\n",acstring1, acstring2 ); else if ( iresult == 0 ) printf( "\"%s\" is equal to \"%s\"\n",acstring1, acstring2 ); else printf( "\"%s\" is less than \"%s\"\n",acstring1, acstring2 ); return 0; 40

Sample Program 1 (cont ) Output Enter two strings: computer programming "computer" is less than "programming" Enter two strings: programming computer "programming" is greater than "computer" 41

Sample Program 2 #include <stdio.h> #include <string.h> int main() { char acstring1[ 20 ], acstring2[ 20 ]; int iresult, icomparecount; printf( "Enter two strings: " ); scanf( "%s %s", acstring1, acstring2 ); printf( "How many characters should be compared: " ); scanf( "%d", &icomparecount ); iresult = strncmp( acstring1, acstring2, icomparecount ); } if (iresult > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", acstring1, acstring2, icomparecount ); else if ( iresult == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", acstring1, acstring2, icomparecount ); else printf( "\"%s\" is less than \"%s\" up to %d characters\n", acstring1, acstring2, icomparecount ); return 0; 42

Sample Program 2 (cont ) Output Enter two strings: computer programming How many characters should be compared: 7 "computer" is less than "programming" up to 7 characters Enter two strings: programming computer How many characters should be compared: 7 "programming" is greater than "computer" up to 7 characters 43

Built in Functions for String Handling strcat Appends a string strchr Finds first occurrence of a given character strcmp Compares two strings strcmpi Compares two strings, non-case sensitive strcpy Copies one string to another strlen Finds length of a string strlwr Converts a string to lowercase strnca t Appends n characters of string strncmp Compares n characters of two strings strncpy Copies n characters of one string to another strnset Sets n characters of string to a given character strrchr Finds last occurrence of given character in string strrev Reverses string strset Sets all characters of string to a given character strspn Finds first substring from given character set in string strupr Converts string to uppercase 44

End Arrays (2) & Strings Q & A! 45