UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.

Slides:



Advertisements
Similar presentations
Problem Solving & Program Design in C
Advertisements

EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 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.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
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.
Week 8 Arrays Part 2 String & Pointer
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 10.
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.
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.
Data Structure and C Part-6. Naming a Function Any valid variable-name can be given to the user-defined function. The main program itself is considered.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
1. An array is a collection of a fixed number of components wherein all of the components are of the same type Example: Suppose that there is a list of.
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.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Introduction to C programming
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
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.
Chapter 8: Character and String CMPD144: Programming 1.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
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:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
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).
UniMAP SEM I - 10/11EKT 120 Computer Programming1 Lecture 8 – Arrays (2) and Strings.
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.
Characters and Strings
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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 - 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,
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
INC 161 , CPE 100 Computer Programming
C Characters and Strings
Fundamentals of Characters and Strings
Chapter 8 - Characters and Strings
EKT150 : Computer Programming
C++ Programming Lecture 20 Strings
Characters and Strings Functions
C Characters and Strings
Presentation transcript:

UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings

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

UniMAP SEM I - 09/10EKT 120 Computer Programming3 Passing Arrays to Function void initialize (int list [ ]) { int count; for (count = 0; count < 5; count ++) list [count] = 0; } Initializes int array of size 5 to 0.

UniMAP SEM I - 09/10EKT 120 Computer Programming4 Array as Parameters to Function If size changes (lets say 10 or 20), need to write another function. Introduce another variable, size. void initialize (int list [ ], int size) { int count; for (count = 0; count < size; count ++) list [count] = 0; }

UniMAP SEM I - 09/10EKT 120 Computer Programming5 Constant Arrays Prevent the function from changing the values in array. Use word const in declaration. Function can modify array x but not array y. void example (int x[ ], const int y[ ], int sizeX[ ],int sizeY[]) { ….. …. }

UniMAP SEM I - 09/10EKT 120 Computer Programming6 Initialize an array to 0 void initializeArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) x [counter] = 0; }

UniMAP SEM I - 09/10EKT 120 Computer Programming7 Read data and store it in an array void fillArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) scanf (“%d”, &x [counter]); }

UniMAP SEM I - 09/10EKT 120 Computer Programming8 Displaying array in a function void printArray (const int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) printf (“%d”, x [counter]); }

UniMAP SEM I - 09/10EKT 120 Computer Programming9 Find and return the sum of an array int sumArray (const int x [ ], int sizeX) { int counter; int sum = 0; for (counter = 0; counter < sizeX; counter ++) sum = sum + x [counter]; return sum; }

UniMAP SEM I - 09/10EKT 120 Computer Programming10 Find and return index of largest element of an array int indexLargestElement (const int x [ ], int sizeX) { int counter; int maxIndex = 0; for (counter = 0; counter < sizeX; counter ++) if ( x[maxIndex] < x[counter] ) maxIndex = counter; return maxIndex; }

UniMAP SEM I - 09/10EKT 120 Computer Programming11 Copy an array into another array void copyArray (const int x [ ], int y [ ], int length) { int counter; for (counter = 0; counter < length; counter ++) y [counter] = x [counter]; }

UniMAP SEM I - 09/10EKT 120 Computer Programming12 How Arrays are passed in a function call #include const int arraySize = 10; void initializeArray (int x [], int sizeX); void fillArray (int x [], int sizeX); void printArray (const int x [], int sizeX); int sumArray (const int x [], int sizeX); int indexLargestElement (const int x [], int sizeX); void copyArray (const int x [], int y [], int length);

UniMAP SEM I - 09/10EKT 120 Computer Programming13 How Arrays are passed in a function call int main() { int listA [arraySize] = {0}; int listB [arraySize]; printArray (listA, arraySize); initializeArray (listB, arraySize); printArray (listB, arraySize); fillArray (listA, arraySize); printArray (listA, arraySize); sumArray (listA, arraySize); copyArray (listA, listB, arraySize); printArray (listB, arraySize); return 0; }

UniMAP SEM I - 09/10EKT 120 Computer Programming14 Sample Program #include void printArray (const int a[][3]);// function prototype //function main begins program execution int main() { //initialize array1, array2, array3 int array1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; int array3 [2][3] = { {1, 2 }, { 4 } }; printf (“Values in array1 by row are : \n); printArray (array1); printf ("Values in array2 by row are : \n"); printArray (array2); printf ("Values in array3 by row are : \n"); printArray (array3); return 0; } // end of main

UniMAP SEM I - 09/10EKT 120 Computer Programming15 Sample Program (cont…) //function to display array with two rows and three columns void printArray (const int a[][3]) { int i; //row counter int j; //column counter //loop through row for (i = 0; i <= 1; i++) { //output column values for (j = 0; j <= 2; j++) { printf ("%d ", a[i][j]); } //end inner for printf ("\n"); //start new line of output } //end outer for } //end function printArray

UniMAP SEM I - 09/10EKT 120 Computer Programming16 Sample Program (cont…) Output Values in array1 by row are : Values in array2 by row are : Values in array3 by row are :

UniMAP SEM I - 09/10EKT 120 Computer Programming17 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. Strings can be treated as array of type char used to store names of people, places, or anything that involves a combination of letters. However, as number can be stored as characters, a string can be an array of numbers, too.

UniMAP SEM I - 09/10EKT 120 Computer Programming18 Example StringPosition of a CharacterLength of the String in the String “William Jacob”Position of ‘W’ is 013 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 06 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

UniMAP SEM I - 09/10EKT 120 Computer Programming19 String Type To use the data type string, the program must include the header file string. #include The statement string info = “Welcome”; declares info 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 info is capable of storing (just about) any size string.

UniMAP SEM I - 09/10EKT 120 Computer Programming20 Character Array (string of characters) char info [10]; Can store “Welcome”, “Good Bye”. char name [50]; Able to store shorter strings than total length. The last value in the string will be a null character (‘\0’).

UniMAP SEM I - 09/10EKT 120 Computer Programming21 Declaration of Strings An example of declaration of an array (or string of characters): It is not necessary that this max size of 10 characters should at all the times be fully used. info could store at any part of the program either the string of characters “Welcome” or the string “Good Bye”. info char info [10]; can store a string up to 10 characters long, and may visualize it as below

UniMAP SEM I - 09/10EKT 120 Computer Programming22 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 strings than its total length (10 in this case). info 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:

UniMAP SEM I - 09/10EKT 120 Computer Programming23 Declaration of Strings (cont..) W info elcome\0 GeyBdoO to indicate end of string indefinite values

UniMAP SEM I - 09/10EKT 120 Computer Programming24 Fundamentals of Strings and Characters String declarations Declare as a character array or a variable of type char * char info[] = “Welcome"; char *infoPtr = “Welcome"; Remember that strings represented as character arrays end with '\0' info has 8 elements Inputting strings Use scanf scanf("%s", word); Copies input into word[] Does not need & (because a string is a pointer) Remember to leave room in the array for '\0'

UniMAP SEM I - 09/10EKT 120 Computer Programming25 Initialization of string Same like other array, but each character is enclosed in ‘ ’ or “ ”. Eg: char newstring[]={‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’}; char newstring[]= “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.

UniMAP SEM I - 09/10EKT 120 Computer Programming26 Initialization of string (cont…) On the other hand, double quotes (“) are constant that specify sequence of characters and between double quotes have always a null character (‘\0’) automatically inserted at the end. char newstring[]= {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’}; char newstring[] = “Welcome”; Single quotes – null char must be added Double quotes – null char automatically inserted

UniMAP SEM I - 09/10EKT 120 Computer Programming27 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 Initialization of string (cont…)

UniMAP SEM I - 09/10EKT 120 Computer Programming28 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: newstring[0] = ‘W’; newstring[1] = ‘e’; newstring[2] = ‘l’; newstring[3] = ‘c’; newstring[4] = ‘o’; newstring[5] = ‘m’; newstring[6] = ‘e’; newstring[7] = ‘\0’;

UniMAP SEM I - 09/10EKT 120 Computer Programming29 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 char newstring[] = {'W','e','l','c','o','m','e','\0'}; char mystring[] = "Good Bye"; int main() { printf ("Size of newstring is %d", sizeof (newstring)); //size of string Welcome printf ("\nSize of mystring is %d", sizeof (mystring));// size of string Good Bye return 0; } What are the result?

UniMAP SEM I - 09/10EKT 120 Computer Programming30 Character and String manipulation Eg: 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.

UniMAP SEM I - 09/10EKT 120 Computer Programming31 Controlling the case of a character ‘K’ is not equal to ‘k’. You use: if (choice == ‘K’ || choice == ‘k’) while (choice == ‘Y’ || choice == ‘y’) Can use a function that temporarily converts the letter to uppercase or lowercase before comparing it. strupr(charVariable) strlwr(charVariable)

UniMAP SEM I - 09/10EKT 120 Computer Programming32 Controlling the case of a character (Example) char choice; printf ( “Continue? (Y or N) : “); scanf (“%c”, &choice); while (strupr(choice) == ‘Y’) { ….. }

UniMAP SEM I - 09/10EKT 120 Computer Programming33 Controlling the case of a character (Example) char name[]; printf (“Enter a name : “); scanf (“%s”, name); strupr(name); printf("The name in uppercase is %s", name );

UniMAP SEM I - 09/10EKT 120 Computer Programming34 Sample Program To convert a string to uppercase #include void main() { char name[20];/* declare an array of characters 0-79 */ printf("Enter in a name in lowercase\n"); scanf( "%s", name ); strupr(name); printf("The name in uppercase is %s", name ); } Output Enter in a name in lowercase john The name in uppercase is JOHN

UniMAP SEM I - 09/10EKT 120 Computer Programming35 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 repeat = ‘Y’; letter = strupr(repeat); Letter = ?

UniMAP SEM I - 09/10EKT 120 Computer Programming36 Strings Conversion Functions Conversion functions In (general utilities library) Convert strings of digits to integer and floating-point values

UniMAP SEM I - 09/10EKT 120 Computer Programming37 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 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

UniMAP SEM I - 09/10EKT 120 Computer Programming38 ASCII Table ASCII Character Set nulsohstxetxeotenqackbelbsht 1Ifvtffcrsosidledc1dc2dc3 2dc4naksynetbcanemsubescfsgs 3rsussp!“#$%&` 4()*+,-./ :; 7FGHIJKLMNO 8PQRSTUVWXY 9Z[\]^_’abC 10defghijklM 11nopqrstUvW 12xyz{|}~del

UniMAP SEM I - 09/10 EKT 120 Computer Programming39 Sample Program 1 #include int main() { char string1[ 20 ], string2[ 20 ]; //declaration of string1 and string2 int result; printf( "Enter two strings: " ); scanf( "%s %s", string1, string2 ); result = strcmp( string1, string2 ); //compare between string1 and string2 if ( result > 0 ) printf( "\"%s\" is greater than \"%s\"\n",string1, string2 ); else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\"\n",string1, string2 ); else printf( "\"%s\" is less than \"%s\"\n",string1, string2 ); return 0; }

UniMAP SEM I - 09/10EKT 120 Computer Programming40 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"

UniMAP SEM I - 09/10 EKT 120 Computer Programming41 Sample Program 2 #include int main() { char string1[ 20 ], string2[ 20 ]; int result, compareCount; printf( "Enter two strings: " ); scanf( "%s %s", string1, string2 ); printf( "How many characters should be compared: " ); scanf( "%d", &compareCount ); result = strncmp( string1, string2, compareCount ); if (result > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", string1, string2, compareCount ); else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", string1, string2, compareCount ); else printf( "\"%s\" is less than \"%s\" up to %d characters\n", string1, string2, compareCount ); return 0; }

UniMAP SEM I - 09/10EKT 120 Computer Programming42 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

UniMAP SEM I - 09/10EKT 120 Computer Programming43 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 strncat 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

UniMAP SEM I - 09/10EKT 120 Computer Programming44 End – Arrays (2) & Strings Q & A!