C ARRAYS.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Chapter 10.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Strings A special kind of array is an array of characters ending in the null character \0 called string arrays A string is declared as an array of characters.
C ARRAYS -a collection of same type data, 1D, 2D- © 1/25.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
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’};
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
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.
Arrays.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous memory allocation.
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.
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.
26/06/ :14:35 CSC Alliance — 1 Kimera Richard Phone: INSTITUTE OF COMPUTER SCIENCE DEPARTMENT.
Pointers and Arrays Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
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.
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.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
INC 161 , CPE 100 Computer Programming
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
(Numerical Arrays of Multiple Dimensions)
Fundamentals of Characters and Strings
Computer Programming BCT 1113
CHP-2 ARRAYS.
© 2016 Pearson Education, Ltd. All rights reserved.
DEPARTMENT OF COMPUTER SCIENCE & APPLICATION
C Scope Rules and Arrays
Quiz 11/15/16 – C functions, arrays and strings
A First Book of ANSI C Fourth Edition
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Arrays in C.
Algorithms & Arrays.
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Arrays, For loop While loop Do while loop
Lecture 8b: Strings BJ Furman 15OCT2012.
Strings.
CNG 140 C Programming (Lecture set 8)
Week 9 – Lesson 1 Arrays – Character Strings
EKT150 : Computer Programming
Declaration, assignment & accessing
Beginning C for Engineers
String What it is Why it’s useful
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Chapter 2 Array and String Visit to more Learning Resources.
UNIT - 3 Noornilo Nafees.
Chapter 8 Character Arrays and Strings
CPS120: Introduction to Computer Science
7 Arrays.
Arrays C provides the option to the user to combine similar data types into a single entity It followed contiguous.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings in C Array of characters is called a string.
C++ Array 1.
CS31 Discussion 1H Fall18: week 6
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Dr. Khizar Hayat Associate Prof. of Computer Science
Introduction to Problem Solving and Programming
Visit for more Learning Resources
Presentation transcript:

C ARRAYS

int studMark0, studMark1, studMark2, ..., studMark999; ARRAYS An array is a collection of elements of the same type that are referenced by a common name. Compared to the basic data type (int, float & char) it is an aggregate or derived data type. All the elements of an array occupy a set of contiguous memory locations. Why need to use array type? Consider the following issue: "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int  studMark0, studMark1, studMark2, ..., studMark999;

ARRAYS Can you imagine how long we have to write the declaration part by using normal variable declaration? void main() { int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000; … return 0; }

ARRAYS By using an array, we just declare like this, int  studMark[1000]; This will reserve 1000 contiguous memory locations for storing the students’ marks. Graphically, this can be depicted as in the following figure.

ARRAYS This absolutely has simplified our declaration of the variables. We can use index or subscript to identify each element or location in the memory. Hence, if we have an index of index, studMark[index] would refer to the indexth element in the array of studMark. For example, studMark[0] will refer to the first element of the array. Thus by changing the value of index, we could refer to any element in the array. So, array has simplified our declaration and of course, manipulation of the data.

ARRAYS One Dimensional Array: Declaration Dimension refers to the array's size, which is how big the array is. A single or one dimensional array declaration has the following form, data_type array_name[array_size]; Here, data_type define the base type of the array, which is the type of each element in the array. array_name is any valid C / C++ identifier name that obeys the same rule for the identifier naming. array_size defines how many elements the array will hold.

ARRAYS For example, to declare an array of 30 characters, that construct a people name, we could declare, char   cName[30]; Which can be depicted as follows, In this statement, the array character can store up to 30 characters with the first character occupying location cName[0] and the last character occupying cName[29].  Note that the index runs from 0 to 29.  In C, an index always starts from 0 and ends with array's (size-1). So, take note the difference between the array size and subscript/index terms.

ARRAYS Examples of the one-dimensional array declarations, int      xNum[20], yNum[50]; float    fPrice[10], fYield; char     chLetter[70]; The first example declares two arrays named xNum and yNum of type int.  Array xNum can store up to 20 integer numbers while yNum can store up to 50 numbers.  The second line declares the array fPrice of type float.  It can store up to 10 floating-point values. fYield is basic variable which shows array type can be declared together with basic type provided the type is similar. The third line declares the array chLetter of type char.  It can store a string up to 69 characters. Why 69 instead of 70? Remember, a string has a null terminating character (\0) at the end, so we must reserve for it.

ARRAYS An array may be initialized at the time of declaration. Array Initialization An array may be initialized at the time of declaration. Giving initial values to an array. Initialization of an array may take the following form, type   array_name[size] = {a_list_of_value}; For example: int    idNum[7] = {1, 2, 3, 4, 5, 6, 7}; float  fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; char   chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'}; The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively. The second line assigns the values 5.6 to fFloatNum[0], 5.7  to  fFloatNum[1], and so on. Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so on.  Note again, for characters we must use the single apostrophe/quote (') to enclose them. Also, the last character in chVowel is NULL character ('\0').

Void main() { int a[5],i; a[0]=4; a[1]=3; a[2]=5; a[3]=55; a[4]=77; a[5]={1,2,3,4,5}; a[]={1,2,3,4,5}; printf(“Enter array Element”); for(i=0;i<5;i++) scanf(“%d”,&a[i]); printf(“%d”,a[i]); }

ARRAYS A two dimensional array has two subscripts/indexes. Two Dimensional/2D Arrays A two dimensional array has two subscripts/indexes.  The first subscript refers to the row, and the second, to the column. Its declaration has the following form, data_type    array_name[1st dimension size][2nd dimension size]; For examples, int  x[3][4]; float matrix[20][25]; The first line declares x as an integer array with 3 rows and 4 columns. Second line declares a matrix as a floating-point array with 20 rows and 25 columns.

2-d Array Declaration and Intialization Ex. int x[2][2]; Initialization Ex. int x[2][2]={{1,2},{3,4}}; //valid int x[2][2]={1,2,3,4}; //valid Row is optional but column should be mention int x[][2]={1,2,3,4}; //valid int x[][2]={{1,2},{3,4}}; //valid int x[][]={{1,2},{3,4}}; //Invalid Error because row and column arenot mentioned.

2 D Array Void main() { int a[3][3],i,j; printf(“Enter Array Element”) for(i=0;i<3;i++) for(j=0;j<3;j++) scanf(“%d”,&a[i][j]); printf(“%d”,a[i][j]); getch(); }

Ques: WAP to perform addition of 2 matrix A and B and store the result in C matrix using 2 dimensional array.

# include <stdio.h> # include <conio.h> void main() { int mata[10][10], matb[10][10], matc[10][10] ; int i, j, row, col ; printf("Enter the order of the matrix : ") ; scanf("%d %d", &row, &col) ; printf("\nEnter the elements of first matrix : \n\n") ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) scanf("%d", &mata[i][j]) ; printf("\nEnter the elements of second matrix : \n") ; scanf("%d", &matb[i][j]) ;

for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) matc[i][j] = mata[i][j] + matb[i][j] ; printf("\nThe resultant matrix is : \n\n") ; { printf("%d \t", matc[i][j]) ; } Output: Enter row=3 Column=3 20 30 25 35 45 35 55 75 12 13 10 10 10 C= 21 32 23 15 16 20 20 20 32 35 36

Strings A special kind of array is an array of characters ending in the null character ‘\0’ called string arrays A string is declared as an array of characters char s[10] char p[30] When declaring a string don’t forget to leave a space for the null character which is also known as the string terminator character

String Initialization of an array of type char for holding strings may take the following form, char array_name[size] = "string"; For example, the array chVowel in the previous example could have been written more compactly as follows, char    chVowel[6] = "aeiou"; When the value assigned to a character array is a string (which must be enclosed in double quotes), the compiler automatically supplies the NULL character but we still have to reserve one extra place for the NULL. For unsized array (variable sized), we can declare as follow, char chName[ ] = “Balaguruswamy"; C compiler automatically creates an array which is big enough to hold all the initializer.

2d Character array(string) Syntax: char array_name[row][column]; Ex: char name[4][4]; char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"}; char Name[][] = {“Sachin", “Sourav", “Rahul", “Dhoni", “Virat", “Raina"}; Format Specifier for string %s

2d Character array(string) If we assign initial string values for the 2D array it will look something like the following, char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"}; Here, we can initialize the array with 6 strings, each with maximum 9 characters long. If depicted in rows and columns it will look something like the following and can be considered as contiguous arrangement in the memory.

Gets and Puts function Scanf is not capable of receiving multi-word string like ‘Parul Institute’ would be unacceptable. So we have to use function call gets for inputting the string and puts for printing the string. Void main() { char name[25]; printf(“Enter your name”); gets(name); puts(“Hello”); puts(name); } Enter you name : Sumit Hello Sumit

ARRAYS The contents of the array in memory after the three strings are read in the array. S1=“you” S2=“are” S3=“cat”

ARRAYS ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56. Take note that for strings the null character (\0) still needed. From the shaded square area of the figure we can determine the size of the array. For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of the colored square. In general, for array_name[x][y]; The array size is = First index x second index = xy. This also true for other array dimension, for example three dimensional array, array_name[x][y][z]; => First index x second index x third index = xyz For example, ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56. And if you want to illustrate the 3D array, it could be a cube with wide, long and height dimensions.

C offers four main operations on strings strlen – return the length of a string strcpy - copy one string into another strcat - append one string onto the right side of the other strcmp – compare alphabetic order of two strings

strcpy strcpy(destinationstring, sourcestring) Copies sourcestring into destinationstring For example strcpy(str, “hello world”); assigns “hello world” to the string str

strlen strlen(str) returns length of string excluding null character strlen(“tttt”) = 4 not 5 since \0 not counted

#include<string.h> Void main() { int len; char ch[6]={“Aman”}; len=strlen(ch); printf(“%d”,len); getch(); }

Example with strlen #include <stdio.h> #include <string.h> main() { int i, count; char x[] = “tommy tucket took a tiny ticket ”; count = 0; for (i = 0; i < strlen(x);i++) if (x[i] == ‘t’) count++; } printf(“The number of t’s in %s is %d \n “, x,count);

Vowels Example with strlen #include <stdio.h> #include <string.h> main() { int i, count; char x[] = “tommy tucket took a tiny ticket ”; count = 0; for (i = 0; i < strlen(x);i++) if ((x[i] == ‘a’)||(x[i]==‘e’)||(x[i]==‘I’)||(x[i]==‘o’)||(x[i]==‘u ’)) count++; } printf(“The number of vowels’s in %s is %d \n “, x,count); }

Example with strcpy #include <stdio.h> #include <string.h> main() { char x[] = “Example with strcpy”; char y[25]; printf(“The string in array x is %s \n “, x); strcpy(y,x); printf(“The string in array y is %s \n “, y); }

strcat strcat(destinationstring,sourcestring) appends sourcestring to right hand side of destinationstring For example if str had value “a big ” strcat(str, “hello world”); appends “hello world” to the string “a big ” to get “ a big hello world”

Example with strcat #include <stdio.h> #include <string.h> main() { char x[] = “Example with strcat”; char y[]= “which stands for string concatenation”; printf(“The string in array x is %s \n “, x); strcat(x,y); }

strcmp strcmp(stringa, stringb) Compares stringa and stringb alphabetically Returns a negative value if stringa precedes stringb alphabetically Returns a positive value if stringb precedes stringa alphabetically Returns 0 if they are equal Note lowercase characters are greater than Uppercase

Example with strcmp #include <stdio.h> #include <string.h> main() { char x[] = “cat”; char y[]= “cat”; char z[]= “dog”; if (strcmp(x,y) == 0) printf(“The string in array x %s is equal to that in %s \n “, x,y); }

End of Array and String