C_Arrays
C_Arrays
Variables of these types can store only one value at a given time.
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 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:
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:
void main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
getch();
}
o/p:
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);
void main()
{
char str[50];
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;
clrscr();
scanf("%d", &n);
gets(name[i]);
{ if(strcmp(name[k], name[i])>0)
{ strcpy(tmp, name[k]);
strcpy(name[k], name[i]);
strcpy(name[i], tmp);