C Scope Rules and Arrays UNIT 4 C Scope Rules and Arrays
C Arrays C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
C Arrays Cont.. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Declaring Arrays 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: type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; Now balance is a variable array which is sufficient to hold up-to 10 double numbers
Initializing Arrays You can initialize array in C either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; You will create exactly the same array as you did in the previous example.
Initializing Arrays Cont.. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th i.e. last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above:
Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays: #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j;
Accessing Array Elements Cont.. /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) printf("Element[%d] = %d\n", j, n[i] ); return 0; When the above code is compiled and executed, it produces the following result: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
Multi- dimensional Arrays C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array: int threedim[5][10][4];
Two- Dimensional Arrays The simplest form of the multidimensional array is the two- dimensional array. A two dimensional array is, in essence, a list of one-dimensional arrays. To declare a two dimensional integer array of size x, y you would write something as follows: type arrayName [ x ][ y ]; Where type can be any valid C data type and arrayName will be a valid C identifier. A two dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimentional array a, which contains three rows and four columns can be shown as below:
Two- Dimensional Arrays Cont.. Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two - Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two- Dimensional Array Elements An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example: int val = a[2][3]; The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array: #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j;
Accessing Two- Dimensional Array Elements /* output each array element's value */ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } return 0; When the above code is compiled and executed, it produces the following result: a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8
Passing Arrays as Function Arguments If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similar way you can pass multi- dimensional array as formal parameters. Way-1 Formal parameters as a pointer as follows. You will study what is pointer in next unit. void myFunction(int *param) { . }
Passing Arrays as Function Arguments Way-2 Formal parameters as a sized array as follows: void myFunction(int param[10]) { . } Way- 3 Formal parameters as an unsized array as follows: void myFunction(int param[]) { . . . . . . . . . }
Passing Arrays as Function Arguments Example /* A Program which reads two integer numbers and finds their sum, difference, multiplication and division using a separate function for each of these operation. */ #include<stdio.h> Float add(int a, int b); Float sub(int a, int b); Float mul(int a, int b); Float div(int a, int b); Main() { int x, y; float a, s ,d, m;
Passing Arrays as Function Arguments Printf(“Enter the values of two variable:”); Scanf(“%d%d”, &x,&y); a= add(x, y); s= sub(x, y); m= mul(x, y); d= div(x, y); Printf(“Addition is : %f \n Subtraction is : %f \n Multiplication is : %f \n Division is : %f”, a,s,m,d); }
Passing Arrays as Function Arguments Float add(int a, int b); { Return (a+b); } Float sub(int a, int b); { Return (a-b); Float mul(int a, int b); { Return (a*b); Float div(int a, int b); { Return (a/b);
C Strings The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that include the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello". Char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; If you follow the rule of array initialization then you can write the above statement as follows: Char greeting[ ] = "Hello";
C Strings Cont.. Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above mentioned string: #include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; } When the above code is compiled and executed, it produces result something as follows: Greeting message: Hello
C Strings Cont.. C supports a wide range of functions that manipulate null-terminated strings:
C Strings Cont.. Following example makes use of few of the above-mentioned functions: #include <stdio.h> #include <string.h> int main () { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* copy str1 into str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); /* concatenates str1 and str2 */
C Strings Cont.. strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); /* total lenghth of str1 after concatenation */ len = strlen(str1); printf("strlen(str1) : %d\n", len ); return 0; } When the above code is compiled and executed, it produces result something as follows: strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 You can find a complete list of C string related functions in C Standard Library.
struper () The strupr functions used to convert characters in string to uppercase. Syntex: strupr (string) # include < stdio.h> # include <string.h> Main () { char arr [10] ; int i, len ; printf( “\n enter string :”) ; scantf ( “%s” ,arr ) ; print ( “The string is Upper Case is : %d’’, strupr (arr)); // convert in uppercase } Output : Enter String : abcd The string in upper Case is : ABCD
Strlwr() The strlwr { } is used to convert characters in string to lower case. Syntex : Strlwr(String ) # include < stdio .h> # include < string .h> main () { char arr [10] ; int i, len; printf ( “ \n enter string :”) ; scantf ( “%s”, &arr ) ; printf ( “The string is Lower Case is : %d’’, stlrwr (arr)) ; // convert in lowercase } Output : Enter String :ABCD The string in lower Case is : abcd
Strrev () The strrev () function is used to convert the srting content in the reserv order. Syntex : strrev(string) # include < stdio.h> # include <string.h> Void Main () { char arr [10] ; printf (“Enter String :”) ; scantf ( “%s” ,&arr ) ; printf( ‘’The string in Reserve Order is : %s’’, strrev (arr)); // reverse the string } Output : Enter String : ABCD The string in Reserv Order is : DCBA
strncat ( ) The strncat ( ) concatenates the content of two string up to length n i.e. appends the source string of the end of the target string up to length n. Syntex : strncat ( target, source ,n); # include < stdio .h> # include < string .h> main () { char s 1 [] = ‘’ Programming’’; char s 2 [] = ‘’ Language ‘’; int n = 4; strncat (s1,s2,n); print (‘’ The concatenated string is % s”, s1); } Output : The concatenated string is: ProgrramingLang Only first four character of the second string is concatenated with the source of string.
# include < stdio .h> # include < string .h> main () { Strcmp() The function strcmp ( ) is used to compare two string up to length n .The function accept two string as parameter and return an integer value, depending upon the relative order of the two string . Syntex : Strcmp (string 1, string 2 ,n) # include < stdio .h> # include < string .h> main () { char s 1 [] = ‘’New Delhi’’; char s 2 [] = ‘’ New York ‘’; int r, n=3; // length n is 3 r= strcmp ( s1,s2,n); // compare first three character only if (r==0) { printf (‘’The string are equal’’); } else { printf (The string are not equal’’); } } Output : The string are equal
Strcmpi () The strcmpi ( ) function is used to compare two string without considering case i.e. ignores the case of characters .The comparison continuous until any character differ or end of string is reached. Syntax : Strcmpi (string 1, string 2 ) # include < stdio .h> # include < string .h> main() { char s 1 [] = ‘’Good ’’; char s 2 [] = ‘’ Morning‘’; int r; r= strcmp ( s1,s2); // compare two string without considering case if (r==0) { printf (‘’The string are equal’’); } else { printf (The string are not equal’’); } } Output : The string are not equal In the above program we compare the content of two string character and also Ignoring the case of character .i.e. string HELLO are same
Strchr () Strchr () is used to find first occurrence of a given character in a string . The function will return a pointer to the character or Null . If the character is not found . Syntax : strchr ( string 1,char) # include < stdio .h> # include < string .h> main () { char s1 [] =‘’ Good ‘’; char ch = G ; int r ; r= strchr(s1 ,ch); //find first occurrence of a given character in a string if (r == NULL) { printf ( ‘’ character not found in string’’ ); } else { printf("character found in string ‘’); } Output: character found in string
C - Storage Classes
C Strings Cont.. There are the following storage classes, which can be used in a C Program: Automatic storage class External storage class Static storage class Register storage class Automatic storage class : A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler.
Automatic storage class Cont.. Syntax: A variable is declared as automatic by its data- type declaration with the specifier auto in the following way: auto data-type variable –name; Following program shows how an automatic storage class variable is declared and fact that if variable is not initialized it contains a garbage value. #include<stdio.h> main() { auto int i,j; printf(“\n %d %d”, i, j); } The output of above program could be… 1211 221 where, 1211 and 221 are garbage values of I and j. when you run this program you may get different values, since garbage values are random
External or Global Storage Class A variable that is declared outside any function is a Global variable. Global variables remain available throughout the entire program. One important thing to remember about global variable is that their values can be changed by any function in the program. To transmit the variables across the functions and blocks, external variables are used. These variables can be accessed by name by any function. When a variable is declared outside a function, storage is permanently assigned to it, and its storage class is extern. External variables never disappear. Because they exist throughout the execution life of the program.
Example Syntax: A variable is declared as external by its data- type declaration with the specifier extern in the following way: extern data- type variable-name; Following example shows definition, declaration and use of external variables: #include<stdio.h> int i, j; main() { printf(“Enter values for i and j:”); scanf(“The value of i is %d and j is %d”, i, j); } Output: Enter values for i and j: 34 12 The value of i is 34 and j is 12
Register Storage Class Automatic variables are allocated storage in the main memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing directly in the CPU. Registers are memory located within the CPU itself where data can be stored and accessed quickly. Normally, the compiler determines what data is to be stored in the registers of the CPU at what times. Thus, register variables provide a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register. Syntax: A variable is declared as register by its data- type declaration with the specifier register in the following way: register data- type variable-name;
Static Storage Class As we have seen, external variables have global scope across the entire program (provided extern declarations are used in files other than where the variable is defined), and have a lifetime over the entire program run. Similarly, static storage class provides a lifetime over the entire program, however; it provides a way to maximum the scope of such variables, and static storage class is declared with the keyword static as the class specifier when the variable is defined. These variables are automatically initialized to zero upon memory allocation just as external variables are. Static storage class can be specified for automatic as well as external variables such as: static extern varx; Syntax: A variable is declared as static by its data- type declaration with the specifier static in the following way: static data- type variable-name;
Example #include <stdio.h> Main() { void increment(void); int i; for(i=0; i<3; i++) { increment(); } Void increment() { int auto_i++=0; static int static_i++=0; printf(“auto=%d \t static=%d \n”, auto_i++, static_i++); Output: auto=0 static=0 auto=0 static=1 auto=0 static=2