[go: up one dir, main page]

0% found this document useful (0 votes)
73 views88 pages

CP Student Manual

Program
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)
73 views88 pages

CP Student Manual

Program
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
You are on page 1/ 88

UNIT I

WEEK 1
Objective: Getting familiar with the programming environment on the computer and writing
the first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()

i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
In the realm of Linux environments and text editors, there are several key players that
are widely used for various tasks ranging from basic text editing to software development.
Here’s an overview of some of the fundamental aspects:

Linux Environment Basics


Linux is a versatile operating system favored for its stability, security, and open-
source nature. It typically consists of:

 Shell: The command-line interface where you interact with the system. Common
shells include Bash (Bourne Again SHell) and Zsh (Z Shell).

 File System: Linux uses a hierarchical file system starting from the root directory `/`.

 Package Management: Different distributions (like Ubuntu, CentOS, Debian) use


package managers (e.g., `apt` for Debian-based, `yum` or `dnf` for RPM-based) to
install, update, and manage software.

Text Editors
Text editors are crucial tools for editing files directly within the terminal or via a
graphical interface. Here are some popular ones:

1.Vi / Vim
 Vi: Vi is a classic text editor that comes pre-installed on most Unix-like systems. It
has two main modes: command mode for navigation and editing commands, and
insert mode for inserting text.

 Vim (Vi Improved): Vim is an enhanced version of Vi with additional features and
improvements, such as syntax highlighting, multiple buffers, plugins, and more
customizable options.

DNRCET Page 1
2. Emacs
 Emacs: Emacs is another powerful text editor with extensive customization options
and its own Lisp-based scripting language (Emacs Lisp). It supports multiple modes
(e.g., text editing, programming modes) and can be extended with various packages.

3. Nano
 Nano: Nano is a straightforward and easy-to-use text editor designed for users who
prefer a simpler interface compared to Vi/Vim or Emacs. It provides basic text editing
capabilities with on-screen shortcuts.

Basic Commands (Vi/Vim)

Opening a file: `vi filename` or `vim filename`


Switching to insert mode: Press `i` in Vi/Vim to insert text.
Saving and quitting:
 In command mode: `:w` (save), `:q` (quit), `:wq` (save and quit), `:q!` (force quit
without saving changes).
Navigation: Use arrow keys or `h`, `j`, `k`, `l` for left, down, up, right respectively in Vi/Vim
command mode.
Search and replace: `/searchterm` to search, `:s/searchterm/replacement` to replace first
occurrence, `:%s/searchterm/replacement/g` to replace all occurrences.

Basic Commands (Emacs)

 Opening a file: `emacs filename`


 Saving and quitting:
Ctrl + x, Ctrl + s` to save, `Ctrl + x, Ctrl + c` to quit.
 Navigation: Arrow keys or Emacs-specific navigation (`Ctrl + n`, `Ctrl + p` for next
and previous lines).
 Search and replace: `Ctrl + s` to search forward, `Alt + %` for replace, `Alt + x
replace-string` for replacing all occurrences.

Choosing an Editor

 Vi/Vim: Excellent for efficient text editing, especially once mastered, due to its
ubiquity and powerful features.
 Emacs: Ideal for users who prefer extensive customization and integration with other
tools through its Lisp-based scripting.

These editors have their own learning curves, but mastering any of them can significantly
boost productivity in Linux environments, whether you’re writing scripts, editing
configuration files, or programming.

DNRCET Page 2
ii) Exposure to Turbo C, gcc
Turbo C and GCC (GNU Compiler Collection) represents encountering two different
environments for programming in C and C++. Here's a breakdown of each:

Turbo C
Turbo C was a popular Integrated Development Environment (IDE) and compiler for
C and C++ developed by Borland. It was widely used in the MS-DOS era and early Windows
environments. Here are some key points about Turbo C:
 IDE: Turbo C provided a simple and integrated environment where you could write,
edit, compile, and debug C and C++ programs.
 Compiler: It included the Borland Turbo C compiler, which adhered to the older
ANSI C standards (pre-ANSI C89/C90).
 Features: Turbo C offered basic debugging tools, a code editor with syntax
highlighting (though limited compared to modern IDEs), and a straightforward
interface suitable for beginners.
 Legacy: While Turbo C was once very popular, it has largely been superseded by
more modern IDEs and compilers due to its outdated standards compliance and lack
of support for modern operating systems.

GCC (GNU Compiler Collection)


GCC, or GNU Compiler Collection, is a robust compiler suite developed by the GNU
Project. It supports various programming languages, including C, C++, Objective-C, Fortran,
Ada, and others. Here's an overview of GCC:
 Compiler: GCC is a command-line compiler that adheres to modern C and C++
standards (C89/C90, C99, C11, C++98, C++11, C++14, C++17, C++20).
 Features: It provides extensive optimization options, supports multiple platforms
(Linux, macOS, Windows via MinGW), and includes advanced debugging features.
 Usage: GCC is commonly used for compiling applications, libraries, and system
software on Unix-like operating systems (Linux, BSD, macOS) and has widespread
adoption in academic, open-source, and commercial software development.
 Tools: Alongside the compiler, GCC includes tools like `g++` for compiling C++
code, `gdb` for debugging, and `make` for building complex projects.

Choosing Between Turbo C and GCC

 Legacy vs Modern: Turbo C is outdated and primarily of historical interest. It's not
suitable for modern software development due to its limited standards compliance and
lack of support for modern platforms.
 Recommendation: For learning and professional development, GCC (or its
derivatives like Clang) is highly recommended. It provides up-to-date language
support, better optimization, and compatibility with modern operating systems and
hardware.
In summary, while Turbo C was influential in its time, GCC represents the modern standard
for C and C++ development. Understanding GCC and its capabilities is crucial for anyone
serious about programming in C and C++ today, whether for academic, professional, or
personal projects.

DNRCET Page 3
iii)Writing simple programs using printf(), scanf()
The printf() function is used to display output and the scanf() function is used to take input
from users.
The printf() and scanf() functions are commonly used functions in C Language. These
functions are inbuilt library functions in header files of C programming.

printf() Function

In C Programming language, the printf() function is used for output.

printf() function can take any number of arguments. First argument must be enclosed within
the double quotes “hello” and every other argument should be separated by comma ( , )
within the double quotes.

Important points about printf():


 printf() function is defined in stdio.h header file. By using this function, we can print
the data or user-defined message on monitor (also called the console).
 printf() can print a different kind of data format on the output string.
 To print on a new line on the screen, we use “\n” in printf() statement.

C language is case sensitive programming language. For example, printf() and scanf() in
lowercase letters treated are different from Printf() and Scanf(). All characters in printf() and
scanf() builtin functions must be in lower case.

Syntax

printf("format specifier",argument_list);

The format string for output can


be %d (integer), %c (character), %s (string), %f (float) %lf (double) and %x (hexadecimal)
variable.

Simple Example of printf() Function


#include<stdio.h>
int main()
{
int num = 450;
// print number
printf("Number is %d \n", num);
return 0;
}
Output:
Number is 450

scanf() Function

The scanf() function is used to read input data from the console.
The scanf() function is builtin function available in the C library. scanf() function can read
character, string, numeric & other data from keyboard in C language.

DNRCET Page 4
scanf() reads formatted data from user and assign them in the variables provided the
additional arguments. Additional arguments must point to variables that have the same
datatype as of user input data format.
Syntax
scanf("format specifier",argument_list);

Simple Example of scanf() Function


#include<stdio.h>
int main()
{
int x;
printf("enter the number =");
scanf("%d",&x);
printf("The number is=%d",x);
return 0;
}
Output:
enter the number =10
The number is=10

DNRCET Page 5
WEEK 2
Objective: Getting familiar with how to formally describe a solution to a problem in a series
of finite steps both using textual notation and graphic notation.
Suggested Experiments /Activities:
Tutorial 2: Problem-solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

i) Sum and average of 3 numbers


Algorithm:

Step 1: Input
 Prompt the user to enter three numbers (num1, num2, num3).
Step 2: Calculate Sum
 Add the three numbers together to get sum: sum = num1 + num2 + num3.
Step 3: Calculate Average
 Divide the sum by 3.0 to get the average: average = sum / 3.0.
Step 4: Output
 Display the sum and average to the user.
Flowchart:

DNRCET Page 6
Program:

ii) Conversion of Fahrenheit to Celsius and vice versa

Algorithm:

Fahrenheit to Celsius Conversion:


Step 1: Input
 Prompt the user to enter a temperature in Fahrenheit (fahrenheit).
Step 2: Calculate Celsius
 Subtract 32 from ‘fahrenheit’.
 Multiply the result by 5.
 Divide the result by 9 to get ‘celsius’.
Step 3: Output
 Display the temperature in Celsius (celsius).
Celsius to Fahrenheit Conversion:
Step 1: Input
 Prompt the user to enter a temperature in Celsius (celsius).
Step 2: Calculate Fahrenheit
 Multiply celsius by 9.
 Divide the result by 5.
 Add 32 to get ‘fahrenheit’.
Step 3: Output
 Display the temperature in Fahrenheit (fahrenheit).

DNRCET Page 7
Flowchart:

Program:

iii)Simple interest calculation


Algorithm:
Step 1: Input
 Prompt the user to enter the principal amount (principal), interest rate per year (rate),
and time period in years (time).
Step 2: Calculate Simple Interest
 Multiply ‘principal’, ‘rate’, and ‘time’.
 Divide the result by 100 to get the simple interest.
Step 3: Output
 Display the computed simple interest.

Flowchart:

DNRCET Page 8
Program:

DNRCET Page 9
Lab 3: Simple computational problems using arithmetic expressions.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv) Distance travelled by an object

i) Finding the square root of a given number

Algorithm:
Step-1: Input:
 Take the input number (num) for which you want to find the square root.
 Take an initial guess (guess) for the square root (can be num/2 for simplicity).
Step-2: Iterative Calculation
 Initialize guess to num / 2.
 Repeat until convergence (for a predefined number of iterations or until the
change in guess is negligible):
 Update guess using the formula:

 Calculate the difference (diff) between guess^2 and num. If diff is sufficiently
small (less than a tolerance value), stop the iteration.
Step-3: Output:
 The final value of guess will be the approximate square root of num.

Flowchart:

DNRCET Page 10
Program:

ii) Finding compound interest

Algorithm:

Step-1: Input:
 Prompt the user to enter the principal amount (P), interest rate per period (r), number
of periods (n), and optionally the number of times interest is compounded per period
(m).
Step-2: Calculate Compound Interest:
 If m (compounding frequency per year) is not provided, assume annual compounding
(m = 1).
 Calculate the compound interest (A) using the formula

Where:
 P is the principal amount (initial investment).
 r is the annual interest rate (decimal).
 n is the number of years the money is invested or borrowed for.
 m is the number of times that interest is compounded per year.

Step-3: Output:
 Display or return the calculated amount ( A), which is the principal plus interest
earned.

DNRCET Page 11
Flowchart:

Program:

DNRCET Page 12
iii) Area of a triangle using heron’s formulae
Algorithm:

Step-1: Input:
 Prompt the user to enter the lengths of the three sides of the triangle: side1, side2,
side3.
Step-2: Calculate Semi-perimeter:
 Compute the semi-perimeter s of the triangle:

Step-3: Calculate Area using Heron's Formula:


 Compute the area area of the triangle using Heron's formula:

Here, \sqrt{} denotes the square root function.


Step-4: Output:
 Display or return the calculated area

Flowchart:

Program:

DNRCET Page 13
iv) Distance travelled by an object
Algorithm:
Step-1: Input:
 Prompt the user to enter initial velocity ( v0), acceleration (a), and time (t).
Step-2: Calculate Distance:
 Calculate the distance ‘d’ traveled by the object using the equation of motion under
constant acceleration:

Here,
 ‘v0’ is the initial velocity of the object.
 ‘a’ is the constant acceleration of the object.
 ‘t’ is the time duration for which the object travels.
Step-3:
 Display or return the calculated distance d.
Flowchart:

Program:

DNRCET Page 14
UNIT II
WEEK 4
Objective: Explore the full scope of expressions, type-compatibility of variables & constants
and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial4: Operators and the precedence and as associativity:
Lab4: Simple computational problems using the operator’ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
iii) Take marks of 5 subjects in integers, and find the total, average in float

i) Evaluate the following expressions


Algorithm:

a. A+B*C+(D*E) + F*G
1. Read values for A, B, C, D, E, F, G.
2. Compute product1 = B * C.
3. Compute product2 = D * E.
4. Compute sum1 = A + product1.
5. Compute sum2 = sum1 + product2.
6. Compute product3 = F * G.
7. Compute result = sum2 + product3.
8. Output the result.

b. A/B*C-B+A*D/3
1. Read values for A, B, C, D.
2. Compute division_result = A / B.
3. Compute product1 = division_result * C.
4. Compute subtraction_result = B - product1.
5. Compute division_result2 = A / 3.
6. Compute product2 = division_result2 * D.
7. Compute result = subtraction_result + product2.
8. Output the result.

c. A+++B---A
1. Read value for A, B.
2. Increment A (A = A + 1).
3. Increment A again (A = A + 1).
4. Add B to A (A = A + B).
5. Decrement A (A = A - 1).
6. Decrement A again (A = A - 1).
7. Output the value of A.

DNRCET Page 15
d. J= (i++) + (++i)
1. Read initial value for i.
2. Evaluate ++i (increment i by 1, use this incremented value).
3. Evaluate i++ (use current value of i, then increment i by 1).
4. Compute J = result of step 2 + result of step 3.
5. Output the value of J.

Flowchart:
a. A+B*C+(D*E) + F*G

b. A/B*C-B+A*D/3

DNRCET Page 16
c. A+++B---A

d. J= (i++) + (++i)

DNRCET Page 17
Program:
a. A+B*C+(D*E) + F*G

b. A/B*C-B+A*D/3

c. A+++B---A

d. J= (i++) + (++i)

DNRCET Page 18
ii) Find the maximum of three numbers using conditional operator

Algorithm:
1. Start
2. Read integers A, B, and C.
3. Set max = (A > B) ? A : B; // Compare A and B, assign the larger one to max
4. Set max = (max > C) ? max : C; // Compare max with C, assign the larger one to max
5. Output max as the maximum of A, B, and C.
6. Stop

Flowchart:

Program:

DNRCET Page 19
iii) Take marks of 5 subjects in integers, and find the total, average in float

Algorithm:

1. Start
2. Initialize variables:
a. integer subject1, subject2, subject3, subject4, subject5
b. float total, average
3. Read marks for each subject:
a. Read subject1, subject2, subject3, subject4, subject5 from the user or some
input source.
4. Calculate total:
a. total = subject1 + subject2 + subject3 + subject4 + subject5
5. Calculate average:
a. average = total / 5.0 // Using 5.0 to ensure floating-point division
6. Output total and average:
a. Print or store total and average with appropriate formatting.
7. Stop
Flowchart

DNRCET Page 20
Program:

DNRCET Page 21
WEEK 5
Objective: Explore the full scope of different variants of “if construct” namely if-else, nullelse,
if-else if*-else, switch and nested-if including in what scenario each one of them can be used
and how to use them. Explore all relational and logical operators while writing conditionals
for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.

i) Write a C program to find the max and min of four numbers using if-else.
Algorithm:
1. Start
2. Initialize variables:
a. int num1, num2, num3, num4;
b. int max, min;
3. Read values for num1, num2, num3, and num4.
4. Assume num1 as both max and min initially:
a. max = num1;
b. min = num1;
5. Compare num2 with max and min:
a. if (num2 > max)
max = num2;
b. else if (num2 < min)
min = num2;
6. Compare num3 with max and min:
a. if (num3 > max)
max = num3;
b. else if (num3 < min)
min = num3;
7. Compare num4 with max and min:
a. if (num4 > max)
max = num4;
b. else if (num4 < min)
min = num4;
8. Output max and min.
9. Stop

DNRCET Page 22
Flowchart:

DNRCET Page 23
Program:

ii) Write a C program to generate electricity bill.


Algorithm:
1. Start
2. Initialize variables Unit, Amount, Charges, Total
3. Reading the values of No.of Units, Carges,
4. First Check Units<=50
Amount=Unit*0.50;
Else
Check Units<=150
Amount=25 + ((unit-50) * 0.75);
Else
Check Units<=250
Amount = 100 + ((unit-150) * 1.20
Else
Amount = 220 + ((unit-250) * 1.50);

5. Calculate
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;

6. Print Current Bill

7. Stop

DNRCET Page 24
Flowchart:

Program:

DNRCET Page 25
iii) Find the roots of the quadratic equation.
Algorithm:

Step 1: Start
Step 2: Read A, B, C as integer
Step 3: Declare disc, deno, x1, x2 as float
Step 4: Assign disc = (B * B) - (4 * A * C)
Step 5: Assign deno = 2 * A;
Step 6: if( disc > 0 )
begin
Print “THE ROOTS ARE REAL ROOTS”
Assign x1 ← (-B / deno) + (sqrt(disc) / deno)
Assign x2 ← (-B / deno) - (sqrt(disc) / deno)
Print x1, x2
end
else if(disc = 0)
begin
Print “ THE ROOTS ARE REPEATED ROOTS"
Assign x1 ← -B / deno
Print x1
end
lse Print “THE ROOTS ARE IMAGINARY ROOTS”
Step7: Stop

Flowchart:

DNRCET Page 26
Program:

iv) Write a C program to simulate a calculator using switch case.


Algorithm:
Step-1: Input operand1, operand2, operator
Step-2: switch (operator):
- case '+':
Display result
break
- case '-':
result = operand1 - operand2
Display result
break
- case '*':
result = operand1 * operand2
Display result
break
- case '/':
if (operand2 != 0):
result = operand1 / operand2
Display result
else:
Display "Error: Division by zero"
break
- default:
Display "Error: Invalid operator"
Break
Step-3: Print the Result
Step-4: Stop

DNRCET Page 27
Flowchart:

Program:

DNRCET Page 28
v) Write a C program to find the given year is a leap year or not.
Algorithm:
Step-1: Start
Step-2: Input year
Step-3:. if (year % 400 == 0):
Display "Leap year"
else if (year % 4 == 0 and year % 100 != 0):
Display "Leap year"
else:
Display "Not a leap year"
Step-4: Stop:

Flowchart:

Program:

DNRCET Page 29
WEEK 6
Objective:
Explore the full scope of iterative constructs namely while loop, do-while loop and for
loop in addition to structured jump constructs like break and continue including when each of
these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
i) Find the factorial of given number using any loop.
ii) Find the given number is a prime or not.
iii)Compute sine and cos series.
iv) Checking a number palindrome.
v) Construct a pyramid of numbers.

i) Find the factorial of given number using any loop.


Algorithm:

Step-1: Start
Step-2: Input: n (The number for which factorial needs to be calculated)
Step-3: Initialization:
Initialize a variable factorial to 1 (since 0!=1 and we start multiplying from 1).
Step-4: Iterative Calculation:
 Use a loop to multiply factorial by each integer from 1 up to n.
 Start the loop from 1 and continue until n.
Step- 5: Output:
 After the loop completes, factorial will contain the factorial of n.
 Return or print the value of factorial.
Step-5: Stop

Flowchart:

DNRCET Page 30
Program:

ii) Find the given number is a prime or not.

Algorithm:
Step-1: Start
Step-2: Input:
 n (the number to be checked)
Step-3: Edge Cases:
 If n is less than or equal to 1, return "Not Prime".
 If n equals 2 or 3, return "Prime" (2 and 3 are prime numbers).
Step-3: Divisibility Check:
 For numbers greater than 3:
 Check if n is divisible by 2 or 3:
 If n%2=0 or n%3=0, return "Not Prime".
 Iterate through potential divisors I starting from 5 up to sqrt{n}:
 Check if n is divisible by i or i+2:
 If n%i=0 or n%(i+2)= 0, return "Not Prime".
Step-5: Output:
 If no divisors are found up to sqrt{n} return "Prime".
Step-6: Stop

DNRCET Page 31
Flowchart:

Program:

DNRCET Page 32
iii)Compute sine and cos series.

Algorithm:

Step-1: Start

Step-2: Input: Angle x(in radians), number of terms N for the series.

Step-3: Initialize:

 Initialize variables to accumulate the sum for cosine and sine ( cos_approx and
sin_approx).
 Initialize the power of x (x_power) to 1 for the first term.

Step-4: Iterative Computation:

 Use a loop to iterate from n=0 to N−1.


 For cosine:
o Compute the term

o Add the term to “ cos_approx”.


 For sine:
o Compute the term:

o Add the term to” sin_approx”.


 Update x_power to x2n+2 for the next iteration.

Step-5: Output: After the loop completes, cos_approx will contain the approximation for
cos (x) and sin_approx will contain the approximation for sin(x).

Step-6: Stop.

DNRCET Page 33
Flowchart:

DNRCET Page 34
Program:

iv) Checking a number palindrome.

Algorithm:
Step-1: Start
Step-2: Input: Assume the number is stored in an integer variable num.
Step-3: Initialization:
 Convert num to a string (or character array) to facilitate easy comparison of digits.
Step-4: Setup Pointers:
 Initialize two pointers: left starting from the beginning of the string (or array), and
right starting from the end.
Step-5: Comparison Loop:
 Iterate while left pointer is less than or equal to right pointer.
 Compare the character at left pointer with the character at right pointer.
 If they are not equal, the number is not a palindrome.
Step-6: Palindrome Check:
 If all characters match for all comparisons ( left <= right), then the number is a
palindrome.
Step-7: Output:
 If the number is a palindrome, print or return that it is a palindrome.
 Otherwise, print or return that it is not a palindrome.

DNRCET Page 35
Flowchart:

Program:

DNRCET Page 36
v) Construct a pyramid of numbers.
Algorithm:
Step-1: Start
Step-2: Input: Number of rows rows for the pyramid.
Step-3: Initialization:
 Start with current_number initialized to 1 (the first number to be printed).
 Determine the number of columns for the widest row of the pyramid. This could be
calculated based on the maximum number of digits in the last row.
Step-4: Outer Loop (for rows):
 Iterate through each row from 1 to rows.
Step-5: Inner Loop (for columns):
 Determine the starting number (start_number) for each row based on the row
number (e.g., for row i, start_number = current_number).
 Print numbers in ascending order from start_number to start_number + i - 1
(where i is the current row number).
 Increment current_number by i after printing each row.
Step-6:
Output: Print each row of numbers, ensuring proper formatting to align the pyramid shape.
Step-7: Stop

DNRCET Page 37
Flowchart:

Program:

DNRCET Page 38
UNIT III
WEEK 7:
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D
and 2-D and more generically n-D arrays and referencing individual array elements from the
defined array. Using integer 1-D arrays, explore search solution linear search.

Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7:1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.

i) Find the min and max of a 1-D integer array.

Algorithm:
Step-1: Start
Step-2: Input: An integer array arr of size n.
Step-3: Initialization:
 Set min to a very large number (INT_MAX in C) or the first element of the array
(arr[0]).
 Set max to a very small number (INT_MIN in C) or the first element of the array
(arr[0]).
Step-4: Iterate through the array:
 Traverse each element of the array from index 1 to n-1.
 For each element arr[i]:
o Update min if arr[i] is smaller than the current min.
o Update max if arr[i] is larger than the current max.
Step-5: Output: After traversing the entire array, min and max will hold the minimum and
maximum values respectively.

Pseudo code:
function findMinMax(arr):
// Initialize min and max
min = arr[0]
max = arr[0]
// Traverse the array
for i = 1 to length of arr - 1 do
// Update min if current element is smaller
if arr[i] < min then
min = arr[i]
// Update max if current element is larger
if arr[i] > max then
max = arr[i]
// Return min and max
return min, max

DNRCET Page 39
Program:

ii) Perform linear search on1D array.

Algorithm:

Step-1: Start
Step-2: Input:
 An integer array arr of size n.
 A target value target that we want to find in the array.
Step-3: Initialization:
 Start at the beginning of the array ( index = 0).
Step-4: Search Process:
 Traverse the array from the beginning to the end ( index from 0 to n-1).
 Compare each element arr[index] with the target value.
 If arr[index] equals target, then:
o Return index as the position of target in the array.
 If target is not found after traversing the entire array, then:
o Return a signal (e.g., -1 or a special value) indicating that target is not
present in the array.
Step-5: Output:
 The position of target in the array (if found) or a signal indicating target is not
present.
Step-6: Stop

Pseudo code:
function linearSearch(arr, target):
// arr is the input array, target is the value to search for
for i = 0 to length of arr - 1 do
if arr[i] equals target then
return i // Return the index of the target found
end if
end for

return -1 // Return -1 if target is not found

DNRCET Page 40
Program:

iii)The reverse of a 1D integer array

Algorithm:
Step-1: Start
Step-2: Input:
 An integer array arr of size n.
Step-3: Initialization:
 Create a new integer array reverse_arr of the same size n to store the reversed
elements.
 Initialize j to n-1 (the last index of reverse_arr).
Step-4: Reverse Process:
 Traverse the original array arr from index 0 to n-1.
 Copy each element arr[i] to reverse_arr[j], where j decrements from n-1 to 0.
Step-5: Output:
 reverse_arr now contains the elements of arr in reverse order.
Step-6: Stop

Pseudo code:
function reverseArray(arr): // arr is the input array of integers
n = length of arr
start = 0
end = n - 1
while start < end do // Swap elements at start and end indices
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp // Move towards the center
start = start + 1
end = end - 1 // Array is now reversed in-place

DNRCET Page 41
Program:

iv) Find 2’s complement of the given binary number.

Algorithm:
Step-1: Start
Step-2: Input:
o A binary number represented as an array or string of n bits, where the most
significant bit (MSB) indicates the sign (0 for positive, 1 for negative).
Step-3: Step-by-Step Process:
a. Identify the Most Significant Bit (MSB):
1. Determine if the binary number represents a positive or negative value
based on the MSB.
2. If the MSB is 0, the number is positive; if 1, it is negative.
b. If the Number is Negative:
1. Invert the Bits: Flip all the bits of the number (change 0 to 1 and 1 to
0).
2. Add 1: Add 1 to the inverted binary number to get the 2's complement.
c. If the Number is Positive:
o The 2's complement of a positive number is the number itself.
Step-4: Output:
o The resulting binary number after applying the 2's complement operation.
Step-5: Stop

Pseudo code:
function twosComplement(binaryNumber):
n = length of binaryNumber
if binaryNumber[0] == '1':
// Negative number case
invertBits(binaryNumber)
addOne(binaryNumber)

return binaryNumber

function invertBits(binaryNumber):
for i = 0 to n - 1 do
if binaryNumber[i] == '0':
binaryNumber[i] = '1'
else:
binaryNumber[i] = '0'

function addOne(binaryNumber):
carry = 1
for i = n - 1 to 0 do
if binaryNumber[i] == '1' and carry == 1:
binaryNumber[i] = '0'
else:
binaryNumber[i] = '1'
carry = 0

DNRCET Page 42
Program:

v) Eliminate duplicate elements in an array.

Algorithm:
Step-1: Start
Step-2: Initialize a hash set or use a boolean array (depending on the range of array elements)
to track seen elements.
 This data structure will help in efficiently checking if an element has already been
encountered.
Step-3: Initialize a pointer or index (write_index) to keep track of the position where unique
elements will be stored in the original array.
 Start write_index at 0.
Step-4:Traverse the array using a loop:
 For each element arr[i] in the array:
o Check if arr[i] is present in the hash set (or boolean array).
o If not present (i.e., it's a unique element):
 Add arr[i] to the hash set (or mark arr[i] as seen in the boolean array).
 Copy arr[i] to arr[write_index].
 Increment write_index.
Step-5: The array up to write_index now contains only unique elements.
 The value of write_index gives the number of unique elements in the array.
Step-6: Return the modified array (if needed) or the number of unique elements
(write_index).
Step-7: Stop.

Pseudo code:
function removeDuplicates(arr):
// Initialize an empty hash set to track seen elements
seen = new Set()
// Initialize a variable to keep track of the write index
write_index = 0
// Iterate through each element in the array
for i from 0 to length(arr) - 1 do:
// Check if the current element is not in the hash set
if arr[i] not in seen then:
// Mark arr[i] as seen by adding it to the hash set
add arr[i] to seen
// Copy arr[i] to the position of write_index in the original array
arr[write_index] = arr[i]
// Increment the write index
write_index = write_index + 1
// Return the modified array or the number of unique elements (write_index)
return write_index

DNRCET Page 43
Program:

DNRCET Page 44
WEEK 8:
Objective: Explore the difference between other arrays and character arrays that can be used
as Strings by using null character and get comfortable with string by doing experiments that
will reverse a string and concatenate two strings. Explore sorting solution bubble sort using
integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions

i) Addition of two matrices

Algorithm:
Step-1: Start
Step-2: Initialize a result matrix C of size m× n.
 Matrix C will store the sum of matrices A and B.
Step-3: Iterate through each element of the matrices A and B:
 For each element at position (i,j):
o Compute C[i][j]=A[i][j]+B[i][j]
Step-4: Output the resulting matrix C.
Step-5: Stop

Pseudo code:
function addMatrices(A, B, m, n):
// Initialize a matrix C of size m x n
initialize C as a matrix of size m x n with all elements 0

// Iterate through each element of A and B


for i from 0 to m-1 do:
for j from 0 to n-1 do:
// Compute the sum of corresponding elements from A and B
C[i][j] = A[i][j] + B[i][j]

// Return the resulting matrix C


return C

Program:

DNRCET Page 45
ii) Multiplication two matrices

Algorithm:

Step-1: Start
Step-2: Initialize a result matrix C of size m×n with all elements initialized to 0.
Step-3: Iterate through each element of the matrices A and B:
 For each element at position (i,j) in C:
o Initialize C[i][j]= 0.
o Compute C[i][j]=C[i][j]+A[i][k]×B[k][j] for k=0 to p−1.
Step-4: Output the resulting matrix C.
Step-5: Stop

Pseudo code:

function multiplyMatrices(A, B, m, p, n):


// Initialize a matrix C of size m x n with all elements 0
initialize C as a matrix of size m x n with all elements 0

// Perform matrix multiplication


for i from 0 to m-1 do:
for j from 0 to n-1 do:
C[i][j] = 0
for k from 0 to p-1 do:
C[i][j] = C[i][j] + A[i][k] * B[k][j]

// Return the resulting matrix C


return C

Program:

DNRCET Page 46
iii) Sort array elements using bubble sort

Algorithm:

Bubble Sort Algorithm


Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly steps
through the list, compares adjacent elements, and swaps them if they are in the wrong order.
The pass through the list is repeated until the list is sorted.
Steps:
Step-1: Start
Step -2: Initialize: Start with an array of nnn elements.
Step -3: Iterate through the array:
o Repeat the following steps n−1n-1n−1 times (where nnn is the number of
elements in the array):
 Compare each pair of adjacent elements.
 If the elements are in the wrong order (i.e., the first element is greater
than the second element for ascending order), swap them.
Step-4: Optimization: Each pass through the array places the next largest element in
its final position, so the number of comparisons can be reduced in subsequent passes.
Step-5: Termination: The algorithm terminates when no more swaps are needed,
which indicates that the array is sorted.
Step-6: Stop
Pseudo code:
procedure bubbleSort(A: list of sortable items)
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n=n-1
until not swapped
end procedure

Program:

DNRCET Page 47
iv) Concatenate two strings without built-in functions

Algorithm:

Step-1: Start
Step-2: Initialize: Start with two strings S1 and S2.
Step-3: Determine lengths: Find the lengths len1and len2 of S1 and S2 respectively.
Step-4: Allocate memory: Allocate memory for the resultant string SSS, which will have a
length of len1+len2 plus one extra byte for the null terminator '\0'.
Step-5: Copy characters:
 Iterate through each character c of S1 and append c to S starting from index 0.
 Iterate through each character c of S2 and append c to S starting from index len1.
Step-5: Add null terminator: Append '\0' at the end of SSS to mark the end of the string.
Step-6: Output: Display or use SSS as the concatenated string.
Step-7: Stop.

Pseudo code:

function concatenateStrings(S1, S2):


len1 = length of S1
len2 = length of S2
totalLength = len1 + len2 + 1 // +1 for null terminator
S = allocate memory for totalLength characters

// Copy characters of S1 to S
for i from 0 to len1-1 do:
S[i] = S1[i]

// Copy characters of S2 to S
for j from 0 to len2-1 do:
S[len1 + j] = S2[j]

S[totalLength - 1] = '\0' // Null terminate the string

return S
Program:

DNRCET Page 48
v) Reverse a string using built-in and without built-in string functions

Algorithm:

Reverse a String using Built-in Functions


Step-1: Start
Step-2: Initialize: Start with a string S.
Step-3: Use Built-in Function:
 Apply the built-in function to reverse the string S.
 This function typically modifies the original string in place or returns a new reversed
string.

Step-4: Stop.

Reverse a String without Built-in Functions


Step-1: Strat
Step-2: Initialize: Start with a string S
Step-3: Allocate Memory: Allocate memory for a new string reversed__S of the same length
as S.
Step-4: Reverse the String:
 Iterate through each character of S from end to start.
 Append each character to reversed_S starting from the beginning.
Step-5: Stop
Pseudo code:

Reverse a String using Built-in Functions


function reverseString(S):
// Assuming `S` is a character array (string) in C
// `strrev` is a built-in function in C from the `<string.h>` library

// Reverse the string `S` in place


strrev(S)

Reverse a String without Built-in Functions


function reverseString(S):
n = length of S
// Convert string S to an array of characters for swapping (if necessary)
// Since strings in some languages are immutable

// Initialize pointers for swapping characters


start = 0
end = n - 1

// Swap characters from start to end


while start < end do:
// Swap characters at start and end indices
temp = S[start]
S[start] = S[end]
S[end] = temp

DNRCET Page 49
// Move towards the center
start = start + 1
end = end – 1

Program:
Reverse a String using Built-in Functions

Reverse a String without Built-in Functions

DNRCET Page 50
UNIT IV
WEEK 9:
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation & value initialization, resizing changing and reordering the contents of an array
and memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain
experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereferences.
i) Write a C program to find the sum of a 1D array using malloc()
ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student details
along with the total.
v) Write a C program to implement realloc()

i) Write a C program to find the sum of a 1D array using malloc()

Algorithm:
Step-1: Start
Step-2: Input the Size of the Array:
 Prompt the user to enter the number of elements (n) in the array.
Step-3: Allocate Memory Dynamically:
 Use malloc() to allocate memory dynamically for an integer array of size n.
Step-4: Check for Successful Allocation:
 Verify if memory allocation was successful ( arr != NULL). If not, handle the error
appropriately (e.g., display an error message and exit).
Step-5: Input Array Elements:
 Read or generate n integers and store them in the allocated memory space ( arr).
Step-6: Calculate the Sum:
 Initialize a variable (sum) to zero.
 Traverse through the array and add each element to sum.
Step-7: Output the Sum:
 Display the computed sum of the array elements.
Step-8: Free Dynamically Allocated Memory:
 Use free(arr) to release the memory allocated for the array.
Step-9: Stop

Pseudo code:
// Pseudo-code for finding sum of 1D array using malloc()
// Declare variables
int n
int* arr
int sum = 0
// Input size of array
Print "Enter the number of elements: "
Read n
// Allocate memory dynamically
arr = malloc(n * sizeof(int))

DNRCET Page 51
if arr == NULL then
Print "Memory allocation failed."
Exit program
// Input array elements
Print "Enter n integers:"
for i = 0 to n-1 do
Read arr[i]
// Calculate sum of elements
sum = 0
for i = 0 to n-1 do
sum = sum + arr[i]
// Output sum of elements
Print "Sum of elements:", sum
// Free dynamically allocated memory
free(arr)

Program:

ii) Write a C program to find the total, average of n students using structures

Algorithm:
Step-1: Start
Step-2: Define a Structure for Student:
 Create a structure student that contains fields for name, marks, total, and
average.
Step-3: Input the Number of Students (n):
 Prompt the user to enter the number of students ( n).
Step-4: Declare an Array of Structures:
 Declare an array students of type student with size n.
Step-5: Input Student Details:
 Use a loop to input details for each student:
o Read the name of the student.
o Read marks for each subject (assuming fixed number of
subjects or dynamically allocate based on input).
o Calculate total marks for each student.
o Calculate average marks for each student.
Step-6: Calculate Total and Average for All Students:
 Initialize variables total_marks and average_marks.
 Traverse through the students array:
o Accumulate total_marks by adding each student's total.
 Calculate average_marks as total_marks / n.
Step-7: Output Results:
 Display the total_marks and average_marks.
Step-8: Stop

DNRCET Page 52
Pseudo code:
// Pseudo-code to find total and average of n students using structures

// Define Structure
struct Student {
string name
int marks[number_of_subjects]
int total
float average
}

// Start
main() {
// Declare variables
int n
struct Student students[n]
int total_marks = 0
float average_marks = 0.0

// Input number of students


Print "Enter the number of students: "
Read n

// Input student details


for i = 0 to n-1 do
Print "Enter details for student ", i+1
Print "Name: "
Read students[i].name

// Initialize total marks


students[i].total = 0

// Input marks for each subject


for j = 0 to number_of_subjects - 1 do
Print "Enter marks for subject ", j+1, ": "
Read students[i].marks[j]
students[i].total = students[i].total + students[i].marks[j]

// Calculate average marks


students[i].average = students[i].total / number_of_subjects

// Calculate total and average marks for all students


total_marks = 0
for i = 0 to n-1 do
total_marks = total_marks + students[i].total

average_marks = total_marks / n

DNRCET Page 53
// Output results
Print "Total marks of all students: ", total_marks
Print "Average marks of all students: ", average_marks

// End
}
Program:

iii)Enter n students data using calloc() and display failed students list
Algorithm:
Step-1: Start
Step-2: Define a Structure for Student:
 Create a structure Student with fields for name, marks, and result.
Step-3: Input the Number of Students (n):
 Prompt the user to enter the number of students ( n).
Step-4: Allocate Memory Dynamically Using calloc():
 Use calloc() to allocate memory dynamically for an array of n Student
structures.
 Check if calloc() was successful (i.e., array pointer is not NULL).
Step-5: Input Student Details:
 For each student from 0 to n-1:
o Prompt and read the name of the student.
o Input the marks (e.g., for one or more subjects).
o Determine the result based on a pass/fail criterion (e.g., total
marks >= pass marks).
Step-6: Display Failed Students:
 Traverse through the array of students:
 If a student's result indicates failure, display their name and marks.
Step-7: Free Dynamically Allocated Memory:
 Use free() to release the memory allocated by calloc().
Step-8: Stop

DNRCET Page 54
Pseudo code:

// Pseudo-code to enter data for n students using calloc() and display failed students list

// Define Structure
struct Student {
string name
int marks
string result
}

// Start
main() {
// Declare variables
int n
struct Student students[n]

// Input number of students


Print "Enter the number of students: "
Read n

// Allocate memory dynamically for array of students


students = calloc(n, size of Student)

// Check if memory allocation is successful


if students == NULL then
Print "Memory allocation failed."
Exit program with error

// Input student details


for i = 0 to n-1 do
Print "Enter details for student ", i+1
Print "Name: "
Read students[i].name

// Input marks
Print "Enter marks: "
Read students[i].marks

// Determine result based on marks (e.g., pass/fail)


if students[i].marks >= 50 then
students[i].result = "Pass"
else
students[i].result = "Fail"

// Display failed students list


Print "Failed Students List:"
for i = 0 to n-1 do

DNRCET Page 55
if students[i].result == "Fail" then
Print students[i].name, " Marks: ", students[i].marks

// Free dynamically allocated memory


free(students)

// End
}
Program:

iv) Read student name and marks from the command line and display the student details
along with the total.

Algorithm:
Step-1: Start
Step-2: Input Number of Students (n):
 Read n from command line arguments (assuming n is provided as an
argument).
Step-3: Declare Variables:
 Declare an array students of size n to store student details.
 Declare variables total_marks and average_marks for calculation.
Step-4: Read Student Details:
 For each student from 0 to n-1:
o Read student name from command line argument.
o Read marks for each subject from command line argument.
o Compute total marks for the student.
Step-5: Calculate Total Marks:
 For each student, calculate the sum of their marks to get total_marks.
Step-6: Display Student Details:
 For each student:
 Print student name, marks for each subject, and total marks.
Step-7: End

DNRCET Page 56
Pseudo code:
// Pseudo-code to read student name and marks from command line and display details

// Start
main(int argc, char *argv[]) {
// Declare variables
int n
struct Student {
string name
int marks[number_of_subjects]
int total_marks
}
struct Student students[n]
int total_marks

// Read number of students from command line argument


n = atoi(argv[1]) // Assuming argv[1] contains the number of students

// Read student details from command line arguments


for i = 0 to n-1 do
students[i].name = argv[2 + i*6] // Assuming argv[2 + i*6] is student name
for j = 0 to number_of_subjects-1 do
students[i].marks[j] = atoi(argv[3 + i*6 + j]) // Assuming argv[3 + i*6 + j] is marks
for subject j
// Calculate total marks
students[i].total_marks = 0
for j = 0 to number_of_subjects-1 do
students[i].total_marks = students[i].total_marks + students[i].marks[j]

// Display student details


for i = 0 to n-1 do
Print "Student Name: ", students[i].name
for j = 0 to number_of_subjects-1 do
Print "Subject ", j+1, " Marks: ", students[i].marks[j]
Print "Total Marks: ", students[i].total_marks
Print "\n"

// End
}
Program:

DNRCET Page 57
v) Write a C program to implement realloc()
Algorithm:
Step-1: Start
Step-2: Function Definition:
 Define a function my_realloc(void *ptr, size_t new_size).
Step-3: Parameters:
 ptr: Pointer to the previously allocated memory block (can be NULL).
 new_size: New size in bytes that the memory block should be resized to.
Step-4: Edge Cases:
 If ptr is NULL:
 Allocate a new block of memory of size new_size using malloc() and return the
pointer.
 If new_size is 0:
 Free the memory block pointed by ptr using free(ptr) and return
NULL.
Step-5: Allocate New Block:
 Allocate a new block of memory of size new_size using malloc(new_size).
Step-6: Copy Data (if necessary):
 If ptr is not NULL and new_size is greater than 0:
o Calculate the minimum size to copy (current_size), which is the
lesser of the current allocated size (malloc_usable_size(ptr)) or
new_size.
o Allocate a new memory block (new_ptr) of new_size bytes.
o Copy the contents of the old memory block ( ptr) to the new memory
block (new_ptr) using memcpy(new_ptr, ptr, current_size).
o Free the old memory block using free(ptr).
Step-7: Return New Pointer:
 Return the pointer to the new memory block ( new_ptr).
Step-8: Stop

Pseudo code:
function my_realloc(ptr, new_size):
if ptr is NULL:
return malloc(new_size)
if new_size is 0:
free(ptr)
return NULL
new_ptr = malloc(new_size)
if new_ptr is NULL:
return NULL // Allocation failed

current_size = size_of_allocated_block(ptr)
copy_size = min(current_size, new_size)

memcpy(new_ptr, ptr, copy_size)

free(ptr)

return new_ptr

DNRCET Page 58
Program:

DNRCET Page 59
WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential structures
(Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 :
Bitfields, linked lists Read and print a date using dd/mm/yyyy format using bit-fields and
differentiate the same without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the
same type.

i) Create and display a singly linked list using self-referential structure.

Algorithm:

Step-1: Start
Step-2: Define the Node Structure:
 Create a structure Node with two components
o data: to store the data of the node (could be an integer, string, etc. depending
on the application).
o next: a pointer to the next node in the list.
Step-3: Initialize Functions:
 Define functions for basic operations such as creating a new node, inserting nodes
at the beginning/end, and displaying the list.
Step-4: Function to Create a New Node:
 Create a function createNode(int data) to dynamically allocate memory for a new
node and initialize its data and next pointer.
Step-5: Function to Insert Node at the Beginning:
 Create a function insertAtBeginning(struct Node **headRef, int data) to insert a
new node at the beginning of the linked list.
Step-6: Function to Display the Linked List:
 Create a function displayList(struct Node *head) to traverse and display all nodes
in the linked list.
Step-7: Main Function:
 Implement the main function to test the linked list operations.
Step-8: Stop

Pseudo code:

// Define a structure for a node in the singly linked list

struct Node {
int data;
Node next; // Self-referential structure: Node contains a pointer to another Node
}

DNRCET Page 60
// Function to create a new node with given data
function createNode(data):
newNode = new Node
newNode.data = data
newNode.next = null
return newNode

// Function to insert a new node at the beginning of the linked list


function insertAtBeginning(headRef, data):
newNode = createNode(data)
if headRef == null:
headRef = newNode
else:
newNode.next = headRef
headRef = newNode

// Function to display the contents of the linked list


function displayList(head):
current = head
while current != null:
print(current.data)
current = current.next

// Main program
function main():
head = null

// Insert nodes at the beginning


insertAtBeginning(head, 5)
insertAtBeginning(head, 10)
insertAtBeginning(head, 15)

// Display the linked list


displayList(head)

Program:

DNRCET Page 61
ii) Demonstrate the differences between structures and unions using a C program.

Algorithm:

Step-1: Start
Step-2: Define a Structure:
 Create a structure (struct) that contains multiple members of different data
types.
Step-3: Define a Union:
 Create a union (union) that contains members of different data types, possibly
overlapping in memory.
Step-4: Allocate Memory:
 Show how memory is allocated for structures and unions.
 Display the size of each structure and union using sizeof().
Step-5: Access Members:
 Access and modify members of structures and unions.
 Observe how modifications in one member of a union affect other members.
Step-6: Demonstrate Usage:
 Use structures when you need to store and access multiple pieces of related
data.
 Use unions when you need to store different types of data in the same memory
location.
Step-7: Stop.

Pseudo code:
// Define a structure for a person
struct Person {
string name;
int age;
float height;
};

// Define a union for storing different types of data


union Data {
int i;
float f;
string str;
};

// Main function
function main():
// Declare variables
struct Person person1;
union Data data;

// Initialize structure members


person1.name = "John Doe";
person1.age = 30;
person1.height = 6.0;

// Display structure data


print("Structure (Person):");
print("Name: " + person1.name);
print("Age: " + person1.age);

DNRCET Page 62
print("Height: " + person1.height);

// Initialize and use union members


data.i = 10;
print("\nUnion (Data):");
print("data.i : " + data.i);

data.f = 3.14;
print("data.f : " + data.f);

data.str = "Hello";
print("data.str : " + data.str);

// Accessing union members after assigning a string


print("\nAfter assigning a string to data.str:");
print("data.i : " + data.i); // Output might not be meaningful since data.i was overwritten
print("data.f : " + data.f); // Output might not be meaningful since data.f was overwritten
print("data.str : " + data.str);

// End of main function

Program:

iii) Write a C program to shift/rotate using bitfields.


Algorithm:

Step-1: Start
Step-2: Define a Structure with Bitfields:
 Create a structure (struct) with bitfields to hold the data that needs to be
shifted or rotated.
Step-3: Initialize the Structure:
 Initialize the structure with data values.
Step-4: Perform Shift Operation:
 Use bitwise shift operators (<<, >>) to perform left or right shifts on the
bitfields.
Step-5: Perform Rotate Operation:
 For rotate operations, implement custom rotate functions using bitwise
operations (<<, >>, |, &) to handle wrapping around bits properly.
Step-6: Display Results:
 Output the results after each shift or rotate operation to observe the changes in
the bitfields.
Step-7: Stop.

DNRCET Page 63
Pseudo code:

// Define a structure with bitfields


struct BitFields {
unsigned int field1 : 4; // 4 bits
unsigned int field2 : 8; // 8 bits
};

// Function to perform left shift on bitfields


function leftShift(struct BitFields *bf):
bf->field1 <<= 1; // Left shift by 1 bit
bf->field2 <<= 1; // Left shift by 1 bit

// Function to perform right shift on bitfields


function rightShift(struct BitFields *bf):
bf->field1 >>= 1; // Right shift by 1 bit
bf->field2 >>= 1; // Right shift by 1 bit

// Function to perform rotate left on bitfields


function rotateLeft(struct BitFields *bf):
unsigned int carry1 = bf->field1 >> 3; // Capture the carry from field1
unsigned int carry2 = bf->field2 >> 7; // Capture the carry from field2
bf->field1 = (bf->field1 << 1) | carry2; // Rotate left field1 and include carry from field2
bf->field2 = (bf->field2 << 1) | carry1; // Rotate left field2 and include carry from field1

// Function to perform rotate right on bitfields


function rotateRight(struct BitFields *bf):
unsigned int carry1 = bf->field1 & 0x1; // Capture the carry from field1
unsigned int carry2 = bf->field2 & 0x1; // Capture the carry from field2
bf->field1 = (bf->field1 >> 1) | (carry2 << 3); // Rotate right field1 and include carry from
field2
bf->field2 = (bf->field2 >> 1) | (carry1 << 7); // Rotate right field2 and include carry from
field1

// Main function
function main():
// Declare a variable of type struct BitFields
struct BitFields bf;

// Initialize the bitfields with example values


bf.field1 = 0b1010; // 4 bits
bf.field2 = 0b11001100; // 8 bits

// Display initial values


print("Initial Bitfields:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform left shift


leftShift(&bf);
print("\nAfter Left Shift:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform right shift

DNRCET Page 64
rightShift(&bf);
print("\nAfter Right Shift:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform rotate left


rotateLeft(&bf);
print("\nAfter Rotate Left:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform rotate right


rotateRight(&bf);
print("\nAfter Rotate Right:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// End of main function

Program:

iv) Write a C program to copy one structure variable to another structure of the same type.

Algorithm:

Step-1: Start
Step-2: Define the Structure:
 Create a structure (struct) with multiple members of various data types.
Step-3: Declare Variables:
 Declare two variables of the structure type (struct) to store data.
Step-4: Initialize Source Structure:
 Assign values to the members of the source structure.
Step-5: Copy Structure:
 Copy each member from the source structure to the destination structure.
Step-6: Display Results (optional):
 Output the values of the destination structure to verify the copy operation.
Step-7: Stop

DNRCET Page 65
Pseudo code:

// Define a structure with multiple members


struct Person {
string name;
int age;
float height;
};

// Function to copy one structure variable to another of the same type


function copyStruct(struct Person source, struct Person *destination):
// Copy each member from source to destination
destination.name = source.name;
destination.age = source.age;
destination.height = source.height;

// Main function
function main():
// Declare two variables of type struct Person
struct Person person1, person2;

// Initialize person1 with example values


person1.name = "Alice";
person1.age = 25;
person1.height = 5.6;

// Display initial values of person1


print("Initial values of person1:");
print("Name: " + person1.name);
print("Age: " + person1.age);
print("Height: " + person1.height);

// Copy person1 to person2


copyStruct(person1, &person2);

// Display values of person2 after copy


print("\nValues of person2 after copy:");
print("Name: " + person2.name);
print("Age: " + person2.age);
print("Height: " + person2.height);

// End of main function

Program:

DNRCET Page 66
UNIT V
WEEK 11:
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical
integration.
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent,
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations
using Euler’s method

i) Write a C function to calculate NCR value.

Algorithm:

Step-1: Start
Step-2: Input Validation:
 Check if r is less than 0 or greater than n. If either condition is true, ncr is not defined
for positive integers, so handle this according to your needs (e.g., return an error, print
a message, etc.).
Step-3: Special Cases:
 If r=0 or r=n, ncr=1 because there is only one way to choose zero items or all n items.
Step-4: Initialization:
 Initialize a variable result to 1. This will accumulate the calculated value of ncr.
Step-5: Iterative Calculation:

 Use the formula ncr=


 Initialize variables to store the factorial values of n, r, and n −r.
 Use a loop to calculate n!,r!, and (n−r)! Iteratively.

 Calculate ncr using the formula result


Step-6: Output:
 After the loop completes, result\text{result}result will contain the value of ncr
Step-7: Stop.

Pseudo code:

function binomial_coefficient(n, r):


if r < 0 OR r > n:
return 0 // Error: r must be between 0 and n inclusive

if r == 0 OR r == n:
return 1 // Base cases: C(n, 0) = 1, C(n, n) = 1

// Initialize variables
result = 1

DNRCET Page 67
numerator = n
denominator = 1

// Calculate binomial coefficient using iterative multiplication and division


for i from 1 to r:
numerator *= (n - i)
denominator *= i
result = numerator / denominator // Ensure to handle integer division

return result

Program:

#include <stdio.h>

ii) Write a C function to find the length of a string.

Algorithm:
Step-1: Start
Step-2: Input:
 Input a string str.
Step-3: Initialization:
 Initialize an integer variable length to 0. This will store the length of the string.
Step-4: Iterate through the string:
 Use a loop to iterate over each character in the string str.
 Increment length by 1 for each character encountered, until the null terminator ( \0 ) is
reached.
Step-5: Output:
 After the loop completes, length will contain the total number of characters in the
string str excluding the null terminator.
Step-6: Stop.

Pseudo code:

function string_length(str):
length = 0
while str[length] is not null:
length = length + 1
return length

DNRCET Page 68
Program:

iii)Write a C function to transpose of a matrix.

Algorithm:
Step-1: Start
Step-2: Input:
 Input a matrix matrix[m][n].
Step-3: Initialize Transposed Matrix:
 Initialize a new matrix transpose[n][m] to store the transposed matrix.
Step-4: Transpose the Matrix:
 Use nested loops to iterate through each element of the original matrix matrix[i][j].
 Assign each element to its corresponding position in the transposed matrix
transpose[j][i].
Step-5: Output:
 After transposing completes, transpose will contain the transposed matrix.
Step-6: Stop.

Pseudo code:
function transpose_matrix(matrix, m, n):
// Create a new matrix to store the transposed matrix
declare transpose[n][m]

// Compute transpose
for i from 0 to m-1:
for j from 0 to n-1:
transpose[j][i] = matrix[i][j]

// Return the transposed matrix


return transpose

Program:

DNRCET Page 69
iv) Write a C function to demonstrate numerical integration of differential equations using
Euler’s method
Algorithm:

Step-1: Start
Step-2: Input:
𝑑𝑦
 Define the differential equation =f(x,y), where y(x0) =y0.
𝑑𝑥
 Specify the initial values x0,y0 step size h, and number of steps N.
Step-3: Initialize:
 Set x=x0 and y=y0
Step-4: Numerical Integration:
 Iterate N times using a loop:
𝑑𝑦
o Compute the slope at the current point =f(x,y)
𝑑𝑥
o Update the next value of y using Euler's method:
Yn+1=yn+h.f(xn,yn)
o Increment x by h.
Step-5: Output:
 Print or return the final value of y, which approximates y(x0+N.h)
Step-6: Stop.

Pseudo code:

function euler_method(f, x0, y0, h, N):


// f is a function pointer representing the derivative function f(x, y)
// x0 and y0 are the initial values of x and y, respectively
// h is the step size
// N is the number of steps to perform the integration

x = x0 // Initialize x
y = y0 // Initialize y

for i from 1 to N:
slope = f(x, y) // Calculate the slope at (x, y) using f(x, y)
y = y + h * slope // Update y using Euler's method: y_n+1 = y_n + h * f(x_n, y_n)
x = x + h // Increment x by h

return y // Return the final value of y after N steps

Program:

DNRCET Page 70
WEEK 12:
Objective: Explore how recursive solutions can be programmed by writing recursive functions
that can be invoked from the main by programming at-least five distinct problems that have
naturally recursive solutions.
Suggested Experiments/Activities:
Tutorial 12: Recursion, the structure of recursive calls
Lab 12: Recursive functions
i) Write a recursive function to generate Fibonacci series.
ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement Ackermann function using recursion.
v) Write a recursive function to find the sum of series.

i) Write a recursive function to generate Fibonacci series.

Algorithm:

Step-1: Start
Step-2: Function Definition:
Define a recursive function fibonacci(n) that takes an integer n as input.
Step-3: Base Case:
If n equals 0 or 1:
Return n.
Step-4: Recursive Case: If n is greater than 1:
 Calculate Fibonacci(n-1) and Fibonacci(n-2) recursively.
 Return the sum of Fibonacci(n-1) and Fibonacci(n-2).
Step-5: Stop.

Pseudo code:

function fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Program:

DNRCET Page 71
ii) Write a recursive function to find the lcm of two numbers.

Algorithm:

Step-1: Start
Step-2: Function Definition:
 Define a recursive function lcm(a, b) that takes two integers a and b as parameters.
Step-3: Base Case: If either a or b is 0:
 Return 0 because the LCM of any number with 0 is 0.
Step-4: Recursive Case: If both a and b are non-zero:
 Calculate the LCM using the formula:

 Use recursion to compute the GCD of a and b.


 Compute the LCM using the formula and return it.
Step-5: GCD Calculation:
Define a helper function gcd(a, b) to compute the Greatest Common Divisor (GCD)
of a and b recursively.

Pseudo code:

function lcm(a, b):


if a == 0 or b == 0:
return 0
else:
return abs(a * b) / gcd(a, b)

function gcd(a, b):


if b == 0:
return a
else:
return gcd(b, a % b)

Program:

DNRCET Page 72
iii)Write a recursive function to find the factorial of a number.

Algorithm:

Step-1: Start
Step-2: Input:
Accept an integer n from the user.
Step-3: Function Definition:
Define a recursive function factorial(n):
 Base Case: If n is 0 or 1, return 1 (since 0! and 1! are both 1).
 Recursive Case: If n is greater than 1, return n * factorial (n - 1).
Step-4: Output:
Print the result of factorial(n)
Step-5: Stop

Pseudo code:
function factorial(n):
// Base case: factorial of 0 or 1 is 1
if n == 0 OR n == 1:
return 1
// Recursive case: n * factorial(n-1)
else:
return n * factorial(n - 1)

Program:

iv) Write a C Program to implement Ackermann function using recursion.

Algorithm:

Step-1: Start
Step-2: Function Definition:
 Define a function ackermann(m, n) that takes two integer parameters m and n.
Step-3: Base Cases:
 If m == 0, return n + 1.
 If n == 0 and m > 0, return ackermann(m - 1, 1).
Step-4: Recursive Case:
 If both m > 0 and n > 0, recursively call ackermann with parameters (m - 1,
ackermann(m, n - 1)).
Step-5: Stop.

DNRCET Page 73
Pseudo code:

function ackermann(m, n):


if m == 0 then
return n + 1
else if n == 0 then
return ackermann(m - 1, 1)
else
return ackermann(m - 1, ackermann(m, n - 1))
Program:

v) Write a recursive function to find the sum of series.


Algorithm:

Step-1: Start
Step-2: Define the Recursive Function:
 Define a function sumOfSeries(int n) that takes an integer n as input and returns
the sum of the series from 1 to n.
Step-3: Base Case:
 If n is 0 or 1, return n itself because:
o Sum of series from 1 to 0 is 0.
o Sum of series from 1 to 1 is 1.
Step-4: Recursive Case:
 If n is greater than 1, recursively compute the sum of the series from 1 to n:

 Return n + sumOfSeries(n - 1).


Step-5: Stop.
Pseudo code:

function sumOfSeries(n):
if n == 0 or n == 1 then
return n
else
return n + sumOfSeries(n - 1)
Program:

DNRCET Page 74
WEEK 13:
Objective: Explore the basic difference between normal and pointer variables, Arithmetic
operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
Lab 13: Simple functions using Call by reference, Dangling pointers.
i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other characters
using pointers
i) Write a C program to swap two numbers using call by reference.
Algorithm:
Step-1: Start
Step-2: Define a Swap Function:
 Define a function swap(int *a, int *b) that takes two integer pointers (int *a
and int *b) as parameters.
Step-3: Swap Values:
 Inside the function, use temporary variable to store the value pointed to by a.
 Assign the value of b to a.
 Assign the temporary value to b.
Step-4: Call the Swap Function:
 Call the swap function with the addresses of the two variables you want to swap.
Step-5: Stop.

Pseudo code:
function swapByReference(a, b):
temp = a
a=b
b = temp
Program:

DNRCET Page 75
ii) Demonstrate Dangling pointer problem using a C program.

Algorithm:
Step-1: Start
Step-2: Allocate Memory:
 Allocate memory dynamically using malloc or calloc to create a pointer ptr.
Step-3: Use the Memory:
 Use ptr to store some data or perform operations.
Step-4: Free the Memory:
 Free the memory pointed to by ptr using free(ptr).
Step-5: Dangling Pointer Scenario:
 Continue to access or use ptr after it has been freed.
Step-6: Undefined Behavior:
 Attempting to dereference or use ptr after it has been freed can lead to undefined
behavior, as the memory it points to may no longer be valid or may have been
allocated to some other process or variable.
Step-7: Stop.

Pseudo code:
function dangling Pointer Example():
// Step 1: Allocate memory
ptr = allocateMemory(sizeof(int))

// Step 2: Use the memory


*ptr = 10
print("Value pointed by ptr:", *ptr)

// Step 3: Free the memory


freeMemory(ptr)

// Step 4: Dangling pointer scenario


// Accessing ptr after it has been freed
print("Value pointed by ptr after free:", *ptr) // Dangling pointer access

function allocateMemory(size):
// Allocate memory of specified size
return allocate(size)

function freeMemory(ptr):
// Free the memory pointed by ptr
free(ptr)

Program:

DNRCET Page 76
iii)Write a C program to copy one string into another using pointer.
Algorithm:
Step-1: Start.
Step-2: Define Pointers:
 Declare two character pointers (src and dest) to store the addresses of the source and
destination strings, respectively.
Step-3: Input Strings:
 Read the source string (src_string) into the character array src.
Step-4: Copy Using Pointers:
 Initialize src to point to the first character of src_string.
 Initialize dest to point to the first character of dest_string.
Step-5: Copy Characters:
 Use a loop to iterate through each character of src_string.
 Copy each character from src to dest.
 Increment both src and dest pointers to move to the next character.
Step-6: Terminate Destination String:
 Append the null character ('\0') to dest_string after copying to mark the end of
the string.
Step-7: Stop.

Pseudo code:

function copyString(source, destination)


// Initialize pointers for source and destination
sourcePointer = address of source[0]
destinationPointer = address of destination[0]

// Loop through each character of source string


while character at sourcePointer is not '\0'
// Copy character to destination
character at destinationPointer = character at sourcePointer

// Move to next character in both strings


increment sourcePointer
increment destinationPointer

// Append null terminator to destination string


character at destinationPointer = '\0'

// End function
Return

Program:

DNRCET Page 77
iv) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers

Algorithm:
Step-1: Start
Step-2: Initialize lowerCount = 0, upperCount = 0, digitCount = 0, otherCount = 0.
Step-3: Initialize a pointer char *ptr to point to the beginning of the string.
Step-4: While (*ptr != '\0'):
a. If (*ptr >= 'a' && *ptr <= 'z'):
Increment lowerCount.
b. Else if (*ptr >= 'A' && *ptr <= 'Z'):
Increment upperCount.
c. Else if (*ptr >= '0' && *ptr <= '9'):
Increment digitCount.
d. Else:
Increment otherCount.
e. Move pointer to the next character (*ptr++).
Step-5: Output or use lowerCount, upperCount, digitCount, and otherCount as required.
Step-6: Stop.

Pseudo code:
function countCharacters(str)
// Initialize counters
lowerCount = 0
upperCount = 0
digitCount = 0
otherCount = 0

// Pointer to navigate through the string


pointer = address of str[0]

// Loop through each character of the string


while character at pointer is not '\0'
// Check character type
if character at pointer is between 'a' and 'z'
increment lowerCount
else if character at pointer is between 'A' and 'Z'
increment upperCount
else if character at pointer is between '0' and '9'
increment digitCount
else
increment otherCount

// Move to the next character


increment pointer

// Output the counts


print "Lowercase characters:", lowerCount

DNRCET Page 78
print "Uppercase characters:", upperCount
print "Digit characters:", digitCount
print "Other characters:", otherCount

Program:

DNRCET Page 79
WEEK14:
Objective: To understand data files and file handling with various file I/O functions. Explore
the differences between text and binary files.
Suggested Experiments/Activities:
Tutorial 14: File handling Lab 14: File operations
i) Write a C program to write and read text into a file.
ii) Write a C program to write and read text into a binary file using fread() and fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line
arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.

i) Write a C program to write and read text into a file.

Algorithm:
Step-1: Start
Step-2: Open File for Writing:
 Open a file in write mode ("w" mode in C) or append mode ("a" mode in C) if you
want to append to an existing file.
 If the file does not exist, it will be created. If it exists, its contents will be overwritten
("w") or appended ("a").
Step-3: Write Text to File:
 Write the text content to the opened file using file I/O functions ( fprintf() in C,
fwrite() for binary data, etc.).
 Close the file after writing to ensure all data is flushed and the file is properly closed
(fclose() in C).
Step-4: Handle Errors:
 Check for any errors during file operations (like file opening, writing, etc.) and handle
them appropriately (e.g., display error messages, retry, etc.).
Step-5: Stop.

Pseudo code:
Writing a Text into a File:
function writeToFile(filename, text)
// Open file for writing ("w" mode creates a new file or truncates existing file)
file = open(filename, "w")

if file is NULL
print "Failed to open file for writing"
return

// Write text to the file


write text to file using file I/O functions

// Close the file


close file

DNRCET Page 80
Reading a Text into a File:
function readFromFile(filename)
// Open file for reading ("r" mode opens an existing file for reading)
file = open(filename, "r")

if file is NULL
print "Failed to open file for reading"
return

// Read text from the file


while not end of file
read line from file
process line (e.g., print, store, etc.)

// Close the file


close file

Program:

ii) Write a C program to write and read text into a binary file using fread() and fwrite()
Algorithm:

Writing Text into a Binary File Algorithm:

Step-1: Start
Step-2: Open File for Writing:
 Open a file in binary write mode ("wb" in C) using fopen().
Step-3: Write Text to File:
 Use fwrite() to write text to the opened file as binary data.
 Specify the size of each data item (sizeof(char) for a character) and the number of
items (length of the text string).
Step-4: Close the File:
 Close the file using fclose() to ensure all data is written properly and the file is closed.
Step-5: Stop

Reading Text from a Binary File Algorithm:


Step-1: Start
Step-2: Open File for Reading:
 Open the binary file in read mode ("rb" in C) using fopen().
Step-3: Read Text from File:
 Use fread() to read binary data from the file into a buffer.
 Specify the size of each data item (sizeof(char) for a character) and the number of
items (length of the text string).
Step-4: Process the Read Data:
 Print or process the read data as needed (e.g., display on screen, store in a variable,
etc.).
Step-5: Close the File:
 Close the file using fclose() to release system resources.
Step-6: Stop.

DNRCET Page 81
Pseudo code:

function writeTextToBinaryFile(filename, text)


file = open(filename, "wb") // open file for binary write

if file is NULL
print "Error opening file for writing"
return

// Write text to file


fwrite(text, sizeof(char), length of text, file)

// Close the file


close file

function readTextFromBinaryFile(filename)
file = open(filename, "rb") // open file for binary read

if file is NULL
print "Error opening file for reading"
return

// Read text from file


buffer = create buffer of sufficient size
bytesRead = fread(buffer, sizeof(char), size of buffer, file)
buffer[bytesRead] = '\0' // null-terminate the buffer for string operations

// Process or display the read text


print "Contents read from binary file:"
print buffer

// Close the file


close file

Program:

DNRCET Page 82
iii)Copy the contents of one file to another file.

Algorithm:
Step-1: Start
Step-2: Open Source File:
 Open the source file (sourceFile) in read mode ("r").
Step-3: Open Destination File:
 Open the destination file (destinationFile) in write mode ("w"). If the file already
exists, its previous contents are discarded.
Step-4: Check File Open Status:
 If either file fails to open (returns NULL), print an error message and exit the program.
Step-5: Read from Source File and Write to Destination File:
 Use a loop to repeatedly:
o Read a chunk of data (e.g., using fread() or fgets()) from
sourceFile.
o Write the read data to destinationFile using fwrite() or
fprintf().
Step-6: Close Files:
 Close both sourceFile and destinationFile using fclose() to ensure all data is
written and resources are released.
Step-7: Handle Errors and Edge Cases:
 Check for errors during file operations (e.g., reading, writing, closing).
 Handle cases where the files may not open or close properly due to permissions, disk
full, or other issues.
Step-8: Stop.

Pseudo code:
function copyFile(sourceFilename, destinationFilename)
// Open source file for reading
sourceFile = open(sourceFilename, "r")
if sourceFile is NULL
print "Error: Could not open source file"
return

// Open destination file for writing (create or overwrite)


destinationFile = open(destinationFilename, "w")
if destinationFile is NULL
print "Error: Could not open destination file"
close sourceFile
return

// Read from source file and write to destination file


while not end of sourceFile
chunk = read a chunk of data from sourceFile
write chunk to destinationFile

// Close both files


close sourceFile
close destinationFile

DNRCET Page 83
Program:

iv) Write a C program to merge two files into the third file using command-line arguments.
Algorithm:
Step-1: Start
Step-2: Check Command-Line Arguments:
 Verify that the program receives exactly three command-line arguments: the names of
two input files (inputFile1 and inputFile2) and the output file (outputFile).
Step-3: Open Input Files:
 Open the first input file (inputFile1) in read mode ("rb").
 Open the second input file (inputFile2) in read mode ("rb").
 If either file fails to open, print an error message and terminate the program.
Step-4: Open Output File:
 Open the output file (outputFile) in write mode ("wb").
 If the output file fails to open, print an error message, close any opened input files,
and terminate the program.
Step-5: Read from Input Files and Write to Output File:
 Use a loop to:
o Read a chunk of data (e.g., using fread()) from inputFile1.
o Write the read data to outputFile (e.g., using fwrite()).
o Repeat the above step for inputFile2.
 Continue until the end of both input files is reached.
Step-6: Close Files:
 Close inputFile1, inputFile2, and outputFile using fclose() to ensure all data
is written and resources are released.
Step-7: Handle Errors and Edge Cases:
 Check for errors during file operations (e.g., reading, writing, closing).
 Handle cases where the files may not open or close properly due to permissions, disk
full, or other issues.
Step-8: Stop.

DNRCET Page 84
Pseudo code:
function mergeFiles(inputFile1, inputFile2, outputFile)
// Open first input file for reading
file1 = open(inputFile1, "rb")
if file1 is NULL
print "Error: Could not open first input file"
return

// Open second input file for reading


file2 = open(inputFile2, "rb")
if file2 is NULL
print "Error: Could not open second input file"
close file1
return

// Open output file for writing


output = open(outputFile, "wb")
if output is NULL
print "Error: Could not open output file"
close file1
close file2
return

// Merge contents of input files into output file


while not end of file1
chunk = read a chunk of data from file1
write chunk to output

while not end of file2


chunk = read a chunk of data from file2
write chunk to output

// Close all files


close file1
close file2
close output
Program:

DNRCET Page 85
v) Find no. of lines, words and characters in a file
Algorithm:
Step-1: Start
Step-2: Open the File:
 Open the file (filename) in read mode ("r").
Step-3: Check File Open Status:
 If the file fails to open (NULL check), print an error message and exit the program.
Step-4: Initialize Counters:
 Initialize three counters:
o lineCount to count the number of lines.
o wordCount to count the number of words.
o charCount to count the number of characters.
Step-5: Read File Line by Line:
 Use a loop to read each line from the file until the end of the file (EOF).
 For each line:
o Increment lineCount.
o Initialize a flag (inWord) to track if currently inside a word.
o Iterate through each character in the line:
o Increment charCount.
o Check if the character is a space, tab, newline, or end of line ('\0'). If
yes, check the inWord flag:
o If inWord is true, increment wordCount and reset inWord.
o If the character is not a space or newline, set inWord to true to indicate
being inside a word.
Step-6: Close the File:
 Close the file using fclose() to release resources.
Step-7: Output Results:
 Print the total counts of lineCount, wordCount, and charCount.
Step-8: Stop.

Pseudo code:
function countLinesWordsChars(filename)
// Open file for reading
file = open(filename, "r")
if file is NULL
print "Error: Could not open file"
return

// Initialize counters
lineCount = 0
wordCount = 0
charCount = 0

// Process each line in the file


while not end of file
line = read a line from file
lineCount = lineCount + 1

DNRCET Page 86
inWord = false

// Process each character in the line


for each character in line
charCount = charCount + 1
if character is space or tab or newline or end of line
if inWord is true
wordCount = wordCount + 1
inWord = false
else
inWord = true

// Close the file


close(file)

// Output results
print "Number of lines:", lineCount
print "Number of words:", wordCount
print "Number of characters:", charCount

Program:

DNRCET Page 87
vi) Write a C program to print last n characters of a given file.
Algorithm:
Step-1: Start
Step-2: Open the File:
 Open the file (filename) in read mode ("rb").
Step-3: Check File Open Status:
 If the file fails to open (NULL check), print an error message and exit the program.
Step-4: Determine File Size:
 Seek to the end of the file using fseek() with offset -n from the end (SEEK_END).
 Use ftell() to get the current position, which corresponds to the size of the file.
 If the file size is less than n, read the entire file instead (edge case handling).
Step-5: Read and Print Last n Characters:
 Seek to the appropriate position (fileSize - n) using fseek().
 Read n characters from the current position using fread().
 Print the read characters to standard output.
Step-6:Close the File:
 Close the file using fclose() to release resources.
Step-7: Stop.
Pseudo code:
function printLastNChars(filename, n)
// Open file for reading
file = open(filename, "rb")
if file is NULL
print "Error: Could not open file"
return

// Determine file size


seek to end of file
fileSize = tell current position

// Adjust n if file size is less than n


if fileSize < n
set n to fileSize

// Seek to the appropriate position to read last n characters


seek to (fileSize - n)

// Read and print last n characters


buffer = read n characters from file
print buffer

// Close the file


close(file)
Program:

DNRCET Page 88

You might also like