You are on page 1of 31

Department of CSE

Arrays

unit-4 programming

C-

An array is collection of logically related data item of same type stored in contiguous memory locations, sharing a common name but separated by subscripts or An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier. For example, an array to contain 5 integer values of type int called billy could be represented like this:

where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length. Like a regular variable, an array must be declared before it is used. Depending on the number of subscripts used,arrays are categorized into one- dimensional arrays,Twodimensional arrays and Multidimensional arrays. One- dimensional arrays: An array with only one subscript is called as one-dimensional array.It is used to store a list of values, all of which share a common name and are seperable by subscript values. . Like a regular variable, an one dimensional array must be declared before it is used. Syntax : type name [size]; where type is a valid type (like int, float...), name is a valid identifier and the size field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain. Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as: int billy [5];

Gonna Institution of Information Technology and Sciences

Page 1

Department of CSE

unit-4 programming

C-

NOTE: The Size field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. Initializing one dimensional arrays. When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros. In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example: int billy [5] = { 16, 2, 77, 40, 12071 }; After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values. for a character array called letters, char letters[6]={a,b,c,d,e}; a 1-d array is used to store a group of values .A loop is used to access each value in group.The following program iiustrate how to process the arrays main( ) { int num[40], ,n,i ; printf(\n How many no. of elements do u want in the array); scanf(%d,n); for ( i = 0 ; i <= n ; i++ ) scanf(%d,&num[i]) ; printf(\n The elements in the array are); for ( i = 0 ; i <= n ; i++ ) printf(%d,num[i]); }

Gonna Institution of Information Technology and Sciences

Page 2

Department of CSE C-programming


Sorting:

unit-4

Selection sort: Selection sort is the most conceptually simple of all the sorting algorithms. It works by selecting the smallest (or largest, if you want to sort from big to small) element of the array and placing it at the head of the array. Then the process is repeated for the remainder of the array; the next smallest element is selected and put into the next slot, and so on down the line. The idea of selection sort is quite simple. Array is imaginary divided into two parts sorted one and unsorted one. At the beginning, sorted part is empty, while unsorted one contains whole array. At every step sort algoritham finds minimal element in the unsorted part and adds it to the end of the sorted one. When unsorted part becomes empty, algoritham stops. When algorithm sorts an array, it swaps first element of unsorted part with minimal element and then it is included to the sorted part.. Let us see an example of sorting an array to make the idea of selection sort clearer. Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort. The selection sort programme is as follows: #include<stdio.h> void main() { int a[25],n,i,min,j,temp; printf(\n how many elements do u want ot enter in the array); scanf(%d,&n); printf(\n Enter the elements into the array); for(i=0;i<n;i++) scanf(%d,&a[i]); printf(\n The elements Before sorting); for(i=0;i<n;i++) printf(%d,a[i]; for (i = 0; i < n; i++) { min = i; for (j = i+1; j <n; j++) { if (a[j] < a[min]) min = j; } temp = a[i];

Gonna Institution of Information Technology and Sciences


Page 3

Department of CSE C-programming


a[i] = a[min]; a[min] = temp; } printf(\n The elements after sorting); for(i=0;i<n;i++) printf(%d,a[i]; } o/p: how many elements do u want ot enter in the array:5 Enter the elements into the array 5,1,12 ,-5,16,2,12,14. The elements before sorting 5,1,12 ,-5,16,2,12,14. The elements after sorting -5,1,2,5,12,14,16 BUBBLE SORT Algorithm

unit-4

1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. 2. If at least one swap has been done, repeat step 1. You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer. Example. Sort {5, 1, 12, -5, 16} using bubble sort.

The programme for Bubble sort is as follows: #include<stdio.h> void main() { int a[25],n,i,j,temp; printf(\n how many elements do u want ot enter in the array); scanf(%d,&n); printf(\n Enter the elements into the array); for(i=0;i<n;i++) scanf(%d,&a[i]); printf(\n The elements Before sorting);

Gonna Institution of Information Technology and Sciences


Page 4

Department of CSE C-programming


for(i=0;i<n;i++) printf(%d,a[i]); for (i = 0; i < n; i++) { for (j = 0; j <n-1-i; j++) { if (a[j+1] < a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } printf(\n The elements after sorting); for(i=0;i<n;i++) printf(%d,a[i]; } O/P: how many elements do u want ot enter in the array:5 Enter the elements into the array 5, 1, 12, -5, 16 The elements before sorting 5, 1, 12, -5, 16 The elements after sorting -5,1,2,5,12,16

unit-4

Insertion sort Algorithm: Insertion sort algorithm somewhat resembles selection sort. Array is imaginary divided into two parts - sorted one and unsorted one. At the beginning, sorted part contains first element of the array and unsorted one contains the rest. At every step, algorithm takes first element in the unsorted part and inserts it to the right place of the sorted one. When unsorted part becomes empty, algorithm stops. Let us see an example of insertion sort routine to make the idea of algorithm clearer. Example. Sort {7, -5, 2, 16, 4} using insertion sort. The programme for Insertion sort is as follows: #include<stdio.h> void main() { int a[25],n,i,j,temp;

Gonna Institution of Information Technology and Sciences


Page 5

Department of CSE C-programming

unit-4

printf(\n how many elements do u want ot enter in the array); scanf(%d,&n); printf(\n Enter the elements into the array); for(i=0;i<n;i++) scanf(%d,&a[i]); printf(\n The elements Before sorting); for(i=0;i<n;i++) printf(%d,a[i]); for (i = 1; i < n; i++) { temp=a[i]; j=i; while((j>0) &&(a[j-1]>index)) { a[j]=a[j-1]; j=j-1; } a[j]=temp; } printf(\n The elements after sorting); for(i=0;i<n;i++) printf(%d,a[i]; } Merging of Two Arrays: The fundamental operation in this algoritham is merging two sorted lists.This algoritham takes two input arrays a and b and an output array c.and three conters idxa,idxb,idxc which are initially set to the beginning of their respective arrays.The smaller of a[indxa],b[indxb] is copied into array c. The following is a simple program that merges two key sequenced integer arrays. #include<stdio.h> #define MAX_LEN 20 void merge(int[], int[], int[],int, int); void main() { int a[10]={2,5,9,16,23,30,44,47,52,60}; int b[5]={3,12,27,39,55}; int alen=10, blen=5; int c[MAX_LEN],i; int idxa=0, idxb=0,idxc=0; printf(first array\n); for(i=0;i<10;i++) printf(%d,a[i]);

Gonna Institution of Information Technology and Sciences


Page 6

Department of CSE C-programming


printf(\n\nsecond array\n); for(i=0;i<5;i++) printf(%d,b[i]); printf(\n\noutput array\n) for(i=0;i<(alen+blen);i++) printf(%d,c[i]); while(idxa<lena && idxb<lenb) { if(a[idxa]<=b[idxa]) { c[idxc]=a[idxa]; idxa++; idxc++; } else { c[idxc]=b[idxb]; idxb++; idxc++; } } if (idxa==lena) { for(i=idxb;i<lenb;i++) { c[idxc]=b[idxb]; idxc++; } } else if(idxb==lenb) { for(i=idxa;i<lena;i++) { c[idxc]=a[idxa]; idxc++; } } } printf(The output array\n); for(i=0;i<(lena+lenb);i++) printf(%d,output[i]); }

unit-4

Gonna Institution of Information Technology and Sciences


Page 7

Department of CSE C-programming

unit-4

Linear Search: In this technique the list will be searched one by one from the beginning until the desired element is found.If the desired element is found in the list then the search is successful otherwise unsuccessful.The example for linear search is
The array we're searching Lets search for the number 3. We start at the beginning and check the first element in the array. Is it 3? Is the first value 3? No, not it. Is it the next element? Is the second value 3? Not there either. The next element? Is the third value 3? Not there either. Next? Is the fourth value 3? Yes!

The following is the program for Linear search; #include<stdio.h> #include<conio.h> void main() { int a[80],n,key,I,flag=0,low,high,mid; clrscr(); printf(Enetr the number of elements); scanf(%d,&n); printf(\n Enter the elements into the array); for (i = 0; i < n; i++) scanf(%d,a[i]); printf(\n Enet rthe element to be searched); scanf(%d,&key); for(i=0;i<n;i++) { if(a[i]==key) { flag=1; break; } }

Gonna Institution of Information Technology and Sciences


Page 8

Department of CSE C-programming


if(flag==1) printf(element found at location %d,i+1); else printf((\n element is not found); } Binary search: Algorithm

unit-4

Algorithm is quite simple. It can be done either recursively or iteratively:


1. get the middle element; 2. if the middle element equals to the searched value, the algorithm stops; 3. otherwise, two cases are possible: searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.

Now we should define, when iterations should stop. First case is when searched element is found. Second one is when subarray has no elements. In this case, we can conclude, that searched value doesn't present in the array.

Examples
Example 1. Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. Step 1 (middle element is 19 > 6): Step 2 (middle element is 5 < 6): Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114 -1 5 6 18 19 25 46 78 102 114 -1 5 6 18 19 25 46 78 102 114

Example 2. Find 103 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. Step 1 (middle element is 19 < 103): -1 5 6 18 19 25 46 78 102 114 Step 2 (middle element is 78 < 103): -1 5 6 18 19 25 46 78 102 114 Step 3 (middle element is 102 < 103): -1 5 6 18 19 25 46 78 102 114 Step 4 (middle element is 114 > 103): -1 5 6 18 19 25 46 78 102 114 Step 5 (searched value is absent): -1 5 6 18 19 25 46 78 102 114

The programme for binary search is as follows: #include<stdio.h> #include<conio.h> void main() { int a[80],n,key,I,flag=0,low,high,mid;

Gonna Institution of Information Technology and Sciences


Page 9

Department of CSE C-programming


clrscr(); printf(Enetr the number of elements); scanf(%d,&n); printf(\n Enter the elements into the array); for (i = 0; i < n; i++) scanf(%d,a[i]); printf(\n the elements after sorting); for (i = 0; i < n; i++) { for (j = 0; j <n-1-i; j++) { if (a[j+1] < a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } for (i = 0; i < n; i++) printf(%d,a[i]); printf(\n Enet rthe element to be searched); scanf(%d,&key); low=0; high=n-1; while(low<=high) { nid=(low+high)/2; if(a[mid]==key) { flag=1; break; } else { if(key<a[mid]) high=mid-1; else low=mid+1; } } if(flag==1) printf(element found at location %d,mid+1); else

unit-4

Gonna Institution of Information Technology and Sciences


Page 10

Department of CSE C-programming


printf(\n elements is not found); }

unit-4

Two- dimensional arrays: An array with two subscripts is termed as two-dimensional array. A two-dimensional array can be thought of as a group of one or more one-dimensional arrays, all of which share a common name and are separable by subscript values. We know that a one-dimensional array can store a row of elements, so, a two dimensional array enables us to store multiple rows of elements.

Declaration of two-dimensional arrays: The general form of declaring a two-dimensional array is:
data_type array_name [rowsize] [colsize]

data_type refers to any valid C data type, array_name refers to any valid C identifier, row size indicates the number of rows and colsize indicates the number of elements in each row. Rowsize and colsize should be integer constants. Each element in a two-dimensional array is identified by the array name followed by a pair of square brackets. Ex: int x [2][2]; X is declared to be an array of two-dimensions and of data type int. rowsize and colsize of x are 2 and 2. Here memory gets allocated to store the array x as follows: 0 0 1 Initialization of two-dimensional array: We can initialize a two-dimensional array also while declaring it, as we initialize. There are two forms of initializing a two-dimensional array; 1. First form of initializing a two-dimensional array:
data_type array_name [rowsize][colsize] = {initialize_list};

X[0][0] X[0][1] X[1][0] X[1][1]

Gonna Institution of Information Technology and Sciences


Page 11

Department of CSE C-programming

unit-4

If the number of values in initalizer_list is equal to the product of rowsize and colsize, the first rowsize values in the initializer_list will be assigned to the first row, the second rowsize values will be assigned to the second row of the array and so on. Ex: int x[2][4] = {1,2,3,4,5,6,7,8}; Since colsize is 4, the first 4 values of the initialize_list are assigned to first row of x and next 4values are assigned of the second row of x as shown here in after. 1 5 2 6 3 7 4 8

2. Second form of initializing a two-dimensional array:


data_type array_name [rowsize][colsize] = { {initialize_list}, {initialize_list}, {initialize_list}..};

The values in initialize_list 1 are assigned to the locations in the first row. The values in initialize_list 2 are assigned to the locations in second row and so on. Ex: int x [2] [4] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; The result of this, the array x gets filled up as follows: 1 5 2 6 3 7 4 8

Processing of two-dimensional arrays: Program: #include<stdio.h> #include<conio.h> void main() { Int x[3][3], i,j; clrscr(); printf(Enter the elements of matrix x of order 3*3\n); for (i=0;i<3;i++) for (j=0;j<3;j++) scanf (%d,&x[i][j]); printf(matrix x\n); for (i=0;i<3;i++) {

Gonna Institution of Information Technology and Sciences


Page 12

Department of CSE C-programming

unit-4

for (j=0;j<3;j++) printf (%d,x[i][j]) ; printf (\n); } getch(); } Input and output: Enter the elements of matrix x of order 3*3 10 20 30 40 50 60 70 80 90 Matrix x 10 20 30 40 50 60 70 80 90 In above program x has been declared to be an array of two dimensions, with rowsize3, colsize3, and thus it can accommodate a table of values (matrix) consisting of 3 rows and 3 columns. As can be seen, both while reading into the array and reading from the array to display them, two loops have been used. The outer loop (i loop) is used to select each row of the table, the inner loop (j loop) is used to select each element in the row selected by i loop. When i=0(first row) j ranges from 0 to 2 t select all the elements of the first row. i=1(second row) j ranges from 0 to 2 t select all the elements of the second row. i=3(third row) j ranges from 0 to 2 t select all the elements of the third row. /* Write a C program to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices */ I) #include<stdio.h> void main() { int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10]; clrscr(); printf("Input rows and columns of A & B Matrix:"); scanf("%d%d",&r1,&c1); printf("Enter elements of matrix A:\n"); for(i=0;i<r1;i++)

Gonna Institution of Information Technology and Sciences


Page 13

Department of CSE C-programming


{ for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("Enter elements of matrix B:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&b[i][j]); } printf("\n =====Matrix Addition=====\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d",a[i][j]+b[i][j]); printf("\n"); } } II)Matrix Multiplication: #include<stdio.h> void main() { int ch,i,j,m,n,p,q,k,a[10][10],b[10][10],c[10][10]; clrscr(); printf("Input rows and columns of A matrix:"); scanf("%d%d",&m,&n); printf("Input rows and columns of B matrix:"); scanf("%d%d",&p,&q); if(n==p) { printf("matrices can be multiplied\n"); printf("resultant matrix is %d*%d\n",m,q); printf("Input A matrix\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("Input B matrix\n"); for(i=0;i<p;i++) for(j=0;j<q;j++)

unit-4

Gonna Institution of Information Technology and Sciences


Page 14

Department of CSE C-programming


scanf("%d",&b[i][j]); /*For Multiplication of two matrices*/ printf("\n =====Matrix Multiplication=====\n"); for(i=0;i<m;++i) for(j=0;j<q;++j) { c[i][j]=0; for(k=0;k<n;++k) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } printf("Resultant of two matrices multiplication is:\n"); for(i=0;i<p;i++) for(j=0;j<q;j++) printf("%5d",c[i][j]); } }

unit-4

Program: Transpose of a matrix #include<stdio.h> #include<conio.h> #include<process.h> void main() { int x[5][5], y[5][5], z[5][5], m,n,p,q,i,j; clrscr(); printf(Enter the number of rows and columns of matrix x\n); scanf (%d%d,&p,&q); for (i=0;i<p;i++) for (j=0;j<q;j++) scanf (%d,&x[i][j]); printf(matrix x\n); for (i=0;i<p;i++) { for (j=0;j<q;j++) printf (%d,x[i][j]) ; printf (\n); }

Gonna Institution of Information Technology and Sciences


Page 15

Department of CSE C-programming


/*the transpose of matrix*/ for (i=0;i<p;i++) { for (j=0;j<q;j++) { y[i][j]=x[j][i]; } } for (i=0;i<p;i++) { for (j=0;j<q;j++) printf (%d,y[i][j]) ; printf (\n); } getch(); }

unit-4

Multidimensional Arrays:
Multidimensional arrays can have three ,four,or more dimensions.An array with three subscripts is called three dimensional arrays,all of which share a common name and separated by its subscript.

Declaration of three-dimensional arrays: The general form of declaring a three-dimensional array is:
data_type array_name [size1][size2][size3];

data_type refers to any valid C data type, array_name refers to any valid C identifier, size1 indicates the number of tables being grouped together,size2 indicates the number of rows in each table and size3 indicates the number of columns in each table.sizes should be integer constants. Example: Ex: int x [2][3][4]; X is declared to be an array of three-dimensions and of data type int. It can accommodate two table values,each tablehaving three rows and four columns. Processing Three dimensional Arrays: #include<stdio.h> #include<conio.h> void main() {

Gonna Institution of Information Technology and Sciences


Page 16

Department of CSE C-programming

unit-4

int x[2][3][3],i,j,k; clrscr(); printf(\n Enter the elements in to the three dimensional arrays); for (i=0;i<2;i++) for (j=0;j<3;j++) for (k=0;k<4;k++) scanf (%d,&x[i][j][k]); printf(The elements in matrix are \n); for (i=0;i<2;i++) for (j=0;j<3;j++) for (k=0;k<4;k++) printf (%d,x[i][j]) ; printf (\n); } In above program x has been declared to be a three-dimensional array of size 2*3*3. The array x can thus accommodate two tables, eachwith thre rows and columns. The outer most loop(i loop) is to select each table. J loop is used to select each row of the table selected by i . the inner most loop (k loop) is used to select the elements of the row selected by j. when i=0 (first table) j=0(first row in first table) k ranges from 0 to 2 to select all the elements in the first row of the first table. j=1(second row in first table) k ranges from 0 to 2 to select all the elements in the second row of the first table. j=2(third row in first table) k ranges from 0 to 2 to select all the elements in the third row of the first table. All the elements of the first table have now been accessed. when i=1,then the second table elements also accessed in the same manner. Merging of arrays: Merging of lists is quite a common process. Whenever a list has a very large number of entries, it is broken up into manageable pieces and stored. The pieces of the list are merged together whenever required. Another common application of merging is in the merge sort. Where the list is recursively broken up into sub-lists and then the sub-lists are merged. In merge sort, the sorting actually a takes place in the merge step. When we merge data from two arrays, the resulting array contains the data in key sequenced order. The merging algorithm is simple. 1. Read a data element from each array. 2. Compare the data elements .

Gonna Institution of Information Technology and Sciences


Page 17

Department of CSE C-programming

unit-4

3. Write the smaller/larger data element to the output array(depending on the

sequence of the arrays to be merged. Of course, the sequence must be the same in both arrays). 4. Read the next element from the array whose element was written to the output array. 5. Continue the loop. As soon as the end of either array is reached , the remaining part of the other array is copied to the output array. Strings Input/Output Functions: Reading the data from the input devices and displaying the results on the screen are the main two tasks of any program.To perform input and ouput tasks we have input and output functions.We send the data through input functions to the program and display the data by using output fuctions. I/O functions are two types .They are 1)Unformatted I/o functions. 2)Formatted I/O functions. Unformatted I/O Functions:These functions are used to input/output a single/group of characters. getchar():It reads single character.The syntax is as follows sy: char variable=getchar(); ex: char x; x=getchar(); putchar():This function is used to display a character.The syntax is as follows sy: putchar(character variable); ex: char x=c; putchar(x); The following program illustrate the concept of getchar() & putchar(); #include<stdio.h> main() { Char ch; Printf(\n Enter any alphabet either in lower case or upper case); Ch=getchar(); If(islower(ch))

Gonna Institution of Information Technology and Sciences


Page 18

Department of CSE C-programming

unit-4

Putchar(toupper(ch)); else Putchar(tolower(ch)); } O/p:Enter any alphabet in lower or uppercase s S getc():This function is used to read a single character.The syntax is as follows sy:char variable=getc(); char c=getc(); putc():This function is used to display a single character.The syntax is as follows sy:putc(character variable); ex:putc; The following program explains the concept of getc() &putc() #include<stdio.h> main() { Char ch; Printf(\n Enter any alphabet either in lower case or upper case); Ch=getc(); If(islower(ch)) putc(toupper(ch)); else putc(tolower(ch)); } o/p: Enter any alphabet in lower or uppercase s S gets() and puts(): The gets() function is used to read the string.The syntax is as follows Sy:gets(character type of array variable); Ex:char name[50]; gets(name); The puts function is used to display the string.The syntax is as follows Sy: puts(character type of array variable); Ex:puts(name); The following program explains gets()and puts() function. #include<stdio.h> main()

Gonna Institution of Information Technology and Sciences


Page 19

Department of CSE C-programming

unit-4

{ char name[50]; puts(Enter name); gets(name); puts(The name is); puts(name); } o/p:Enter name:Siva ram. The name is:siva ram. getch ()and getche(): The getch() reads a single character and it does not display character on the screen. The getche () reads a single character and echoes on the screen. The following program illustrate the concept of getch() and getche() #include<stdio.h> main() { char ch; char c; printf(\n input a character); ch=getch(); printf(%c,ch); printf(\n enter a character); c=getche(); printf(%c,c); } o/p:input a character a a enter a character b b

The formatted input/output functions: scanf():


The scanf function: read information from a standard input device (keyboard).
scanf("conversion specifier", variable);

Gonna Institution of Information Technology and Sciences


Page 20

Department of CSE C-programming

unit-4

The conversion specifier argument tells scanf how to convert the incoming data. 1. scanf starts with a string argument and may contain additional arguments. 2. Additional arguments must be pointers. 3. scanf returns the number of successful inputs. Common Conversion Specifiers Used with Scanf Conversion Specifier %d %f %c Description Receives integer value Receives floating-point numbers Receives character

%s

Receives string

While reading the strings the scanf() function skips the white spaces until it finds a character.Once it finds the character ,it continues reading characters until a white space.

inclusion of field width: A positive number between the percent sign and the conversion character in a conversion specification to specify the field width of the input data.The field width specifies maximum number of characters to be read.The number of characters in the input field may be less than the specified field width.But the number of characters read from the input field never exceeds the specified field width.If it exceeds it discard the remaining characters. Ex:scanf(%19s,name) In above example the scanf can read 19 characters. If we pass more than 19 it discards all remaining characters after 19th character. Sometimes it is easier to specify what is not to be included in the scan set rather than what is valid. For instance, suppose that we want to read a whole line. We can do this by stating that all characters except the newline*(\n) are valid. To specify invalid characters, we start the scan set with the caret (^) symbol. The

Gonna Institution of Information Technology and Sciences


Page 21

Department of CSE C-programming

unit-4

caret is the negation symbol and in effect says that the following characters are not allowed in the string. To read a line, we would code the scanf as shown below. scanf (%81[\n], line); In this example, scanf reads until it finds the newline and then stops.

The scan set conversion code: We can use scan set conversion code to read strings. The scan set identify the valid characters. The scanset conversion specification consists of the open bracket([),followed by the edit characters and terminated by close bracket(]) Edited conversion reads the input stream as a string. Each character read by scanf/fscanf is compared against the scan set. If the character just rad is nin the scan set, it is placed in the string and the scan continues. The first character that does not match the scan set stops the read. The nonmatching character remains in the input stream for the next read operation. If the first character read is not in the scan set, the scanf/fscanf terminates and a null staring is returned. Ex:scanf(%10[0123456789],str) In the above example the scanf can read 10 characters and characters should be from 0to 9 only.It checks each character in input string with scanset.If the character matches with scan set then it is placed in string .

Gonna Institution of Information Technology and Sciences


Page 22

Department of CSE C-programming

unit-4

String "Merkkijono" stored in memory C has no string handling facilities built in; consequently, strings are defined as arrays of characters. C allows a character array to be represented by a character string rather than a list of characters, with the null terminating character automatically added to the end. For example, to store the string "Merkkijono", we would write char string[] = "Merkkijono"; or char string[] = {'M', 'e', 'r', 'k', 'k', 'i', 'j', 'o', 'n', 'o', '\0'}; In the first example, the string will have a null character automatically appended to the end by the compiler; by convention, library functions expect strings to be terminated by a null character. The latter declaration indicates individual elements, and as such the null terminator needs to be added manually. Strings do not always have to be linked to an explicit variable. As you have seen already, a string of characters can be created directly as an unnamed string that is used directly (as with the printf functions.) To create an extra long string, you will have to split the string into multiple sections, by closing the first section with a quote, and recommencing the string on the next line (also starting and ending in a quote): char string[] = "This is a very, very long " "string that requires two lines."; While strings may also span multiple lines by putting the backslash character at the end of the line, this method is deprecated. There is a useful library of string handling routines which you can use by including another header file. #include <string.h> //new header file In the following example, a character based array named word is declared, and each element is assigned a character. The last element is filled with a zero value, to signify the end of the character string (in C, there is no string type, so character based arrays are used to hold strings). A printf statement is then used to print out all elements of the array.

Gonna Institution of Information Technology and Sciences


Page 23

Department of CSE C-programming


/* Introducing array's, 2 */ #include <stdio.h> main() { char word[20];

unit-4

word[0] = 'H'; word[1] = 'e'; word[2] = 'l'; word[3] = 'l'; word[4] = 'o'; word[5] = 0; printf("The contents of word[] is -->%s\n", word ); } Sample Program Output The contents of word[] is Hello CHARACTER ARRAYS [STRINGS] Consider the following program, #include <stdio.h> main() { static char name1[] = {'H','e','l','l','o'}; static char name2[] = "Hello"; printf("%s\n", name1); printf("%s\n", name2); } Sample Program Output Helloxghifghjkloqw30-=kl`' Hello The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in name2[5], whilst name1 has not. This can often result in garbage characters being printed on the end. To insert a null at the end of the name1 array, the initialization can be changed to,

Gonna Institution of Information Technology and Sciences


Page 24

Department of CSE C-programming


static char name1[] = {'H','e','l','l','o','\0'};

unit-4

Consider the following program, which initialises the contents of the character based array word during the program, using the function strcpy, which necessitates using the include file string.h #include <stdio.h> #include <string.h> main() { char word[20]; strcpy( word, "hi there." ); printf("%s\n", word ); } Sample Program Output hi there. DECLARING ARRAYS Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program. /* Introducing array's */ #include <stdio.h> main() { int numbers[100]; float averages[20]; numbers[2] = 10; --numbers[2]; printf("The 3rd element of array numbers is %d\n", numbers[2]); } Sample Program Output The 3rd element of array numbers is 9

Gonna Institution of Information Technology and Sciences


Page 25

Department of CSE C-programming

unit-4

The above program declares two arrays, assigns 10 to the value of the 3rd element of array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number of elements that each array is to have is included inside the square brackets. SOME VARIATIONS IN DECLARING ARRAYS int numbers[10]; static int numbers[10] = { 34, 27, 16 }; static int numbers[] = { 2, -3, 45, 79, -14, 5, 9, 28, -1, 0 }; static char text[] = "Welcome to New Zealand."; static float radix[12] = { 134.362, 1913.248 }; double radians[1000];

Accessing the values of an array. In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as: name[index] Following the previous examples in which billy had 5 elements and each of those elements was of type int, the name which we can use to refer to each element is the following:

For example, to store the value 75 in the third element of billy, we could write the following statement:

Gonna Institution of Information Technology and Sciences


Page 26

Department of CSE C-programming


billy[2] = 75;

unit-4

and, for example, to pass the value of the third element of billy to a variable called a, we could write: a = billy[2];

Therefore, the expression billy[2] is for all purposes like a variable of type int. Notice that the third element of billy is specified billy[2], since the first one is billy[0], the second one is billy[1], and therefore, the third one is billy[2]. By this same reason, its last element is billy[4]. Therefore, if we write billy[5], we would be accessing the sixth element of billy and therefore exceeding the size of the array. int billy[5]; billy[2] = 75; // declaration of a new array // access to an element of the array.

If we wish to initialize as we declare, we write: int point[6]={0,0,1,0,0,0}; If not all elements in the array are initialized, the remaining elements will contain a value of 0. If we want to access a variable stored in an array, for example with the above declaration, the following code will store a 1 in the variable x int x; x = point[2]; ASSIGNING INITIAL VALUES TO ARRAYS The declaration is preceded by the word static. The initial values are enclosed in braces, eg,

#include <stdio.h> main()

Gonna Institution of Information Technology and Sciences


Page 27

Department of CSE C-programming


{ int x; static int values[] = { 1,2,3,4,5,6,7,8,9 }; static char word[] = { 'H','e','l','l','o' }; for( x = 0; x < 9; ++x )

unit-4

printf("Values [%d] is %d\n", x, values[x]); }

Sample Program Output Values[0] is 1 Values[1] is 2 .... Values[8] is 9

The previous program declares two arrays, values and word. Note that inside the squarebrackets there is no variable to indicate how big the array is to be. In this case, C initializes the array to the number of elements that appear within the initialize braces. So values consist of 9 elements (numbered 0 to 8) and the char array word has 5 elements.

The following program shows how to initialise all the elements of an integer based array to the value 10, using a for loop to cycle through each element in turn.

#include <stdio.h> main()

Gonna Institution of Information Technology and Sciences


Page 28

Department of CSE C-programming


{ int count; int values[100]; for( count = 0; count < 100; count++ ) values[count] = 10; }

unit-4

MULTI DIMENSIONED ARRAYS Multi-dimensioned arrays have two or more index values which specify the element in the array.

multi[i][j] In the above example, the first index value i specifies a row index, whilst j specifies a column index.

Declaration and calculations

int

m1[10][10];

static int m2[2][2] = { {0,1}, {2,3} };

sum = m1[i][j] + m2[k][l];

NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the braces are,

{ 0, 1 },

Gonna Institution of Information Technology and Sciences


Page 29

Department of CSE C-programming


{ 2, 3 }

unit-4

Remember that arrays are split up into row and columns. The first is the row, the second is the column. Looking at the initial values assigned to m2, they are,

m2[0][0] = 0 m2[0][1] = 1 m2[1][0] = 2 m2[1][1] = 3

Example : Given a two dimensional array write a program that totals all elements printing the total.

#include <stdio.h> main() { static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} }; int row, column, sum; sum = 0; for( row = 0; row < 4; row++ ) for( column = 0; column < 3; column++ ) sum = sum + m[row][column]; printf("The total is %d\n", sum ); }

Gonna Institution of Information Technology and Sciences


Page 30

Department of CSE C-programming

unit-4

Multidimensional arrays Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.

jimmy represents a bidimensional array of 3 per 5 elements of type int.

Gonna Institution of Information Technology and Sciences


Page 31

You might also like