Aut - Unit 2
Aut - Unit 2
INTRODUCTION TO ARRAYS:
An array is a collection of similar data items that are stored under a common name.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
to store roll numbers of the students in a class
to store marks of a students
to store list of names of employees etc..
Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
Code Optimization: Less code is required, one variable can store numbers of
value.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily sort the data using swapping technique.
Random Access: With the help of array index you can randomly access any
elements from array.
Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensional array:
Array having only one subscript [ ] variable is called One-Dimensional array.
It is also called as Single Dimensional Array or Linear Array or list.
The elements of one dimensional array is also called as linear array
Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
After an array is declared it must be initialized.
An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization
(i) Compile time Array initialization:
- Compile time initialization of array elements is same as ordinary variable
initialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to
initialize array by getting the input from the user.
Syntax:
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1D array:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
A variable can be assigned to another variable but array can’t be assigned to
another array directly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3], b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}
Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linear search
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:
The linear search is simple - It is very easy to understand and implement;
It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
{
found=1;
break;
}
}
if (found==1)
printf("%d is present in array and position is %d\n", item,i);
else
printf("%d is not present in array.\n", item);
return 0;
}
Binary Search:
Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
This method can be applied only if list is in sorted order.
List is divided into two halves separated by middle element.
Left half Middle Right half
Concept of Binary search:
i. Find the middle element
ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is less
than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements next
to the middle element.
vi. If the value is high than that element, then the search will start with the elements
before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.
We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.
Advantages:
Faster than linear search.
Disadvantages :
Binary search algorithm can work only with the sorted array (either ascending or
descending order).
It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:
Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
Array Initialization:
(i) Compile time Initialization
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];
Disadvantages of an array:
The elements in an array must be same data type.
The size of an array is fixed. we can’t expand the size in run time.
The insertion and deletion operations in an array require shifting of
elements which takes more time.
INTRODUCTION TO STRINGS
Nowadays, computers are widely used for word processing applications such as creating,
inserting, updating, and modifying textual data. Besides this we need to search for a
particular pattern within a text, delete it, or replace it with another pattern. So there is
actually a lot we as users do to manipulate the textual data.
Programming Tip: Character constants are enclosed in single quotes. String constants are
enclosed in double quotes.
In C language, a string is a null-terminated character array. This means that after the last
character, a null character ('\0') is stored to signify the end of the character array. For
example, if we write
We are declaring a character array that has five usable characters namely, H, E, L, L, and O.
Apart from these characters, a null character ('\0') is stored at the end of the string. So, the
internal representation of the string becomes HELLO'\0'. To store a string of length 5, we
need 5 + 1 locations (1 extra for the null character). The name of the character array (or
the string) is a pointer to the beginning of the string. Figure 6.1 shows the difference
between character storage and string storage.
Then the null character will not be appended automatically to the character array. This is
because str can hold only 5 characters and the characters in HELLO have already filled the
locations allocated to it.
Note
Like we use subscripts (also known as index) to access the elements of an array, similarly
subscripts are also used to access the elements of the character array. The subscript starts
with a zero (0). All the characters of a string array are stored in successive memory
locations. Figure 6.2 shows how str[] is stored in ed in memory.
Thus we see that a string is a sequence of characters. In Figure 6.2, 1000, 1001, 1002, and
so on are the memory addresses of individual characters. From the figure, we see that H is
stored at memory location 1000 but in reality the ASCII codes of characters are stored in
memory and not the character itself, i.e., at address 1000, 72 will be stored since the ASCII
code for H is 72.
The above statement declares a constant string as we have assigned value to it while
declaring the string. However, the general form of declaring a string is
char str[size];
When we declare the string in this way, we can store size -1 characters in the array
because the last character would be the null character. For example, char mesg [100]; can
store a maximum of 99 usable characters.
Till now we have seen one way of initializing strings. The other way to initialize a string is
to initialize it as an array of characters, like
In this example, we have explicitly added the null character. Also observe that we have not
mentioned the size of the string (or the character array). Here, the compiler will
automatically calculate the size based on the number of elements initialized. So, in this
example 6 memory slots will be reserved to store the string variable, str.
We can also declare a string with size much larger than the number of elements that are
initialized. For example, consider the statement below:
In such cases, the compiler creates a character array of size 10; stores the value "HELLO" in
it and finally terminates the value with a null character. Rest of the elements in the array
are automatically initialized to NULL. Figure 6.3 shows the memory representation of such
a string.
char str[3];
str = "HELLO";
The above declaration is illegal in C and would generate a compile time error because of
two reasons. First, the array is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration.
Note
An array name cannot be used as the left operand of an assignment operator. Therefore,
the following statement is illegal in C.
str2 = strl;
Reading Strings
If we declare a string by writing
char str[100];
scanf("%s", str);
Programming Tip: Using & operand with a string variable in the scanf statement is
optional as string variable is a character array and denotes the address where the array
begins.
Although the syntax of scanf() function is well known and easy to use, the main pitfall with
this function is that the function terminates as soon as it finds a blank space. For example,
if the user enters Hello World, then str will contain only Hello. This is because the moment
a blank space is encountered, the string is terminated by the scanf() function. You may
also specify a field width to indicate the maximum number of characters that can be read
in. Remember that extra characters are left unconsumed in the input buffer.
Unlike int (%d), float (f), and char (c), %s format does not require ampersand before the
variable name.
Note
When scanf() encounters a white space character, it ter- minates reading further and
appends a null character to the string that has been read. The white space character is
left in the input stream and might be mistakenly read by the next scanf() statement. So
in order to delete the white space character from the input stream, either use a space in
the format string before the next conversion code or FLUSH the input stream by using the
fflush function by writing fflush(stdin).
The next method of reading a string is by using gets () function. The string can be read by
writing
gets (str);
gets () is a simple function that overcomes the drawbacks of the scanf() function. The gets
() function takes the starting address of the string which will hold the input. The string
inputted using gets () is automatically terminated with a null character.
Last but not the least, strings can also be read by calling the getchar() function repeatedly
to read a sequence of single characters (unless a terminating character is entered) and
simultaneously storing it in a character array as shown below.
i=0;
str[i] = ch;
i++;
Note that in this method, you have to deliberately append the charac- ters with a null
character. The other two functions automatically do this.
Writing Strings
Strings can be displayed on screen using three ways:
printf("%s", str);
We use the conversion character 's' to output a string. We may also use width and
precision specifications along with %s (as discussed in Chapter 2). The width specifies the
minimum output field width. If the string is short, extra space is either left padded or right
padded. A negative width left pads short string rather than the default right justification.
The precision specifies the maximum number of characters to be displayed. If the string is
long, the extra characters are truncated. For example,
printf("%5.3s", str);
The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To make
the string left justified, we must use a minus sign. For example,
printf("%-5.3s", str);
Note
When the field width is less than the length of the string, the entire string will be printed.
Also if the number of characters to be printed is specified as zero, then nothing is printed
on the screen.
The next method of writing a string is by using puts () function. The string can be displayed
by writing
puts (str);
puts () is a simple function that overcomes the drawbacks of the printf() function. The puts
() function writes a line of output on the screen. It terminates the line with a newline
character ('\n'). It returns an EOF (-1) if an error occurs and returns a positive number on
success. Last but not the least, strings can also be written by calling the putchar() function
repeatedly to print a sequence of single characters.
i=0;
putchar (str[i]);
i++;
Note
#include <conio.h>
int main()
clrscr();
getch();
return 0;
Output
| Introduction to C |
| Introduction to C |
| Introduction to C |
| Intr |
| Intr |
| Intr |
The printf() function in UNIX supports specification of variable field width or precision, i.e.,
if we write,
Then the printf() statement will print first p characters of str in the field width of w.
HE
HEL
HELL
HELLO
HELLO
HELL
HEL
HE
H
#include <stdio.h>
#include <conio.h>
int main()
int i, w, p;
printf("\n");
p = i+1;
printf("\n");
{
p = i+1;
getch();
return 0;
sprintf() Function
The library function sprintf() is similar to printf (). The only difference is that the formatted
output is written to a memory area rather than directly to a standard output
(screen). sprintf() is useful in situations when formatted strings in memory have to be
transmitted over a communication channel or to a special device. The syntax
of sprintf() can be given as
Here, buffer is the place where string needs to be stored. The arguments command is an
ellipsis so you can put as many types of arguments as you want. Finally, format is the
string that contains the text to be printed. The string may contain format tags.
#include <stdio.h>
main()
char buf[100];