






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of character arrays in c programming language, including their initialization, comparison, sorting, and the use of functions. It covers the difference between passing arrays by value and by reference, and includes examples and tips.
Typology: Study notes
1 / 12
This page cannot be seen from the preview
Don't miss anything!







to Program chapter 4 4.4, 4.5, 4.6, 4.8, 4.
on rrays
Deitel & Deitel - C++ How
Character Arrays Initialization Of Character Arrays Arrays Comparis Sorting A Searching arrays Functions And arrays Example 1 Multidimensional Arrays Example 2 Tips
haracter Arrays
hile dealing with words and sentences, we actually make use of character arrays. s and storing integer values. Here we ave to ing a name. A simple variable can't be used a single racter array to grab a name. A character array is not different rom an intege character array, we will write as under: har name [100] ; er array. There are some special properties enter a ters. These characters in the array occupy 15-20 character paces. ow w as happened to the remaining character spaces in e array. Similarly, a question arises, will an array displayed on the screen, show 100 blanks for the remaining. Here C has a haract en we place a string in a puter keeps a mark to identify that the array was of this size hile t strin ze. That marker is a special character, alled null character. The ASCII code of null character is all zeros. In C language, we eprese erminate a string. All ith the null character. ow, w will see how the character arrays are stored in memory. While declaring a haracter array, we normally declare its size larger than the required one. By using a store a string. We declare a character array as nder.
is array simply by using the cin statement in the
; ove statement, there is an array on right hand side of cin instead of a simple has a built-in intelligence that allows the compiler (program) read hole e le character as in case of simple he compiler determines that the name is not a simple variable. ather it is a string or character array. Thus cin reads a character array until the user enter key is pressed, cin takes the whole input (i.e. string) itself, attaches a null character at end of the string. In this way, the total number of spaces occupied in the array by e string is the number of characters entered by the user plus 1 (this one character is e null character inserted at the end of the string by C automatically). The null
be careful while declaring a character array. he size of array should be one more than the number of characters you want to store.
itialization Of Character Arrays
Up to now, we were dealing with integer array h see what needs to be done for stor to store a name (which is a string of characters) as a variable stores only character. We need a cha f r array. To declare a c In this way, we declare a string or charact of character arrays. Suppose that we declare an array of 100 characters. We name with 15-20 charac s N e have to see what h th characters with a name in 15-20 spaces and c er handling capability i.e. the notion of strings. Wh character array, the com w he g stored in it is of the other si c r nt the null character as “ \0 ”. C uses this character to t strings are terminated w N e c character array, it becomes easy to u char name [100] ; Now we can store a string in th following way. cin >> name In the ab variable. The cin stream to w string at a tim rather than a sing variable of type char. T R presses the enter key. When and stores it into the array name. The C language, by the th th character is used to determine where the populated area of the array has ended. If we put a string larger than the size of the array in absence of a null character in it, then it is not possible to determine where a string is terminated in the memory. This can cause severe logical error. So, one should T
In
docsity.com
f the array name up to the null character and the remaining part of the
e s in the first array are equal to the orresponding values of the second array, then both the arrays will be equal. Suppose,
i es. l operator ( != ). The advantage of using not- qual operator is that in case if the values at some position are not equal to each other, remaining values. We terminate the loop here and If the values at a position are equal, we continue to
the characters o array is ignored. When we are displaying the characters one by one, it is necessary to stop the displaying process at the end of a string (which means when null character is reached). For this purpose, we may put a condition in the loop to terminate the loop when the null character is reached. So we can use if statement in the loop to check the null character. We can modify the above for loop so that it could terminate when null c haracter reaches in the array.
for ( i = 0 ; i < 100 ; i ++ ) { if (name [ i ] == ‘\0’) break ;
cout << name [ i ] ; }
Here a while loop can also be used instead of a 'for loop'.
We can use this character-by-character manipulation of the array to compare the characters of two arrays of the same size. Two arrays can be equal only when first of all their sizes are equal. Afterwards, we compare the values of the two arrays with on to one correspondence. If all the value c we have two integer arrays num1 and num2 of size 100 each and want to find whether both arrays are equal. For this purpose, we will declare a flag and set it to zero, that means that arrays are not equal this time. For this flag, we write int equals = 0 ; To compare the values of the arrays one by one, we write a for loop i.e. for ( i = 0 ; < 100 ; i ++ ). In the body of the for loop, we use an if statement to check the valu In the if statement, we use the not equa e then we need not to compare the say that the arrays are not equal. compare the next values. If all the values are found same, we set the flag equal to 1 and display the results that both the arrays are identical. The same criterion applies to character arrays. The comparison of character arrays is very common. While finding a name in a database, we will compare two character arrays (strings). The comparison of two strings is so common in programming that C has a function in its library to manipulate it. We will discuss it later in the lecture on string handling. For the time being, we will write our own function to find the equality of two strings.
Following is the code of a program, which takes two arrays of 5 numbers from the user and compares them for equality.
// This program takes two arrays of 5 integers from user //displays them and after comparing them displays the result
i < 5 ; i ++)
he values in the second array are : “ ; r ( i = 0 ; i < 5 ; i ++ um2 [ i ];
s
{ if ( num1 [ i ] != num2 [ i ] )
equals = 0 ; //set the flag to false
main ( ) { int num1 [5], num2 [5], i, equals = 0 ; // input of 5 integers of first array cout << “Please enter five integers for the first array” << endl ; for ( i = 0 ; cin >> num1 [ i ] ;
// input of 5 integers of 2nd array cout << “Please enter five integers for the second array” << endl ; for ( i = 0 ; i < 5 ; i ++) cin >> num2 [ i ] ;
//display the elements of two arrays cout << “\n The values in the first array are : “ ; for ( i = 0 ; i < 5 ; i ++) cout << “\t” << num1 [ i ] ;
cout << “\n T fo ) cout << “\t” << n
// compare the two array for ( i = 0 ; i < 5 ; i ++ )
{ cout << “\n The arrays are not equal “ ;
break ; } equals = 1; //set flag to true }
if (equals) cout << “\n Both arrays are equal” ; }
Similarly, we can write a program that compares two strings (character arrays) of the same size. While comparing strings, a point to remember is that C language is case- sensitive. In C-language ‘A’ is not equal to ‘a’. Similarly, the string “AZMAT” is no equal to the string “azmat” or “Azmat”.
A sample out-put of the program is given below.
Please enter five integers for the first array
t
docsity.com
echnique of linear search. In this technique, there may be as many mparisons as numbers in the array. We make comparison of the number to be found any number in the array. er by using a binary search algorithm.
ch Algorithm
rch algorithm, the ‘divide and conquer’ strategy is applied. This plies only to sorted arrays in ascending or descending order. Suppose that earch a number in an ascending array. For this purpose, we divide the o parts (say left and right). We compare the target value with the value at ion of the array. If it does not match, we see whether it is greater or less dle value. If it is greater than the middle value, we discard the left part of ing an ascending array, the left part contains the smaller numbers than e middle. Our target number is greater than the middle number. Therefore, it will be the right part of the array. Now we have a sub-array, which is the half of the actual rray (right side portion of main array). Now we divide this array into two parts and is not found, we discard a portion of the array ccording to the result whether target value is greater or less than the middle value. In s
ould ay
en
n
sed value (that has placed at some other place) and manipulates it
to a
to the function. As the array is eclared in the calling function, it is visible there. The calling function knows its size being called does not know the size of the array. So it is necessary to the array along with its name. Suppose we have declared a character array in the program by the following statement:
The same applies to the search algorithms. For finding out a particular number in an array, we can use t co with each number in the array and find it out if it matches However, we can perform even bett
Binary Sear
In binary sea algorithm ap we want to s array into tw middle locat than the mid the array. Be th in a check the target value. If target value a each iteration of testing the target value, we get an array that is half of the previou array. Thus, we find the target value.
The binary search is more efficient than the linear search. In binary search, each iteration reduces the search by a factor of two (as we reduce to half array in each iteration). For example, if we have an array of 1000 elements, the linear search c require 1000 iterations. The binary search would not require more than 10. If an arr has elements 2 n,^ then the maximum number of iterations required by binary search will be n. If there are 1000 elements (i.e. 2^10 , actually it will 1024), the number of iterations would not be more than 10.
In C language, the default mechanism of calling a function is ‘call by value’. Wh we call a function, say fn , and pass it a parameter x (argument value) by writing statement fn(x), the calling mechanism puts the value of x at some other place. The calls the function and gives this value to it. This means a copy of the value is sent to the program. The original x remains untouched and unchanged at its place. The function uses the pas in its own way. When the control goes back to the calling program, the value of original x is found intact. This is the call by value mechanism. Now let’s see what happens when we pass an array to a function. To pass an array function, we will tell the function two things about the array i.e. the name of the array and the size. The size of the array is necessary to pass d but the function pass the size of
rray elements and displays them.
in its return type. Secondly, we nction will get. We write these parameters with
void reverse ( char [], int ) ; ary. These brackets indicate that an r will be passed to the function. If we skip these brackets and simply aracter will be passed to the function. In dition, the second parameter i.e. of type int , is of array's size. Note that in the t is not s of the parameters in function prototype. However, if we an error. The compiler will simply ignore these names. w we will define the function reverse. In the function's definition, we will use the rray and variable names. These names are local to this function so we can give these
stored in it. We call reverse ( ame, 100 ) ; name of the array to the function i.e. name
hich reverses the array and displays it. After this, the control comes back to the main next to the function call statement. The return type of the is void so it does not return any thing. Now in the main, we write the tement cout << name ; What will be displayed by this statement? Whether it will be e orig eversed array. In this stance, we see that whatever the function reverse did to the array ( that was passed It means that the original array in the calling n changed. Here we change (reverse) the order of the characters of s of the array in the calling function are ersed. This means that the called function has not a copy of the array but has the s a copy ' call by value' mechanism, which is by default in case of ys, the by default mechanism is ‘ call by reference’. While ssing arrays to a function, we don’t need to use & and * operators, as we use for echanism. sed to the function. This is ray, the name of the array has the address of
char name[50] ; We have a function (say reverse, you should write it as an exercise) that reverses the a
Firstly, we need to write the prototype of the function reverse. We say that this function returns nothing so we use the keyword void have to write the parameters this fu their type. Now the prototype of this function will be written as
In the above statement, the brackets [] are necess array of type cha write char, it will mean that a single ch ad prototype of the function we have not written the names of the parameters. I necessary to write the name write the names, it is not No a variables a name other than the one used in declaration in the calling program. We write this as below. void reverse ( char characters [], int arraySize ) { // The body of the function. } Here, the body of the function is left over for an exercise.
Let’s say we have a character array name and a name ‘adnan’ is the reverse function by passing the array name to it. For this we write n In this function call, we are sending the and the size of the array that is 100. When this call of the function is executed the control goes to the function reverse. The statements in this function are executed w function to the statement function sta th inal name ‘adnan’ or something else. It will display the r in to it) is appearing in the calling function. program has bee array in the function and find that the character rev original array itself. Whereas in case of simple variables, a called function use of variables passed to it in a simple variables. In arra pa variables in call by reference m Thus if we pass an array to a function, the array itself is pas due to the fact that when we declare an ar
docsity.com
Here in the function getvalues , we can get the values of the array from user by using the cin statement.
Following is the output of the execution of the program. he array is populated with values num[0] = 0
um[2] = 2
um[7] = 7
um[9] = 9
num[1] = 1 n num[3] = 3 num[4] = 4 num[5] = 5 num[6] = 6 n num[8] = 8 n
in daily life. In mathematics, there are rays. Let’s talk about vectors. A vector is a set of values which ave independent coordinates. There may be two-dimensional vector or three-
number of columns. So we can declare an array numbers of two rows and ree columns as follows.
we can do the addition, multiplication and other anipulations of matrices. A value in a two-dimensional array is accessed by using
e can do addition, multiplication and other manipulations of two-dimensional 1, 2, 3 ing n pair of brackets [] after the 7
There may be many applications of arrays many applications of ar h dimensional vector. There are dot and cross products of vectors besides many other manipulations. We do all the manipulations using arrays. We manipulate the arrays with loops. Then there is a mathematical structure matrix, which is in rows and columns. These rows and columns are manipulated in two-dimensional arrays. To work with rows and columns, C provides a structure i.e. a two-dimensional array. A two dimensional array can be declared by putting two sets of brackets [] with the name of array. The first bracket represents the number of rows while the second one depicts the th int numbers [2] [3] ; Using two-dimensional arrays, m the row number and column number. To put values in a two-dimensional array is different from the one-dimensional array. In one-dimensional array, we use a single ' for loop' to populate the array while nested loops are used to populate the two- dimensional array. W arrays. In C language, we can declare arrays of any number of dimensions (i.e. … n ). We declare a n-dimensional array by putt name of the array. So a three-dimensional array with values of dimensions 3, 5 and respectively, will be declared as int num [3] [5] [7] ;
t
mensional array of two rows and three st, we will declare the array by writing int matrix [2] [3] ;
r.
r ( col = 0 ; col < maxcols ; col ++)
alue for position [“ << row << “, ” << col << ”]” ; [row] [col] ; }
ents of the array one row at a time. It fills all the rements the row after each iteration. In the ove code segment, the inner loop executes for each iteration of the outer loop. Thus, hen th row 0, the inner loop is executed for a ons equal to the number of columns i.e. 3 in our program. Thus the ]. Then to 1 and the inner loop is again executed hich completes the second row (i.e. the positions [1,0], [1,1] and [1,2] ). All the having two rows and three columns are found. milarly, to display these values one by one, we again use nested loops.
o
int matrix [2] [3], row, col, maxrows = 2, maxcols = 3 ; // get values for the matrix for ( row = 0 ; row < maxrows ; row ++) { for (col = 0 ; col < maxcols ; col ++) { cout << “Please enter a value for position [“ << row << “, ” << col << ”] ” ; cin >> matrix [row] [col] ; } } // Display the values of matrix cout << “The values entered for the matrix are “ << endl ; for ( row = 0 ; row < maxrows ; row ++)
Let’s have a matrix (two-dimensional array) of two rows and three columns. We wan to fill it with values from the user and to display them in two rows and three columns.
Solution To solve this problem, we use a two-di columns. Fir
We declare different variables in our program. To put the values in the array, we use two nested for loops, which can be written as unde
for ( row = 0 ; row < maxrows ; row ++ ) { fo { cout << “Please enter a v cin >> matrix
}
The inner for loop totals the elem columns of a row. The outer for loop inc ab w e outer loop starts with the value of number of iterati first row is completed for the three columns with positions [0,0], [0,1] and [0, the outer loop increments the row variable w values of matrix Si
Following is the code of the program. //This program takes values from user to fill a two-dimensional array (matrix) having tw //rows and three columns. And then displays these values in row column format.
main ( ) {
docsity.com