0% found this document useful (0 votes)
16 views56 pages

Understanding Algorithms and Programming Concepts

The document provides an overview of algorithms, their characteristics, and performance analysis methods, including time and space complexity. It also covers modular programming, problem-solving steps, and various algorithms for tasks such as exchanging values, summation, and generating Fibonacci sequences. Additionally, it discusses programming concepts like tokens, identifiers, arrays, variables, constants, pointers, escape sequences, and control statements in C programming.

Uploaded by

santhosha7003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views56 pages

Understanding Algorithms and Programming Concepts

The document provides an overview of algorithms, their characteristics, and performance analysis methods, including time and space complexity. It also covers modular programming, problem-solving steps, and various algorithms for tasks such as exchanging values, summation, and generating Fibonacci sequences. Additionally, it discusses programming concepts like tokens, identifiers, arrays, variables, constants, pointers, escape sequences, and control statements in C programming.

Uploaded by

santhosha7003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 01

1. What is an Algorithm? Give one of its advantages

An algorithm is a well-defined, step-by-step procedure or set of rules designed to solve a specific


problem or perform a task.

Advantage: An algorithm acts a blue print of a program and helps during program development.

2. Write the Characteristics of algorithm./ Define an algorithm. Mention any 4 characteristics of


an algorithm.

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.

3. Definiteness: Each step of the algorithm must be clear and unambiguous.

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.

3. Mention two methods for analysing the performance of an algorithm.

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.

4. What is Modular Programming?

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.

5. Explain the different steps in Problem Solving.


1. Analysing the Problem 4. Implementation or Coding
2. Designing Algorithm 5. Testing and Debugging
3. Analysis of Algorithm

1
6. Define an Algorithm. Mention two qualities of a good Algorithm.

An algorithm is a well-defined, step-by-step procedure or set of rules designed to solve a specific


problem or perform a task.

Qualities:

1. Simplicity: The algorithm is simple.


2. Clarity: The implementation must be easy and clear to understand.
3. Reusability: The algorithm should be reusable in other programs or problems.
4. Modifiability: The algorithm should be easy to modify if needed.

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.

Algorithm (Using a Temporary Variable):

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]

Step Current Number Action (sum = sum + number) Updated Sum


Init – sum = 0 0
1 5 sum = 0 + 5 5
2 10 sum = 5 + 10 15
3 15 sum = 15 + 15 30
4 20 sum = 30 + 20 50
sum = 50
Applications : Financial Calculations, Data Aggregation, Statistical Analysis

10. Write an algorithm to generate the Fibonacci sequence.

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.

11. Write an algorithm to find the factorial of a number.

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

12. Write an algorithm to reverse the digits of an Integer.


1. Start.
2. Input the integer n.
3. Initialize a variable reverse to 0 (reverse=0).
4. While n is not equal to 0:
1. last_digit= n%10
2. reverse = reverse * 10 + last_digit .
3. n=n/10.
5. Output reverse
6. End.

Example:For n=123:

Step while (n>0) last_digit=n%10 reverse=reverse*10+last_digit n=n/10


1 while(123>0) True last_digit = 123%10 reverse=0*10+3 n=123/10
last_digit=3 reverse=3 n=12
2 while(12>0) True last_digit = 12%10 reverse=3*10+2 n=12/10
last_digit=2 reverse=32 n=12
3 while(1>0) True last_digit = 1%10 reverse=32*10+1 n=1/10
last_digit=1 reverse=321 n=0

5
4 while(0>0) False
Output: reverse = 321

13. Write an algorithm to convert character to number.


1. Start
2. Input a character ch (digit between '0' and '9')
3. Subtract ASCII value of '0' from ch → num = ch - '0'
4. Display num
5. Stop

Suppose input ch = '7'

Character ASCII Value Expression (ch - '0') Result (num)


'7' 55 55 - 48 7

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

Student (i) Marks marks≥50? Count=count + 1 Updated Count


1 45 No - 0
2 67 Yes Count = Count+1 1
3 89 Yes Count = Count+1 2
4 32 No - 2
5 50 Yes Count = Count+1 3

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

Student (i) Marks Sum = Sum + Marks Updated Sum


1 10 Sum = 0 + 10 10
2 20 Sum = 10 + 20 30
3 30 Sum = 30 + 30 60
4 40 Sum = 60 + 40 100
5 50 Sum = 100 + 50 150

UNIT 02

1. Define Token with an Example.

A token is the smallest unit in a program that has meaning to the compiler.

Example: In int a = 10; → int, a, =, 10, ; are tokens.

2. Write any two rules for identifiers.

➢ Identifiers must begin with a letter or underscore.


➢ They cannot use keywords (e.g., int, while).

3. Define an Identifier. Give an example for a Valid Identifies.

An identifier is the name given to variables, functions, or arrays in a program.

Example: marks, total_sum.

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.

An array is a collection of homogeneous elements stored in continuous memory.

Syntax: data_type array_name[size];

Example: int marks[5];

Initialization: int num[3] = {10, 20, 30};

Printing array: for(int i=0; i<5; i++) {

printf("%d", arr[i]);

5. Define variable and constant. Give one example for each. / What is a Constant? How it is
declared in C.

Variable: A named memory location whose value can change.

Example: int age = 20;

Constant: A fixed value that cannot be changed during execution.

Example: const float pi = 3.14;

6. Define (a) Keyword (b) Identifier


➢ Keyword: A reserved word with special meaning in C (e.g., if, while).
➢ Identifier: User-defined name for variables, arrays, or functions (e.g., total, sum).
7. What is Pointer? Give an Example.

A pointer is a variable that stores the address of another variable.

Ex: int a = 10;

int *p = &a;

8. What are escape sequences?

Escape sequences are special character combinations used to represent non-printable characters.

Examples: \n (new line), \t (tab).

9. Differentiate between if and if else.


➢ if: Executes a block only if the condition is true.
8
➢ if-else: Executes one block if condition is true, another block if condition is false.
10. What is the difference between break and continue statements?
➢ break: Terminates the loop immediately.
➢ continue: Skips the current iteration and continues with the next one.

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

o Example: /* Program to add two numbers */

2. Link Section/Preprocessor Directives: Used to include header files that contain library
functions.

o Example: #include <stdio.h>

3. Definition Section: Used for defining constants or macros.

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

Basic Structure of C Program

#include <stdio.h> // Link sectio

#define PI 3.14 // Definition section

int main() // main function

int a, b, sum; // Variable declaration

9
printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

sum = a + b; // Program statements

printf("Sum = %d", sum);

return 0;

// User-defined functions can be written here

12. Example bitwise operators in C with suitable examples

Operator Meaning Example (a=5, b=3) Binary Operation Result


& AND a&b 0101 & 0011 = 0001 1
| OR a|b 0101 | 0011 = 0111 7
^ XOR a^b 0101 ^ 0011 = 0110 6
~ NOT ~a ~0101 = 1010 (2’s comp) -6
<< Left Shift a << 1 0101 << 1 = 1010 10
>> Right Shift a >> 1 0101 >> 1 = 0010 2
Truth Table

A B A&B A|B A^B


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

Categories of Data Types:

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

▪ Floating-Point Types (float, double, long double)

▪ Character Type (char)

▪ Void Type (void)

o Derived Data Types: These are built from primitive data types. Examples include:

▪ Arrays: A collection of elements of the same data type.

▪ Structures: A user-defined type that groups different data types.

▪ Unions: Similar to structures but can store different data types in the same memory location.

▪ Pointers: Variables that store memory addresses.

Data Use Range Format Size Example


Type Specifiers (bytes)

-32,768 to 32,767 (for 16-


Stores whole numbers, int a =
int bit) or -2,147,483,648 to %d or %i 2 or 4
without decimals 100;
2,147,483,647 (for 32-bit)

Stores fractional numbers,


containing one or more float g =
float ~1.2E-38 to ~3.4E+38 %f 4
decimals. Sufficient for 3.14f;
storing 6-7 decimal digits

Stores fractional numbers,


double h
containing one or more
double ~2.3E-308 to ~1.7E+308 %d 8 =
decimals. Sufficient for
3.14159;
storing 6-7 decimal digits

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:

1. Implicit Type Casting (Type Conversion / Type Promotion):

o Done automatically by the compiler.

o Example: Assigning an integer to a float.

2. Explicit Type Casting (Type Casting / Type Conversion):

o Done manually by the programmer using (type).

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.

Feature Call by Value Call by Reference


Definition A copy of the actual value is passed to The address (reference) of the variable
the function. is passed to the function.
Effect on Original Changes made inside the function do Changes made inside the function
Variable not affect the original variable. affect the original variable.
Memory Used Requires more memory (copies of Requires less memory (no copies,
variables are created). only addresses).

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.

Functions Description Example

strlen(str) Returns the length of the string (excluding strlen("Hello") returns 5


the null terminator).

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

strcmp(str1, Compares two strings lexicographically. strcmp("abc", "xyz") returns negative


str2) Returns 0 if equal, negative if str1 is less,
and positive if str1 is greater.

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:

for (initialization; condition; //for loop to print numbers from 1 to 5


increment/decrement) {
for (i = 1; i <= 5; i++) {
// Block of code to be executed
printf("%d\n", i); }
}

Explanation:

o Initialization: i = 1 is executed once before the loop starts.

o Condition: i <= 5 is checked before each iteration.

o Increment/Decrement: i++ increases the value of i after each iteration.

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.

Syntax: // while loop to print numbers from 1 to 5

while (condition) { while (i <= 5) {

// Block of code to be executed } printf("%d\n", i);

Example: i++;}

Explanation:

o The loop continues as long as i <= 5 is true.

o After each iteration, i is incremented by 1.

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 {

// Block of code to be executed printf("%d\n", i);

} while (condition); i++;

} while (i <= 5);

Example:

Explanation:

o The block of code inside the do section is executed first, even if the condition is false.

o After each execution, the condition (i <= 5) is checked.

o The loop stops when i becomes greater than 5.

18. Differentiate between while and do-while loop. Illustrate with example

Feature while loop do-while loop

Syntax while (condition) { // code } do { // code } while (condition);

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.

Example int i = 1; while (i <= 5) { int i = 1; do { printf("%d\n", i); i++; }


printf("%d\n", i); i++; } while (i <= 5);

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.

Syntax: data_type *pointer_name;

Example: int a = 10;

int *p = &a; // p stores address of a

printf("%d", *p); // prints value of a (10)

➢ & → gives address of a variable.


➢ * → dereference operator, gives the value at the stored address.

Pointer to Array (Pointer Arrays)

• A pointer can be used to store the address of the first element of an array.

• Example: int arr[3] = {10, 20, 30};

int *p = arr; // pointer points to the first element of the array

Here,

• p points to arr[0]

• *(p+1) gives arr[1]

• *(p+2) gives arr[2]


17
#include <stdio.h>
int main() {
int a = 5;
int *ptr;

// Pointer initialization
ptr = &a;

printf("Value of a = %d\n", a);


printf("Address of a = %p\n", &a);
printf("Value using pointer = %d\n", *ptr);

// Pointer to array
int arr[3] = {10, 20, 30};
int *p = arr;

printf("Array elements using pointer:\n");


for (int i = 0; i < 3; i++) {
printf("%d ", *(p + i));
}

return 0;
}
Output:

Value of a = 5

Address of a = 0x7ffee2f49a3c

Value using pointer = 5

Array elements using pointer:

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.

Syntax: data_type *pointer_name;

Example: int a = 10;

int *p = &a; // p stores address of a

printf("%d", *p); // prints value of a (10)

➢ & → gives address of a variable.


➢ * → dereference operator, gives the value at the stored address.

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

Size of Integer Pointer = 8 bytes


Size of Character Pointer = 8 bytes
Size of Float Pointer = 8 bytes
Size of Double Pointer = 8 bytes
Note: The size of a pointer depends on the system architecture, not on the data type it points to.

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

1. Formatted Input: scanf()

• Used to read values from the user.

• Requires format specifiers to indicate the type of data.

• General Syntax: scanf("format_specifier", &variable);

Example:

int age;

scanf("%d", &age); // reads an integer

2. Formatted Output: printf()

• Used to display values to the user.

• Format specifiers decide how the data is displayed.

• General Syntax: printf("format_specifier", variable);

Example:

float salary = 1234.56;

printf("Salary = %.2f", salary); // prints with 2 decimal places

3. String Input – gets()

• Used to read a string (including spaces).

• Syntax: gets(string_variable);

Example:

char name[30];

gets(name); // Reads a line of text

4. String Output – puts()

• Used to print a string followed by a newline (\n).

• Syntax: puts(string_variable);

20
Example: puts(name); // Prints the string

Common Format Specifiers

Specifier Meaning Example

%d Integer 10

%f Float (decimal) 10.50

%.2f Float with 2 decimal places 10.50

%c Character A

%s String Hello

%lf Double 123.456

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:

if (condition) { if (number > 5) {

// Code to be executed if condition is true printf("Number is greater than 5\n");

} }

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:

if (condition) { if (number > 5) {

// Code to be executed if condition is true printf("Number is greater than 5\n");

} else { } else {

// Code to be executed if condition is false printf("Number is less than or equal to


5\n");}
}

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:

if (condition1) { int number = 0;

// Code to be executed if condition1 is true if (number > 0) {

} else if (condition2) { printf("Number is positive\n");

// Code to be executed if condition2 is true } else if (number < 0) {

} else { printf("Number is negative\n");

// Code to be executed if both condition1 } else {


and condition2 are false
printf("Number is zero\n");
}
}

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:

switch (expression) { int day = 2;

case constant1: switch (day) {

// Code to be executed if expression case 1:


equals constant1
printf("Monday\n");
break;
break;
case constant2:
case 2:
// Code to be executed if expression
printf("Tuesday\n");
equals constant2
break;
break;
case 3:
// You can have any number of case
statements printf("Wednesday\n");

default: break;

// Code to be executed if no cases match default:

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

A unary operator is an operator in C that operates on only one operand.

A binary operator is an operator in C that operates on two operands.

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.

Syntax of Ternary Operator: condition ? expression1 : expression2;

• condition: The condition to be evaluated.

• expression1: This is executed if the condition is true.

• expression2: This is executed if the condition is false.

How It Works:

• If the condition is true, the value of expression1 is returned.

• If the condition is false, the value of expression2 is returned.

Page | 24
Example:

#include <stdio.h> }

int main() { In this example:

int a = 10, b = 20; • The condition a > b is checked.

// Using ternary operator to find the • If true, a is returned.


maximum of two numbers
• If false, b is returned. Since a is not
int max = (a > b) ? a : b; greater than b, the value of b
(which is 20) is returned and stored
printf("Maximum value is: %d\n",
in max.
max); // Output: Maximum value is: 20

return 0;

Unary Operators

Operator Meaning Example Result


++a Pre-increment (increase before use) ++a (a=10) 11
a++ Post-increment (increase after use) a++ (a=10) prints 10, then a=11
--a Pre-decrement --a (a=10) 9
a-- Post-decrement a-- (a=10) prints 10, then a=9
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

Page | 25
Relational operators:

Operator Name Example Description

== Equal to x == y Returns 1 if the values are equal

!= Not equal x != y Returns 1 if the values are not equal

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

Operator Name Example Description

&& AND x < 5 && x < 10 Returns 1 if both statements are true

|| OR x < 5 || x < 4 Returns 1 if one of the statements is 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.

X Y X&Y X|Y X^Y

0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assignment operators:

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

24. Distinguish structure and union with an example.

Aspect Array Structure Union


Data Type Same type for all Can have different types Can have different types for
elements for members members
Memory Continuous block, same Separate memory for each Shared memory for all
Allocation type member members

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.

Function Meaning Return Value Example

isalnum(int c) Checks if c is an alphanumeric Non-zero if true, 0 isalnum('A') → non-zero


character (letter or digit). otherwise. (true), isalnum('@') → 0

isalpha(int c) Checks if c is an alphabetic letter Non-zero if true, 0 isalpha('A') → non-zero


(either uppercase or lowercase). otherwise. (true), isalpha('1') → 0

iscntrl(int c) Checks if c is a control character Non-zero if true, 0 iscntrl('\n') → non-zero


(like \n, \t). otherwise. (true), iscntrl('A') → 0

isdigit(int c) Checks if c is a decimal digit (0–9). Non-zero if true, 0 isdigit('5') → non-zero


otherwise. (true), isdigit('A') → 0

isgraph(int c) Checks if c is any printable Non-zero if true, 0 isgraph('@') → non-zero


character except space. otherwise. (true), isgraph(' ') → 0

islower(int c) Checks if c is a lowercase Non-zero if true, 0 islower('a') → non-zero


alphabetic letter. otherwise. (true), islower('A') → 0

isprint(int c) Checks if c is any printable Non-zero if true, 0 isprint(' ') → non-zero


character including space. otherwise. (true), isprint('\n') → 0

ispunct(int c) Checks if c is a punctuation Non-zero if true, 0 ispunct(',') → non-zero


character. otherwise. (true), ispunct('A') → 0

isspace(int c) Checks if c is a whitespace Non-zero if true, 0 isspace(' ') → non-zero


character (like space, tab, newline). otherwise. (true), isspace('A') → 0

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

isxdigit(int c) Checks if c is a hexadecimal digit Non-zero if true, 0 isxdigit('f') → non-zero


(0-9, a-f, A-F). otherwise. (true), isxdigit('G') → 0

tolower(int c) Converts c to its lowercase Lowercase tolower('A') → 'a',


equivalent if it's an uppercase equivalent if c is tolower('a') → 'a'
letter. uppercase, otherwise
c.

toupper(int c) Converts c to its uppercase Uppercase toupper('a') → 'A',


equivalent if it's a lowercase letter. equivalent if c is toupper('A') → 'A'
lowercase, otherwise
c.

26. What are Command Line Arguments? Write a C program to Demonstrate.

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[])

o argc (Argument Count):


The number of arguments passed to the program, including the program name itself.

o argv (Argument Vector):


An array of pointers to strings (character arrays) representing the arguments.

Key Points:

o argv[0]: Contains the name (or path) of the program.

o argv[1] to argv[argc-1]: Contains the additional arguments passed.

o argc is always at least 1 (since argv[0] exists).

Page | 29
Example Program: Run:
#include <stdio.h> ./program_name arg1 arg2 arg3

int main(int argc, char *argv[]) { Output:


Number of arguments: 4
printf("Number of arguments: %d\n", argc);
Argument 0: ./program_name
for (int i = 0; i < argc; i++) {
Argument 1: arg1
printf("Argument %d: %s\n", i, argv[i]);
Argument 2: arg2
}return 0;
Argument 3: arg3
}

Usage:

o Parsing input for the program at runtime.

o Configuring program behavior dynamically.

o Useful for utilities, scripts, and tools.

27. Write a short note on Structures in C.

A structure is a user-defined data type in C that allows grouping variables of different data types under a
single name.

Example: Combining int, float, and char into a single structure.

Why Use Structures?

• Structures allow logical grouping of different data types.

• Helps in managing complex data (e.g., student records, employee information).

• Enhances readability and reusability of code.

SYNTAX: Example:

struct structure_name { struct student

data_type member1; {

data_type member2; char name[50];

// more members int roll_number;

}; float marks; };

Page | 30
Declaring Structure Variables

• Structure variables can be declared at the time of definition or separately.


struct student s1, s2; // Declaration of structure variables

Accessing Structure Members

Use the dot operator (.) to access members of the structure.


s1.roll_number = 101;

printf("%d", s1.roll_number);

Initialization of Structures

Structures can be initialized like arrays.


struct student s1 = {"John Doe", 101, 89.5};

Array of Structures

An array of structures allows storing multiple records.


struct student class[30];

class[0].roll_number = 101;

Advantages and Disadvantages

• Advantages: Group related data., Improves code organization.

• Disadvantages:Larger memory footprint compared to individual variables.

28. Write a short note on Union in C.

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.

Why Use Unions?

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

union union_name union data

{ {

data_type member1; int i;

data_type member2; float f;

// more members char str[20];

}; };

Declaring Union Variables

• Syntax: Union variables can be declared similarly to structures.


union data d1;

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

char str[20]; // 20 bytes

};

Accessing Union Members

Use the dot operator (.) to access and assign values to union members.
d1.i = 10;

printf("%d", d1.i);

Advantages:

• Saves memory by sharing space between members.

• Useful for saving different types of data using the same variable.

Disadvantages:

• Only one member can hold a value at a time.

• Data can be lost when switching between members.


Page | 32
UNIT 03

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 Variable/Check Result Action


Input n = 35 — —
Step 4 n % 2 → 35 % 2 ≠0 Not divisible → continue
Step 5 sr = √35 sr ≈ 5 —
Step 6 div = 3 div = 3 —
Step 7a n % div → 35 % 3 ≠ 0 Not divisible
Step 7b div = div + 2 div = 5 —
Step 7a n % div → 35 % 5 = 0 Divisible → smallest divisor found
Step 8 Print result 5 Smallest divisor = 5
Step 9 End — —

2. Write an algorithm to compute a prime factor of an integer.

Step 1: Start

Step 2: Declare the variables n and i

Page | 33
Step 3: Read number n

Step 4: While n is divisible by 2, repeat the following steps

a) Print 2

b) Divide n by 2 (n = n / 2)

Step 5: After Step 4, n must be odd

For i = 3 to √n, repeat the following steps

a) While i divides n, print i and divide n by i (n = n / i)

b) After i fails to divide n, increment i by 2 and continue

Step 6: If n is greater than 2, print n

Step 7: End.

Step Variable / Check Result Action


Input n = 60 — —
Step 4 While divisible by 2 60 % 2 = 0 Print 2, n = 60/2 = 30
Step 4 While divisible by 2 30 % 2 = 0 Print 2, n = 30/2 = 15
Step 4 15 % 2 ≠ 0 Stop loop —
Step 5 i = 3 (odd numbers up to √15 ≈ 3.8) — —
Step 5a 15 % 3 = 0 Print 3, n = 15/3 = 5
Step 5a 5 % 3 ≠ 0 Increment i = 5 —
Step 6 n > 2 (n = 5) Print 5 —
End Factors found 2, 2, 3, 5

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 2: Declare variables a[], n, i, and max.

Step 3: Read n elements of the array and store them in a[].

Step 4:

Set the first element as temporary maximum → max = a[0].


Page | 34
Initialize i = 1.

Step 5: Repeat while i < n:

a) If a[i] > max, then set max = a[i].

b) Increment i by 1.

Step 6: Print the largest element max.

Step 7: End.

Example Input: a = [12, 45, 23, 67, 34], n = 5

Working:

Step i a[i] Current max Comparison & Action

Init 0 12 max = 12 First element chosen as max

1 1 45 12 → 45 Since 45 > 12, update max

2 2 23 45 23 < 45, no change

3 3 67 45 → 67 Since 67 > 45, update max

4 4 34 67 34 < 67, no change

Final Output: Largest element = 67

4. Write an algorithm to find the square root of a number.

Algorithm 1: Using In-Built Function

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

Algorithm 2: Using Newton’s Method

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

5. What is Pseudorandom Numbers? Give one application.

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.

6. Write an algorithm to Reverse the Elements of an Array.

Step 1: Start

Step 2: Declare variables a[ ], n, i, j, and temp

Step 3: Read n elements and store them in array a

Step 4: Initialize i = 0, j = n - 1

Step 5: While i < j, do the following steps:


a) Exchange i-th element with j-th element
b) Increment i by 1 and decrement j by 1

Step 6: Print elements of array a

Step 7: End

Input Array: a = [10, 20, 30, 40, 50] , n = 5

Step i j Array Before Swap Operation Array After Swap


Init 0 4 [10, 20, 30, 40, 50] Start, set i=0, j=4 [10, 20, 30, 40, 50]
1 0 4 [10, 20, 30, 40, 50] Swap a[0] and a[4] [50, 20, 30, 40, 10]
2 1 3 [50, 20, 30, 40, 10] Swap a[1] and a[3] [50, 40, 30, 20, 10]
3 2 2 [50, 40, 30, 20, 10] Condition i < j fails (stop loop) [50, 40, 30, 20, 10]

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

Example: 12=2×2×3 (prime factorization).

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

Iteration a b r = a mod b Action

Initial 48 18 - Start values

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

1. Define Binary Search.

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:

a. Sorting by Exchange – Bubble sort


b. Sorting by Insertion – Insertion sort
c. Sorting by Selection – Selection sort
d. Sorting by Diminishing increment – Shell sort
e. Sorting by Partitioning – Quick sort
3. What do you mean by two way merge?/ What is TWO way merging? Give an example

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.

Aspect Linear Search 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.

Algorithm Type Iterative Divide and Conquer

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.

Example List Works on: [3, 7, 1, 5] (unsorted) Requires: [1, 3, 5, 7] (sorted)

5. What is Pattern Matching? Give an example.

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.

Example of Pattern Matching


In the text:
"abababacaba",
and the pattern:
"aba"

Pattern matching would return the positions where "aba" occurs: at indices 0, 2, and 4.

6. Write any two application of text line editing.


• Word Processors (e.g., MS Word, Notepad, Google Docs): Used for inserting, deleting, copying,
and moving lines of text while preparing documents, reports, or books.
• Programming and Code Editors (e.g., VS Code, Sublime Text, Eclipse): Used to edit source code
by performing operations like line insertion, deletion, searching, and replacing text.

7. Write an algorithm to search an element using linear search.

Algorithm: Linear Search (A[ ], n, key)

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.

3. If loop ends, return -1 (Key not found).

Case 1: Key Found

Let’s take an example: Array A = [12, 45, 23, 67, 89], n = 5, key = 23

Working Table

Step i A[i] Condition (A[i] == key?) Action

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

Output: Key found at position 2.

Case 2: Key Not Found

Example: Array A = [12, 45, 23, 67, 89], n = 5, key = 50

Working Table

Step i A[i] Condition (A[i] == key?) Action

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

5 4 89 89 == 50 → False i = 5 (loop ends)

Output: -1 (Key not found).

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

pos = linearSearch(A, n, 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

Algorithm: Binary Search (A[0…n-1], key)

Input: An array A of n elements in sorted order, and a key element to be searched.

Output: Returns the position of key element if found, otherwise returns -1.

Steps:

1. Set first = 0, last = n - 1.

2. Repeat steps until first <= last:

o Find middle index: mid = (first + last) / 2.

o If key == A[mid], return mid.

o Else if key < A[mid], set last = mid - 1.

o Else set first = mid + 1.

3. If not found, return -1.

Case 1: Key Found

Example: Array: A = [10, 20, 30, 40, 50, 60, 70] (n=7), Key = 40

Iteration first last mid A[mid] Comparison Action

1 0 6 3 40 key == A[mid] Found at index 3

Key 40 found at index 3.

Case 2: Key Not Found

Example: Array: A = [10, 20, 30, 40, 50, 60, 70] (n=7), Key = 25

Iteration first last mid A[mid] Comparison Action

1 0 6 3 40 key < A[mid] last = mid - 1 → 2

2 0 2 1 20 key > A[mid] first = mid + 1 → 2

3 2 2 2 30 key < A[mid] last = mid - 1 → 1

Now first > last, loop stops.

Key 25 not found → return -1.


Page | 42
10. Write a program to search an element using binary search.

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

printf("Enter number of elements: ");


scanf("%d", &n);

int A[n];
printf("Enter %d elements in sorted order:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}

printf("Enter the key to search: ");


scanf("%d", &key);

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 2: Read an array of n elements – A[0…n–1]

Step 3: Read Hash Table Size → tablesize

Step 4: Create Hash Table (HT) of size equal to tablesize

Step 5: Initialize all the elements of Hash Table to –1

Step 6: For i = 0 to n–1 do

a) Calculate a Hash value or index using


H(A[i]) = A[i] mod tablesize / pos = A[i] mod tablesize
b) If HT[pos] is equal to –1, then store A[i] in HT[pos] else store it in next empty slot

Step 7: Read a key to be searched in hash table (key)

Step 8: Calculate a Hash value or index using

H(key) = key mod tablesize

pos = key mod tablesize

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.

Step 10: End


Page | 44
WORKING: Consider a hash table with some elements:
25, 46, 10, 36, 18, 29, and 43, and the table size is 11

Index Position Step 1 Step 2

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(K)=Kmod table size

• H(25)=25mod 11=3

• H(46)=46mod 11=2

• H(10)=10mod 11=10

• H(36)=36mod 11=3 → (3 already occupied, so store in next empty slot)

• H(18)=18mod 11=7

• H(29)=29mod 11=7 → (7 already occupied, so store in next empty slot)

• H(43)=43mod 11=10 → (10 already occupied, so store in next empty slot)

Key to be searched in hash table: Key = 18

H(Key)=Key mod table size =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])

A is an array of n elements to be sorted.

Step 1: for pass=1 to n-1

Step 2: for j =0 to n-pass-1

Step 3: if a[j] > a[j+1] then

temp=a[j]

a[j]=a[j+1]

a[j+1]=temp

Step 4: End for

Step 5:End for

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

Algorithm: SELECTIONSORT(A[O…N-1]) Algorithm: MIN(A[0…N-1],k,n)

A is an array of n elements to be sorted. A is an array of n elements and k is the number


of passes.
Step 1: set loc =0
Step 1: Set min=A[k], loc=k
Step 2: Repeat step 3 and 4 for k=0 to n-2
Step 2: Repeat step 3 for j=k+1 to n-1
Step 3: loc=CALL MIN(A,k,n)
Step 3: if min > A[j]
Step 4: [Interchange A[k] and A[loc]]
min=A[j]
temp=A[k]
loc=j
A[k]=A[loc]
end if
A[loc]=temp
Step 4: return loc
Step 5: End for

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: A is an array of n elements

Step 1: Set array A[0..n-1] of n elements

Step 2: Set increment size incr

Step 3: while incr>=1 do

a) for all increments to be sorted (i.e. for j=incr to n-1)


i. set k=A[j]
ii. for (i=j-incr; i>0 && k<a[i]; i=i-incr)
A[i+incr]=A[i]
iii. set A[i+incr]=k
b) Decrease incr by factor of 2 (i.e. inc=inc/2)
15. Sort the following array using insertion sort 43,75,21,37,12 .Explain insertion sort with example.

Algorithm: INSERTIONSORT(A[0..N-1],N)

A is an array of n elements

Step 1: Repeat step 2 to 5 for pass=1 to n-1

Step 2: set k=A[pass]

Step 3: Repeat step 4 for j=pass-1 to 0

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 i := 0 to (strlen - patlen), do

for j := 0 to patlen, do

if STR[i + j] ≠ PATTERN[j], then

break the loop

end for

if j == patlen then

display the position i (i.e., as the pattern is found)

count = count + 1

end if

Step 8: Print count


Step 9: End

Page | 48
PROGRAMS

1. Write a C program to remove the duplicate entries in a single dimensional array.

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

3. Write a C program to demonstrate the string operations.

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

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


printf("Length of str1: %d\n", strlen(str1));
printf("Comparison: %d\n", strcmp(str1,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;
}

7. Write a C program to perform multiplication of 2 matrices./ Write a program to find the


multiplication of two matrices/ Write a program to multiply two matrices.

#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

Syntax for(initialization; while(condition){ // do{ // statements


condition; statements increment;}while(condition);
increment){ // increment;}
statements}

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

You might also like