Understanding Algorithms and Programming Concepts
Understanding Algorithms and Programming Concepts
Advantage: An algorithm acts a blue print of a program and helps during program development.
1. Input: An algorithm usually takes some input data, which is necessary to produce a result.
2. Output: It provides at least one output, which is the solution to the problem or the result of the task.
4. Finiteness: An algorithm must have a finite number of steps and should terminate after completing
the task.
5. Effectiveness: The steps of the algorithm must be simple enough to be carried out, in a finite amount
of time, by a person or a computer.
1. Time Complexity: Time complexity measures the amount of time an algorithm takes to complete
as a function of the size of the input (denoted as n). It gives an upper bound on the running time in
the worst, average, or best-case scenario.
2. Space Complexity: Space complexity refers to the amount of memory an algorithm uses in terms
of the size of the input.
Modular Programming is a software design technique in which a program is divided into separate,
independent modules, each responsible for a specific task. These modules can be developed, tested, and
maintained individually, and later combined to form the complete system.
1
6. Define an Algorithm. Mention two qualities of a good Algorithm.
Qualities:
7. Define Asymptotic notation List any two. / Explain the various Asymptotic Notations with their
significance.
Asymptotic notations are mathematical tools used to describe the time complexity and space
complexity of algorithms in terms of input size (n). They help in analyzing the performance and
efficiency of algorithms, especially for large inputs.
1. Big-O Notation (O-notation)
• Represents the upper bound of an algorithm’s growth rate.
• Describes the worst-case complexity.
• Ensures that the algorithm will not take more time than this bound.
Example:
If an algorithm takes at most 3n² + 2n + 4 steps, its complexity is O(n²).
2. Omega Notation (Ω-notation)
• Represents the lower bound of an algorithm’s growth rate.
• Describes the best-case complexity.
• Ensures that the algorithm will take at least this much time.
Example:
If an algorithm takes at least 2n steps, its complexity is Ω(n).
3. Theta Notation (Θ-notation)
• Represents the tight bound of an algorithm’s growth rate.
• Describes both upper and lower bounds.
• Indicates the average-case complexity (exact rate of growth).
Example:
If an algorithm takes between 2n and 5n steps, its complexity is Θ(n).
2
8. Write an algorithm to exchange the values of two variables.
1. Start. Working:
2. Input two variables, A and B. 1. Start
3. Store the value of A in a temporary 2. Lets input A = 10, B= 20
variable, temp (temp = A)
3. temp = 10 (temp =)
4. Assign the value of B to A (A=B) 4. A=20 (A=B)
5. Assign the value of temp (which holds the 5. B=10(B=temp)
original value of A) to B(B=temp) 6. Output A=20, B=10
6. Output the new values of A and B. 7. End
7. End.
Algorithm (Without Using a Temporary Variable):
1. Start. Working:
2. Input two variables, A and B. 1. Start
3. Add A and B and store the result in A (A 2. Lets input A=10, B=20
= A + B).
3. A=10+20=> A=30 (A=A+B)
4. Subtract B from A and store the result in 4. B=30-20=> B=10 (B=A-B)
B (B = A - B).
5. A=30-10 => A=20 (A=A-B)
5. Subtract the new value of B from A and 6. Output A=20, B=10
store the result in A (A = A - B).
7. End
6. Output the new values of A and B.
7. End.
9. Write an algorithm for summation of set of numbers. / Write an algorithm for summation of N-
natural numbers.
Algorithm:
1. Start
2. Declare a list of numbers.
3. Initialize a variable sum = 0 to store the sum of numbers.
4. For each number in the list:
a. Add the current number to sum.
5. After the loop ends, print the value of sum.
6. End
3
Example:Suppose the list = [5, 10, 15, 20]
Algorithm
1. Start
2. Input the number n (number of Fibonacci terms to generate).
3. Initialize variables:
a. a = 0 (this holds F(0))
b. b = 1 (this holds F(1))
4. Print a and b (the first two terms of the Fibonacci sequence).
5. For i=2 to n (generate subsequent terms):
a. Set next = a + b (next term in the sequence).
b. Print next.
c. Update a = b and b = next (move forward in the sequence).
6. End
Working
1. Input n = 6.
2. Initialize a = 0, b = 1.
3. Print 0, 1.
4. Loop from 2 to 6:
a. next=a+b → next = 0 + 1 = 1, print 1
Update a = 1, b = 1
b. next=a+b→ next = 1 + 1 = 2, print 2
Update a = 1, b = 2
c. next=a+b→ next = 1 + 2 = 3, print 3
Update a = 2, b = 3
d. next=a+b→ next = 2 + 3 = 5, print 5
4
5. End
• The sequence generated: 0, 1, 1, 2, 3, 5.
1. Start 1. Start
2. Input the number n. 2. Input n = 5.
3. Initialize a variable fact = 1 to store the 3. Initialize fact = 1.
factorial. 4. Loop from i=2 to 5:
4. If n=0 or n=1, return fact = 1. a. fact = 1 * 2 → fact = 2
5. For each number i from 2 to n: b. fact = 2 * 3 → fact = 6
Multiply fact by i (i.e., fact = fact * i). c. fact = 6 * 4 → fact = 24
6. After the loop ends, fact will hold the d. fact = 24 * 5 → fact = 120
value of n!. 5. The final value of fact is 120.
7. Print fact. 6. End
8. End
Example:For n=123:
5
4 while(0>0) False
Output: reverse = 321
14. Write an algorithm for a given set of ‘n’ students examination marks (in range 0 to 100) make a
count of the number of students that passes the examination. A pass is awarded for all marks of
50 and above. / Write an algorithm for counting.
Algorithm
1. Start
2. Input number of students n
3. Initialize a counter variable count = 0.
4. For each element in the list (repeat steps for each student i to n):
b. Input marks of student i
c. if marks>=50,Increment count by 1(count=count+1).
5. Print the value of count.
6. End
Example: Suppose n = 5 and the marks are: 45, 67, 89, 32, 50
6
15. Write an algorithm for a given set of ‘n’ students that adds these numbers and display the
resultant sum. Assume ‘n’ is greater than or equal to zero. / Write an algorithm for counting.
1. Start
2. Input number of students n
3. Initialize sum = 0.
4. For each element in the list (repeat steps for each student i to n):
d. Input marks of student i
e. add marks to sum -> sum=sum+marks
5. Print the value of sum.
6. End
Example: Suppose n = 5 and the marks are: 10, 20, 30, 40, 50
UNIT 02
A token is the smallest unit in a program that has meaning to the compiler.
7
4. What is an array? Give the syntax and example. / Define array. Give an example. / What is an
array? How it is initialized. / Write the statements to print the elements of an array.
printf("%d", arr[i]);
5. Define variable and constant. Give one example for each. / What is a Constant? How it is
declared in C.
int *p = &a;
Escape sequences are special character combinations used to represent non-printable characters.
11. Explain the structure of a C program/ Write the basic structure of C program
A C program follows a well-defined structure consisting of different sections. The basic structure is:
1. Documentation Section: Contains comments about the program (name, purpose, author, date).
2. Link Section/Preprocessor Directives: Used to include header files that contain library
functions.
o Example:#define PI 3.14
4. Global Declaration Section: Variables and functions declared here can be used throughout the
program.
5. main() Function Section: Every C program must have a main() [Link] of the
program begins [Link] contains:
o Variable declarations
o Program statements - Use functions like printf() for output and scanf() for input to interact
with the user. These functions are defined in the stdio.h header file.
6. Subprogram Section: Contains user-defined functions that are called from main().
9
printf("Enter two numbers: ");
return 0;
13. Explain the different data types supported by C language Mention their range and size/ What is
datatype? Explain different datatypes with examples
A data type in programming defines the kind of data that can be stored and manipulated within a program.
o Primitive Data Types: These are basic types provided by the programming language. In C,
primitive data types include:
10
▪ Integer Types (int, short, long, unsigned int, etc.)
o Derived Data Types: These are built from primitive data types. Examples include:
▪ Unions: Similar to structures but can store different data types in the same memory location.
Stores a single
-128 to 127 (signed) or 0 to char j =
char character/letter/number, %c 1
255 (unsigned) 'A';
or ASCII values
11
14. What is type casting? Write a C program to differentiate implicit and explicit type casting.
Type casting in C is the process of converting a variable from one data type to another.
It is of two types:
o Example: (float)a / b.
#include <stdio.h>
int main() {
int a = 5, b = 2;
float result1, result2;
// Implicit Type Casting
result1 = a / b; // both are integers, result is 2 (converted to 2.0 automatically)
// Explicit Type Casting
result2 = (float)a / b; // 'a' is explicitly converted to float before division
printf("Implicit Type Casting Result = %f\n", result1);
printf("Explicit Type Casting Result = %f\n", result2);
return 0;
}
15. Explain the difference between call by reference and call by value with an example for each.
12
Usage Used when we don’t want the function Used when the function should
to modify original values. modify the original values.
Call by Value
#include <stdio.h>
void change(int x) {
x = x + 10; // changes only local copy
}
int main() {
int a = 5;
change(a);
printf("Value of a (after call by value): %d\n", a);
return 0;
}
Output: Value of a (after call by value): 5
Call by Reference
#include <stdio.h>
void change(int *x) {
*x = *x + 10; // changes original variable
}
int main() {
int a = 5;
change(&a);
printf("Value of a (after call by reference): %d\n", a);
return 0;
}
Output: Value of a (after call by reference): 15
16. Mention any 5 string library functions/ Explain various operations performed on strings with
example for each.
13
strcpy(dest, Copies the source string (src) to the strcpy(dest, "World") copies "World"
src) destination string (dest). into dest
strncpy(dest, Copies at most n characters of the source strncpy(dest, src, 4) copies first 4 chars
src, n) string to the destination. from src
strcat(dest, Concatenates the source string (src) to the strcat(str1, "World") appends "World"
src) end of the destination (dest). to str1
strncat(dest, Appends the first n characters of the source strncat(str1, src, 3) concatenates 3 chars
src, n) to the destination. of src
strncmp(str1, Compares the first n characters of the strncmp("abc", "abd", 2) returns 0 (first
str2, n) strings. 2 chars same)
strchr(str, c) Searches for the first occurrence of character strchr("Hello", 'e') returns pointer to 'e'
c in the string str.
strrchr(str, c) Searches for the last occurrence of character strrchr("Hello", 'l') returns pointer to
c in the string. last 'l'
strstr(str1, Searches for the first occurrence of the strstr("Hello World", "World") returns
str2) substring str2 in str1. pointer to World
strdup(str) Duplicates the string str and returns a pointer char *copy = strdup("Hello");
to the newly allocated copy.
strtok(str, Splits the string str into tokens based on the strtok("a,b,c", ",") returns tokens "a",
delim) delimiter delim. "b", "c"
17. Explain loop control structures in C with general syntax./ Explain various forms of looping
structures available in C.
In C programming, looping control structures allow the execution of a block of code repeatedly based
on a condition. Loops are an essential part of programming as they enable automation of repetitive tasks.
The three primary types of loops in C are:
1. for loop
2. while loop
14
3. do-while loop
Each loop operates differently but serves the purpose of repeating a set of instructions.
1. for Loop
The for loop is used when you know how many times you want to repeat a block of code. It has three
components: initialization, condition, and increment/decrement.
Syntax: Example:
Explanation:
The loop runs as long as the condition (i <= 5) is true. When i becomes 6, the loop stops.
2. while Loop: The while loop is used when you want to repeat a block of code as long as a condition is
true. It checks the condition before executing the block of code.
Example: i++;}
Explanation:
o When i becomes 6, the condition i <= 5 becomes false, and the loop stops.
15
3. do-while Loop: The do-while loop is similar to the while loop, but the key difference is that it executes
the block of code at least once before checking the condition. The condition is evaluated after the code is
executed.
Syntax: int i = 1;
do { do {
Example:
Explanation:
o The block of code inside the do section is executed first, even if the condition is false.
18. Differentiate between while and do-while loop. Illustrate with example
Condition The condition is checked before the The condition is checked after the loop
Check loop body executes (pre-test loop). body executes (post-test loop).
Execution The loop body may not execute at all The loop body executes at least once,
Guarantee if the condition is false initially. even if the condition is false initially.
Best Use Case When you want to repeat a block of When you need to ensure that the loop
code as long as the condition is true. body is executed at least once, regardless
of the condition.
Common Used when the condition needs to be Used when the loop must run at least
Scenario evaluated before the loop begins. once, often when input or data must be
processed before evaluating a condition.
16
Flow of 1. Check condition 2. Execute loop 1. Execute loop body 2. Check condition
Execution body if true 3. Repeat 3. Repeat if true
When Condition The loop body will not execute at all The loop body will execute once, even if
is False Initially if the condition is false. the condition is false initially.
Common Use Situations where it's possible that the Situations where the loop body must run
loop body should not be executed if at least once before condition checking.
the condition is false initially.
19. What is pointers. How to initialize pointer arrays/ Illustrate the declaration and initialization of
pointers with an example./ What is pointer? Explain with an example./ Write a short note on
Pointer.
A pointer is a variable that holds the address of another variable, allowing indirect access to data.
• A pointer can be used to store the address of the first element of an array.
Here,
• p points to arr[0]
// Pointer initialization
ptr = &a;
// Pointer to array
int arr[3] = {10, 20, 30};
int *p = arr;
return 0;
}
Output:
Value of a = 5
Address of a = 0x7ffee2f49a3c
10 20 30
18
20. What is a Pointer. Write a program to find the size of Integer Character and Real Pointer.
A pointer is a variable that holds the address of another variable, allowing indirect access to data.
#include <stdio.h>
int main() {
int *iptr; // pointer to int
char *cptr; // pointer to char
float *fptr; // pointer to float
double *dptr; // pointer to double
printf("Size of Integer Pointer = %lu bytes\n", sizeof(iptr));
printf("Size of Character Pointer = %lu bytes\n", sizeof(cptr));
printf("Size of Float Pointer = %lu bytes\n", sizeof(fptr));
printf("Size of Double Pointer = %lu bytes\n", sizeof(dptr));
return 0;
}
Output:
19
21. Explain formatted input and output statements.
C provides functions for formatted input (taking values from the user) and formatted output (displaying
values in a specific format).
Example:
int age;
Example:
• Syntax: gets(string_variable);
Example:
char name[30];
• Syntax: puts(string_variable);
20
Example: puts(name); // Prints the string
%d Integer 10
%c Character A
%s String Hello
22. Explain different forms of If statement with syntax and example. / Explain decision – making
statements in C language.
In C programming, selection statements allow us to make decisions based on certain conditions. These
statements enable the program to execute different blocks of code depending on the outcome of a
condition. The most common selection statements in C are:
1. if statement
2. if-else statement
3. if-else if ladder
4. switch statement
Each of these statements is used to select and execute specific code blocks based on conditions.
1. if Statement: The if statement is the simplest form of a selection statement. It executes a block of code
if a specified condition is true.
Syntax: Example:
} }
21
Explanation: If the condition number > 5 is true, the block inside the if statement will execute.
2. if-else Statement: The if-else statement is used when we want to execute one block of code if the
condition is true and another block if the condition is false.
Syntax: Example:
} else { } else {
Explanation: If the condition number > 5 is false, the code in the else block will execute.
[Link]-else if Ladder: The if-else if ladder allows you to test multiple conditions. Once a condition
evaluates to true, the corresponding block of code is executed, and the remaining conditions are skipped.
Syntax: Example:
Explanation: The else if checks another condition if the previous if condition is false. If all conditions are
false, the else block executes.
22
4. switch Statement: The switch statement allows for a variable to be tested against multiple constant
values, with a corresponding block of code executed for each match. It is useful when you have many
possible conditions based on the value of a single variable.
Syntax: Example:
default: break;
} printf("Invalid day\n");
Explanation: The value of day is compared with each case. If day equals 2, it prints
"Tuesday." The break statement exits the switch after a match, preventing fall-through to
other cases.
23
23. Explain various operators available in C.
The ternary operator in C is a shorthand way of writing simple if-else statements. It is the
only operator in C that takes three operands, and it is sometimes called the conditional
operator.
How It Works:
Page | 24
Example:
#include <stdio.h> }
return 0;
Unary Operators
Page | 25
Relational operators:
> Greater than x>y Returns 1 if the first value is greater than the second
value
< Less than x<y Returns 1 if the first value is less than the second value
>= Greater than or x >= y Returns 1 if the first value is greater than, or equal to,
equal to the second value
<= Less than or x <= y Returns 1 if the first value is less than, or equal to, the
equal to second value
Logical operators:
&& AND x < 5 && x < 10 Returns 1 if both statements are true
! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1
Bitwise operators:
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and the
second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and the
second operand decides the number of places to shift.
Page | 26
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assignment operators:
= 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
Page | 27
Access Access by index (e.g., Access by dot operator Access by dot operator (e.g.,
arr[0]) (e.g., [Link]) u.i)
Usage Homogeneous data Heterogeneous data Memory-efficient handling of
collection collection different data types
Size Total size is n * Sum of sizes of all Size of the largest member
sizeof(type) members
Simultaneous All elements hold values All members hold values Only one member holds a
Use value
25. Mention any 5 character library functions/ Explain various operations performed on characters
with example for each.
Page | 28
isupper(int c) Checks if c is an uppercase Non-zero if true, 0 isupper('A') → non-zero
alphabetic letter. otherwise. (true), isupper('a') → 0
Command line arguments are inputs provided to a program when it is executed. They are passed from the
terminal (or command prompt) to the main() function of the program.
Syntax in main():
int main(int argc, char *argv[])
Key Points:
Page | 29
Example Program: Run:
#include <stdio.h> ./program_name arg1 arg2 arg3
Usage:
A structure is a user-defined data type in C that allows grouping variables of different data types under a
single name.
SYNTAX: Example:
data_type member1; {
}; float marks; };
Page | 30
Declaring Structure Variables
printf("%d", s1.roll_number);
Initialization of Structures
Array of Structures
class[0].roll_number = 101;
A union is a user-defined data type in C, similar to structures, but it allows storing different data types in
the same memory location.
Key Difference from Structures: In a union, all members share the same memory, meaning only one
member can hold a value at any given time.
• Memory Efficiency: Unions provide a way to save memory by allowing multiple members to use
the same memory space.
• Applications: Useful in situations where only one out of many variables is required at a time (e.g.,
defining a variable that can store different data types like int, float, or char but only one at a time).
Page | 31
SYNTAX : EXAMPLE:
{ {
}; };
Memory Sharing: All members share the same memory space, and the size of the union is determined by
the largest member.
union data {
int i; // 4 bytes
float f; // 4 bytes
};
Use the dot operator (.) to access and assign values to union members.
d1.i = 10;
printf("%d", d1.i);
Advantages:
• Useful for saving different types of data using the same variable.
Disadvantages:
1. How do find the smallest divisor of an integer? / Write an Algorithm to find the smallest exact
divisor of an Integer.
Step 1: Start
Step 2: Declare variables n, sr, div
Step 3: Read n
Step 4: If n mod 2 == 0, then
Print “2 is the smallest divisor” and go to Step 9
Step 5: Compute sr = √n
Step 6: Initialize divisor div = 3
Step 7: While div ≤ sr, do
a) If n mod div == 0, then
Print "div is the smallest divisor" and go to Step 9
b) Else, set div = div + 2
Step 8: Print "n is the smallest divisor" (means n is prime)
Step 9: End
Example : n=35
Step 1: Start
Page | 33
Step 3: Read number n
a) Print 2
b) Divide n by 2 (n = n / 2)
Step 7: End.
3. Explain the algorithm to find the maximum element in a set/ Write an algorithm to find
maximum number in an array of n elements. / Write an Algorithm to find the maximum
element in an array of size N.
Step 1: Start
Step 4:
b) Increment i by 1.
Step 7: End.
Working:
Step 1: Start
Step 2: Declare variable n
Step 3: Read a number n
Step 4: Use math function → square_root = sqrt(n)
Step 5: Print square_root
Step 6: Exit
Let m be the number whose square root is to be found, and l be the tolerance limit.
Step 1: Start
Step 2: Declare variables m, n, l, root
Page | 35
Step 3: Read a number m and tolerance limit l
Step 4: Initialize root = 0
Step 5: Set initial guess n = m / 2
Step 6: Repeat the following steps until |n – root| < l:
a) root = 0.5 * (n + (m / n))
b) Set n = root
c) Check if |root - n| < l, if yes → stop
Step 7: Print root
Step 8: End
Pseudorandom numbers are numbers generated by an algorithm that only appear to be random but are
actually determined by an initial seed value.
Application: Used in simulations such as Monte Carlo methods for solving complex problems.
Step 1: Start
Step 4: Initialize i = 0, j = n - 1
Step 7: End
Page | 36
7. What is Factorization? Write an algorithm to find GCD of two numbers a and b.
Factorization is the process of expressing a number as a product of its factors (smaller numbers that
exactly divide it).
Step 1: Start
Step 2: Declare variables a, b, r
Step 3: Read two numbers a and b
Step 4: If a = 0, GCD of a and b is b, return b and stop
Step 5: If b = 0, GCD of a and b is a, return a and stop
Step 6: If a < b, swap a and b
Step 7: Repeat the following steps until remainder r becomes zero:
a) r = a mod b
b) a = b
c) b = r
Step 8: Return a (this is the GCD)
Step 9: End
1 48 18 48 mod 18 = 12 a = 18, b = 12
2 18 12 18 mod 12 = 6 a = 12, b = 6
3 12 6 12 mod 6 = 0 a = 6, b = 0 → stop
Page | 37
UNIT 04
Binary Search is an efficient searching algorithm that uses the divide-and-conquer approach to find the
position of a target element in a sorted array. It works by repeatedly dividing the search interval in half.
2. What is sorting. Mention different sorting methods./ What is sorting? List any two sorting
techniques.
Sorting is the process of arranging the elements of a list in a particular order, typically ascending or
descending.
Techniques:
Two-way merging is the process of combining two sorted arrays (or lists) into a single sorted array.
Both input arrays are assumed to be already sorted, and the goal is to merge them so that the result is also
sorted. It is a fundamental operation used in the Merge Sort algorithm.
4. List any two differences between linear search and binary search algorithm./ Mention any two
differences between linear search and binary search.
Definition Sequentially checks each element Divides the list into halves and eliminates
until the target is found or the list one half each step based on comparisons.
ends.
Pre-condition Can work on both sorted and Requires the list to be sorted before
unsorted lists. searching.
Efficiency Inefficient for large datasets. More efficient for large datasets when the
list is sorted.
Page | 38
Search Steps Sequentially examines each element. Compares the middle element and
eliminates half of the list.
Use Case Small or unsorted datasets. Large, sorted datasets where efficiency is
required.
Implementation Simple and easy to implement. Slightly more complex due to recursion
or iterative halving.
Pattern matching refers to the process of finding all occurrences of a pattern (a sequence of characters or
elements) within a larger text or dataset. It is a crucial concept in string processing, where the goal is to
check if a given string (pattern) appears in a larger string or dataset, and if so, where it occurs.
Pattern matching would return the positions where "aba" occurs: at indices 0, 2, and 4.
Let A[ ] be a linear array with n elements, and key be the element to be searched.
Steps:
1. Set i = 0.
Page | 39
2. While (i < n) do
a. If A[i] == key, then return i (position of key).
b. Else, increment i = i + 1.
Let’s take an example: Array A = [12, 45, 23, 67, 89], n = 5, key = 23
Working Table
1 0 12 12 == 23 → False i=1
2 1 45 45 == 23 → False i=2
3 2 23 23 == 23 → True Return i = 2
Working Table
1 0 12 12 == 50 → False i=1
2 1 45 45 == 50 → False i=2
3 2 23 23 == 50 → False i=3
4 3 67 67 == 50 → False i=4
Page | 40
8. Write a program to search an element using linear search.
#include <stdio.h>
int linearSearch(int A[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (A[i] == key) {
return i; // key found at index i
}
}
return -1; // key not found
}
int main() {
int n, i, key, pos;
printf("Enter number of elements: ");
scanf("%d", &n);
int A[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
if (pos != -1)
printf("Key %d found at position %d\n", key, pos);
else
printf("Key %d not found in the array\n", key);
return 0;
}
Page | 41
9. Write a pseudocode to implement binary search. Illustrate with example/ Write an algorithm to
perform binary search on set of elements
Output: Returns the position of key element if found, otherwise returns -1.
Steps:
Example: Array: A = [10, 20, 30, 40, 50, 60, 70] (n=7), Key = 40
Example: Array: A = [10, 20, 30, 40, 50, 60, 70] (n=7), Key = 25
#include <stdio.h>
int binarySearch(int A[], int n, int key) {
int first = 0, last = n - 1, mid;
while (first <= last) {
mid = (first + last) / 2;
if (A[mid] == key) {
return mid; // Key found at mid
}
else if (key < A[mid]) {
last = mid - 1; // Search in left half
}
else {
first = mid + 1; // Search in right half
}
}
return -1; // Key not found
}
int main() {
int n, key, i, result;
int A[n];
printf("Enter %d elements in sorted order:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
Page | 43
result = binarySearch(A, n, key);
if (result == -1) {
printf("Key %d not found in the array.\n", key);
} else {
printf("Key %d found at position %d (index %d).\n", key, result + 1, result);
}
return 0;
}
11. Write an algorithm to perform hash search on set of elements / Write a short note on hash
search.
Step 1: Start
Step 9: If element in HT[pos] is equal to key then display “element is found” else continue searching for
element in next position until element is found or until same starting pos is reached again. If it is reached
the same pos, then element is not found.
0 -1 43
1 -1
2 -1 46
3 -1 25
4 -1 36
5 -1
6 -1
7 -1 18
8 -1 29
9 -1
10 -1 10
Hash Function:
• H(25)=25mod 11=3
• H(46)=46mod 11=2
• H(10)=10mod 11=10
• H(18)=18mod 11=7
Hash table value in position 7 is 18 and key is 18. So, Element is found.
Page | 45
12. Write Bubble sort algorithm to sort the given set of elements. Trace the Bubble sort algorithm
for the following elements, 28, 20, 1, 30, 8, 15, 05 / Perform the Bubble sort operation on the
following elements 23,5,13,65,8 to arrange the in ascending order.
Algorithm : Bubblesort(A[0..n-1])
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
13. Write an algorithm for selection sort. Illustrate with an example/ Explain selection sort with an
example./ Write an algorithm to sort the set of elements using selection sort
Page | 46
14. Write an algorithm for shell sort. Illustrate with an example./ Write Shell sort algorithm to sort
the given set of elements. Trace the Shell sort algorithm for the following elements, 23, 12, 67,
44, 11, 99, 55.
Algorithm: INSERTIONSORT(A[0..N-1],N)
A is an array of n elements
Step 4: if(k<A[j])
A[j+1] = A[j]
Step 5: A[j+1]=k
Step 6: End
Page | 47
16. Explain keyword searching in text/ Explain Pattern searching.
PROBLEM: Count the number of the occurrences of the given word in the text and print the number of
occurrences of the word.
Step 1: Start
Step 2: Read a Main String and store it in array STR[0...n]
Step 3: Read a pattern to be searched and store it in array PATTERN[0...m]
Step 4: Calculate the length of the main string STR[] and store it in strlen
→ Set strlen = length of STR[]
Step 5: Calculate the length of the pattern PATTERN[] and store it in patlen
→ Set patlen = length of PATTERN[]
Step 6: Declare variable i, j, count. Initialize its value to 0.
The variable count will keep track of how many times the pattern is found.
Step 7:
for j := 0 to patlen, do
end for
if j == patlen then
count = count + 1
end if
Page | 48
PROGRAMS
#include <stdio.h>
int main() {
int arr[50], n, i, j, k;
printf("Enter size of array: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr[i]==arr[j])
{
for(k=j; k<n-1; k++)
{ arr[k] = arr[k+1]; }
n--;
j--;
}
}
}
printf("Array after removing duplicates:\n");
for(i=0; i<n; i++)
{ printf("%d ", arr[i]); }
return 0;
}
Page | 49
2. Write a C program to find the roots of the Quadratic Equation.
#include <stdio.h>
#include <math.h>
int main() {
float a,b,c,d,root1,root2;
printf("Enter a, b, c: ");
scanf("%f%f%f",&a,&b,&c);
d = b*b - 4*a*c;
if(d>0){
root1 = (-b+sqrt(d))/(2*a);
root2 = (-b-sqrt(d))/(2*a);
printf("Roots: %.2f and %.2f", root1, root2);
} else if(d==0){
root1 = -b/(2*a);
printf("Equal roots: %.2f", root1);
} else {
printf("Roots are imaginary");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
Page | 50
strcpy(str2,str1);
printf("Copy: %s\n", str2);
return 0;
}
4. Write a C program to read 2x2 matrices and perform Addition and Subtraction operations the
matrices.
#include <stdio.h>
int main() {
int a[2][2], b[2][2], sum[2][2], sub[2][2], i, j;
printf("Enter elements of first 2x2 matrix:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ scanf("%d",&a[i][j]);
}}
printf("Enter elements of second 2x2 matrix:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ scanf("%d",&b[i][j]);
}}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
sum[i][j] = a[i][j] + b[i][j];
sub[i][j] = a[i][j] - b[i][j];
}}
printf("Sum:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ printf("%d ",sum[i][j]); printf("\n"); } }
printf("Subtraction:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ printf("%d ",sub[i][j]); printf("\n"); } }
Page | 51
return 0;
}
5. Write a program to find whether a given number is prime number or not.
#include <stdio.h>
int main() {
int n,i,flag=0;
printf("Enter number: ");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0 && n>1)
printf("Prime");
else
printf("Not Prime");
return 0;
}
6. Write a C program to compute GCD of two integers. Use a function to compute GCD/ Write a
program to find GCD of 2 integers./ Write a C program to find GCD OF 2 numbers.
#include <stdio.h>
int gcd(int a,int b){
while(b!=0){
int t=b;
b=a%b;
a=t;
}
return a;
}
Page | 52
int main() {
int x,y;
printf("Enter two numbers: ");
scanf("%d%d",&x,&y);
printf("GCD = %d",gcd(x,y));
return 0;
}
#include <stdio.h>
int main() {
int a[10][10], b[10][10], mul[10][10], r1,c1,r2,c2,i,j,k;
printf("Enter rows & cols of first matrix: ");
scanf("%d%d",&r1,&c1);
printf("Enter rows & cols of second matrix: ");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("Multiplication not possible");
return 0;
}
printf("Enter first matrix:\n");
for(i=0;i<r1;i++)
{ for(j=0;j<c1;j++)
{ scanf("%d",&a[i][j]); }}
printf("Enter second matrix:\n");
for(i=0;i<r1;i++)
{ for(j=0;j<c1;j++)
{ scanf("%d",&b[i][j]); }}
for(i=0;i<r1;i++){
for(j=0;j<c2;j++){
mul[i][j]=0;
for(k=0;k<c1;k++){
Page | 53
mul[i][j]+=a[i][k]*b[k][j];
}}}
printf("Result:\n");
for(i=0;i<r1;i++)
{ for(j=0;j<c2;j++)
{ printf("%d ",mul[i][j]);
printf("\n"); } }
return 0;
}
8. Write a program to find the factorial of a number.
#include <stdio.h>
int main(){
int n,i,f=1;
printf("Enter number: ");
scanf("%d",&n);
if(n<0)
{
printf(“Factorial cant be found for negative numbers”);
return 0;
}
for(i=1;i<=n;i++)
{ f=f*i; }
printf("Factorial = %d",f);
return 0;
}
9. Write a program to find the sum of all the digits of a given integer.
#include <stdio.h>
int main(){
int n,sum=0;
printf("Enter number: ");
scanf("%d",&n);
while(n>0){
sum+=n%10;
Page | 54
n/=10;
}
printf("Sum of digits = %d",sum);
return 0;
}
10. Write a C program to swap the values of two variables.
#include <stdio.h>
int main(){
int a,b,temp;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
temp=a;
a=b;
b=temp;
printf("After swap: a=%d b=%d",a,b);
return 0;
}
11. Write a C-program to sort n-numbers using bubble sort.
#include <stdio.h>
int main(){
int n,i,j,temp,a[20];
printf("Enter n: ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++) { scanf("%d",&a[i]); }
for(i=0;i<n-1;i++){
for(j=0;j<n-i-1;j++){
if(a[j]>a[j+1]){
temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;
}}}
printf("Sorted array: ");
for(i=0;i<n;i++) { printf("%d ",a[i]); }
return 0;
}
Page | 55
12. Write a C program to find the largest of 3 nos.
#include <stdio.h>
int main(){
int a,b,c;
printf("Enter 3 numbers: ");
scanf("%d%d%d",&a,&b,&c);
if(a>=b && a>=c)
{ printf("Largest = %d",a); }
else if(b>=a && b>=c)
{ printf("Largest = %d",b); }
else
{ printf("Largest = %d",c); }
return 0;
}
Feature for Loop while Loop do-while Loop
Initialization Done within the Done before the loop. Done before the loop.
loop statement.
Condition Checking At the beginning At the beginning of At the end of each iteration.
of each iteration. each iteration.
Iteration Done in the loop Done inside the loop Done inside the loop body.
(Increment/Decrement) header (after each body.
iteration).
Execution Guarantee May execute zero May execute zero or Executes at least once, even
or more times. more times. if the condition is false
initially.
When to Use When the number When the number of When the loop must execute
of iterations is iterations is unknown but at least once before checking
known. depends on a condition. the condition.
Page | 56