Fundamental of Programming (C)

Similar documents
Fundamentals of Programming

ONE DIMENSIONAL ARRAYS

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

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Week 8 Lecture 3. Finishing up C

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Write a C program using arrays and structure

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture5 C Characters and Strings

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Introduction to string

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

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

Chapter 8 Character Arrays and Strings

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

Arrays, Strings, & Pointers

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Array Initialization

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


Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Fundamental of Programming (C)

Principles of C and Memory Management

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

ARRAYS(II Unit Part II)

Chapter 13. Strings. Introduction

C Characters and Strings

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Chapter 8 - Characters and Strings

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Programming Language B

Chapter 10. Arrays and Strings

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

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Fundamental of Programming (C)

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

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Fundamental of Programming (C)

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

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

BİL200 TUTORIAL-EXERCISES Objective:

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

C Strings. Abdelghani Bellaachia, CSCI 1121 Page: 1

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

Chapter 8 C Characters and Strings

LAB7 : Characters and Strings

Intermediate Programming, Spring 2017*

CS 222: Pointers and Manual Memory Management

CSC 2400: Computer Systems. Arrays and Strings in C

Personal SE. Functions, Arrays, Strings & Command Line Arguments

C-LANGUAGE CURRICULAM

Computers Programming Course 11. Iulian Năstac

Create a Program in C (Last Class)

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

ESC101N: Fundamentals of Computing End-sem st semester

Fundamentals of Programming & Procedural Programming

C programming basics T3-1 -

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

CSC 2400: Computer Systems. Arrays and Strings in C

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Multiple Choice Questions ( 1 mark)

Chapter 3: Arrays and More C Functionality

Fundamentals of Programming

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

COMP1917: 09 Arrays and Strings

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

C: How to Program. Week /May/28

C mini reference. 5 Binary numbers 12

Pointers, Arrays, and Strings. CS449 Spring 2016

Computers Programming Course 10. Iulian Năstac

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Arrays, Strings, and Pointers

Approximately a Test II CPSC 206

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

Arrays, Pointers, and Strings

A First Book of ANSI C Fourth Edition. Chapter 9 Character Strings

Arrays, Strings, and Pointers

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

today cs3157-fall2002-sklar-lect05 1

Library Functions. General Questions

Characters and Strings

Fundamentals of Programming

Strings. Daily Puzzle

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

Course organization. Course introduction ( Week 1)

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Transcription:

Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 7 Array and String Department of Computer Engineering

Outline Array String Department of Computer Engineering 2/33

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 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. 0 1 2 3 4 5 6 7 8 9 a 10 You can use a[0]=10; x=a[2]; a[3]=a[2]; etc. You can use scanf("%d",&a[3]); Department of Computer Engineering 3/33

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

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! Department of Computer Engineering 5/33

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. Department of Computer Engineering 6/33

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}; Department of Computer Engineering 7/33

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; Department of Computer Engineering 8/33

A Simple Example #include <stdio.h> #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; } Department of Computer Engineering 9/33

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) Department of Computer Engineering 10/33

Multidimensional Arrays Representation 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] Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] Array name Row subscript int a[n][m] ; &a[i][j] = [(m * i) + j] * (sizeof(int)) + &a[0] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] Column subscript a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Department of Computer Engineering 11/33

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; Department of Computer Engineering 12/33

Examples Initialization Example: short b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 3 2 4 If not enough, unspecified elements set to zero short b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 3 0 4 Department of Computer Engineering 13/33

An Example #include <stdio.h> #include <stdlib.h> 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; } Department of Computer Engineering 14/33

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 Department of Computer Engineering 15/33

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 Department of Computer Engineering 16/33

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'; s h [0] i [1] 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])...! [2] \0 [3]? [4]? [5]? [6]? [7]? [8]? [9] Department of Computer Engineering 17/33

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'; */ char s[ ] = "unix"; /* s has five elements */ Department of Computer Engineering 18/33

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 Department of Computer Engineering 19/33

Example char str[11]="unix and c"; printf("%s", str); printf("\n"); str[6]='\0'; printf("%s", str); printf("\n"); str str u [0] u [0] n [1] n [1] i [2] i [2] x [3] x [3] [4] [4] a [5] a [5] n [6] \0 [6] d [7] d [7] [8] [8] c [9] c [9] \0 [10] \0 [10] printf("\n"); printf(str); printf("\n"); str[2]='i'; printf(str); printf("\n"); str u [0] n [1] I [2] x [3] [4] a [5] \0 [6] d [7] [8] c [9] \0 [10] Department of Computer Engineering 20/33

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"; puts(sentence); // printf("the quick brown fox\n"); Department of Computer Engineering 21/33

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: No ampersand(&) when inputting strings into character arrays! (We ll explain why later ) s1 s1 s2 s2 Department of Computer Engineering 22/33

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); Department of Computer Engineering 23/33

Inputting Strings with gets( ) gets( ) gets a line from the standard input 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); Department of Computer Engineering 24/33

Difference between gets and scanf gets( ) read a line scanf("%s", ) read up to the next space char line[80]; gets(line); puts(line); char line[80]; scanf("%[ ^\n]s", line); printf( %s\n", line); Department of Computer Engineering 25/33

The C String Library String functions are provided in an ANSI standard string library Access this through the include file: #include <string.h> Includes functions such as: Computing length of string Copying strings Concatenating strings Department of Computer Engineering 26/33

strlen strlen returns the length of a NULL terminated character string: size_t strlen (char * str) ; Department of Computer Engineering 27/33

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 Department of Computer Engineering 28/33

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 Department of Computer Engineering 29/33

Example #include <string.h> #include <stdio.h> 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); Department of Computer Engineering 30/33

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 Department of Computer Engineering 31/33

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. Department of Computer Engineering 32/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! Department of Computer Engineering 33/33