UNIT 5: ARRAY, POINTER, STRING
Arrays is the
collection of similar data items that can be represented by a single variable
name. The individual data data items in an array are called elements.
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.
All arrays
consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Suppose we have
to calculate the average marks of eight students (ie Bina, Deepak, Gita, Hari,
janak, kamal, ram and sita).
If the marks of
each student has a unique variable name, each value should be read separately
as:
Printf (“enter
marks of Bina: “);
Scanf(“%d”,&marks
0);
Printf (“enter
marks of Deepak: “);
Scanf(“%d”,&marks
1);
Printf (“enter
marks of gita: “);
Scanf(“%d”,&marks
2);
………………………..
And so on
To calculate
the average marks we have to calculated as:
Avrg_marks =(
marks0+ marks1+ marks2+ marks3+ marks4+ marks5+ marks6+ marks7)/8
/*avgmarks.c*/
/*calculates
the average of eight students marks*/
int main (void)
{
int I, sum;
int marks[8];
Printf(“enter marks of eight students
\n”);
For(i=0;i<8;i++)
{
Printf(“enter marks of student
%d:”i);
Scanf(“%d”, &marks[i];
}
Sum =0;
For(i=0;i<8;i++)
{
Sum = sum +marks[i];
Printf(“enter marks of student
%d:”sum/8);
return 0;
}
Output:
A sample run of
above program is:
Enter marks of
eight students
Enter marks of
student 0:65
Enter marks of
student 1:70
Enter marks of
student 2:77
Enter marks of
student 3:80
Enter marks of
student 4:89
Enter marks of
student 5:58
Enter marks of
student 6:76
Average marks
is 70
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];
Here balance
is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can
initialize an 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 { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
The above
statement assigns the 5th element in the array with a value of 50.0.
All arrays have 0 as the index of their first element which is also called the
base index and the last index of an array will be total size of the array minus
1. Shown below is the pictorial representation of the 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 the 10th element from the array and assign the
value to salary variable.
To calculate
the average temperature of seven days of the week:
/*avgtemp.c*/
/*calculates
the average of seven days temperature*/
int main (void)
{
int i, sum;
float temp[7];
Printf(“enter temperature of seven days
\n”);
For(i=0;i<7;i++)
{
Printf(“enter temperature of day
%d:”i+1);
Scanf(“%f”, &temp[i]);
}
Sum =0;
For(i=0;i<7;i++)
{
Sum = sum +temp[i];
Printf(“average temperature of
the week= %f”sum/7);
return 0;
}
Output:
A sample run of
above program is:
Enter
temperature of seven days
Enter
temperature of day 1:23
Enter
temperature of day 2:22
Enter
temperature of day 3:20
Enter
temperature of day 4:19
Enter
temperature of day 5:21
Enter
temperature of day 6:23
Enter
temperature of day 7:20
Average
temperature of the week=21.142857
Write a C
program to accept marks of 10 students and print it in ascending order.
#include
<stdio.h>
#include<conio.h>
int main()
{
int marks[10],i,j,temp;
printf("accept marks of
student:");
for(i=0;i<10;i++)
scanf("%d",&marks[i]);
for (i = 0; i < 10; i++)
{
for (j = i+1; j < 10; j++)
{
if (marks[i] >
marks[j])
{
int tmp = marks[i];
marks[i] =
marks[j];
marks[j] = tmp;
}
}
}
printf("\n\nAscending : ");
for (i = 0; i < 10; i++)
printf(" %d\n ",
marks[i]);
return 0;
}
Write a C
program to accept marks of 10 students and print it in descending order.
#include
<stdio.h>
#include<conio.h>
int main()
{
int marks[10],i,j,temp;
printf("accept marks of
student:");
for(i=0;i<10;i++)
scanf("%d",&marks[i]);
for (i = 0; i < 10; i++)
{
for (j = i+1; j < 10; j++)
{
if (marks[i] <
marks[j])
{
int tmp = marks[i];
marks[i] =
marks[j];
marks[j] = tmp;
}
}
}
printf("\n\ndescending :
");
for (i = 0; i < 10; i++)
printf(" %d\n ",
marks[i]);
return 0;
}
Multi-dimensional Arrays in C
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 integer array −
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of 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 considered as a
table which will have x number of rows and y number of columns. A
two-dimensional array a, which contains three rows and four columns can
be shown as follows −
Thus, every element in the 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 the 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 a two-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 the 4th element from the 3rd
row of the array. You can verify it in the above figure. Let us check the
following program where we have used a nested loop to handle a two-dimensional
array −
Example:
#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;
/* 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
Pointer
A pointer
is a variable whose value is the address of another variable, i.e., direct
address of the memory location. The general form of a pointer variable
declaration is −
type *var-name;
Here, type
is the pointer's base type; it must be a valid C data type and var-name
is the name of the pointer variable. The asterisk * used to declare a pointer
is the same asterisk used for multiplication. Take a look at some of the valid
pointer declarations −
int
*ip; /* pointer to an integer
*/
double *dp; /* pointer to a double */
float
*fp; /* pointer to a float */
char
*ch /* pointer to a character
*/
The actual data
type of the value of all pointers, whether integer, float, character, or otherwise,
is the same, a long hexadecimal number that represents a memory address
Why pointers?
Some reasons
to use pointers are:
1. To return more than one value from a called
function to calling function using pass by reference.
2. To pass array and
strings more conveniently from one function to another.
3. To manipulate arrays
more easily and use some portion of it instead of whole array.
4. To create complex data
structures, such as linked lists and binary trees , where one data structure
must contain references to other data structures.
5. To communicate
information about memory , memory allocation function returns the address of allocated memory using
pointers.
Pointer address
In C language address operator &
is used to determine
the address of a variable. The &
(immediately preceding a variable
name) returns the address of the variable associated with it.
Pointer dereferences
Dereferencing
is used to access or manipulate data contained in memory location pointed to by
pointer. * (asteric) is used with pointer variable when dereferencing the
pointer variable, it refers to variable being pointed. So this is called
dereferencing pointer.
Declaration of C Pointer variable
The general syntax of pointer declaration is,
datatype
*pointer_name
;
The data
type of the pointer and the variable
to which the pointer variable is pointing must be the same.
Initialization of C Pointer variable
Pointer Initialization is the process of assigning address of a variable to a pointer
variable. It contains the address of a variable of the same data type.
inta
=10;
int*
ptr
;//pointer declaration
ptr
=&
a
;//pointer initialization
Pointer variable always points to variables of the same
datatype. For example:
inta
;
int*
ptr
=&
a
;
While declaring a pointer variable, if it is not assigned
to anything then it contains garbage value. Therefore, it is recommended to
assign a NULL
value to it,
A pointer that is assigned a NULL
value is called a NULL pointer in C.
int
*
ptr
=NULL;
Pointer Arithmetic
Pointer
arithmetic is one of the powerful features of C language. In pointer
arithmetic, a pointer is valid operand only for the addition (+) and
subtraction (-) operators.
Features of
pointer operand are:
1. An integer can be added
to or subtracted from pointer
2. Pointer can be
subtracted from same type
3. Pointer can not be added
to a pointer
4. Multiplication and
division are not aloowed.
Operation are:
Increment pointer: It is a condition that also comes under addition. When a
pointer is incremented, it actually increments by the number equal to the size
of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it
will increment by 2(size of an int) and the new address it will points
to 1002. While if a float type pointer is incremented then it will
increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a
pointer is decremented, it actually decrements by the number equal to the size
of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it
will decrement by 2(size of an int) and the new address it will points
to 998. While if a float type pointer is decremented then it will
decrement by 4(size of a float) and the new address will be 996.
Below is the
program to illustrate pointer increment/decrement:
// C program to illustrate // pointer increment/decrement #include <stdio.h> // Driver Code int main() { // Integer
variable int N = 4; // Pointer to
an integer int *ptr1, *ptr2; // Pointer stores // the
address of N ptr1 =
&N; ptr2 =
&N; printf("Pointer
ptr1 " "before
Increment: "); printf("%p
\n", ptr1); //
Incrementing pointer ptr1; ptr1++; printf("Pointer
ptr1 after" "
Increment: "); printf("%p
\n\n", ptr1); printf("Pointer
ptr1 before" "
Decrement: "); printf("%p
\n", ptr1); //
Decrementing pointer ptr1; ptr1--; printf("Pointer
ptr1 after" "
Decrement: "); printf("%p
\n\n", ptr1); return 0; } |
Output:
Pointer ptr1 before Increment:
0x7ffcb19385e4
Pointer ptr1 after Increment:
0x7ffcb19385e8
Pointer ptr1 before Decrement:
0x7ffcb19385e8
Pointer ptr1 after Decrement:
0x7ffcb19385e4
Relationship between arrays and pointers
An array is a
block of sequential data. Let's write a program to print addresses of array
elements.
#include <stdio.h>
int main() {
int x[4];
int i;
for(i = 0; i < 4; ++i) {
printf("&x[%d] = %p\n", i, &x[i]);
}
printf("Address of array x: %p", x);
return 0;
}
Output
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
There is a
difference of 4 bytes between two consecutive elements of array x. It is
because the size of int is 4 bytes (on
our compiler).
Notice that,
the address of &x[0] and x is the same. It's because the
variable name x points to the first element of the array.
Relation between Arrays and Pointers
From the above
example, it is clear that &x[0] is equivalent
to x. And, x[0] is equivalent
to *x.
Similarly,
- &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
- &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
- ...
- Basically,
&x[i] is
equivalent to x+i and x[i] is equivalent to *(x+i).
String
String are
form of data used in programming languages for text manipulation, such as
words, name and sentences. By convention, a string in C is an array of
character terminated by the end-of-string sentinel ‘\0’ or null character. The
null character is a byte with value zero. To store the world “Hari” the string
variable should be capable of holding at least 5 characters in total, such as
char name [5];
the variable name can be initialized at the time of
its definition as an array of character as:
char name [ ]
= {‘H’, ‘a’,’r’,’i’,’\0’};
or
char name [ ]=
“Hari”;
in this case
compiler automatically provides the terminating null character. So the contents
of memory will be:
name:
‘H’
|
‘a’
|
‘r’
|
‘i’
|
‘\0’
|
String constant:
A string
constant, syntactically is a sequence of characters enclosed in double quotes.
For example,
“Hari”, is a character array of size five, with the string terminating
character at last. The string constants are different from character constants.
For example, “H” and ‘H’ are not the same. The array “H” has two elements; the
first is character ‘H’ and second is ‘\0’, where as the character ‘H’ has only
one element ‘H’.
String constant example:
Let us see the
following example
printf(“%s”,
“Welcome”);
Here “Welcome”
is a string constant. That mean the string itself is stored somewhere in memory,
but it can’t be changed. Each character occupies one byte of memory, and the
last character of the string is the null character for string termination. The
memory contents is as:
|
W
|
e
|
l
|
c
|
o
|
m
|
e
|
\0
|
|
No comments:
Post a Comment