Professional Documents
Culture Documents
Chandigarhuniversity@stringc PDF
Chandigarhuniversity@stringc PDF
H E l l o ‘\0’
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to
print above mentioned string:
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("%s”,greeting”);
}
When the above code is compiled and executed, it produces result something as follows:
Greeting message: Hello
4.1Initialization of strings:
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR,
char c[5]="abcd"; OR,
char c[]={'a','b','c','d','\0'}; OR;
char c[5]={'a','b','c','d','\0'};
5.0Searching Algorithms on Array
Before studying searching algorithms on array we should know what is an algorithm?
An algorithm is a step-by-step procedure or method for solving a problem by a computer in a
given number of steps. The steps of an algorithm may include repetition depending upon the
problem for which the algorithm is being developed. The algorithm is written in human
readable and understandable form. To search an element in a given array, it can be done in two
ways Linear search and Binary search.
5.1Linear Search
A linear search is the basic and simple search algorithm. A linear search searches an element
or value from an array till the desired element or value is not found and it searches in a sequence
order. It compares the element with all the other elements given in the list and if the element is
matched it returns the value index else it return -1. Linear Search is applied on the unsorted or
unordered list when there are fewer elements in a list.
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.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is less than what we are looking for. So,
the value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a match.