Chapter 2 Array and String. Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose.

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
To remind us We finished the last day by introducing If statements Their structure was:::::::::
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Chapter 8 Arrays and Strings
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Input, Output, and Processing
Topics to be covered  Introduction to array Introduction to array  Types of array Types of array  One dimensional array One dimensional array  Declaration.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
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.
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:
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.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
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.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
UNIT - 3 ARRAYS AND STRINGS. Array An Array is a collection of similar data items, that are stored under a common name. Types –One-Dimensional array –Two-Dimensional.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Explain Declaration,Initialization of Array Explain Types of Array One Dimensional,Two Dimensional and Multi Dimensional Array Explain Arrays.
MAHENDRAN. Session Objectives Explain Declaration,Initialization of Array Explain Types of Array One Dimensional,Two Dimensional and Multi Dimensional.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
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.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
C Formatted Input/Output
Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU.
EGR 2261 Unit 10 Two-dimensional Arrays
BASIC ELEMENTS OF A COMPUTER PROGRAM
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
TMF1414 Introduction to Programming
ICS103 Programming in C Lecture 3: Introduction to C (2)
MULTI-DIMENSIONAL ARRAY
Array 9/8/2018.
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Visit for more Learning Resources
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Programming and Data Structure
Computer Science 210 Computer Organization
CS111 Computer Programming
Chapter 5 POINTERs.
Lecture 8b: Strings BJ Furman 15OCT2012.
Chapter 2 Array and String Visit to more Learning Resources.
UNIT - 3 Noornilo Nafees.
Chapter 8 Character Arrays and Strings
Exercise Arrays.
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Chapter 5 POINTERs Visit to more Learning Resources.
Dr. Khizar Hayat Associate Prof. of Computer Science
Introduction to Problem Solving and Programming
Visit for more Learning Resources
Presentation transcript:

Chapter 2 Array and String

Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose : To store multiple values in a single variable but of same data type. Syntax : datatype arrayname[dim1][dim2]….[dimn]; where dimension indicates number of slots. e.g. int x[5]; => This indicates one dimensional array with 5 slots x

 Memory Requirement Total no of bytes required for any array can be calculated as follows, bytes = size of given data type * dim1*dim2*….*dimn. e.g. int x[5] => bytes = 2*5=10 int y[5][3] => bytes = 2*5*3=30

There are mainly two types of the array: One – Dimentional array Two – Dimentional array  One – Dimentional Array: A list of items can be given one variable name using only one dimension and such a variable is called a one dimensional array. Syntax: datatype array-name[size]; Ex: int a[5];

To access particular slot syntax: arrayname[logical slotno] e.g. a[0]- content of 0 th slot(logical)

If & is placed before the array name with slot no then it indicates the address of corresponding slot. Initialization of one – dimentional arrays:  After an array is declared, its element must be initialized. Otherwise, they will contain “garbage”. An array can be initialized at either of the following stages: 1.At compile time 2.At run time 1. Compile time initialization: Syntax: Type array-name[size] = {list of values}; The value in the list are separed by commas.

Ex: int a[3] = {0,0,0} ; int a[3] = {10, 20, 30, 40} ; will not work. It is illegal in C. Ex:int counter[] = {1,1,1,1} counter array contain four element with initial value 1.

2. Run time initialization : An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. Ex: for(i=0; i<100 ; i++) { if (i < 50 ) sum[i] = 0.0; else sum[i] = 1.0; }

Ex: int x[3]; scanf (“%d%d%d”, &x[0], &x[1], &x[2] ) ; Will initialize array elements with the values entered through the keyboard.

Example – 1 : Accept n nos. in an array and display the sum and average of these n nos. #include void main() { int i,arr[20],n; float sum=0; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); sum += arr[i]; } printf("The sum of the numbers is : %d\n",sum); printf("The average of the numbers is : %.3f\n",sum/n); getch(); }//main Output: Enter the value for n (max 20): 6 Enter 6 numbers : The sum of the numbers is : 248 The average of the numbers is : 41.3

Example – 2 : Accept n elements in an array and sort the array in ascending order. #include void main() { int i,arr[20],n,j,temp; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(arr[i] > arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } printf("\nThe elements in ascending order are :\n"); for(i=0;i<n;i++) printf("%d\t",arr[i]); getch(); }//main Output: Enter the value for n (max 20): 6 Enter 6 numbers : The elements in ascending order are :

Example – 3 : Accept n elements in an array and find the sum of all odd numbers and even numbers. #include void main() { int i,arr[20],n,sum1=0,sum2=0; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++) { if(arr[i]%2 == 0) sum1+=arr[i]; else sum2+=arr[i]; }//for printf("The sum of even numbers is %d\n",sum1); printf("The sum of odd numbers is %d\n",sum2); getch(); }//main Output: Enter the value for n (max 20): 10 Enter 10 numbers : The sum of even numbers is 154 The sum of odd numbers is 125

 TWO – DIMENTIONAL ARRAY: If you want to store data into table or matrix form at that time you can use the two dimensional array. Declaration of two dimentional array: Syntax : data_type array-name[dim1][dim2]; Where dim1 indicates total rows and dim2 indicates total columns. Ex:ITEM 1ITEM2ITEM 3 SALES MAN SALES MAN SALES MAN SALES MAN

Memory representation of the two dimentional array for v[4][3]. column 0 column 1 column2 [0][0][0][1] [0][2] Row 0 [1][0][1][1] [1][2] Row 1 [2][0][2][1] [2][2] Row 2 [3][0][3][1] [3][2] Row

Initializing two dimentional array: Ex: int table[2][3] = {0,0,0,1,1,1}; int table[2][3] = { {0,0,0}, {1,1,1} } ;

Initializing two dimentional array: When the array is completely initialized with all values, we need not specify the size of the first dimension. That is, the statement is permitted. int table[][3] = { {0,0,0}, {1,1,1) };

If the value is missing in an initializes, they are automatically set to zero. Ex: int table[2][3] ={ {1,1}, {2} } ; int m[3][5] = { 0, 0 }; or int m[3][5] = { {0}, { 0} };

Example – 1 : Write a program for addition and subtraction of two matrices. #include void main() { int a[10][10],b[10][10],c[10][10],i,j,r,c; printf(“\n Enter no of rows and columns”); scanf(“%d%d”,&r,&c); printf("Enter %d elements of first matrix\n“,r*c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&a[i][j]); printf("Enter %d elements of second matrix \n“,r*c);

for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&b[i][j]); for(i=0;i<r;i++) for(j=0;j<c;j++) c[i][j] = a[i][j]+b[i][j]; printf("The addition of the two matrices is : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%d\t",c[i][j]); printf("\n"); }

for(i=0;i<r;i++) for(j=0;j<c;j++) c[i][j] = a[i][j]-b[i][j]; printf("The subtraction of the two matrices is : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%d\t",c[i][j]); printf("\n"); } getch(); }

Enter no of rows and columns 3 3 Enter 9 elements of first matrix Enter 9 elements of second matrix The addition of the two matrices is : The subtraction of the two matrices is :

Example – 2 :Write a program to display the transpose of entered matrix #include void main() { int a[5][5],i,j,r,c,b[5][5]; clrscr(); printf(“\n Enter no of rows and columns”); scanf(“%d%d”,&r,&c); printf("Enter %d elements of matrix \n“ r*c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&a[i][j]); for(i=0;i<r;i++) for(j=0;j<c;j++) b[j][i]=a[i][j]);

printf("The transpose of the matrix is : \n\n"); for(i=0;i<c;i++) { for(j=0;j<r;j++) printf("%d\t“,b[i][j]); printf("\n"); } getch(); } Output: Enter no of rows and columns 3 2 Enter 6 elements of matrix The transpose of the matrix is :

 What is a String : String is a group of characters. Any group of character defined between double quotation mark is a constant string. Ex: printf(“Hello How are you”); output : Hello How are you If you want to include double quotes with string than also it is possible. Ex: printf(“\”Hello How are you”\”); output : “Hello How are you” String

Declaring and Initialising String Variable : A String Variable is always declared as an array : Syntax : char string_name[size]; where size determines the number of character in the string. Size should be maximum number of the character + 1. Ex: char city[10]; char name[30];

Initialization of string variable : char array may be initialized when they are declared. You can initialized char array with two form: char city[9] = “New York”; char city[9] = {‘N’, ‘e’, ‘w’, ‘ ’, ‘Y’, ‘o’, ‘r’, ‘k’,’\0’ };

C also permit us to initialize character array without specifying the number of elements. Ex: char string[] = {‘G’,’O’,’O’,’D’,’\0’}; It defines the string as five elements array.

Reading String : Ex: char address[15]; scanf(“%s”,address); (& sign is not included before address) The problem with the scanf() function is that it terminates its input on the first white space it finds. Ex: If input string is “New York” then in address array stores only “New”. After New, string will be terminated. For this reason to read the string gets() function is used which reads white spaces also. Syntax: gets(arrayname); Ex. gets(address);

Writing string to screen : We have used printf() function with %s format to print the string to the screen. Ex: printf(“%s”,name); We can use puts() function to display the string. syntax : puts(stringname); e.g. puts(name);

Features of the %s format specification : (1) The integer value on the right side of the decimal point specifies the number of character to be printed. Ex: %10.4s specifies 4 character printed. (2) When the number of character to be printed is specified by zero, nothing is printed. Ex: %10.0s (3) The minus sign in the specification causes the string to be printed left side. Ex: %-10.4s 4 character printed left side.

Another nice features for printing output is: printf(“%*.*s\n”,w,d,string); prints the first d characters of the string in the field width of w. Write the program for writing string using %s format : void main() { char country[15] = “United Kingdom” printf(“%15s \n”,country); printf(“%5s \n”,country); printf(“%15.6s \n”,country); printf(“%-15.6s \n”,country); printf(“%15.0s \n”,country); printf(“%0.3s \n”,country); } Output : United Kingdom United Uni

The C library provides a function which converts string of digits into their integer value. Ex: number = “1988”; year = atoi(number);  String Handling function : There are mainly four types of string handling function: 1. strcat() – Concatenation of two string 2. strcmp() – Compares two string 3. strcpy() – copies one string over another string 4. strlen() – finds the length of the string.

strcat() : - Using this function you can concat two string: syntax : strcat(string1,string2); Ex: str1 = “Very \0” str2 = “Good\0” str3 =“Bad\0” strcat(str1,str2); output : Very Good\0 It also allows to concat three string together Ex: strcat(strcat(str1,str2),str3); output : Very GoodBad

strcmp() : This function compares two string If both are equal then it returns 0 and if they are not equal then it will return numeric difference between the nonmatching character. Ex: strcmp(“their”,”there”); will return numeric difference between ASCII ‘i’and ‘r’.

strcpy () : using this function we can copy contents of one string to contents of another string. syntax : strcpy(str1,str2); Ex: str1 = “Very \0” str2 = “Good\0” strcpy(str1,str2); will store “Good\0” in str1. strlen() : This function is used to find the length of the string. n = strlen(string); where n is an integer variable. Ex: str1 = “Very \0” will store 5 to n.