0% found this document useful (0 votes)
92 views

Unit-5 Arrays

1. The document discusses one dimensional and two dimensional arrays in C programming. It defines what arrays are, how to declare and initialize them, and how elements are accessed. 2. For one dimensional arrays, it provides syntax examples and discusses initializing array elements. It also covers string arrays. 3. For two dimensional arrays, it explains how they store tabular data in rows and columns and provides examples of declaring and initializing 2D arrays. Memory storage of 2D arrays is also explained.

Uploaded by

parmesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Unit-5 Arrays

1. The document discusses one dimensional and two dimensional arrays in C programming. It defines what arrays are, how to declare and initialize them, and how elements are accessed. 2. For one dimensional arrays, it provides syntax examples and discusses initializing array elements. It also covers string arrays. 3. For two dimensional arrays, it explains how they store tabular data in rows and columns and provides examples of declaring and initializing 2D arrays. Memory storage of 2D arrays is also explained.

Uploaded by

parmesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-IV

• UNIT-IV
• Arrays: Introduction to one dimensional and two
dimensional Arrays- Declaration, Initialization and
Accessing array elements, Array applications, C
programming examples.
• Strings: Introduction, String Input/output functions,
Declaration, Initialization and Accessing Strings, Array
of Strings, String Manipulation functions- strlen,
strcat, strcmp, strcpy, strrev, C programming
examples.
Definition of array
• Array- array is a collection of similar data types stored
contiguously in memory under the same name.
• Array- it is a collection of homogeneous elements.
• HOW TO CREATE AN ARRAY
• Before we create an array, we need to decide on two
properties:
• Element type: what kind of data will your array hold?
ints, double, chars? Remember, we can only choose one type.
• Array size: how many elements will your array contain?
• When we initially write our program, we must pick an array
size. An array will stay this size throughout the execution of
the program. In other words, we can change the size of an
array at compile time, but cannot change it at run-time.
• USING ARRAYS IN C
• In C, the arrays can be classified based on how
the data items are arranged for human
understanding
• Arrays are broadly classified into three
categories,
• 1. One dimensional arrays
• 2. Two dimensional arrays
• 3. Multi dimensional arrays
1. ONE DIMENSIONAL ARRAYS
• One dimensional array is a linear list consisting of
related and similar data items. In memory all the data
items are stored in contiguous memory locations one
after the other.
• syntax-
Datatype array_name[size];
Ex- int a[10];
created an array of 10 integers
float x[5];
created an array of 5 floating point values
double z[8];
created an array of 8 double values.
Referencing\ accessing array elements
• Array elements are accessed with subscript, the
number in the brackets following the array name.
• This number specifies the elements position in the
array.
• The subscript would be 0,1,...... n-1.
• // C program to read an array elements and
find the sum of the elements.
#include <stdio.h>
main()
{ int a[10];
int i, SIZE, total=0;
printf(“\n Enter the size of the array : “);
scanf(“%d”,&size);
for (i = 0; i < SIZE ; i++)
scanf(“%d”,&a[i]);
for (i = 0; i < SIZE ; i++)
total += a[i];
printf("Total of array element values is %d\n", total);
getch();}
Few important points about the array
• 1. an array is a collection of similar elements.
• 2. the first element in the array is numbered
from 0 to n-1.
• 3. while declaring an array we have to specify
type and size(dimension) of an array to the
compiler.
• 4. however big an array all the elements are
always stored in contiguous memory location.
Initializing array elements
 We have four options for initializing one dimensional arrays.
 But, first, REMEMBER THIS: Just like regular variables, arrays that have not been initialized may
contain “garbage values.”
 But, now, the stakes are even higher. If you declare an array with 31 elements, and forget to initialize it,
you end up with 31 garbage values!
 Option 1 Initializing all memory locations
If you know all the data at compile time, you can specify all your data within
brackets:
int x [5] = {75, 79, 82, 70, 68};
• during compilation, 5 contiguous memory locations are reserved by the
compiler for the variable temp and all these locations are initialized as shown
in Fig. If the size of integer is 2 bytes, 10 bytes will be allocated for the
variable temp.

• x[0] x[1] x[2] x[3] x [4]

• 1000 1002 1004 1006 1008 Address


• Figure: Storage Representation of array
• Option 2 initialization without size
• If we omit the size of your array, but specify an initial
set of data, the compiler will automatically determine
the size of your array. This way is referred as
initialization without size.
• int X [] = {75, 79, 82, 70, 68};
• the array size will be set of the total number of initial
values specified.
• Here, the compiler creates an array of 5 elements.
x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array
• Option 3 Partial Array Initialization
• If the number of values to be initialized is less than the size of
the array, then the elements are initialized in the order from 0th
location. The remaining locations will be initialized to zero
automatically.
• Even though compiler allocates 5 memory locations, using this
declaration statement, the compiler initializes first three
locations with 75,70 and 82,the next set of memory locations
are automatically initialized to 0‟s by the compiler as shown in
figure
x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array
• Option 4
• If you do not know any data ahead of time, but you want to
initialize everything to 0, just use 0 within { }.
• For example:
• int x [5] = {0};
x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array

For example:
int x [5] = {5};
x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array
Array of characters(string)
• In c language array of characters are treated as
character string.
• The size in the character array represents the
maximum number of characters that the string can
hold.
• For example: char name[6];
• Declares name as an character array (string) that can
hold a maximum of 6 characters.
• “SNIST” S •Whenever compiler find array of
characters , it terminates with the
N
additional character call it as null
I character.
S • so name[5]- contains the null character.
T •When declaring character arrays, we
\0
must always use one extra space for the
null character.
• Initialization of character array
• char name[]= {„s‟,‟n‟,‟i‟,‟s‟,‟t‟,‟\0‟};
• or char name[]=“snist”;- in this declaration compiler
automatically inserts the null character.
• Bound checking
• In c there is no check to see whether the subscript
used for an array exceeds the size of an array or not.
This will leads to
Ex- main() unpredictable results.
{ There is no error message
int x[50]; from compiler
for(i=0;i<=60;i++)
{
x[i]=i;
}
}
TWO DIMENSIONAL ARRAYS
• Whenever you want to store the tabular data use the
two dimensional array.
• Example- store the student name, rollno, and
attendance.
• The data must be in rows and columns.- matrix
• Declaration of two dimensional array
data type array_name[rows][columns];
2- dimensional arrays
• Example
• char names[3][4];
• in the above declaration
• char(dataType)  specifies type of element in each slot
• names(array_name)  specifies name of the array
• [3](rows)  specifies number of rows
• [4](cols)  specifies number of columns
• Initialization of two dimensional arrays
• An array may be initialized at the time of declaration:

char names [3][4] = {


{‘J’, 'o', 'h', 'n'},
{‘M’, 'a', 'r', 'y'},
{‘I’, 'v', 'a', 'n'}
};
 While initializing a 2-d array it is necessary to mention the column
dimension. so that compiler automatically arrange the elements in rows
and columns.
 Row dimension is optional.
 In memory all the elements are stored in row – major- format.
• They are stored in memory as
col0 col1 col2
Row0 [0][0] [0][1] [0][2]
Row1 [1][0] [1][1] [1][2]
Row2 [2][0] [2][1] [2][2]
Initializing 2D arrays
•An array may be initialized at the time of declaration:

• int x[4][3]={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
• int x[3][2]={1,2,3,4,5,6};
• int x[][2]={1,2,3,4,5,6};
• int x[2][]={1,2,3,4,5,6}; Never work
• int x[][]={1,2,3,4,5,6};
Initializing 2D arrays

char names[3][4] = {
{ 'J', 'o', 'h', 'n'} ,
{ 'M', 'a', 'r', 'y'} ,
• An integer array may be initialized to
{ 'I', 'v', 'a', 'n'}
all zeros as follows:
};
int nums[3][4] = {0};
• This only works for zero.
nums[0][0] = 16;
• To access an element of a 2D
printf("%d", nums[1][2]);
array, you need to specify both the
row and the column: ...
'J' 4269

Address   
'J' 'o' 'h' 'n' is stored: 'o' 4270
'M' 'a' 'r' 'y' 'h' 4271
'n' 4272
'M' 4273
'a' 4274
• Two-dimensional arrays in C are stored in "row-major format":
the array is laid out contiguously, one row at a time: 'r' 4275
'y' 4276
...
3. Multidimensional array
• C allows arrays of three or more dimensions.
• Syntax
Data type array_name[size1][size2]..[sizen];

Array declarations should understand from right-to-left


int a[10][3][2];
“an array of ten arrays of three arrays of two ints”
array of three Array of 4 rows and 2 columns
arrays
int arr[3][4][2] =
{
{ { {
{ 2, 4 }, { 7, 6 }, { 8, 9 },
{ 7, 8 }, { 3, 4 }, { 7, 2 },
{ 3, 4 }, { 5, 3 }, { 3, 4 },
{ 5, 6 } { 2, 3 } { 5, 1 }
}, }, }
};
/* write a c program to calculate the addition of two
matrices*/ //addition of matrix
#include<stdio.h> for(i=0;i<m;i++)
#include<conio.h> {
main() for(j=0;j<n;j++)
{ {
int m,n,i,j,a[10][10],b[10][10],c[10][10]; c[i][j]=a[i][j]+b[i][j];
printf("\n enter the size of the matrix\n"); }//forj
scanf("%d %d", &m,&n); }//for i
printf("enter the elements of matrix a\n"); //display resultant matrix
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
scanf("%d", &a[i][j]); printf("%d\t",c[i][j]);
}//forj }
}//fori printf("\n");
printf("\nenter the elements of matrix b\n"); }//fori
for(i=0;i<m;i++) }
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}//forj
}//fori
strings
• A string is an array of characters.
• A group of characters stored in an array is
called string.
• Declaration
Char arry_name[size];

Size specifies no of characters in the array.


When string stored into an array, compiler
automatically insert null character „\n‟at the
end of the string.
The size must be specified one extra space.
Initialization of strings

• char name[10]= “hyderabad”;


or
• char name[10]= {„h‟,‟y‟,‟d‟,‟e‟,‟r‟,‟a‟,‟b‟,‟a‟,‟d‟,‟\0‟};
• When character array is initialized we must explicitly specify
the null character.
• Character array initialized without specifying the size also.
• char name[]=“hyderabad”;
• Compiler automatically determines the size of this array based
on the no of elements initialized.
Reading string from terminal(keyboard)
• scanf() can be used to read a string with format
specifier %s.
char name[10];
Scanf(“%s”,name);
Scanf() function assigns the characters typed at
keyboard to array until the enter key is pressed.
 once enter key is pressed, scanf() places a „\0‟ character
at the end of an array.
Note – problem with the scanf() function is that it terminates
input on the first white space it finds. So a string with multiple
words are not accepted by the string.
ex- hyderabad snist would not be accepted.
• To read the multiple words of a string use another
function gets().

main()
{
char name[30];
printf(“enter the string”);
gets(name);
}
Writing\ display strings on to a screen
• We can use printf() function to display string on
to a screen with %s format specifier.
Printf(“%s”,name);

 in this case also printf() function cannot print the


multiple words.
like hyderabad snist
To overcome this problem use puts() to display multiple
words.
unlike printf() function, puts() places the cursor to the
next line. \n is not necessary.
Use puts and gets functions

main()
{
char name[30];
puts(“enter the string”);
gets(name);
puts(name);
}
Print a string using loops
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( i <= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
With the help of null character
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
String Library Functions
Function Library Description
strcpy(s1, s2) string.h Copies the value of s2 into
s1
strcat(s1, s2) string.h Appends s2 to the end of s1
strrev(s1) string.h reverse characters of s1
onto the other string
strcmp(s1, s2) string.h Compared s1 and s2
alphabetically; returns a
negative value if s1 should
be first, a zero if they are
equal, or a positive value if
s2 should be first
strlen(s1) string.h Returns the number of
characters in s1 not counting
the null
strcpy()
• Since C never lets us assign entire arrays, we use the strcpy
function to copy one string to another:
#include <string.h>
#include<stdio.h>
main()
{
char string1[] = "Hello, world!";
char string2[20];
strcpy(string2, string1);
puts(string2);
}
The above code copies the contents of string1 to string2.
strcmp()
• The standard library's strcmp function compares two strings, and returns 0
if they are identical, or a negative number if the first string is
alphabetically ``less than'' the second string, or a positive number if the
first string is ``greater.'' Here is an example:
#include <string.h>
#include<stdio.h>
main()
{
char string3[] = "this is";
char string4[] = "a test";
if(strcmp(string3, string4) == 0)
printf("strings are equal\n");
else
printf("strings are not equal\n");
}
strcat()
The standard library function is strcat, which concatenates strings. It does not
concatenate two strings together and give you a third, new string; what it really
does is append one string onto the end of another. Here's an example:
#include <string.h>
#include<stdio.h>
main()
{
char string5[20] = "Hello, ";
char string6[] = "world!";
printf("%s\n", string5);
strcat(string5, string6);
puts(string5);
}
The first call to printf prints ``Hello, '', and the second one prints ``Hello, world!'',
indicating that the contents of string6 have been tacked on to the end of string5.
Notice that we declared string5 with extra space, to make room for the appended
characters.
strlen()
The length of the string can be found by using the
function strlen() function.
#include <string.h>
#include<stdio.h>
main()
{
char string7[] = "abc";
Int len;
len = strlen(string7);
printf("%d\n", len);
}

You might also like