Algorithm Development
Algorithm Development
Algorithm in C language
An algorithm is a sequence of instructions that are carried out in a predetermined sequence in order
to solve a problem or complete a work. A function is a block of code that can be called and executed
from other parts of the program.
A set of instructions for resolving an issue or carrying out a certain activity. In computer science,
algorithms are used for a wide range of operations, from fundamental math to intricate data
processing.
One of the common algorithms used in C is the sorting algorithm. A sorting algorithm arranges a
collection of items in a certain order, such as numerically or alphabetically.
There are many sorting algorithms, each with advantages and disadvantages. The most common
sorting algorithms in C are quicksort, merge, and sort.
Algorithm Analysis
Analysis of algorithms usually involves measuring their time and space complexity.
As with space complexity, which describes the amount of memory or disk space needed, time
complexity describes how long an algorithm determines to perform a task.
There are different ways to analyze the time complexity of algorithms, such as Big O and Omega
notation.
In addition to measuring time and space complexity, algorithm analysis also includes other criteria
such as stability, parallelism, and scalability.
Stability - This refers to the ability of the algorithm to maintain the relative order of the
elements in the data set.
Parallelization - This is referring to the capacity to execute operations in parallel across
several processors.
Scalability - On the other hand, it refers to the ability of an algorithm to handle large
volumes of data and other inputs.
We put all analysis of algorithm in two types. They are:-
1. Prior-analysis.
2. Posterior analysis.
1. Prior Analysis: “Priori” means “before”. Hence Priori analysis means checking the
algorithm before its implementation. In this, the algorithm is checked when it is written in
the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that
all other factors, for example, processor speed, are constant and have no effect on the
implementation. This is done usually by the algorithm designer. This analysis is
independent of the type of hardware and language of the compiler. It gives the approximate
answers for the complexity of the program.
2. Posterior analysis: “Posterior” means “after”. Hence Posterior analysis means checking
the algorithm after its implementation. In this, the algorithm is checked by implementing
it in any programming language and executing it. This analysis helps to get the actual and
real analysis report about correctness(for every possible input/s if it shows/returns correct
output or not), space required, time consumed, etc. That is, it is dependent on the language
of the compiler and the type of hardware used.
Algorithm Complexity
Algorithmic complexity is a measure to measure the efficiency and performance of the algorithm.
Algorithms are usually evaluated in terms of the time and space required to solve a problem or
achieve a specific goal.
Two factors are used in the complexity of the algorithm. They are:-
1. Time factor.
2. Space factor.
Time factor:
Space analysis:
1. On the other hand, space complexity refers to the amount of memory or storage space
required to execute the algorithm.
2. This is important because it determines the number of resources required to run algorithms
that can affect the overall performance of your application or system.
3. If the space complexity of the algorithm is O(n), it uses an amount of memory that grows
linearly with the size of the input.
If the algorithm has O(1) space complexity, it uses a fixed amount of memory regardless of the
size of the input.
MAX (list)
max = list[0]
For i = 1 the length of the list
list IF[i] > max
max = list[i]
End for
Maximum return
Maximum end
Let's see the prime number program in C. In this c program, we will take an input from the user
and check whether the number is prime or not.
#include<stdio.h>
int main(){
int n, i, m=0, flag=0;
printf("Enter the number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is prime");
return 0;
}
Output:
Enter the number to check prime:56
Number is not prime
Enter the number to check prime:23
Number is prime
rand() function
In the C programming language, the rand() function is a library function that generates the random
number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need
to implement the stdlib.h header file because rand() function is defined in the stdlib header file. It
does not contain any seed number. Therefore, when we execute the same program again and again,
it returns the same values.
The rand() function returns the random integers whose range from 0 to RAND_MAX. The
RAND_MAX is a symbolic constant that defines in stdlib.h header file, whose value is greater but
less than 32767 depending on the C libraries.
srand() function
The srand() function is a C library function that determines the initial point to generate different
series of pseudo-random numbers. A srand() function cannot be used without using a rand()
function. The srand() function is required to set the value of the seed only once in a program to
generate the different results of random integers before calling the rand() function.
Syntax
1. int srand (unsigned int seed)
seed: It is an integer value that contains a seed for a new sequence of pseudo-random numbers.
Generate the random numbers using srand() function
Let's write a program to get the random numbers using srand() function in C.
srandNum.c
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <time.h> // use time.h header file to use time
4.
5. int main()
6. {
7. int num, i;
8. time_t t1; // declare time variable
9.
10. printf(" Enter a number to set the limit for a random number \n");
11. scanf (" %d", &num);
12.
13. /* define the random number generator */
14. srand ( (unsigned) time (&t1)); // pass the srand() parameter
15. printf("\n"); // print the space
16. /* generate random number between 0 to 50 */
17. for (i = 0; i <num; i++)
18. {
19. printf( "%d \n", rand() % 50);
20. }
21. return 0;
22. }
Output
Enter a number to set the limit for a random number
10
44 32 23 35 6 33 1 4 22 18
2nd execution of the program:
Enter a number to set the limit for a random number
15
13 30 24 27 4 30 28 35 36 13 44
As we can see in the above Output, it returns different sequences of random numbers on every
execution of the programming code.
// Driver code
int main()
{
int a = 10, b = 15;
// Function call
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
a = 35, b = 10;
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
a = 31, b = 2;
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
return 0;
}
The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next
element. And follow the same process until the respective element is found.
Now, the element to be searched is found. So algorithm will return the index of the element
matched.
Linear Search complexity
Now, let's see the time complexity of linear search in the best case, average case, and worst case.
We will also see the space complexity of linear search.
1. Time Complexity
o Best Case Complexity - In Linear search, best case occurs when the element we are
finding is at the first position of the array. The best-case time complexity of linear search
is O(1).
o Average Case Complexity - The average case time complexity of linear search is O(n).
o Worst Case Complexity - In Linear search, the worst case occurs when the element we
are looking is present at the end of the array. The worst-case in linear search could be when
the target element is not present in the given array, and we have to traverse the entire array.
The worst-case time complexity of linear search is O(n).
The time complexity of linear search is O(n) because every element in the array is compared only
once.
2. Space Complexity
Algorithm
1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound'
is the index of the first array element, 'upper_bound' is the index of the last array element,
'val' is the value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit
Working of Binary search
Now, let's see the working of the Binary Search Algorithm.
To understand the working of the Binary search algorithm, let's take a sorted array. It will be easy
to understand the working of Binary search with an example.
There are two methods to implement the binary search algorithm -
o Iterative method
o Recursive method
The recursive method of binary search follows the divide and conquer approach.
Let the elements of array are -
Usage:
Databases, search engines, and data processing are just a few of the applications that use the binary
search strategy.
Characteristics:
o The array of input values must be sorted.
o With each iteration, the method shrinks the search range by half, making it particularly
efficient for huge datasets.
o The algorithm has an O (log n) worst-case time complexity.
o Finding the desired value is done by the programme using a divide-and-conquer strategy.
Output
o Best Case Complexity - In Binary search, best case occurs when the element to search is
found in first comparison, i.e., when the first middle element itself is the element to be
searched. The best-case time complexity of Binary search is O(1).
o Average Case Complexity - The average case time complexity of Binary search
is O(logn).
o Worst Case Complexity - In Binary search, the worst case occurs, when we have to keep
reducing the search space till it has only one element. The worst-case time complexity of
Binary search is O(logn).
2. Space Complexity
Space Complexity O(1)
Advantages:
o For large datasets, the binary search algorithm is exceptionally efficient, and it is capable
of handling a wide range of input sizes.
o The algorithm is simple to implement in almost all programming languages.
Disadvantages:
o Before using the binary search technique, the input array must be sorted, which takes more
time and memory.
o The algorithm cannot be applied to unsorted arrays.
o The algorithm may yield inaccurate results if the input array is not sorted.
o The binary search algorithm is not appropriate for tiny datasets since the technique's
overhead may outweigh its benefits.
Conclusion:
A sorted array can be quickly searched for a specific element using the binary search technique. It
employs a divide-and-conquer strategy to cut the search range in half with each iteration, allowing
it to be highly efficient for large datasets. However, before using the binary search technique, the
input array must be sorted, which takes extra time and memory. The binary search algorithm is a
sophisticated data processing tool that is widely utilised in various sectors.
Sorting techniques, Insertion Sort, Selection Sort, Bubble Sort, Heap Sort
and Quick Sort
Sorting algorithms
C provides a rich set of data types and operators that can be used to implement various sorting
algorithms such as bubble sort, insertion sort and quick sort.
These algorithms are useful in many applications because they can be used to sort data of different
sizes and types.
There are different sorting algorithms.
They are:-
1. Bubble sort: An uncomplicated sorting algorithm that compares nearby components
repeatedly and switches them out if they are out of order.
Bubble sort is a simple and intuitive sorting algorithm. It repeatedly swaps adjacent
elements if they are in the wrong order until the array is sorted. In this algorithm, the largest
element "bubbles up" to the end of the array in each iteration. Bubble sort is inefficient for
large data sets, but it is useful for educational purposes and small data sets. In this section,
we will implement the bubble sort algorithm in C programming language.
Algorithm
In the algorithm given below, suppose arr is an array of n elements. The assumed swap function
in the algorithm will swap the values of given array elements.
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort
Working of Bubble sort Algorithm
Now, let's see the working of Bubble sort Algorithm.
To understand the working of bubble sort algorithm, let's take an unsorted array. We are taking a
short and accurate array, as we know the complexity of bubble sort is O(n2).
Let the elements of array are -
First Pass
Sorting will start from the initial two elements. Let compare them to check which is greater.
Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.
Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like -
Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be in between 35 and 10.
Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the end
of the array. After first pass, the array will be -
Now, move to the second iteration.
Second Pass
The same process will be followed for second iteration.
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -
Now, the first step is to define the bubble sort function. This function takes an integer array and
the size of the array as its parameters. The function returns nothing as it modifies the original array.
Here is the function definition:
1. void bubble_sort(int arr[], int n) {
2. int i, j;
3. for (i = 0; i < n - 1; i++) {
4. for (j = 0; j < n - i - 1; j++) {
5. if (arr[j] > arr[j + 1]) {
6. int temp = arr[j];
7. arr[j] = arr[j + 1];
8. arr[j + 1] = temp;
9. }
10. }
11. }
12. }
The function has two loops. The outer loop runs from the first element to the second-last element
of the array. The inner loop runs from the first element to the second-last element of the unsorted
part of the array. The condition of the inner loop is n - i - 1 because the last i elements of the array
are already sorted.
In each iteration of the inner loop, we compare adjacent elements. If the left element is greater than
the right element, we swap them. After the inner loop completes, the largest element is guaranteed
to be at the end of the unsorted part of the array.
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already
sorted. The best-case time complexity of bubble sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time complexity
of bubble sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending order,
but its elements are in descending order. The worst-case time complexity of bubble sort
is O(n2).
Space Complexity
Stable YES
o The space complexity of bubble sort is O(1). It is because, in bubble sort, an extra variable
is required for swapping.
o The space complexity of optimized bubble sort is O(2). It is because two extra variables
are required in optimized bubble sort.
Output
The main function creates an integer array arr of size 7 and initializes it with random numbers. We
then calculate the size of the array by dividing the size of the array by the size of an integer element.
Next, we call the bubble_sort function to sort the array. Finally, we print the sorted array using a
for loop.
When we run the program, we should see the following output:
Sorted array: 11 12 22 25 34 64 90
This output shows that our bubble sort implementation correctly sorted the array in ascending
order.
Characteristics:
Bubble sort is a simple sorting algorithm.
It works by repeatedly swapping adjacent elements if they are in the wrong order.
The algorithm sorts the array in ascending or descending order.
It has a time complexity of O(n2) in the worst case, where n is the size of the array.
Usage:
Bubble sort is useful for educational purposes and small data sets.
It is not suitable for large data sets because of its time complexity.
Advantages:
Bubble sort is easy to understand and implement.
It requires minimal additional memory space to perform the sorting.
Disadvantages:
It is not efficient for large data sets because of its time complexity.
It has poor performance compared to other sorting algorithms, such as quicksort and
mergesort.
Conclusion:
Bubble sort is a simple and intuitive sorting algorithm that is useful for educational
purposes and small data sets. However, its time complexity makes it inefficient for large
data sets. Therefore, it is not commonly used in real-world applications. Other sorting
algorithms, such as quick sort and merge sort, are more efficient for large data sets.
2. Insertion sort: a method of sorting that creates a sorted list one individual element at a
time by placing each one in the appropriate spot.
Insertion sort is a simple sorting algorithm that iteratively constructs a sorted section of an array
one element at a time. It is an in-place comparison-based method with an average time complexity
of O(n2).
The array is divided into two halves by the method: sorted and unsorted. The first element of the
array is first considered the sorted component, whereas the remaining items are originally
considered the unsorted component.
The algorithm subsequently compares each unsorted element to the elements in the sorted segment,
beginning at the end, and adjusts the bigger elements one position to the right until the unsorted
element is found in the correct location.
After determining the proper location, the unsorted element is placed into the sorted component at
that location.
This procedure is repeated until all of the members of the unsorted part have been inserted into the
sorted part, resulting in a fully sorted array.
The Algorithm for Insertion sort is:-
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the next
element. Else, shift greater elements in the array towards the right.
To understand the working of the insertion sort algorithm, let's take an unsorted array. It will be
easier to understand the insertion sort via an example.
Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now,
12 is stored in a sorted sub-array.
Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25. Along with
swapping, insertion sort will also check it with all elements in the sorted array.
For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the sorted
array remains sorted after swapping.
Now, two elements in the sorted array are 12 and 25. Move forward to the next elements that are
31 and 8.
Both 31 and 8 are not sorted. So, swap them.
ADVERTISEMENT
ADVERTISEMENT
Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that are 31 and
32.
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.
ADVERTISEMENT
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already
sorted. The best-case time complexity of insertion sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time complexity
of insertion sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending order,
but its elements are in descending order. The worst-case time complexity of insertion sort
is O(n2).
2. Space Complexity
Stable YES
1. #include <stdio.h>
2.
3. void insert(int a[], int n) /* function to sort an aay with insertion sort */
4. {
5. int i, j, temp;
6. for (i = 1; i < n; i++) {
7. temp = a[i];
8. j = i - 1;
9.
10. while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead fro
m their current position*/
11. {
12. a[j+1] = a[j];
13. j = j-1;
14. }
15. a[j+1] = temp;
16. }
17. }
18.
19. void printArr(int a[], int n) /* function to print the array */
20. {
21. int i;
22. for (i = 0; i < n; i++)
23. printf("%d ", a[i]);
24. }
25.
26. int main()
27. {
28. int a[] = { 12, 31, 25, 8, 32, 17 };
29. int n = sizeof(a) / sizeof(a[0]);
30. printf("Before sorting array elements are - \n");
31. printArr(a, n);
32. insert(a, n);
33. printf("\nAfter sorting array elements are - \n");
34. printArr(a, n);
35.
36. return 0;
37. }
Output:
Usage:
Insertion sort is useful for sorting small arrays and has decent speed when the input array is already
partially sorted. It is frequently used as a building piece in more advanced sorting algorithms such
as merge sort and quicksort.
Advantages:
Easy implementation: Because the approach is simple to build and understand, it is a great
option for teaching basic sorting concepts.
Because it sorts the array in place, insertion sort does not require any additional memory
space.
Insertion sort is an adaptive sorting algorithm that works best with partially sorted input
arrays.
Stable sorting means that the method keeps equal elements in the input array in the same
relative order.
Disadvantages:
o Slow for large arrays: With an average time complexity of O(n2), the algorithm is slow for
large arrays.
o Insertion sort is inefficient for random input arrays because it involves a large number of
comparisons and shifts.
o The algorithm is not suited for parallelization since each iteration is dependent on the
outcome of the preceding iteration.
Conclusion:
Insertion sort provides a straightforward and efficient approach for tiny or partially sorted arrays.
It is not ideal for huge arrays or random input, but it can be used to construct more complex sorting
algorithms. Overall, insertion sort is a solid solution for efficiently sorting small or partially sorted
arrays with little memory utilization.
Algorithm
SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT
Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is the
smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array
that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a sorted
way.
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
Now, the array is completely sorted.
1. Time Complexity
Case Time Complexity
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already sorted.
The best-case time complexity of selection sort is O(n2).
o Average Case Complexity - It occurs when the array elements are in jumbled order that is not
properly ascending and not properly descending. The average case time complexity of selection
sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse
order. That means suppose you have to sort the array elements in ascending order, but its elements
are in descending order. The worst-case time complexity of selection sort is O(n2).
2. Space Complexity
Space Complexity O(1)
Stable YES
o The space complexity of selection sort is O(1). It is because, in selection sort, an extra variable is
required for swapping.
After converting the given heap into max heap, the array elements are -
Next, we have to delete the root element (89) from the max heap. To delete this node, we have to
swap it with the last node, i.e. (11). After deleting the root element, we again have to heapify it to
convert it into max heap.
After swapping the array element 89 with 11, and converting the heap into max-heap, the elements
of array are -
In the next step, again, we have to delete the root element (81) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (54). After deleting the root element, we again
have to heapify it to convert it into max heap.
After swapping the array element 81 with 54 and converting the heap into max-heap, the elements
of array are -
In the next step, we have to delete the root element (76) from the max heap again. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have
to heapify it to convert it into max heap.
After swapping the array element 76 with 9 and converting the heap into max-heap, the elements
of array are -
In the next step, again we have to delete the root element (54) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (14). After deleting the root element, we again
have to heapify it to convert it into max heap.
After swapping the array element 54 with 14 and converting the heap into max-heap, the elements
of array are -
In the next step, again we have to delete the root element (22) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (11). After deleting the root element, we again
have to heapify it to convert it into max heap.
After swapping the array element 22 with 11 and converting the heap into max-heap, the elements
of array are -
In the next step, again we have to delete the root element (14) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have
to heapify it to convert it into max heap.
After swapping the array element 14 with 9 and converting the heap into max-heap, the elements
of array are -
In the next step, again we have to delete the root element (11) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have
to heapify it to convert it into max heap.
After swapping the array element 11 with 9, the elements of array are -
Now, heap has only one element left. After deleting it, heap will be empty.
After completion of sorting, the array elements are -
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already
sorted. The best-case time complexity of heap sort is O(n logn).
o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time complexity
of heap sort is O(n log n).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending order,
but its elements are in descending order. The worst-case time complexity of heap sort
is O(n log n).
The time complexity of heap sort is O(n logn) in all three cases (best case, average case, and worst
case). The height of a complete binary tree having n elements is logn.
2. Space Complexity
Space Complexity O(1)
Stable N0
1. #include <stdio.h>
2. /* function to heapify a subtree. Here 'i' is the
3. index of root node in array a[], and 'n' is the size of heap. */
4. void heapify(int a[], int n, int i)
5. {
6. int largest = i; // Initialize largest as root
7. int left = 2 * i + 1; // left child
8. int right = 2 * i + 2; // right child
9. // If left child is larger than root
10. if (left < n && a[left] > a[largest])
11. largest = left;
12. // If right child is larger than root
13. if (right < n && a[right] > a[largest])
14. largest = right;
15. // If root is not largest
16. if (largest != i) {
17. // swap a[i] with a[largest]
18. int temp = a[i];
19. a[i] = a[largest];
20. a[largest] = temp;
21.
22. heapify(a, n, largest);
23. }
24. }
25. /*Function to implement the heap sort*/
26. void heapSort(int a[], int n)
27. {
28. for (int i = n / 2 - 1; i >= 0; i--)
29. heapify(a, n, i);
30. // One by one extract an element from heap
31. for (int i = n - 1; i >= 0; i--) {
32. /* Move current root element to end*/
33. // swap a[0] with a[i]
34. int temp = a[0];
35. a[0] = a[i];
36. a[i] = temp;
37.
38. heapify(a, i, 0);
39. }
40. }
41. /* function to print the array elements */
42. void printArr(int arr[], int n)
43. {
44. for (int i = 0; i < n; ++i)
45. {
46. printf("%d", arr[i]);
47. printf(" ");
48. }
49.
50. }
51. int main()
52. {
53. int a[] = {48, 10, 23, 43, 28, 26, 1};
54. int n = sizeof(a) / sizeof(a[0]);
55. printf("Before sorting array elements are - \n");
56. printArr(a, n);
57. heapSort(a, n);
58. printf("\nAfter sorting array elements are - \n");
59. printArr(a, n);
60. return 0;
61. }
Output
Return Description
value
<0 If the ASCII value of a character of the first string is less than the ASCII
value of a character of the second string, then the function will return
negative value.
>0 If the ASCII value of a character of the first string is greater than the
ASCII value of a character of the second string, then the function will
return positive value.
o We have created two arrays of char type str1 and str2. We take the user input as strings.
o We have defined a stringcompare() function which will take two pointers of char type as a
parameter. The 'a' pointer holds the address of str1 and 'b' pointer holds the address of str2. Inside
the function, we have created a while loop which will execute until the pointer a or b is not reached
to a null character.
Output:
Strings Concatenation in C
The concatenation of strings is a process of combining two strings to form a single string. If there
are two strings, then the second string is added at the end of the first string.
For example, Hello + javaTpoint = Hello javaTpoint
We can concatenate the strings in the following two ways:
o Concatenate two strings using loop
o Concatenate two strings using pointer
o Concatenate two strings using strcat() function
Concatenate two strings using loop
1. #include <stdio.h>
2. int main()
3. {
4. char first_string[20]; // declaration of char array variable
5. char second_string[20]; // declaration of char array variable
6. int i; // integer variable declaration
7. printf("Enter the first string");
8. scanf("%s",first_string);
9. printf("\nEnter the second string");
10. scanf("%s",second_string);
11. for(i=0;first_string[i]!='\0';i++);
12.
13.
14. for(int j=0;second_string[j]!='\0';j++)
15. {
16.
17. first_string[i]=second_string[j];
18. i++;
19. }
20. first_string[i]='\0';
21. printf("After concatenation, the string would look like: %s", first_string);
22. return 0;
Analysis of the above program
o In the above program, we declare two strings, i.e., first_string and second_string. The
values of these two strings are taken by the user as an input.
o We will concatenate these two strings and store the result of concatenation in
the first_string
o We declare a new integer variable named 'i'. After declaration, we will run a loop that
iterates from i=0 till the null character of the first_string is encountered. When the
execution of the loop is completed, then the value of 'i' becomes equal to the length of the
string plus one.
o We will define another new loop, which is basically used to concatenate the two strings.
This loop starts from j=0 and executes until the null character of the second_string is
encountered. On each iteration, the character located at the jth position in
the second_string gets stored in the ith position of the first_string. In this way, both the
strings are combined together to form a single string.
Output
Concatenate two strings using pointer
1. #include <stdio.h>
2. int main()
3. {
4. char string1[20]; // char array declaration
5. char string2[20]; // char array declaration
6. int i=0,j=0; // declaration of integer variables
7. char *str1; // declaration of char pointer
8. char *str2; // declaration of char pointer
9. str1=string1;
10. str2=string2;
11. printf("Enter the first string");
12. scanf("%s",string1);
13. printf("\nEnter the second string");
14. scanf("%s", string2);
15. while(string1[i]!='\0')
16. {
17.
18. ++str1;
19. i++;
20. }
21. while(string2[j]!='\0')
22. {
23. *str1=*str2;
24. str1++;
25. str2++;
26. j++;
27. }
28. printf("The concatenated string is %s",string1);
29.
30. return 0;
31. }
o In the above program, we have declared character array variables, i.e., string1 and string2.
We take the two strings as user input and store them in the variables string1 and string2,
o We declare two char pointers str1 and str2. The str1 contains the address of string1, and
str2 contains the address of string2.
o We create a loop which iterates until the null character of string1 is encountered. When the
execution of the loop is completed, then the pointer str1 points to the location that exists
just after the location of the last character.
o We define another while loop that iterates till the null character of string2 is encountered.
On each iteration, the character stored at the jth location in the string2 is appended to the
string1 by using the statement *str1=*str2.
Output
Concatenation of two strings using strcat()
Now we will see how to concatenate two strings using strcat() function. The strcat() is an inbuilt
function defined in a string.h header file.
Let's look at the example.
1. #include <stdio.h>
2. #include<string.h>
3. int main()
4. {
5. char s1[20]; // declaration of char array
6. char s2[20]; // declaration of char array
7. printf("Enter the first string : ");
8. scanf("%s", s1);
9. printf("\nEnter the second string :");
10. scanf("%s",s2);
11. strcat(s1,s2);
12. printf("The concatenated string is : %s",s1);
13. return 0;
14. }
In the above code, we use the strcat() function to concatenate two strings. It takes two strings as a
parameter and then appends the second string at the end of the first string.
Output