UNIT-4 Programming in C
UNIT-4 Programming in C
Definition: An array is a collection of elements of same type that share a common name.
Syntax:
datatype arrayname[size] ;
0 1 2 3 4
While declaring an array, we can initialise it with some values. The general format to
initialise one dimensional array is as follows:
Syntax:
Here, V0, V1, …, Vsize-1 are the initial values of the specified array. If we omit the
values then an array contains garbage values. The number of values must be less than or
equal to the size of the array. When there are few values then the remaining elements are
assigned with zeros.
Reading the arrays elements: To read the array elements thru keyboard, we write and
execute the following example
for(i=0;i<=n-1;i++)
scanf(“%d”,&num[i]);
Accessing elements of the Array:
Once we store the elements of an array, we may access the elements of the array. To
access the array elements, we use the index numbers of the array. The index numbers helps us
to identify a particular location of the array. The following example is used to accessing the
elements of an array and prints them on the screen.
main()
{
int a[]={ 5, 6, 9, 7, 3};
int i;
clrscr();
printf(“The Elements are \n”);
for(i=0 ; i<5; i++)
printf(“ %d \n”, a[i]);
getch();
}
Two-Dimensional Arrays
When an array uses only two subscripts then it is called “two-dimensional array”. A
two-dimensional array is useful for matrix operations.
Syntax:
datatype arrayname[rowsize][columnsize] ;
0 1 2
While declaring an array, we can initialise it with some values. The general format to
initialise two dimensional array is as follows:
Syntax:
Here, If we omit the values then an array contains garbage values. The number of
values must be less than or equal to the size of the array. When there are few values then the
remaining elements are assigned with zeros.
Example-1:
This example initialises the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 6 8
1 1 3 5
Example-1:
This example initialises the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 8 0
1 5 0 0
Each two dimensional array element is referred or accessed by specifying the array
name followed by two subscripts. The subscripts must be enclosed within square brackets.
For example,
The remaining elements can be accessed as a[0][1], a[2][3], a[1][2] and so on.
The two dimensional array that contains ‘m’ rows and ‘n’ columns can be read using
loops as follows:
for(i=0;i<=m-1;i++)
for(j=0;j<=n-1;j++)
scanf(“%d”,&a[i][j]);
Multidimensional Arrays
A multi-dimensional array can be termed as an array of arrays that stores
homogeneous data in tabular form. Data in multidimensional arrays is generally
stored in row-major order in the memory.
Syntax:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array.
size1, size2,…, sizeN: Size of each dimension.
Examples:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000
elements.
To get the size of the array in bytes, we multiply the size of a single element with
the total number of elements in the array.
For example:
Size of array int x[10][20] = 10 * 20 * 4 = 800 bytes. (where int = 4
bytes)
Similarly, size of int x[5][10][20] = 5 * 10 * 20 * 4 = 4000 bytes.
(where int = 4 bytes)
The most commonly used forms of the multidimensional array are:
1. Two Dimensional Array
2. Three Dimensional Array
Dynamic Array
we can’t change the size of the array after its declaration. Due to this, we may
encounter situations where our array doesn’t have enough space left for required
elements or we allotted more than the required memory leading to memory
wastage. To solve this problem, dynamic arrays come into the picture.
A Dynamic Array is allocated memory at runtime and its size can be changed
later in the program.
We can create a dynamic array in C by using the following methods:
1. Using malloc() Function
2. Using calloc() Function
Syntax:
ptr = (cast-type*) malloc(byte-size);
We can use this function to create a dynamic array of any type by simply
allocating a memory block of some size and then typecasting the returned void
pointer to the pointer of the required type.
Example:
ptr = (int*) malloc(100 * sizeof(int));
In the above example, we have created a dynamic array of type int and size 100
elements.
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Memory allocated
printf("Memory successfully allocated using "
"malloc.\n");
return 0;
}
Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
2. Dynamic Array Using calloc() Function
The “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type and
initialized each block with a default value of 0.
The process of creating a dynamic array using calloc() is similar to the malloc()
method. The difference is that calloc() takes arguments instead of one as
compared to malloc(). Here, we provide the size of each element and the number
of elements required in the dynamic array. Also, each element in the array is
initialized to zero.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
Example:
ptr = (int*) calloc(5, sizeof(float));
In the above example, we have created a dynamic array of type float having five
elements.
Let’s take another example to create a dynamic array using the calloc() method.
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Memory allocated
printf("Memory successfully allocated using "
"malloc.\n");
return 0;
}
Output:
Enter size of elements:6
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6,
A string is a sequence of one or more characters. Any group of characters enclosed within
double quotes is a string constant. In ‘C’ language, strings are manipulated using arrays and
pointers.
Operations on strings:
To manipulate strings, an array must be declared with character data type. A string can be
declared as follows:
(OR)
In the above examples, the C compiler automatically inserts ‘\0’ character at the end. So,
the conceptual view for the above examples is as shown below:
D E L H I \0
Here, it stores the string “DELHI” into memory and assigns the starting location
address to the pointer variable ‘city’. The conceptual view for the above example is as shown
below:
4650 D E L H I \0
To store more than one string in the array, then the array can be declared as follows
char arrayname[size1][size2];
Here, ‘size1’ specifies the number of strings and ‘size2’ refers the number of
characters in each string.
This example reserves 3 memory locations to store 3 strings. Each string may contain
10 characters (10 bytes). The conceptual view for the above declaration is
City[0 D E L H I \0
]
City[1 B A N G A L O R E \0
]
City[2 C H E N N A I \
] 0
Strings can be read and write using formatted I/O functions by the format character
“%s”. While using “%s” character, the address operator and subscript should not be specified
for the array.
When %s character is used with scanf( ) function, it terminates its input at the first
white space character (white space characters are blanks, tabs and carriage return i.e.‘\n’). For
example, if we input “NEW DELHI”, then it takes only “NEW”.
Example:
#include<stdio.h>
Main( )
char name[30];
scanf(“%s”,name);
printf(“%s”,name);
These functions are also used to read and write strings. The gets( ) function reads a
string upto carriage return i.e. ‘\n’ pressed. The puts( ) functions writes the specified string on
the monitor. These functions will not require any format character to read and write strings.
Example:
#include<stdio.h>
main( )
{
char name[30];
gets(name);
puts(name);
In ‘C’ language, there are several function are used to manipulate strings. These
functions are included in “string.h” file. The following are some of the most commonly used
string functions:
1. Strlen( ) Function:
This function finds the length of the given string. It means it counts and returns the
number of characters present in the string. The output of this function is an integer.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
int n;
n = strlen(name);
Output 5
2. Strrev( ) Function:
This function is used to reverse all the characters in the given string except null
character.
Syntax: strrev(string); Where ‘string’ is constant or array variable.
Example:
#include<stdio.h>
#include<string.h>
main( )
strrev(name);
puts(name);
Output EDCBA
3. Strlwr( ) Function:
This function converts all the uppercase letters in the given string into lowercase.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
strlwr(name);
puts(name);
Output abcde
4. Strupr( ) Function:
This function converts all the lowercase letters in the given string into uppercase.
Example:
#include<stdio.h>
#include<string.h>
main( )
strlwr(name);
puts(name);
} Output ABCDE
5. Strcpy( ) Function:
This function copies the contents of one string (source) to another string (destination).
The contents of the source string are unchanged.
Example:
#include<stdio.h>
#include<string.h>
main( )
strcpy(b, a);
puts(b);
The above example copies the contents of ‘a’ to ‘b’. Hence the output is ABCDE.
6. Strcat( ) Function:
This function appends the contents of one string (source) to another string
(destination). This is called concatenation of two strings. The contents of the source string are
unchanged.
#include<stdio.h>
#include<string.h>
main( )
strcat(b, a);
puts(b);
The above example append the contents of ‘a’ to ‘b’. Hence the output is DEFABC
7. Strcmp( ) Function:
Here,
Example:
#include<stdio.h>
#include<string.h>
main( )
int c;
gets(a);
c = strcmp(a, b);
if (c = = 0)
else
if (c < 0)
else
if (c > 0)