0% found this document useful (0 votes)
8 views40 pages

C_Arrays

Uploaded by

YASIR TP
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views40 pages

C_Arrays

Uploaded by

YASIR TP
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

ARRAYS

So far we have used only fundamental data types ,namely char ,


int ,float ,double etc;

Variables of these types can store only one value at a given time.

We need a powerful data type that would facilitate efficient


storing or accessing and manipulation of values

Some examples where the concept of array can be used:


oList employees in an organization
oTest scores of a class students
oList of customers and their telephone numbers.
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.
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:
eg: 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:

Compile time Initialization


double balance[5] = {1000.0, 2.0, 3.4, 17.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
• 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, 17.0, 50.0};
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:
#include <stdio.h>
void main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* 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[j] );
}
getch();
}
o/p:

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
C
programming language allows
multidimensional arrays. Here
is the general form of a
multidimensional array
declaration:
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:
Declaration:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a
valid C identifier.
Eg: int mat1[3][3];

A two-dimensional array can be think as a table which will have x


number of rows and y number of columns. A 2-dimensional array a,
which contains three rows and four columns can be shown as below:
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.
Compile time initialization

int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11}};


int a[ ][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11}};
int a[3 ][4] = { {0, 1, 2} , {4, 5, 6, 7} , {8 }};

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};
int a[3][4] = {0,1,2,3,4,5,6,7,8};
When all elements are to be initialized to zero ,the following shortcut
method may be used.
int a[3 ][4] = { {0} , {0} , {0}};
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;
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:
void 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] );
}
}
getch();
}
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
void main () {
{ for ( j = 0; j < 2; j++ )
/* an array with 5 rows and 2 columns*/ {
int a[3][4] ; printf("a[%d][%d] = %d\n", i,j, a[i][j] );
int I,j; }
Printf(“Enter the elements of matrix”); }
for ( i = 0; i < 3; i++ ) getch();
{ }
for ( j = 0; j < 4; j++ )
{
scanf(“%d”,&a[i][j]);
}
}
/* output each array element's value */
for ( i = 0; i < 5; i++ )
a[0][0]: 0
a[0][1]: 0
a[1][0]: 0
a[1][1]: 0
a[2][0]: 0
a[2][1]: 0
a[3][0]: 0
a[3][1]: 0
a[4][0]: 0
a[4][1]: 0
STRINGS
A string is a sequence of characters that is treated as a single data
item.
Any group of characters defined between double quotation marks is
a string constant.
Eg:”Balaguru Swami”

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 comprise the
string followed by a null.
Declaration and Initialization of Strings:

C does not support c as a data type.


It allows to represent string as a character arrays.
 General form of declaration of string is:-

char string_name[size]
Eg:
char greeting[6]
char city[10]
char nam[20]
C permits strings to be initialized in either of the following two forms:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char greeting[] = "Hello";


Note:
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>

void main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
getch();
}

o/p:

Greeting message: Hello


Reading strings from terminal:

Using scanf function:

include <stdio.h>

void main ()
{
char greeting[6];
printf(“Enter a string”);
scanf(“%s", greeting );
printf(“\n%s\n”,greeting);
printf(“\n%5s\n”,greeting);
getch();
}
inputs like “New York” or “hello good morning” have spaces.
Scanf doesn’t handle these spaces very well.
To solve this problem, we use the function gets
Reading a line of text:

scanf(“%[^\n]”,greeting);

Note:-This is rarely used


Using getchar() and gets() functions:

Getchar() reads one character .


We can use this function repeatedly to read successive characters from
the input and place them in character array.
Another convenient method of reading a string of text with white
spaces is to use gets() function.
gets(str)
The C library function gets(str) reads a line from stdin and stores it into
the string pointed to by str.
It stops when either the newline character is read or when the end-of-
file is reached, whichever comes first.
#include <stdio.h>

void main()
{
char str[50];

printf("Enter a string : ");


gets(str);

printf("You entered: %s", str);


getch();
}
puts()

The C library function puts(str) writes a string to stdout up to but not including
the nullcharacter.
A newline character is appended to the output.:
#include <stdio.h>
#include <string.h>

void main()
{
char str1[15];
char str2[15];

gets( "tutorialspoint");
gets("compileonline");

puts(str1);
puts(str2);

getch();
}
Arrays of Strings
Acommon application of two dimensional arrays is to store an array of strings.
In this section we see how an array of strings can be declared and operations
such as reading, printing and sorting can be performed on them.
A string is an array of characters; so, an array of strings is an array of arrays
of characters.
We can declare a two dimensional character array of MAX strings of
size SIZE as follows:
char names[MAX][SIZE];
Since names is an array of character arrays, names[i] is the character array,
i.e. it points to the character array or string, and may be used as a string of
maximum size SIZE - 1.
As usual with strings, a NULL character must terminate each character string in
the array.
We can think of an array of strings as a table of strings, where each row of
the table is a string as seen in Figure
/*To sort the list of names*/

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{ int i, k, n;

char name[20][20], tmp[20];

clrscr();

printf("\nEnter the strength (max. 20): ");

scanf("%d", &n);

for(i = 0; i<=n; i++)

gets(name[i]);

for(k = 0; k <= n; k++)

for(i = k+1; i <= n; i++)

{ if(strcmp(name[k], name[i])>0)

{ strcpy(tmp, name[k]);

strcpy(name[k], name[i]);

strcpy(name[i], tmp);

You might also like