You are on page 1of 13

3/23/2022

Arrays are refered to as structured data types.


An array is defined as finite ordered collection of
Arrays homogenous data, stored in contiguous memory
locations.
Here the words,
finite means data range must be defined.
ordered means data must be stored in continuous
memory addresses.
homogenous means data must be of similar data 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.

Declaring Arrays
To declare an array, 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.
e.g. double balance[10];
Now balance is a variable array which is
sufficient to hold upto 10 double numbers.

Initializing Arrays
double balance[5] = {1000.0, 2.0, 3.4, 7.0, All arrays have 0 as the index of their first
50.0}; element which is also called base index and last
The number of values between braces { } can not index of an array will be total size of the array
be larger than the number of elements that we minus 1.
declare for the array between square brackets [
].
If you omit the size of the array, an array just
big enough to hold the initialization is created.
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.
Following is an example to assign a single
element of the array:
balance[4] = 50.0;

1
3/23/2022

Accessing Array Elements


An element is accessed by indexing the array int main ()
name. This is done by placing the index of the {
element within square brackets after the name of
int n[ 10 ]; // array declaration
the array.
int i,j;
double salary = balance[9];
for ( i = 0; i < 10; i++ )
The above statement will take 10th element from
the array and assign the value to salary {
variable. n[ i ] = i + 100; // run-time array
initialization
}
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0; }

Two-Dimensional Arrays
Element[0] = 100 type arrayName [ x ][ y ];
Element[1] = 101 Where type can be any valid C data type
Element[2] = 102 and arrayName will be a valid C identifier.
Element[3] = 103 A two-dimensional array can be think as a table
which will have x number of rows and y number of
Element[4] = 104
columns.
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Initializing Two-Dimensional Arrays


Thus, every element in array a is identified by Multidimensional arrays may be initialized by
an element name of the form a[ i ][ j ], where a specifying bracketed values for each row.
is the name of the array, and i and j are the int a[3][4] = { {0, 1, 2, 3} ,
subscripts that uniquely identify each element in
{4, 5, 6, 7} ,
a.
{8, 9, 10, 11}
int a[3][4];
};
The nested braces, which indicate the intended
row, are optional.
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

2
3/23/2022

Accessing Two-Dimensional Array


Elements
An element in 2-dimensional array is accessed by int main ()
using the subscripts, i.e., row index and column {
index of the array. For example: int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; //
compile-time
int val = a[2][3]; initialization
int i, j;
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;
}

Run-time initialization of
Run-
two dimensional array
a[0][0]: 0 int arr[3][4];
a[0][1]: 0 int i,j,k;
a[1][0]: 1 printf("Enter array element");
a[1][1]: 2 for(i=0;i<3;i++)
a[2][0]: 2 {
a[2][1]: 4 for(j=0; j < 4; j++)
a[3][0]: 3 {
a[3][1]: 6 scanf("%d",&arr[i][j]);
a[4][0]: 4 }
a[4][1]: 8 }

Multi-
Multi-dimensional Array
for(i=0; i < 3; i++) 2D Array:
{ int array[2][3];
for(j=0; j < 4; j++) array[0] => [0, 1, 2]
{ array[1] => [0, 1, 2]
printf("%d",arr[i][j]); 3D Array:
} int array[2][3][2];
} array[0] => [0] => [0, 1]
[1] => [0, 1]
[2] => [0, 1]
array[1] => [0] => [0, 1]
[1] => [0, 1]
[2] => [0, 1]

3
3/23/2022

4D Array: Display Largest Element of an array


int array[2][3][2][5];
int main()
array[0] => [0] => [0] => [0, 1, 2, 3, 4]
{
[1] => [0, 1, 2, 3, 4]
int i,n;
[1] => [0] => [0, 1, 2, 3, 4]
float arr[100];
[1] => [0, 1, 2, 3, 4]
printf("Enter total number of elements(1 to 100):
[2] => [0] => [0, 1, 2, 3, 4]
");
[1] => [0, 1, 2, 3, 4]
scanf("%d",&n);
array[1] => [0] => [0] => [0, 1, 2, 3, 4]
for(i=0;i<n;++i)
[1] => [0, 1, 2, 3, 4]
{
[1] => [0] => [0, 1, 2, 3, 4]
printf("Enter Number %d: ",i+1);
[1] => [0, 1, 2, 3, 4]
scanf("%f",&arr[i]);
[2] => [0] => [0, 1, 2, 3, 4]
}
[1] => [0, 1, 2, 3, 4]

for(i=1;i<n;++i) Output
{ Enter total number of elements(1 to 100): 8
if(arr[0]<arr[i]) Enter Number 1: 23.4
arr[0]=arr[i]; Enter Number 2: -34.5
} Enter Number 3: 50
printf("Largest element = %f",arr[0]); Enter Number 4: 33.5
return 0; Enter Number 5: 55.5
} Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5
Largest element = 55.5

Addition of two matrix


int main() for(i=0;i<r;++i)
{ for(j=0;j<c;++j)
int {
r,c,a[100][100],b[100][100],sum[100][100],i,j; printf("Enter element a[%d][%d]: ",i+1,j+1);
printf("Enter number of rows (between 1 and 100): scanf("%d",&a[i][j]);
");
}
scanf("%d",&r);
printf("Enter elements of 2nd matrix:\n");
printf("Enter number of columns (between 1 and
for(i=0;i<r;++i)
100): ");
for(j=0;j<c;++j)
scanf("%d",&c);
{
printf("\nEnter elements of 1st matrix:\n");
printf("Enter element b[%d][%d]: ",i+1,j+1);
scanf("%d",&b[i][j]);
}

4
3/23/2022

/*Adding Two matrices */ Enter number of rows (between 1 and 100):2


for(i=0;i<r;++i) Enter number of columns (between 1 and 100):2
for(j=0;j<c;++j) Enter elements of 1st matrix:
sum[i][j]=a[i][j]+b[i][j]; Enter element a[1][1]: 1
printf("\nSum of two matrix is: \n\n"); Enter element a[1][2]: 5
for(i=0;i<r;++i) Enter element a[2][1]: 6
for(j=0;j<c;++j) Enter element a[2][2]: 2
{ Enter elements of 2nd matrix:
printf("%d ",sum[i][j]); Enter element b[1][1]: 4
if(j==c-1) Enter element b[1][2]: 8
printf("\n\n"); Enter element b[2][1]: 4
} Enter element b[2][2]: 3
return 0; }

String and Character array


Sum of two matrix is: string is a sequence of characters that is
5 13 treated as a single data item and terminated by
null character '\0'.
10 5
C language does not support strings as a data
type.
A string is actually one-dimensional array of
characters in C language.
For example : The string "hello world" contains
12 characters including '\0' character which is
automatically added by the compiler at the end of
the string.

Declaring and Initializing a string


variables
String Input and Output
Legal initialization Input function scanf() can be used
char name[10]=“Hello"; with %s format specifier to read a string input
from the terminal. But there is one problem
char name[10]={'L','e','s','s','o','n','s','\0'};
with scanf() function, it terminates its input on
first white space it encounters. Therefore if you
Illegal initialization try to read an input string "Hello World"
char ch[3]="hell"; using scanf() function, it will only
read Hello and terminate after encountering white
char str[4];
spaces.
str="hell";
However, C supports a format specification known
as the edit set conversion code %[..] that can
be used to read a line containing a variety of
characters, including white spaces.

5
3/23/2022

void main() Another method to read character string with


{ white spaces from terminal is gets() function.
char str[20]; char text[20];
clrscr(); gets(text);
printf("Enter a string"); printf("%s",text);
scanf("%[^\n]",&str);
printf("%s",str);
getch();
}

String Handling Functions


int main() These functions are packaged in string.h library.
{
char name[30];
Method Description
printf("Enter name: ");
strcat() It is used to concatenate(combine) two
gets(name); //Function to read string from user.
string
printf("Name: ");
strlen() It is used to show length of a string
puts(name); //Function to display string. return
0; strcpy() Copies one string into another
} strcmp() It is used to compare two string

1) strcat() function 3) strcmp() function


strcat("hello","world"); int strcmp(char *string1, char *string2);
strcat() function will add the The strcmp function compares the contents of
string "world" to "hello". string1 and string2 and returns a value
2) strlen() function indicating their relationship.
strlen() function will return the length of the Return Value
string passed to it. if Return value if < 0 then it indicates string1
int j; is less than string2
j=strlen(“hello"); if Return value if > 0 then it indicates string2
is less than string1
printf("%d",j);
if Return value if = 0 then it indicates string1
output : 5
is equal to string2

6
3/23/2022

int j; printf("Copied string: ");


j=strcmp(“helloo",”hello"); puts(b);
printf("%d",j); return 0;
output: 111 }
4) strcpy() function
Syntax: strcpy(destination,source);
int main()
{
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a);

Pass single element of array to


Passing Arrays as Function Arguments
function
Pass single element of array to function void display(int);
Pass one-dimensional arrays to function int main()
Pass two-dimensional arrays to function {
int c[]={2,3,4};
display(c[2]);
return 0;
}
void display(int a)
{
printf("%d",a);
}

Pass one-
one-dimensional arrays to
function
//function definition double getAverage(int [], int); // function
double getAverage(int arr[], int size) declaration
{ int main ()
int i; {
double avg; int balance[5] = {1000, 2, 3, 17, 50}, e;
double sum; double avg;
for (i = 0; i < size; i++) /* pass pointer to the array as an argument */
{ avg = getAverage( balance, 5 ) ; //call by
reference
sum += arr[i];
printf( "Average value is: %f ", avg );
}
return 0;
avg = sum / size;
}
return avg;
}

7
3/23/2022

Pass two-
two-dimensional arrays to
function
void Function(int c[2][2]); void Function(int c[2][2])
int main() {
{ int i,j;
int c[2][2],i,j; printf("Displaying:\n");
for(i=0;i<2;++i)
printf("Enter 4 numbers:\n");
{
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{ for(j=0;j<2;++j)
{
{ printf("%d\n",c[i][j]);
scanf("%d",&c[i][j]); }
} }
} }
Function(c);
return 0; }

Size of Array
Output void func(int a[])
Enter 4 numbers: {
2 printf("\nIn func:");
3 printf("\nThe number of elements in a is %d\n",
sizeof(a)/sizeof(a[0]));
4
}
5
int main()
Displaying:
{
2
int a[]={3,5,8,9,11};
3
printf("\nThe number of elements in a is %d\n",
4
sizeof(a)/sizeof(a[0]));
5
func(a);
return 0; }

Matrix Multiplication using Function


Output: void input(int a[][10], int b[][10], int r1,int c1,
The number of elements in a is 5 int r2, int c2);
In func: void mult(int a[][10],int b[][10],int mult[][10],int
The number of elements in a is 2 r1,int c1,int r2,int c2);
void display(int mult[][10], int r1, int c2);
void func(int *a) int main()
void func(int a[]) {
void func(int a[5]) int a[10][10], b[10][10], mult[10][10], r1, c1, r2,
c2, i, j, k;
All three are same as void func(int *a) when
printf("Enter rows and column for first matrix: ");
passing array to a function.
scanf("%d%d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&r2, &c2);

8
3/23/2022

void input(int a[][10], int b[][10], int r1,int


/* If colum of first matrix in not equal to row
c1, int r2, int c2)
of second matrix, asking user to enter the size
of matrix again. */ {
while (c1!=r2) int i,j;
{ printf("\nEnter elements of matrix 1:\n");
printf("Error! column of first matrix not equal for(i=0; i<r1; ++i)
to row of second.\n"); {
printf("Enter rows and column for first matrix: for(j=0; j<c1; ++j)
"); scanf("%d%d", &r1, &c1); {
printf("Enter rows and column for second matrix: printf("Enter elements a%d%d:
"); scanf("%d%d",&r2, &c2); ",i+1,j+1);
} scanf("%d",&a[i][j]);
input(a,b,r1,c1,r2,c2); }
mult(a,b,mult,r1,c1,r2,c2); printf("\nEnter elements of matrix 2:\n");
display(mult,r1,c2); }
return 0; }

void mult(int a[][10],int b[][10],int


mult[][10],int r1,int c1,int r2,int c2)
for(i=0; i<r2; ++i) {
{ int i,j,k;
for(j=0; j<c2; ++j) for(i=0; i<r1; ++i)
{ for(j=0; j<c2; ++j)
printf("Enter elements b%d%d: {
",i+1,j+1); mult[i][j]=0;
scanf("%d",&b[i][j]); }
} for(i=0; i<r1; ++i)
} for(j=0; j<c2; ++j)
} for(k=0; k<c1; ++k)
{ mult[i][j]+=a[i][k]*b[k][j]; }
}

void display(int mult[][10], int r1, int c2) Output:


{ Enter rows and column for first matrix: 3 2
int i, j; Enter rows and column for second matrix: 3 2
printf("\nOutput Matrix:\n"); Error! column of first matrix not equal to row of
second.
for(i=0; i<r1; ++i) Enter rows and column for first matrix: 2 3
{ Enter rows and column for second matrix: 3 2
for(j=0; j<c2; ++j) Enter elements of matrix 1:
{ Enter elements a11: 3
printf("%d ",mult[i][j]); Enter elements a12: -2
if(j==c2-1) Enter elements a13: 5
printf("\n\n"); Enter elements a21: 3
} Enter elements a22: 0
} Enter elements a23: 4
}

9
3/23/2022

Calculate Length without Using


strlen()
strlen () Function
Enter elements of matrix 2: int main()
Enter elements b11: 2 {
Enter elements b12: 3 char s[1000],i;
Enter elements b21: -9 printf("Enter a string: ");
Enter elements b22: 0 scanf("%s",s);
Enter elements b31: 0 for(i=0; s[i]!='\0'; ++i);
Enter elements b32: 4 printf("Length of string: %d",i);
Output Matrix: 24 29 return 0;
6 25 }

Concatenate Two Strings


Output int main()
Enter a string: welcome {
Length of string: 7 char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s",s1);
printf("Enter second string: ");
scanf("%s",s2);
for(i=0; s1[i]!='\0'; i++);
/* i contains length of string s1. */
for(j=0; s2[j]!='\0'; j++, i++)
{
s1[i]=s2[j];
}

Copy String Manually


s1[i]='\0'; int main()
printf("After concatenation: %s",s1); {
return 0; char s1[100], s2[100], i;
} printf("Enter string s1: ");
Output: scanf("%s",s1);
Enter first string: lol for(i=0; s1[i]!='\0'; ++i)
Enter second string: :) {
After concatenation: lol:) s2[i]=s1[i];
}
s2[i]='\0';
printf("String s2: %s",s2);
return 0;
}

10
3/23/2022

Find the Frequency of Characters


Output: int main()
Enter String s1: welcome {
String s2: welcome char c[1000],ch;
int i,count=0;
printf("Enter a string: ");
gets(c);
printf("Enter a character to find frequency: ");
scanf("%c",&ch);
for(i=0;c[i]!='\0';++i)
{
if(ch==c[i])
++count;
}

Find Number of Vowels,


Consonants, Digits and White
int main() Space Character
printf("Frequency of %c = %d", ch, count);
{
return 0;
char line[150];
}
int i,v,c,ch,d,s,o;
Output:
o=v=c=ch=d=s=0;
Enter a string: This website is awesome.
printf("Enter a line of string:\n");
Enter a character to find frequency: e gets(line);
Frequency of e = 4 for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i'
|| line[i]=='o' || line[i]=='u' || line[i]=='A'
|| line[i]=='E' || line[i]=='I' || line[i]=='O'
|| line[i]=='U')
++v;

else if((line[i]>='a'&& line[i]<='z') ||


(line[i]>='A'&& line[i]<='Z'))
printf("Vowels: %d",v);
++c;
printf("\nConsonants: %d",c);
else if(line[i]>='0'&&c<='9')
printf("\nDigits: %d",d);
++d;
printf("\nWhite spaces: %d",s);
else if (line[i]==' ')
return 0;
++s;
}
}
Output:
Enter a line of string: This program is easy 2
understand Vowels: 9
Consonants: 18
Digits: 1
White spaces: 5

11
3/23/2022

Count number of words in a string


void main()
{ enter the string: welcome to c-programming
char s[200]; class!
number of words in given string are: 4
int count = 0, i;
printf("enter the string\n");
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are:
%d\n", count +1);
}

Array Application B. Array Used for Maintaining multiple variable names


using single name
A. Stores Elements of Same Data Type Suppose we need to store 5 roll numbers of students
int a[30]; then without declaration of array we need to
a[0] = 10; declare following –
a[1] = 20; int roll1,roll2,roll3,roll4,roll5;Now in order to
a[2] = 30; get roll number of first student we need to access
roll1.
a[3] = 40;
Guess if we need to store roll numbers of 100
a[4] = 50; students then what will be the procedure.
Similarly if we declare the character array then Maintaining all the variables and remembering all
it can hold only character. So in short character these things is very difficult.
array can store character variables while
Consider the Array :
floating array stores only floating numbers.
int roll[5];So we are using array which can store
multiple values and we have to remember just single
variable name.

C. Array Can be Used for Sorting Elements D. Array Can Perform Matrix Operation
We can store elements to be sorted in an array Matrix operations can be performed using the
and then by using different sorting technique we array.We can use 2-D array to store the matrix.
can sort the elements. Matrix can be multi-dimensional
Different Sorting Techniques are :
Bubble Sort
Insertion Sort
Selection Sort
Bucket Sort

12
3/23/2022

E. Array Can be Used in CPU Scheduling


CPU Scheduling is generally managed by Queue.
Queue can be managed and implemented using the
array. Array may be allocated dynamically i.e at
run time. F. Array Can be Used in Recursive
Function
When the function calls another function or the
same function again then the current values are
stores onto the stack and those values will be
retrieve when control comes back. This is similar
operation like stack.

13

You might also like