Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 2 Final Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

UNIT 2

(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.

Why use loops in 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.

The syntax of do-while loop in c language is given below:

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.

The syntax of while loop in c language is given below:

while(condition)
{
//code to be executed
}
Example of the while loop in C language

Simple program of while loop that prints 1 to 10.

#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:

for(initialization; condition; increment/decrement)


{
//code to be executed
}

For Loop Flowchart


for loop Examples

Simple program of for loop that prints table of 1.

#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

For Loop Examples


2.1. Program-1: Program to find the factorial of a number

Algorithm:

Step 1: Start.

Step 2: Initialize variables.

Step 3: Check FOR condition.

Step 4: If the condition is true, then go to step 5 otherwise go to step 7.

Step 5: f = f * i.
Step 6: Go to step 3.

Step 7: Print value of factorial.

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);

for (i = 1; i <= a; i++)

f=f*i;

printf("Factorial of %d is %d\n", a, f);

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;

Output: Infinite loop

Output is Infinite loop , Because condition is not present


C program for Palindrome number using For Loop
Before going to the program first let us understand what is a Palindrome
Number?
Palindrome Number:

It is a number which remains same even when the number is reversed.

For example,

Numbers like 0, 1, 2, 11, 44, 121, 222, 242, 345543 are called as
Palindrome Numbers.

Algorithm

o Get the number from user


o Hold the number in temporary variable
o Reverse the number
o Compare the temporary number with reversed number
o If both numbers are same, print palindrome number
o Else print not palindrome number

Program code to find whether a Number is Palindrome or Not?

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:

enter the number=151


palindrome number

enter the number=5621


not palindrome number

Difference between For, While and do- while Loop

Sr. For loop While loop Do while loop


No

1. Syntax: Syntax: While(condition), Syntax: Do


For(initialization;
condition; {. {.
incr/Decrement)
Statements; Statements;
{.
} } While(condition);
Statements;

2. It is known as entry It is known as entry It is known as exit


controlled loop controlled loop. controlled loop.
Sr. For loop While loop Do while loop
No

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.

4. There is no semicolon; There is no semicolon; There is semicolon; after


after the condition in the after the condition in the the condition in the syntax
syntax of the for loop. syntax of the while loop. of the do while loop.

5. Initialization and Initialization and updating Initialization and updating


updating is the part of the is not the part of the is not the part of the
syntax. syntax. syntax

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() displays the string inside quotation

printf("Hello, World!");

return 0;

2. C Program to Print an Integer (Entered by the User)

#include <stdio.h>

int main() {

int number;

printf("Enter an integer: ");

// reads and stores input

scanf("%d", &number);

// displays output

printf("You entered: %d", number);

return 0;

3. C Program to Add Two Integers

#include <stdio.h>
int main()
{
int number1, number2, sum;

printf(" Enter two integer values \n ");


scanf("%d %d", &number1, &number2);

sum = number1 + number2;

printf(" Sum of the two integer values is %d", sum);


return 0;
}
4. C Program to Find Average of Two Numbers
#include <stdio.h>

int main()
{
int number1, number2;
float res;

printf("Enter the First Number to find = ");


scanf("%d",&number1);

printf("Enter the Second Number to find = ");


scanf("%d",&number2);

int sm = number1 + number2;

res = sum/2; //(float)sum/2;

printf("The Sum of %d and %d = %d\n", number1, number2, sm);


printf("The Average of %d and %d = %.2f\n", number1, number2, res);

return 0;
}

5. C Program to Calculate Cube of a Number


/* C Program to find Cube of a Number */

#include<stdio.h>

int main()
{
int number, cube;

printf(" \n Please Enter any integer Value : ");


scanf("%d", &number);

cube = number * number * number;

printf("\n Cube of a given number %d is = %d", 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;
}

C Program to Check Odd or Even using IF Condition


#include<stdio.h>

int main()
{
int number;

printf(" Enter an int value to check \n");


scanf("%d", &number);

if ( number%2 == 0 ) //Check whether remainder is 0 or not


printf("Given number %d is EVEN NUMBER \n", 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

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable ++x


by 1

-- Decrement Decreases the value of a variable --x


by 1

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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

 Relational Operators Or Comparison operators

C has six relational operators that can be used to formulate a Boolean


expression for making a decision and testing conditions, which returns true or
false :

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

!= not equal to
Logical Operators
&& Logical Returns true if both statements are true x < 5 && x <
and 10

|| Logical or Returns true if one of the statements is x < 5 || x < 4


true

! Logical Reverse the result, returns false if the !(x < 5 && x <
not result is true 10)

The If-Else statement

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

/* C Program to Find Largest of Two numbers */


#include <stdio.h>
int main()
{
int a, b;
printf("Please Enter Two different values\n");
scanf("%d %d", &a, &b);

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);

if(marks >= 50)


{
printf("Congratulations\n"); //s1
printf("You cleared the subject"); //s2
}
else
{
printf("You Failed\n");//s3
printf("Better Luck Next Time");//s4
}
return 0;
}
C Program to Print Even Numbers from 1 to N
/* C Program to Print Even Numbers from 1 to N using For Loop and If */

#include<stdio.h>

int main()
{
int i, number;

printf("\n Please Enter the Maximum Limit Value : ");


scanf("%d", &number);

printf("\n Even Numbers between 1 and %d are : \n", number);


for(i = 1; i <= number; i++)
{
if ( i % 2 == 0 )
{
printf(" %d\t", i);
}
}

return 0;
}

// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if the two integers are equal.


if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}

//checks if both test expressions are false


else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}

Program to calculate the grade of the student according to the


specified marks.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }
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.

How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Access Array Elements


Suppose you declared an array mark as above. The first element is mark[0] , the
second element is mark[1] and so on.

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]

 Suppose the starting address of mark[0] is 2120d. Then, the address of


the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and
so on.
This is because the size of a float is 4 bytes.

 Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.
 To create an array, define the data type (like int) and specify the name
of the array followed by square brackets [].

int myNumbers[] = {25, 50, 75, 100};

Access the Elements of an Array


To access an array element, refer to its index number.

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

Loop Through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[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;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

Two dimensional Arrays

C language supports multidimensional arrays also. The simplest form


of a multidimensional array is the two-dimensional array. Both the
row's and column's index begins from 0.

Two-dimensional arrays are declared as follows,

data-type array-name[row-size][column-size]

/* Example */

int a[3][4];
Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};


Initialization of a 3d array

You can initialize a three-dimensional array in a similar way to a two-


dimensional array. Here's an example,

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];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

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

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

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];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

String and Character Array


String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0'. A string is actually a one-
dimensional array of characters in C language. These are often used to
create meaningful and readable programs.
For example: The string "home" contains 5 characters including
the '\0' character which is automatically added by the compiler at the
end of the string.

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose

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 () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

Example of strcpy() function:


#include<stdio.h>
#include<string.h>

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.

So, the elements must be arranged in-

 Either ascending order if the elements are numbers.


 Or dictionary order if the elements are strings.

To apply binary search on an unsorted array,

 First, sort the array using some sorting technique.


 Then, use binary search algorithm.

Binary Search Algorithm-


Consider-

 There is a linear array ‘a’ of size ‘n’.


 Binary search algorithm is being used to search an element ‘item’ in this linear array.
 If search ends in success, it sets loc to the index of the element otherwise it sets loc to -1.
 Variables beg and end keeps track of the index of the first and last element of the array or sub array in which the
element is being searched at that instant.
 Variable mid keeps track of the index of the middle element of that array or sub array in which the element is being
searched at that instant.

Binary Search Example-


Consider-

 We are given the following sorted linear array.


 Element 15 has to be searched in it using Binary Search Algorithm.
Step-01:

 To begin with, we take beg=0 and end=6.


 We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 6) / 2
=3

 Here, a[mid] = a[3] = 20 ≠ 15 and beg < end.


 So, we start next iteration.
Step-02:

 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

 Here, a[mid] = a[1] = 10 ≠ 15 and beg < end.


 So, we start next iteration.
Step-03:

 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

 Here, a[mid] = a[2] = 15 which matches to the element being searched.


 So, our search terminates in success and index 2 is returned.
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the
list.\n", search);

return 0;
}

Binary Search Algorithm Advantages-


The advantages of binary search algorithm are-

 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-

 It employs recursive approach which requires more stack space.


 Programming binary search algorithm is error prone and difficult.
 The interaction of binary search with memory hierarchy i.e. caching is poor.
(because of its random access nature)

Linear Search Algorithm


Searching-
 Searching is a process of finding a particular element among several given elements.
 The search is successful if the required element is found.
 Otherwise, the search is unsuccessful.

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.

Linear Search Algorithm is applied when-

 No information is given about the array.


 The given array is unsorted or the elements are unordered.
 The list of data items is smaller.

Linear Search Algorithm-


Consider-

 There is a linear array ‘a’ of size ‘n’.


 Linear search algorithm is being used to search an element ‘item’ in this linear array.
 If search ends in success, it sets loc to the index of the element otherwise it sets loc to -1.

Then, Linear Search Algorithm is as follows-


Best case-

In the best possible case,

 The element being searched may be found at the first position.


 In this case, the search terminates in success with just one comparison.
 Thus in best case, linear search algorithm takes O(1) operations.

Worst Case-

In the worst possible 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.

Linear Search Example-


Consider-

 We are given the following linear array.


 Element 15 has to be searched in it using Linear Search Algorithm.

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.

Linear Search Algorithm works in the following steps-

Step-01:

 It compares element 15 with the 1st element 92.


 Since 15 ≠ 92, so required element is not found.
 So, it moves to the next element.

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:

 It compares element 15 with the 3rd element 53.


 Since 15 ≠ 53, so required element is not found.
 So, it moves to the next element.

Step-04:

 It compares element 15 with the 4th element 10.


 Since 15 ≠ 10, so required element is not found.
 So, it moves to the next element.
Step-05:

 It compares element 15 with the 5th element 15.


 Since 15 = 15, so required element is found.
 Now, it stops the comparison and returns index 4 at which element 15 is present.
 #include <stdio.h>
 int main()
 {
 int a[10], i, item,n;
 printf("\nEnter number of elements of an array:\n");
 scanf("%d",&n);
 printf("\nEnter elements: \n");
 for (i=0; i<n; i++)
 scanf("%d", &a[i]);
 printf("\nEnter item to search: ");
 scanf("%d", &item);
 for (i=0; i<=9; i++)
 if (item == a[i])
 {
 printf("\nItem found at location %d", i+1);
 break;
 }
 if (i > 9)
 printf("\nItem does not exist.");
 return 0;
 }
Bubble sort Algorithm
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like the
movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the array
elements in bubble sort move to the end in each iteration.

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

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 –

Now, compare 32 and 35.

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 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 –

Now, move to the fourth iteration.

Fourth pass
Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.


#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++){
printf("%d ", arr[x]);
}
return 0;
}

Implementation of bubble sort in C


#include<stdio.h>

int main()
{
int arr[] = {5, 6, 2 ,6, 9, 0, -1}, n = 7, i, j;

for(i = 0; i < n - 1; ++i)


{
int swapped = 0;

for(j = 0; j < (n - i - 1); ++j)


if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;

swapped = 1;
}
if(!swapped)
break;
}

printf("\nArray after sorting: ");


for(i = 0; i < n; ++i)
printf("%d ", arr[i]);

return 0;
}

// Bubble sort in C

#include <stdio.h>

// perform the bubble sort


void bubble Sort(int array[], int size)
{

// loop to access each array element


for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step - 1; ++i) {

// compare two adjacent elements


// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

// 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};

// find the array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");


printArray(data, size);
}
Selection Sort-

 Selection sort is one of the easiest approaches to sorting.


 It is inspired from the way in which we sort things out in day to day life.
 It is an in-place sorting algorithm because it uses no auxiliary data structures while
sorting.

How Selection Sort Works?

Consider the following elements are to be sorted in ascending order using selection
sort-
6, 2, 11, 7, 5

Selection sort works as-


 It finds the first smallest element (2).
 It swaps it with the first element of the unordered list.
 It finds the second smallest element (5).
 It swaps it with the second element of the unordered list.
 Similarly, it continues to sort the given elements.

As a result, sorted elements in ascending order are-


2, 5, 6, 7, 11

Selection Sort Algorithm-


Let A be an array with n elements. Then, selection sort algorithm used for sorting is as
follows-

for (i = 0 ; i < n-1 ; i++)


{
index = i;
for(j = i+1 ; j < n ; j++)
{
if(A[j] < A[index])
index = j;
}
temp = A[i];
A[i] = A[index];
A[index] = temp;
}

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

Selection Sort Example-

Consider the following elements are to be sorted in ascending order-


6, 2, 11, 7, 5
Step-01: For i = 0

Step-02: For i = 1
Step-03: For i = 2

Step-04: For i = 3

Step-05: For i = 4

Loop gets terminated as ‘i’ becomes 4.

The state of array after the loops are finished is as shown-


With each loop cycle,
 The minimum element in unsorted sub-array is selected.
 It is then placed at the correct location in the sorted sub-array until array A is
completely sorted.

Time Complexity Analysis-

 Selection sort algorithm consists of two nested loops.


 Owing to the two nested loops, it has O(n 2) time complexity.

Time Complexity

Best Case n2

Average Case n2

Worst Case n2

Code for Selection Sort:

#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];

printf("How many numbers u are going to enter?: ");


scanf("%d",&count);

printf("Enter %d elements: ", count);


// Loop to get the elements stored in array
for(i=0;i<count;i++)
scanf("%d",&number[i]);

// Logic of selection sort algorithm


for(i=0;i<count;i++){
for(j=i+1;j<count;j++){
if(number[i]>number[j]){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}

printf("Sorted elements: ");


for(i=0;i<count;i++)
printf(" %d",number[i]);

return 0;
}
Insertion Sort-

 Insertion sort is an in-place sorting algorithm.


 It uses no auxiliary data structures while sorting.
 It is inspired from the way in which we sort playing cards.

How Insertion Sort Works?

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.

Insertion Sort Algorithm-


Let A be an array with n elements. The insertion sort algorithm used for sorting is as
follows-

for (i = 1 ; i < n ; i++)


{
key = A [ i ];
j = i - 1;
while(j > 0 && A [ j ] > key)
{
A [ j+1 ] = A [ j ];
j--;
}
A [ j+1 ] = key;
}

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

Insertion Sort Example-

Consider the following elements are to be sorted in ascending order-


6, 2, 11, 7, 5

The above insertion sort algorithm works as illustrated below-

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 Analysis-

 Selection sort algorithm consists of two nested loops.


 Owing to the two nested loops, it has O(n 2) time complexity.

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.

How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Access Array Elements


Suppose you declared an array mark as above. The first element is mark[0] , the
second element is mark[1] and so on.

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]

 Suppose the starting address of mark[0] is 2120d. Then, the address of


the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and
so on.
This is because the size of a float is 4 bytes.

 Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.
 To create an array, define the data type (like int) and specify the name
of the array followed by square brackets [].

int myNumbers[] = {25, 50, 75, 100};

Access the Elements of an Array


To access an array element, refer to its index number.

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

Loop Through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[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;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

Two dimensional Arrays

C language supports multidimensional arrays also. The simplest form


of a multidimensional array is the two-dimensional array. Both the
row's and column's index begins from 0.

Two-dimensional arrays are declared as follows,

data-type array-name[row-size][column-size]

/* Example */

int a[3][4];
Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};


Initialization of a 3d array

You can initialize a three-dimensional array in a similar way to a two-


dimensional array. Here's an example,

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];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

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

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

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];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

String and Character Array


String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0'. A string is actually a one-
dimensional array of characters in C language. These are often used to
create meaningful and readable programs.
For example: The string "home" contains 5 characters including
the '\0' character which is automatically added by the compiler at the
end of the string.

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose

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 () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

Example of strcpy() function:


#include<stdio.h>
#include<string.h>

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.

Sorting is a process of linear ordering of list objects. Sorting techniques


are categorized into
Internal Sorting
External Sorting
Internal Sorting takes place in the main memory of a computer.

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:

Step1: bubble Sort(array)

Step2: for i <- 1 to index Of Last Unsorted Element-1

Step3: if left Element > right Element

Step4: swap left Element and right Element

Step5: end bubble Sort

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.

Advantages of Bubble Sort:

 Bubble sort is easy to understand and implement.


 It does not require any additional memory space.
 It is a stable sorting algorithm, meaning that elements with the same key
value maintain their relative order in the sorted output.

Disadvantages of Bubble Sort:

. 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.

Assume that the array []=[7,5,4,2] needs to be sorted in ascending order.


The minimum element in the array i.e. 2 is searched for and then swapped with
the element that is currently located at the first position, i.e. 7. Now the
minimum element in the remaining unsorted array is searched for and put in the
second position, and so on.

Algorithm:

Algorithm 1 for the Selection Sort


The selection sort algorithm is as follows:

Step 1: Set Min to location 0 in Step 1.


Step 2: Look for the smallest element on the list.

Step 3: Replace the value at location Min with a different value.

Step 4: Increase Min to point to the next element

Step 5: Continue until the list is sorted.

Algorithm 2 for the Selection Sort


Time complexity
In the worst, average and best case, the time complexity is O(n²), where n is the
number of elements to be sorted.

This is because the algorithm performs a number of comparisons proportional to


the square of the number of elements, irrespective of their initial arrangement.

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.

Advantages of Selection Sort Algorithm

 Simple and easy to understand.


 Works well with small datasets.

Disadvantages of the Selection Sort Algorithm

 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.

Insertion Sort is a sorting algorithm that operates in a way similar to the


process by which many people sort cards in their hands during a game. It simply
takes one element at a time and inserts it into the correct position within the
already sorted list, moving all subsequent elements.

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:

1. It starts from the second element (index 1 in zero-based array),


considering the first element as already sorted.
2. It takes the current element and compares it with all preceding elements
in the array.
3. If the current element is smaller than its predecessor, it swaps the two
elements and continues to compare with all other preceding elements.
4. This process continues until the current element is larger than its
predecessor or until it reaches the beginning of the array, indicating that
the current element is the smallest in the array up to that point.
5. It moves on to the next element in the array and repeats the process until
all the elements in the array have been sorted.
Algorithm:

Algorithm 1 for Insertion Sort


 Step 1 − If the element is the first one, it is already sorted.
 Step 2 – Move to next element
 Step 3 − Compare the current element with all elements in the sorted array
 Step 4 – If the element in the sorted array is smaller than the current
element, iterate to the next element. Otherwise, shift all the greater element
in the array by one position towards the right
 Step 5 − Insert the value at the correct position
 Step 6 − Repeat until the complete list is sorted

Algorithm 2 for Insertion Sort


An example with the data set 51, 11, 61, 21, 41, and 31 for step-by-step
understanding is given below:

Complexity Analysis of Insertion Sort:

Time Complexity of Insertion Sort


 The worst-case time complexity of the Insertion sort is O(N^2) or O(n²)
 The average case time complexity of the Insertion sort is O(N^2)or O(n²)
 The time complexity of the best case is O(N).

Space Complexity of Insertion Sort


The auxiliary space complexity of Insertion Sort is O(1)
Characteristics of Insertion Sort
 This algorithm is one of the simplest algorithms with a simple
implementation
 Basically, Insertion sort is efficient for small data values
 Insertion sort is adaptive in nature, i.e. it is appropriate for data sets that are
already partially sorted.

Advantages and Disadvantages of Insertion Sort

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.

How to write a C program to find the roots of a quadratic


equation?
Solution

Find roots of a quadratic equation, ax2+bx+c.
 There will be 2 roots for given quadratic equation.
Analysis
Input − a,b,c values
Output − r1, r2 values
Procedure
Design (Algorithm)
 Start
 Read a, b, c values
 Compute d = b2 4ac
 if d > 0 then
o r1 = b+ sqrt (d)/(2*a)
o r2 = b sqrt(d)/(2*a)
 Otherwise if d = 0 then
o compute r1 = -b/2a, r2=-b/2a
o print r1,r2 values
 Otherwise if d < 0 then print roots are imaginary
 Stop

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

Notion of order of complexity in C

In C programming, the Order of Complexity of an algorithm depends on the


number of operations performed by the program. For example, if we have an
array of size n and we want to search for a particular element in the array, the
Order of Complexity of the algorithm will depend on the number of elements in
the array.

You might also like