Unit 2 Final Notes
Unit 2 Final Notes
Unit 2 Final Notes
(LOOP)
Syllabus
Conditional Branching and Loops :
Evalua1ion of Conditional and consequent branching
Iteration and loops
Array : Array ( 1-D.2-D).Character Array and String
Basic Algorithms: Searching. Basic Sorting Algorithms (Bubble,
Insertion and Selection). Finding root or equations. notion of
order of complexity through example programs (no formal
definition required)
Loops :
Any repeated task more than one time is called loop.
The looping can be defined as repeating the same process multiple times until a
specific condition satisfies. There are three types of loops used in the C
language.
The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and
again, we can repeat the same code for a finite number of times. For example, if
we need to print the first 10 natural numbers then, instead of using the printf
statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or
linked lists).
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do-while loop
The do-while loop continues until a given condition satisfies. It is also called
post tested loop or exit control loop. It is used when it is necessary to execute
the loop at least once (mostly menu driven programs). Even if the condition is
not true for the first time the control will enter in a loop.
do{
//code to be executed or Statement
}
while(condition);
do while example
1) There is given the simple program of c language do while loop where we
are printing the table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
2) Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
while loop in C
The block of statements is executed in the while loop until the condition
specified in the while loop is satisfied. It is also called a pre-tested loop. If the
condition is not true first time than control will never enter in a loop.
while(condition)
{
//code to be executed
}
Example of the while loop in C language
#include<stdio.h>
#include<conio.h>
int main()
{
int i=1;
while(i<=10)
{
printf("%d \n",i);
i++;
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
for loop
The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested
loop. It is better to use for loop if the number of iteration is known in advance.
The For Loop is a loop where the program tells the compiler to run a specific
code FOR a specified number of times.
This loop allows using three statements, first is the counter initialization, next is
the condition to check it and then there is an increment/decrement operation to
change the counter variable. You will understand it once we see some programs.
The syntax of for loop in c language is given below:
#include<stdio.h>
int main()
{
int i=0;
for(i=1;i<=10;i++)
{
printf("%d \n",i);
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Algorithm:
Step 1: Start.
Step 5: f = f * i.
Step 6: Go to step 3.
Step 8: Stop.
Flowchart:
#include <stdio.h>
#include <conio.h>
void main()
int i, a ,f = 1;
printf("Enter a number:\n");
scanf("%d", &a);
f=f*i;
getch();
Output:
Program: Print table for the given number using C for loop
#include<stdio.h>
int main()
{
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
return 0;
}
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Example 3
#include <stdio.h>
int main()
{
int i;
for(i=0;;i++)
{
printf("%d",i);
}
return 0;
For example,
Numbers like 0, 1, 2, 11, 44, 121, 222, 242, 345543 are called as
Palindrome Numbers.
Algorithm
1. #include<stdio.h>
2. int main()
3. {
4. int n,r,sum=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=(sum*10)+r;
12. n=n/10;
13. }
14. if(temp==sum)
15. printf("palindrome number ");
16. else
17. printf("not palindrome");
18. return 0;
19. }
Output:
3. If the condition is not If the condition is not true Even if the condition is not
true first time than first time than control will true for the first time the
control will never enter never enter in a loop. control will enter in a
in a loop loop.
6. For loop is use when we While loop is use when Do while loop is use when
know the number of we don't know the number we don't know the number
iterations means where of iterations means where of iterations means where
the loop will terminate. the loop will terminate. the loop will terminate.
1. Program to Display "Hello, World!"
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
// displays output
return 0;
#include <stdio.h>
int main()
{
int number1, number2, sum;
int main()
{
int number1, number2;
float res;
return 0;
}
#include<stdio.h>
int main()
{
int number, cube;
return 0;
}
In ‘C’ programming conditional statements are possible with the help of the
following two constructs:
1. If statement
if (condition)
instruction;
The condition evaluates to either true or false. True is always a non-zero
value, and false is a value that contains zero. Instructions can be a single
instruction or a code block enclosed by curly braces { }.
1.PROGRAM:
#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
int main()
{
int number;
else
printf("Given number %d is ODD NUMBER \n", number);
return 0;
}
C divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Operator Name Description Example
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
Operator Example Same as
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== equal to
!= not equal to
Logical Operators
&& Logical Returns true if both statements are true x < 5 && x <
and 10
! Logical Reverse the result, returns false if the !(x < 5 && x <
not result is true 10)
The if-else is statement is an extended version of If. The general form of if-
else is as follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
Program:
#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}
C Program to Find Largest of Two Numbers using Else If Statement
if(a > b)
{
printf("%d is Largest\n", a);
}
else if (b > a)
{
printf("%d is Largest\n", b);
}
else
{
printf("Both are Equal\n");
}
return 0;
}
C Program to find Largest of Three numbers using Else If Statement
#include <stdio.h>
int main()
{
int a, b, c;
printf("Please Enter three different values\n");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c)
{
printf("\n%d is Highest Among both %d and %d", a, b, c);
}
else if (b > a && b > c)
{
printf("\n%d is Highest Among both %d and %d", b, a, c);
}
else if (c > a && c > b)
{
printf("\n%d is Highest Among both %d and %d", c, a, b);
}
else
{
printf("\nEither any two values or all the three values are equal");
}
return 0;
}
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
C Nested If..else statement
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
PROGRAM:
#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}
PROGRAM:
#include<stdio.h>
int main()
{
int marks;
printf("Enter you subject Marks:\n");
scanf("%d",&marks);
#include<stdio.h>
int main()
{
int i, number;
return 0;
}
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
dataType arrayName[arraySize];
For example,
float mark[5];
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
If the size of an array is n , to access the last element, the n-1 index is used. In
this example, mark[4]
Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
Try it Yourself »
Example of Array In C programming to find out the average of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];
Initialization of a 2d array
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
Example 2: Sum of two matrices
// C program to find the sum of two matrices of order 2*2
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Multidimensional arrays
In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays. For example,
Float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as a table with 3 rows and each row has 4 columns.
Initialization of a 2d array
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Sum Of Matrix:
2.2 0.5
-0.9 25.0
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
#include <stdio.h>
#include <string.h>
int main () {
int main()
{
char s1[50], s2[50];
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
}
The searching of an element in the given array may be carried out in the following two ways-
1. Linear Search
2. Binary Search
Binary Search-
Binary Search is one of the fastest searching algorithms.
It is used for finding the location of an element in a linear array.
It works on the principle of divide and conquer technique.
Binary Search Algorithm can be applied only on Sorted arrays.
Since a[mid] = 20 > 15, so we take end = mid – 1 = 3 – 1 = 2 whereas beg remains unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 2) / 2
=1
Since a[mid] = 10 < 15, so we take beg = mid + 1 = 1 + 1 = 2 whereas end remains unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (2 + 2) / 2
=2
first = 0;
last = n - 1;
middle = (first+last)/2;
return 0;
}
It eliminates half of the list from further searching by using the result of each comparison.
It indicates whether the element being searched is before or after the current position in the list.
This information is used to narrow the search.
For large lists of data, it works significantly better than linear search.
Binary Search Algorithm Disadvantages-
The disadvantages of binary search algorithm are-
Searching Algorithms-
Searching Algorithms are a family of algorithms used for the purpose of searching.
The searching of an element in the given array may be carried out in the following two ways-
Linear Search-
Linear Search is the simplest searching algorithm.
It traverses the array sequentially to locate the required element.
It searches for an element by comparing it with each element of the array one by one.
So, it is also called as Sequential Search.
Worst Case-
The element being searched may be present at the last position or not present in the array at all.
In the former case, the search terminates in success with n comparisons.
In the later case, the search terminates in failure with n comparisons.
Thus in worst case, linear search algorithm takes O(n) operations.
Now,
Linear Search algorithm compares element 15 with all the elements of the array one by one.
It continues searching until either the element 15 is found or all the elements are searched.
Step-01:
Step-02:
It compares element 15 with the 2nd element 87.
Since 15 ≠ 87, so required element is not found.
So, it moves to the next element.
Step-03:
Step-04:
Algorithm
1. begin Bubble Sort(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
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.
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 b
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 -
Now, move to the third iteration.
Third Pass
The same process will be followed for third iteration.
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be –
Fourth pass
Similarly, after the fourth iteration, the array will be -
int main()
{
int arr[] = {5, 6, 2 ,6, 9, 0, -1}, n = 7, i, j;
swapped = 1;
}
if(!swapped)
break;
}
return 0;
}
// Bubble sort in C
#include <stdio.h>
// print array
void print Array(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
bubbleSort(data, size);
Consider the following elements are to be sorted in ascending order using selection
sort-
6, 2, 11, 7, 5
Here,
i = variable to traverse the array A
index = variable to store the index of minimum element
j = variable to traverse the unsorted sub-array
temp = temporary variable used for swapping
Step-02: For i = 1
Step-03: For i = 2
Step-04: For i = 3
Step-05: For i = 4
Time Complexity
Best Case n2
Average Case n2
Worst Case n2
#include<stdio.h>
int main(){
/* Here i & j for loop counters, temp for swapping,
* count for total number of elements, number[] to
* store the input numbers in array. You can
increase
* or decrease the size of number array as per
requirement
*/
int i, j, count, temp, number[25];
return 0;
}
Insertion Sort-
Firstly,
It selects the second element (2).
It checks whether it is smaller than any of the elements before it.
Since 2 < 6, so it shifts 6 towards right and places 2 before it.
The resulting list is 2, 6, 11, 7, 5.
Secondly,
It selects the third element (11).
It checks whether it is smaller than any of the elements before it.
Since 11 > (2, 6), so no shifting takes place.
The resulting list remains the same.
Thirdly,
It selects the fourth element (7).
It checks whether it is smaller than any of the elements before it.
Since 7 < 11, so it shifts 11 towards right and places 7 before it.
The resulting list is 2, 6, 7, 11, 5.
Fourthly,
It selects the fifth element (5).
It checks whether it is smaller than any of the elements before it.
Since 5 < (6, 7, 11), so it shifts (6, 7, 11) towards right and places 5 before them.
The resulting list is 2, 5, 6, 7, 11.
Here,
i = variable to traverse the array A
key = variable to store the new number to be inserted into the sorted sub-array
j = variable to traverse the sorted sub-array
Step-01: For i = 1
Step-02: For i = 2
Step-03: For i = 3
Step-04: For i = 4
Loop gets terminated as ‘i’ becomes 5. The state of array after the loops are finished-
Time Complexity
Best Case n
Average Case n2
Worst Case n2
/* C Program to sort an array in ascending order using
Insertion Sort */
1. #include <stdio.h>
2. int main()
3. {
4. int n, i, j, temp;
5. int arr[64];
6.
7. printf("Enter number of elements\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d integers\n", n);
11. for (i = 0; i < n; i++)
12. {
13. scanf("%d", &arr[i]);
14. }
15. for (i = 1 ; i <= n - 1; i++)
16. {
17. j = i;
18. while ( j > 0 && arr[j-1] > arr[j])
19. {
20. temp = arr[j];
21. arr[j] = arr[j-1];
22. arr[j-1] = temp;
23. j--;
24. }
25. }
26. printf("Sorted list in ascending order:\n");
27. for (i = 0; i <= n - 1; i++)
28. {
29. printf("%d\n", arr[i]);
30. }
31. return 0;
32. }
C Arrays
An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it.
dataType arrayName[arraySize];
For example,
float mark[5];
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
If the size of an array is n , to access the last element, the n-1 index is used. In
this example, mark[4]
Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
Try it Yourself »
Example of Array In C programming to find out the average of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];
Initialization of a 2d array
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
Example 2: Sum of two matrices
// C program to find the sum of two matrices of order 2*2
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Multidimensional arrays
In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays. For example,
Float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as a table with 3 rows and each row has 4 columns.
Initialization of a 2d array
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Sum Of Matrix:
2.2 0.5
-0.9 25.0
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
#include <stdio.h>
#include <string.h>
int main () {
int main()
{
char s1[50], s2[50];
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
}
SORTING
A sorting algorithm is an algorithm that puts elements of a list in a certain
order. The most used orders are numerical order and lexicographical order.
Efficient sorting is important to optimizing the use of other algorithms that
require sorted lists to work correctly and for producing human - readable
input.
Sorting algorithms are often classified by :
Computational complexity (worst, average and best case) in terms of the
size of the list (N).
For typical sorting algorithms good behaviour is O(NlogN) and worst case
behaviour is O(N2) and the average case behaviour is O(N).
Memory Utilization
Stability - Maintaining relative order of records with equal keys.
No. of comparisions.
Methods applied like Insertion, exchange, selection, merging etc.
Bubble Sort
Bubble Sort is a straightforward sorting algorithm that works by continually
comparing pairs of adjacent elements and swapping them if they are in the
wrong sequence.
This process repeats for the entire list of elements until there are no more swaps
to make, which means the list is entirely sorted.
The peculiarity of Bubble Sort is that it "bubbles" the larger elements towards
the end of the array, hence its name.
How it works
Imagine having a list of numbers. The algorithm starts at the beginning of the
list and compares the first two numbers. If the first number is bigger than the
second, it swaps them. Then it moves to the next number and does the same
thing, and continues to do so until it reaches the end of the list. This completes a
single pass through the list.
After the first pass, the largest number will have "bubbled" to the end of the list.
The process is then repeated for the rest of the list, except for the last element,
then the second last, and so on, until you get to the start of the list.
Algorithm:
Algorithm 1:
OR
Algorithm 2
The basic bubble sort algorithm can be explained as follows:
Example 1:
a[5]= {5,1,4,2,8}
Example 2: a[5]={4,9,5,1,0}
What is bubble sort complexity?
Time complexity is O(n 2) average and worst. The optimized solution has O(n)
best time. Bubble sort is for beginners to explore the sorting techniques. The
space complexity is O(1), it is an in-place operation.
. Bubble sort has a time complexity of O(N2) which makes it very slow for
large data sets.
Bubble sort is a comparison-based sorting algorithm, which means that it
requires a comparison operator to determine the relative order of elements
in the input data set. It can limit the efficiency of the algorithm in certain
cases.
Selection Sort
Selection Sort is a straightforward sorting algorithm based on in-place
comparison, that is, it works by repeatedly finding the minimum element
from the unsorted part of the list and placing it at the beginning.
The Selection sort algorithm is based on the idea of finding the minimum or
maximum element in an unsorted array and then putting it in its correct position
in a sorted array.
How it works
Suppose we have an array of n unsorted numbers. The algorithm works as
follows:
1. Starting from index 0, it searches for the minimum value in the array.
2. Once the minimum is found, it swaps it with the element at the starting
index.
3. It moves to the next index and repeats the process for the remaining
subarray.
4. This process is repeated until all elements in the array are sorted.
These steps are performed repeatedly until the entire array is sorted.
Algorithm:
Space complexity
Since this is an in-place sorting algorithm, thus requiring no additional space to
sort a collection, the space complexity is O(1), making it a good choice for
situations where memory usage is a crucial factor.
Selection sort has a time complexity of O(n^2) in the worst and average case.
Does not work well on large datasets.
Does not preserve the relative order of items with equal keys which means it is
not stable.
Insertion Sort
Insertion sort is a type of sorting algorithm used to arrange data in a set in
either ascending or descending order. Insertion sort is an in-place sorting
algorithm. In other words, it does not use any extra space or temporary array to
sort the data set. It sorts the elements of a set by modifying the order within the
list itself.
Keeping the cards example in mind, with any number of cards in hand the set is
always sorted from the left side. Similarly, in insertion algorithm, the sorting of
arrays always takes place from the left side. The process for this sorting begins
at index 1 (and never 0). Think of each index, starting from index 1, as a new
card handed over. Each new card received will be inserted into the sorted left
subarray. Hence, the element at index 1 is the key and each element is matched
with the key.
How it works
The functioning of the algorithm can be summarized in the following steps:
Advantages Disadvantages
The main advantage of the insertion The disadvantage of the insertion sort
sort is its simplicity. is that it does not perform as well as
other, better sorting algorithms
It also exhibits a good performance With n-squared steps required for
when dealing with a small list. every n element to be sorted, the
insertion sort does not deal well with
a huge list.
The insertion sort is an in-place The insertion sort is particularly
sorting algorithm so the space useful only when sorting a list of few
requirement is minimal. items.
Implementation Code
# include<stdio.h>
# include<conio.h>
# include<math.h>
main (){
float a,b,c,r1,r2,d;
printf (“enter the values of a b c”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0){
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“The real roots = %f %f”, r1, r2);
}
else if (d= =0){
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“roots are equal =%f %f”, r1, r2);
}
else
printf(“Roots are imaginary”);
getch ();
}
Testing
Case 1: enter the values of a b c: 1 4 3
r1 = -1
r2 = -3
Case 2: enter the values of a b c: 1 2 1
r1 = -1
r2 = -1
Case 3: enter the values of a b c: 1 1 4
Roots are imaginary