0% found this document useful (0 votes)
19 views

IP LAB MANUAL 2023

This lab manual is designed for first-year B.Tech students at V S M College of Engineering, focusing on programming fundamentals using C. It includes a comprehensive index of experiments covering topics such as basic Linux commands, programming environments, and various C programming exercises. The manual emphasizes hands-on learning through practical coding tasks, algorithms, and flowcharts to develop problem-solving skills in programming.

Uploaded by

balalove91
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)
19 views

IP LAB MANUAL 2023

This lab manual is designed for first-year B.Tech students at V S M College of Engineering, focusing on programming fundamentals using C. It includes a comprehensive index of experiments covering topics such as basic Linux commands, programming environments, and various C programming exercises. The manual emphasizes hands-on learning through practical coding tasks, algorithms, and flowcharts to develop problem-solving skills in programming.

Uploaded by

balalove91
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/ 106

LABMANUAL

INTRODUCTION TO PROGRAMMING

I B.TECH - I SEM (Common for all branches)

(JNTUK)

(R23)

HUMANITIES & BASIC SCIENCES DEPARTMENT

V S M COLLEGE OF ENGINEERING
RAMCHANDRAPURAM

E.G. Dt. - 533255

1
INDEX
EXP NO. NAME OF THE EXPERIMENT PAGE NO.
1 i) Basic Linux environment and its editors like Vi, Vim &Emacs
etc. 4-8
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()
2 i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa 9-12
iii) Simple interest calculation
3 i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae 13-17
iv) Distance travelled by an object
4 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 18-22
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
5 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. 23-33
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.
6 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. 34-41
7 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 42-48
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.
8 i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions 49-57
v) Reverse a string using built-in and without built-in string
functions
9 i) Write a C program to find the sum of a 1D array using malloc()

2
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 58-65
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()


10 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. 66-71
iv) Write a C program to copy one structure variable to another
structure of the same type.
11 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. 72-78
iv) Write a C function to demonstrate numerical integration of
differential equations using Euler’s method
12 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.
79-88
iv) Write a C Program to implement Ackermann function using
recursion.
v) Write a recursive function to find the sum of series.
13 i) Write a C program to swap two numbers using call by
reference.
89-94
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.
14 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 95-106
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.

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

i)Basic Linux environment and its editors like Vi, Vim &Emacs etc.
What is Linux?
Just like Windows, iOS, and Mac OS, Linux is an operating system. In fact, one of the
most popular platforms on the planet, Android, is powered by the Linux operating system. An
operating system is software that manages all of the hardware resources associated with your
desktop or laptop. To put it simply, the operating system manages the communication
between your software and your hardware. Without the operating system (OS), the software
wouldn’t function.
You can install Linux on as many computers as you like without paying any thing for
software or server licensing. Linux is also distributed under an open source license. Open
source follows these key tenets:
 The freedom to run the program, for any purpose.
 The freedom to study how the program works, and change it to make it do what you
wish.
Linux commands are used to perform a variety of tasks, including displaying information
about files and directories.
1. Is – Displays information about files in the current directory.
2. pwd – Displays the current working directory.
3. mkdir – Creates a directory.
4. cd – To navigate between different folders.
5. cd .. – To navigate back to the previous folders.
6. rmdir – Removes empty directories from the directory lists.
7. cp – Moves files from one directory to another.
8. mv – Rename and Replace the files
9. rm – Delete files
10. locate– Find a file in the database.
11. cat – Display file contents on terminal
12. clear – Clear terminal

What is the editor in Linux?


A Linux system supports multiple text editors. There are two types of text editors in Linux,
which are given below: Command-line text editors such as Vi, nano, pico, and more.GUI
text editors such as gedit (for Gnome), Kwrite, and more.

4
Vi: The default editor that comes with the UNIX operating system is called vi (visual
editor). Using vi editor, we can edit an existing file or create a new file from scratch. we can
also use this editor to just read a text file. The advanced version of the vi editor is the
vimeditor.

Vim is an advanced and highly configurable text editor built to enable efficient text editing.
Vim text editor is developed by Bram Moolenaar. It supports most file types and vim editor
is also known as a programmer’s editor.It's based on shortcuts, called the Vim language,
which can make coding and writing faster and more efficient. With Vim, you can jump to
any specific text position and rapidly make precise edits.

EmacsEmacs originally was an acronym for Editor MACroS,is a text editor designed for
POSIX operating systems and available on Linux, BSD, macOS, Windows, and more. Users
love Emacs because it features efficient commands for common but complex actions and for
the plugins and configuration hacks that have developed around it for nearly 40 years.
EMAC is a national interstate mutual aid agreement that enables states to share resources
during times of disaster.
Example: ctrl-x ctrl-f : Find file or Open a file. This command prompts for a file name and
opens it in buffer for editing.

ii)Exposure to Turbo C, gcc

Turbo C
The Turbo C compiler is one of the most popular compilers used to convert a program
written in a high level language into machine code that can be executed by a computer.
Turbo C was an integrated development environment (IDE) for programming in the C
language. It was developed by Borland and first introduced in 1987. At the time, Turbo C
was known for its compact size, comprehensive manual, fast compile speed and low price.
Turbo C was a software development tool for writing programs in the C language. As an
IDE, it included a source code editor, a fast compiler, a linker and an offline help file for
reference.
Is Turbo C and C++ same?
C is structured programming language. Turbo C refers to a specific compiler made by
Borland that can be used for C programming. C++ is a superset of C, meaning everything
that you can do in C, you can do in C++.
How to Compile a Program in Turbo C?
Step 1: Open turbo C IDE(Integrated Development Environment), click on File, and then
click on New
Step 2: Write a program that we need to be executed.
Step 3: Click on Compile menu and then on Compile option, or press the keys and press
Alt + F9 to compile the code.
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled
to generate the object code and then that object code is Run.
Step 5: Output is displayed in terminal window.

5
Compiling with Turbo C requires you to use terminal commands to enter your code into the
IDE environment. Once you are finished entering your code, you can then run it through the
compiler using specific compiler options depending on what type of output file you want to
generate. These options include creating an executable (.exe) file or creating static libraries
(.lib)
The Turbo C compiler is one of the most popular compilers used to convert a program
written in a high level language into machine code that can be executed by a computer. The
compiler is responsible for translating the source code, detecting any potential errors at
compile time which includes syntax errors, type mismatches and incorrect argument types,
and then it produces an object file with all of the compiled instructions ready to run on the
computer.
Run time errors are different from compile time errors as they only appear after running a
program. These occur when an action is performed on something unexpected due to user
input or other causes and can often be difficult to detect without proper debugging tools.
Error detection consists of inspecting data structures and variables in order to identify any
issues with their values or sizes that could result in an incorrect operation or cause a fault.
After an error is detected, corrective measures can be taken to fix it before any damage is
done. Error correction involves making changes in order to correct any logic flaws or data
inconsistency issues so that the system runs smoothly again.

What is GCC?
The GNU Compiler Collection, commonly known as GCC, is a set of compilers and
development tools available for Linux, Windows, various BSDs, and a wide assortment of
other operating systems. It includes support primarily for C and C++ and includes Objective-
C, Ada, Go, Fortran, and D. The Free Software Foundation (FSF) wrote GCC and released it
as completely free software.
GCC is a toolchain that compiles code, links it with any library dependencies, converts that
code to assembly, and then prepares executable files. It follows the standard UNIX design
philosophy of using simple tools that perform individual tasks well.
How to download GCC?
Nearly all Linux distributions either come pre-installed with GCC or have it in their primary
repositories, making it easy to install.
 If you do not wish to set up an IDE and prefer the old-school way, then download
the C compiler which is called gcc from the GCC website
https://gcc.gnu.org/install/
 Once you have downloaded and installed the gcc compiler, all you have to do is,
open any text editor, copy and paste the C program code for C Hello World
Program, and save it with the name the helloworld.c like any other file you save
with a name.
 Now, Open the Command prompt or Terminal(if you use Ubuntu or Mac OS),
and go to the directory where you have saved the helloworld.c program file.

6
 Type the command gcchello.c to compile the code. This will compile the code,
and if there are no errors then it will produce an output file with name
a.out(default name)
 Now, to run the program, type in ./a.out and you will see Hello, World displayed
on your screen.

iii)Writing simple programs using printf(), scanf()

printf()

Algorithm:
1. Include the standard input-output library (stdio.h)
2. Define the main function, which is the entry point of the program
3. Use the printf function to print the "Hello, World!" message
4. Return 0 to indicate successful execution of the program

Pseudo Code
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Output:
Hello World

Flowchart

7
scanf()

Algorithm:

1. Start
2. Declare variables a,b.
3. Prompt the user to enter the number using printf statement
4. Read and store the number in the number variable.
5. Repeat the steps 3,4 again.
6. Using printf statement Display the contants of a,b.
7. End.

Pseudo Code:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("A : %d \t B : %d" ,a , b);
return 0;
}
Output:
Enter first number : 5
Enter second number :6
A: 5 B: 6

FlowChart

8
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:
1. Sum and average of 3 numbers
2. Conversion of Fahrenheit to Celsius and vice versa
3. Simple interest calculation

i) Sum and average of 3 numbers

Algorithm
1. Start
2. Declare variables num1, num2, num3, sum, and average.
3. Prompt the user to input three numbers.
4. Read and store the three numbers in num1, num2, and num3.
5. Calculate the sum: sum = num1 + num2 + num3.
6. Calculate the average: average = sum / 3.0.
7. Display the sum and average.
8. End.

Pseudo code
#include <stdio.h>
int main()
{
float num1, num2, num3;
float sum, average;
printf("Enter three numbers: ");
scanf("%f%f%f", &num1, &num2, &num3);
sum = num1 + num2 + num3;
average = sum / 3.0;
printf("Sum: %f\n", sum);
printf("Average: %f\n", average);
return 0;
}

Output

9
Flowchart:

ii) Conversion of Fahrenheit to Celsius and vice versa

Algorithm:

1. Start
2. Declare variables Fahrenheit and Celsius.
3. Prompt the user to input the temperature in Fahrenheit.
4. Read and store the temperature in Fahrenheit.
5. Calculate the equivalent temperature in Celsius using the formula: celsius = (fahrenheit -
32) * 5/9.
6. Display the temperature in Celsius.
7. End.

Pseudo code
#include <stdio.h>
int main() {
double fahrenheit, celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit);
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
printf("Temperature in Celsius: %.2lf\n", celsius);
return 0;
}

10
Output

Flowchart

iii) Simple interest calculation

Algorithm:
1. Start
2. Declare variables principal, rate, time, and interest.
3. Prompt the user to enter the principal amount.
4. Read and store the principal amount in the principal variable.
5. Prompt the user to enter the annual interest rate (as a decimal).
6. Read and store the interest rate in the rate variable.
7. Prompt the user to enter the time period in years.
8. Read and store the time period in the time variable.
9. Calculate simple interest using the formula: interest = principal * rate * time.
10. Display the calculated simple interest.
11. End.

Pseudo code
#include <stdio.h>

11
int main() {
double principal, rate, time, interest;
printf("Enter principal amount: ");
scanf("%lf", &principal);
printf("Enter annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter time period (in years): ");
scanf("%lf", &time);
interest = principal * rate * time;
printf("Simple Interest: %.2lf\n", interest);
return 0;
}

Output:

Flowchart

12
WEEK 3
Objective: Learn how to define variables with the desired data-type, initialize them with
appropriate values and how arithmetic operators can be used with variables and constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
1. Finding the square root of a given number
2. Finding compound interest
3. Area of a triangle using heron’s formulae
4. Distance travelled by an object

i) Finding the square root of a given number


Algorithm:
1. Start
2. Declare variables number and result.
3. Prompt the user to enter the number for which the square root is to be found.
4. Read and store the number in the number variable.
5. Calculate the square root using the sqrt function and store the result in the result variable.
6. Display the calculated square root.
7. End.

Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double number, result;
printf("Enter a number: ");
scanf("%lf", &number);
result = sqrt(number);
printf("Square root: %.4lf\n", result);
return 0;
}
Output:

Flowchart

13
ii) Finding compound interest

Algorithm:

1. Start
2. Declare variables principal, rate, time, n, compoundInterest.
3. Prompt the user to enter the principal amount.
4. Read and store the principal amount in the principal variable.
5. Prompt the user to enter the annual interest rate (as a decimal).
6. Read and store the interest rate in the rate variable.
7. Prompt the user to enter the time period in years.
8. Read and store the time period in the time variable.
9. Prompt the user to enter the number of times interest is compounded per year (n).
10. Read and store the compounding frequency in the n variable.
11. Calculate the compound interest using the formula:compoundInterest = principal *
pow(1 + rate / n, n * time) - principal
12. Display the calculated compound interest.
13. End.

Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double principal, rate, time, n, ci;
printf("Enter principal amount: ");
scanf("%lf", &principal);
printf("Enter annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter time period (in years): ");
scanf("%lf", &time);
printf("Enter compounding frequency (n): ");
scanf("%lf", &n);
ci= principal * (pow(1 + rate / n, n * time) - 1);
printf("Compound Interest: %.2lf\n", ci);
return 0;
}

Output:

14
Flowchart

iii) Area of a triangle using heron’s formulae

Algorithm:
1. Start
2. Declare variables side1, side2, side3, s, and area.
3. Prompt the user to enter the length of the first side of the triangle (side1).
4. Prompt the user to enter the length of the second side of the triangle (side2).
5. Prompt the user to enter the length of the third side of the triangle (side3).
6. Calculate the semi-perimeter s using the formula: s = (side1 + side2 + side3) / 2.
7. Calculate the area area using Heron's formula: area = sqrt(s * (s - side1) * (s - side2) * (s -
side3)).
8. Display the calculated area.
9. End.

Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double side1, side2, side3, s, area;
printf("Enter the length of the first side: ");
scanf("%lf", &side1);
printf("Enter the length of the second side: ");
scanf("%lf", &side2);
printf("Enter the length of the third side: ");
scanf("%lf", &side3);
s = (side1 + side2 + side3) / 2;

15
area = sqrt(s * (s - side1) * (s - side2) * (s - side3));
printf("Area of the triangle: %.2lf\n", area);
return 0;
}

Output:

Flowchart

iv) Distance travelled by an object

Algorithm
1. Start
2. Declare variables:
a. initialVelocity (initial velocity of the object)
b. acceleration (acceleration of the object)
c. time (time taken)
d. distance (to store the result)

16
3. Prompt the user to enter initialVelocity, acceleration, and time.
4. Read initialVelocity, acceleration, and time from the user.
5. Calculate the distance using the formula:
Distance = initialVelocity * time + 0.5 * acceleration * time * time

6. Display the calculated distance.


7. End

Pseudo code:
#include <stdio.h>
int main() {
double initialVelocity, acceleration, time;
printf("Enter initial velocity (m/s): ");
scanf("%lf", &initialVelocity);
printf("Enter acceleration (m/s^2): ");
scanf("%lf", &acceleration);
printf("Enter time (s): ");
scanf("%lf", &time);
double distance = initialVelocity * time + 0.5 *acceleration * time * time;
printf("Distance traveled: %.2lf meters\n", distance);
return 0;
}

Output:

Flowchart :

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

a. A+B*C+(D*E) + F*G
Algorithm
Step 1:Start
Step 2: READ a , b , c , d , e , f , g
Step 3: SET res := a + b * c + ( d * e ) + f * g
Step 4: PRINT res
Stop 5: Stop

PSEUDO CODE:
#include <stdio.h>
int main()
{
int a, b, c, d,e,f,g,res;
printf("Enter a,b,c,d,e,f,g values:");
scanf("%d %d %d%d%d %d%d ", &a, &b, &c, &d, &e, &f, &g);
res=a+b*c+(d*e)+f*g;
printf("result = %d", res);
return 0;

Output:

Enter a,b,c,d,e,f,g values:1 2 3 4 5 6 7

result = 69

b. A/B*C-B+A*D/3
Algorithm
Step 1:Start
Step 2: READ a , b , c , d
Step 3: SET res := a/b*c-b+a*d/3
Step 4: PRINT res
Stop 5: Stop

PSEUDO CODE:
#include <stdio.h>

18
int main()
{
int a, b, c, d ,res;
printf("Enter a,b,c,d values:");
scanf("%d %d %d%d ", &a, &b, &c, &d);
res= a/b*c-b+a*d/3;
printf("result = %d", res);
return 0;

Output:

Enter a,b,c,d values:


12
13
14
15
result=34

c. A+++B---A
Algorithm
Step 1:Start
Step 2: READ a , b
Step 3: SET res := a+++b---a
Step 4: PRINT res
Stop 5: Stop

Pseudo Code:
#include <stdio.h>
int main()
{
int a, b ,res;
printf("Enter a, b values:");
scanf("%d %d ", &a, &b);
res= a+++b---a;
printf("result = %d", res);
return 0;

Output:

Enter a,b values:1


2
result = 1

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

19
Algorithm

Step 1:Start

Step 2: READ i.j

Step 3: SET j := (i++) + (++i)

Step 4: PRINT j

Stop 5: Stop

Pseudo Code:

#include <stdio.h>

int main()
{
int i, j ,res;
printf("Enter i, j values:");
scanf("%d %d ", &i, &j);
j= (i++) + (++i);

printf("result = %d", j);

return 0;

Output:

Enter i,j values:


1
2
result = 1

ii) Find the maximum of three numbers using conditional operator

Algorithm :
Step 1:Start
Step 2: READ a , b , c
Step 3: SET max := ( a > b ) ? ( ( a > c ) ? a : c ) : ( ( b > c ) ? b : c )
Step 4: PRINT max
Stop 5: Stop
Pseudo Code:
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("Enter Three Integers\n");

20
scanf("%d %d %d", &a, &b, &c);
max = (a > b)?((a > c)?a:c):((b > c)?b:c);
printf("Maximum Number is = %d\n", max);
return 0;
}
Output:
Enter three numbers: 20
10
50
The maximum of the three numbers is: 50

iii) Take marks of 5 subjects in integers, and find the total, average in float
Algorithm:
Begin procedure main():-
Step 1: SET total := 0
Step 2: PRINT Enter marks for 5 subjects : \ n "
End procedure
Step 3: Repeat step 1 to 2 while i < 5 ;
Step 1: PRINT i + 1 )
Step 2: SET i := i + 1
End of for block
Step 3: READ marks [ i ]
Step 4: SET total := total + marks [ i ]
Step 5: SET average := ( float ) total / 5.0
Step 6: PRINT total
Step 7: PRINT average
Step 8: RETURN 0

Psuedo Code:
#include <stdio.h>
int main()
{
int marks[5];
int total = 0;
float average;
printf("Enter marks for 5 subjects:\n");
for (int i = 0; i < 5; i++)
{
printf("Enter mark for subject %d: ", i + 1);
scanf("%d", &marks[i]);
total += marks[i];
}
average = (float)total / 5.0;
printf("Total marks: %d\n", total);
printf("Average marks: %.2f\n", average);
return 0;
}

21
OUTPUT:

Enter marks for 5 subjects:

Enter mark for subject 1: 15

Enter mark for subject 2: 13

Enter mark for subject 3: 12

Enter mark for subject 4: 14

Enter mark for subject 5: 10

Total marks: 64

Average marks: 12.80

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

Algorithm:

Begin procedure main():-

Step 1: PRINT Enter four numbers :

Step 2: READ num1 , num2 , num3 , num4

Step 3: SET max := min = num1

Step 4: if num2 > max then :

Step 1: SET max := num2

End of if block

Step 5: else :

Step 1: if num2 < min then :

Step 1: SET min := num2

End of if block

End of else block

Step 6: if num3 > max then :

Step 1: SET max := num3

End of if block

Step 7: else :

Step 1: if num3 < min then :

Step 1: SET min := num3

End of if block

End of else block

23
Step 8: if num4 > max then :

Step 1: SET max := num4

End of if block

Step 9: else :

Step 1: if num4 < min then :

Step 1: SET min := num4

End of if block

End of else block

Step 10: PRINT max

Step 11: PRINT min

Step 12: RETURN 0

End procedure

Pseudo Code:

#include <stdio.h>

int main()

int num1, num2, num3, num4;

int max, min;

printf("Enter four numbers: ");

scanf("%d %d %d %d", &num1, &num2, &num3, &num4);

max = min = num1;

if (num2 > max)

max = num2;

else if (num2 < min)

min = num2;

if (num3 > max)

max = num3;

24
else if (num3 < min)

min = num3;

if (num4 > max)

max = num4;

else if (num4 < min)

min = num4;

printf("Maximum number: %d\n", max);

printf("Minimum number: %d\n", min);

return 0;

Output

Enter four numbers: 5

10

15

Maximum number: 15

Minimum number: 5

ii) Write a C program to generate electricity bill.

Algorithm:

Begin procedure main():-

Step 1: PRINT Enter no of units consumed :

Step 2: READ units

Step 3: if units < 50 then :

Step 1: SET amt := units * 3.50

Step 2: SET unitcharg := 25

End of if block

Step 4: else :

25
Step 1: if units < = 100 then :

Step 1: SET amt := 130 + ( ( units - 50 ) * 4.25 )

End of if block

Step 2: SET unitcharg := 35

End of else block

Step 5: else :

Step 1: if units < = 200 then :

Step 1: SET amt := 130 + 162.50 + ( ( units - 100 ) * 5.26 )

End of if block

Step 2: SET unitcharg := 45

End of else block

Step 6: else :

Step 1: SET amt := 130 + 162.50 + 526 + ( ( units - 200 ) * 7.75 )

Step 2: SET unitcharg := 55

End of else block

Step 7: SET total := amt + unitcharg

Step 8: PRINT total

Step 9: RETURN 0

End procedure

Pseudo Code:00

#include <stdio.h>

int main()

{
int units;
float amt, unitcharg, total;
printf(" Enter no of units consumed : ");
scanf("%d", &units);

26
if (units < 50)
{
amt = units * 3.50;
unitcharg = 25;
}
else if (units <= 100)
{
amt = 130 + ((units - 50 ) * 4.25);
unitcharg = 35;
}
else if (units <= 200)
{
amt = 130 + 162.50 + ((units - 100 ) * 5.26);
unitcharg = 45;
}
else
{
amt = 130 + 162.50 + 526 + ((units - 200 ) * 7.75);
unitcharg = 55;
}
total= amt+ unitcharg;
printf("electricity bill = %.2f", total);
return 0;
}
Output
Enter no of units consumed : 280

electricity bill = 1493.50

iii) Find the roots of the quadratic equation.

Algorithm:

Begin procedure main():-

27
Step 1: PRINT b , c ) of the quadratic equation ( ax ^ 2 + bx + c ) : "

Step 2: READ a , b , c

Step 3: SET discriminant := b * b - 4 * a * c

Step 4: if discriminant > 0 then :

Step 1: SET sqrt_discriminant := sqrt ( discriminant )

Step 2: SET root1 := ( - b + sqrt_discriminant ) / ( 2 * a )

Step 3: SET root2 := ( - b - sqrt_discriminant ) / ( 2 * a )

Step 4: PRINT Roots are real and different : \ n

Step 5: PRINT root1

Step 6: PRINT root2

End of if block

Step 5: else :

Step 1: if discriminant = 0 then :

Step 1: SET root1 := - b / ( 2 * a )

End of if block

Step 2: PRINT Roots are real and same : \ n

Step 3: PRINT root1

End of else block

Step 6: else :

Step 1: SET sqrt_discriminant := sqrt ( fabs ( discriminant ) )

Step 2: PRINT Roots are complex and different : \ n

Step 3: PRINT - b / ( 2 * a ) , sqrt_discriminant / ( 2 * a )

Step 4: PRINT - b / ( 2 * a ) , sqrt_discriminant / ( 2 * a )

End of else block

Step 7: RETURN 0

End procedure

28
Pseudo Code:

#include <stdio.h>

#include <math.h>

int main()

float a, b, c;

float discriminant, sqrt_discriminant, root1, root2;

printf("Enter coefficients (a, b, c) of the quadratic equation (ax^2 + bx + c): ");

scanf("%f %f %f", &a, &b, &c);

discriminant = b * b - 4 * a * c;

if (discriminant > 0)

sqrt_discriminant = sqrt(discriminant);

root1 = (-b + sqrt_discriminant) / (2 * a);

root2 = (-b - sqrt_discriminant) / (2 * a);

printf("Roots are real and different:\n");

printf("Root 1 = %.2f\n", root1);

printf("Root 2 = %.2f\n", root2);

else if (discriminant == 0)

root1 = -b / (2 * a);

printf("Roots are real and same:\n");

printf("Root 1 = Root 2 = %.2f\n", root1);

} else

sqrt_discriminant = sqrt(fabs(discriminant));

29
printf("Roots are complex and different:\n");

printf("Root 1 = %.2f + %.2fi\n", -b / (2 * a), sqrt_discriminant / (2 * a));

printf("Root 2 = %.2f - %.2fi\n", -b / (2 * a), sqrt_discriminant / (2 * a));

return 0;

Output:
Enter coefficients (a, b, c) of the quadratic equation (ax^2 + bx + c): 3

Roots are real and different:

Root 1 = -0.67

Root 2 = -1.00

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

Algorithm:

Step 1: Read a,b

Step 2: Print “Enter an operator”

Step 3: do

Begin

Step 4: Read ch

Step 5: switch(ch)

Begin

Step 6:

case 1:

Begin

Calculate c = a+b

Print “result”

30
break;

End

case 2:

Begin

Calculate c = a-b

Print “result”

break;

End

case 3:

Begin

Calculate c = a*b

Print “result”

break;

End

case 4:

Begin

Calculate c = a/b

Print “result”

break;

End

#include <stdio.h>
int main()
{
char ch;
int a, b, result;
printf("Enter an Operator (+, *, *, /): ");
scanf("%c", &ch);
printf("Enter two operands: \n");
scanf("%d %d ", &a, &b);
switch(ch)
{
case '+':
result = a + b;

31
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
printf("result = %d",result);
return 0;
}
Output

Enter an operator (+, -, *, /): +

Enter two operands: 5 2

Result: 7

Enter an operator (+, -, *, /): -

Enter two operands: 5 2

Result: 3

Enter an operator (+, -, *, /): *

Enter two operands: 5 2

Result: 10

Enter an operator (+, -, *, /): /

Enter two operands: 5 2

Result: 2.5

v) Write a C program to find the given year is a leap year or not

Algorithm:
Step 1: Start
Step 2: Read year
Step 3: If the year is divisible by 4 then go to Step 4 else go to Step 7
Step 4: If the year is divisible by 100 then go to Step 5 else go to Step 6
Step 5: If the year is divisible by 400 then go to Step 6 else go to Step 7
Step 6: Print "Leap year"

32
Step 7: Print "Not a leap year"
Step 8: Stop

Pseudo Code:

#include <stdio.h>

int main()

int year;

printf("Enter a year: ");

scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

printf("%d is a leap year.\n", year);

else

printf("%d is not a leap year.\n", year);

return 0;

Output
Enter a year: 2024

2024 is a leap year.

Enter a year: 2022

2022 is not a leap year.

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

Algorithm:

Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, fact = 1
Step 4: if i <= n go to step 4 otherwise go to step 7
Step 5: Calculate fact = fact * i
Step 6: Increment the i by 1 (i=i+1) and go to step 3
Step 7: Print fact
Step 8: Stop

Pseudo Code:

#include <stdio.h>

int main()

int loop;

int factorial=1;

int number = 5;

for(loop = 1; loop<= number; loop++)

factorial = factorial * loop;

printf("Factorial of %d = %d \n", number, factorial);

return 0;

34
OUTPUT:

Factorial of 5 = 120

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

Algorithm:

Step 1: Start

Step 2: Read number n

Step 3: Set f=0

Step 4: For i=2 to n-1

Step 5: If n mod 1=0 then

Step 6: Set f=1 and break

Step 7: Loop

Step 8: If f=0 then

print 'The given number is prime'

else

print 'The given number is not prime'

Step 9: Stop

Pseudo Code:

#include <stdio.h>

int main()

int i, num, temp = 0;

printf("Enter any numb to Check for Prime: ");

scanf("%d", &num);

for (i = 2; i <= num / 2; i++)

35
if (num % i == 0)

temp++;

break;

if (temp == 0 && num != 1)

printf("%d is a Prime number", num);

else

printf("%d is not a Prime number", num);

return 0;

OUTPUT:

Enter any number to Check for Prime: 5

5 is a Prime number

Enter any numb to Check for Prime: 10

10 is not a Prime number

iii) Compute sine and cos series

36
#include <stdio.h>

#include <math.h>

double compute_sine(double x, int terms)

double result = x;

double numerator = x;

double denominator = 1;

int sign = -1;

for (int i = 1; i < terms; i++)

numerator *= x * x;

denominator *= (2 * i) * (2 * i + 1);

result += sign * (numerator / denominator);

sign *= -1;

return result;

double compute_cosine(double x, int terms)

double result = 1;

double numerator = 1;

double denominator = 1;

int sign = -1;

for (int i = 1; i < terms; i++)

numerator *= x * x;

denominator *= (2 * i) * (2 * i - 1);

37
result += sign * (numerator / denominator);

sign *= -1;

return result;

int main()

double angle_radians;

int terms;

printf("Enter the angle in radians: ");

scanf("%lf", &angle_radians);

printf("Enter the number of terms: ");

scanf("%d", &terms);

double sine_result = compute_sine(angle_radians, terms);

double cosine_result = compute_cosine(angle_radians, terms);

printf("Sine(%lf) = %.6f\n", angle_radians, sine_result);

printf("Cosine(%lf) = %.6f\n", angle_radians, cosine_result);

return 0;

OUTPUT:

Enter the angle in radians: 5

Enter the number of terms: 1 2 3 4 5

Sine(5.000000) = 5.000000

Cosine(5.000000) = 1.000000

iv) Checking a number palindrome.

Algorithm:
Step 1: Start

38
Step 2: Read the input number from the user

Step 3: Declare and initialize the variable reverse and assign input to a temp variable
tempNum=num

Step 4: Start the while loop until num !=0 becomes false

rem = num % 10

reverse*= 10 + rem

num = num / 10

Step 5 : Check if reverse == tempNum

Step 6: If it’s true then the number is a palindrome

Step 7: If not, the number is NOT a palindrome

Step 8: Stop

Pseudo Code:
#include <stdio.h>
int main()
{
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0)
{
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}

OUTPUT:

Enter an integer: 15

39
15 is not a palindrome.

Enter an integer: 1001

1001 is a palindrome.

v) Construct a pyramid of numbers.

Algorithm:

Begin procedure main():-

Step 1: PRINT Enter a number to define the rows : \ n

Step 2: READ rows

Step 3: PRINT \ n

Step 4: Repeat step 1 to 2 while i < = rows ;

Step 1: Repeat step 1 to 2 while j < = i ;

Step 1: PRINT j

Step 2: SET := + 1

End of for block

Step 1: PRINT \ n

Step 2: SET := + 1

End of for block

Step 4: RETURN 0

End procedure

Pseudo Code:

#include <stdio.h>

int main()

int i, j, rows;

printf (" Enter a number to define the rows: \n ");

scanf("%d", &rows);

40
printf("\n");

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

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

printf ("%d ", j);

printf ("\n");

return 0;

OUTPUT:

Enter a number to define the rows: 6

12

123

1234

12345

123456

41
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

1)Read the entered array size and store that value into the variable n.
2) Read the entered elements using scanf and store the entered array elements into the
arrayusing for loop for(i=0;i<n;i++).
3) Initialise min, max values with the 1st element of the array.
4) Compare min, max values with a[i],
If min value is greater than a[i] then initialise min=a[i] and if max value is less than a[i]
then initialise max=a[i]. Repeat this step for each element of the string using for loop
which is having the structure for(i=1;i<n;i++).
Print the minimum of the array and maximum of the array values

Pseudo code:
#include
<stdio.h> int
main()

{
int a[1000],i,n,min,max;
printf("Enter size of the array :
");scanf("%d",&n);
printf("Enter elements in array :
");for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];

42
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);

printf("\nmaximum of array is : %d",max);


return 0;
}
Output:-
Enter size of the array: 5
Enter elements in array:
12
3
4
5
minimum of an array is: 1

maximum of an array is: 5

ii) Perform linear search on1D


array. Algorithm
1) Begin with the leftmost element of arr[] and one by one compare x with each element.

2) If x matches with an element then return the index.

3) If x does not match with any of the elements then return -1.

Pseudo code:
#include<stdio.h>

int main()
{
int a[20],i,x,n;
printf("How many
elements?");scanf("%d",&n);

43
printf("Enter array
elements:n");for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("nEnter element to
search:");scanf("%d",&x);

for(i=0;i<n;+
+i) if(a[i]==x)
break;
if(i<n)
printf("Element found at index
%d",i);else
printf("Element not found");

return 0;

}
Output:-
How many
elements?10 Enter
array elements:n1 2
6
8
Enter element to
search:6Element found
at index 3

iii) The reverse of a 1D integer


arrayAlgorithm
1) Read the entered array size and store that value into the variable n.
2) Read the entered elements using scanf and store the entered array elements into the
arrayusing for loop for(i=0;i<n;i++).
3) First iteration: i = n - 1 = 5, i >= 0, j
= 0rev[0] = arr[5]
In the same way:
Second iteration: rev[1] =
arr[4]Third iteration: rev[2] =
arr[3] Fourth iteration: rev[3]
= arr[2] Fifth iteration: rev[4]
= arr[1]
Sixth iteration: rev[5] = arr[0]
Pseudo code:

#include
<stdio.h> int
main()

44
{
int n, arr[n], i;
printf("Enter the size of the array:
");scanf("%d", &n);
printf("Enter the elements:
");for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(i = n-1; i >= 0; i--)
{
rev[j] =
arr[i];j++;
}
printf("The Reversed array:
");for(i = 0; i < n; i++)
{
printf("%d ", rev[i]);
}
}
Output:

Enter the size of the array: 5


Enter the elements: 1 2 3 4 5
The Reversed array: 5 4 3 2 1

i) Find 2’s complement of the given binary


number. Algorithm
Step-1 :Input a binary string from user. Store it in a variable say binary.
Step-2:Find ones complement of the binary string. Store the result in some variable
sayonesComp.
Step-:3Declare and initialize another binary string variable to store twos complement,
saytwosComp = "".
Initialize a variable to store carry bit during addition, say carry = 1.
Step-4 :Run a loop from length of binary string to 1, decrement 1 in each iteration. The loop
structure should look like for(i=SIZE-1; i>=1; i--) (where SIZE is length of the binary
string). Step-1 5Inside the loop there can be three cases.
If both current binary bit and carry bit are 1 then, put 0 to twos complement. Which is
if(onesComp[i]=='1' && carry==1) then, twosComp[i] = '0', carry is still preserved to 1.
If current binary bit is 0 and carry bit is 1 then, put 1 to twos complement and set carry bit to
0. Which is if(onesComp[i]=='0' && carry==1) then, twosComp[i] = '1' and carry = 0.
If carry bit is 0, then assign the value of onesComp to twosComp

45
Pseudo code:

#include

<stdio.h>#define

SIZE 8

int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE +
1];int i, carry=1;

printf("Enter %d bit binary value: ", SIZE);

/* Input 8-bit binary string


*/gets(binary);

/* Find ones complement of the binary number


*/for(i=0; i<SIZE; i++)
{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[SIZE] = '\0';

/*
* Add 1 to the ones complement
*/
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else

46
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';

printf("Original binary = %s\n", binary);


printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n",
twosComp);

return 0;
}

Output:-
Enter 8 bit binary value: 10011000
Original binary = 10011000
Ones complement =
01100111Twos complement
= 01101000

ii) Eliminate duplicate elements in an array.


Algorithm

1)Start with an array that may contain duplicate


elements. 2)Initialize an empty result array to store
unique elements. 3)For each element in the original
array:
4) Check if it already exists in the result

array. 5)If it doesn't exist, add it to the


result array.
The result array will now contain only the distinct elements from the original array
Pseudo code:

#include <stdio.h>
// Function to eliminate duplicate elements in an
arrayint removeDuplicates(int arr[], int n) {
if (n <=
1)
return
n;
int uniqueIndex = 0;

47
for (int i = 0; i < n - 1;
i++) { int isDuplicate =
0;

for (int j = i + 1; j < n;


j++) { if (arr[i] == arr[j])
{
isDuplicate =
1;break;
}
}

if (!isDuplicate) {
arr[uniqueIndex] =
arr[i];uniqueIndex++;
}
}

arr[uniqueIndex] = arr[n -
1];uniqueIndex++;

return uniqueIndex;
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5, 6, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array:
"); for (int i = 0; i < n;
i++) {printf("%d ",
arr[i]);
}

n = removeDuplicates(arr, n);

printf("\nArray after removing duplicates:


");for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n
");return
0;
}
Output:
Original array: 1 2 2 3 4 4 5 6 6 7
Array after removing duplicates: 1 2 3 4 5 6 7

48
WEEK-8
Objective: Explore the difference between other arrays and character arrays that can be
usedas 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: 2 D 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

matricesAlgorithm:
1) Start with two matrices, matrix1 and matrix2, with the same dimensions (number of rows
and columns).
2) Create a result matrix, resultMatrix, with the same dimensions as the input matrices to
storethe sum.
3) Iterate through each element of the matrices using nested loops, i.e., two loops for rows
andcolumns.
4) For each element at position [i][j] in the result matrix, add the corresponding elements
frommatrix1 and matrix2 at the same position.
5) Store the result in the corresponding position in the result matrix.
After iterating through all elements, the resultMatrix will contain the sum of the two
input matrices

Pseudo code:

#include<stdio.h
>

int main()

{
int rows, cols;
printf("Enter the number of rows:
");scanf("%d", &rows);
printf("Enter the number of columns:
");scanf("%d", &cols);
int matrix1[rows][cols], matrix2[rows][cols], resultMatrix[rows][cols];

// Input the first matrix

49
printf("Enter elements of the first
matrix:\n");for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input the second matrix
printf("Enter elements of the second
matrix:\n");for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++) {
scanf("%d",
&matrix2[i][j]);
}
}

// Add the matrices


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result matrix


printf("Resultant matrix after
addition:\n");for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++) {
printf("%d ",
resultMatrix[i][j]);
}
printf("\n");
}

return 0;
}
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first
matrix:2 3
46
Enter elements of the second
matrix:5 7
89

50
Resultant matrix after
addition:7 10
12 15

ii) Multiplication two

matricesAlgorithm:

1) Start with two matrices, matrix1 and matrix2, with compatible dimensions for
multiplication (the 2)number of columns in matrix1 must be equal to the number of rows
in matrix2).
3) Create a result matrix, resultMatrix, with dimensions [rows1][cols2], where rows1 is
thenumber of rows in matrix1, and cols2 is the number of columns in matrix2.
4) Initialize elements of the resultMatrix to 0.
Perform matrix multiplication using nested
loops:
For each element at position [i][j] in the result matrix:
5) Initialize a temporary variable sum to 0.
Iterate through a common index k (from 0 to the number of columns in matrix1 or
thenumber of rows in matrix2):
Add the product of matrix1[i][k] and matrix2[k][j] to sum.
Set resultMatrix[i][j] to sum.
After completing the multiplication, the resultMatrix will contain the product of the two
input matrices.
Pseudo code:

#include<stdio.h
>

int main()
{
int rows1, cols1, rows2, cols2;
printf("Enter the number of rows for matrix 1:
");scanf("%d", &rows1);
printf("Enter the number of columns for matrix 1:
");scanf("%d", &cols1);
printf("Enter the number of rows for matrix 2:
");scanf("%d", &rows2);
printf("Enter the number of columns for matrix 2:
");scanf("%d", &cols2);

if (cols1 != rows2) {
printf("Matrix multiplication is not possible. The number of columns in matrix 1 must be
equal to the number of rows in matrix 2.\n");
return 1; // Exit with an error code
}

51
int matrix1[rows1][cols1], matrix2[rows2][cols2], resultMatrix[rows1][cols2];

// Input the first matrix


printf("Enter elements of the first
matrix:\n");for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++)
{ scanf("%d",
&matrix1[i][j]);
}

// Input the second matrix


printf("Enter elements of the second
matrix:\n");for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++)
{ scanf("%d",
&matrix2[i][j]);
}
}

// Multiply the matrices


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++)
{
int sum = 0;
for (int k = 0; k < cols1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
resultMatrix[i][j] = sum;
}
}
// Display the result matrix
printf("Resultant matrix after
multiplication:\n");for (int i = 0; i < rows1;
i++) {
for (int j = 0; j < cols2; j++) {
printf("%d ",
resultMatrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows for matrix 1: 2

52
Enter the number of columns for matrix 1:
2Enter the number of rows for matrix 2: 2
Enter the number of columns for matrix 2:
2Enter elements of the first matrix:
23
45
Enter elements of the second
matrix:5 6
78
Resultant matrix after
multiplication: 31 36
55 64
i) Sort array elements using bubble sort
Algorithm:

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted,
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.

1) Start from the first element (index 0) and compare it with the next element (index 1).
2) If the elements are out of order (the current element is greater than the next element in
thecase of ascending order), swap them.
3) Move to the next pair of elements (index 1 and index 2) and repeat the comparison
andswap if necessary.
4) Continue this process for each pair of adjacent elements until you reach the end of
thearray.
5) After one pass through the array, the largest element will have "bubbled up" to the end
ofthe array.
6) Repeat steps 1-5 for a total of (n-1) passes (where n is the number of elements in the
array) to completely sort the array.
Pseudo code:

#include <stdio.h>
void bubbleSort(int arr[], int
n) { int temp;
int swapped;

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


swapped = 0; // Flag to optimize for already sorted arrays

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


// Compare adjacent
elements if (arr[j] > arr[j +
1]) {
// Swap the
elementstemp =
arr[j];

53
arr[j] = arr[j +
1];arr[j + 1] =
temp;
swapped = 1; // Mark as swapped
}
}

// If no two elements were swapped in inner loop, the array is already


sortedif (swapped == 0) {
break;
}
}
}
int main()
{
int n;
printf("Enter the number of elements in the array:
");scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n",
n);for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
printf("Sorted array using Bubble
Sort:\n");for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Output:
Enter the number of elements in the array: 12 45 8 6 13 56 11 9
Enter 12 elements:
12
15
15
19
21
Sorted array using Bubble Sort:
6 8 9 11 12 13 15 15 19 21 45 56

54
ii) Concatenate two strings without built-in functions
Algorithm:
To concatenate two strings without using built-in functions, you can create a new character
array (string) and copy the characters from the first string into it, followed by the characters
from the second stringCreate a character array (result) to store the concatenated string.
1. Initialize variables to keep track of the positions in both input strings (str1 and str2)
and in the result string (resultPos).
2. Iterate through the characters of the first string (str1) and copy them to the result
string one by one.
3. Update the resultPos and str1 positions accordingly.
4. Iterate through the characters of the second string (str2) and copy them to the result
string one by one, starting from the resultPos position.

5. Update the resultPos and str2 positions accordingly.


6. Append a null character '\0' at the end of the result string to mark the end of the
concatenated string

Pseudo code:

#include <stdio.h>
void concatStrings(char result[], const char str1[], const char str2[]) {
int resultPos = 0;
int str1Pos = 0;
int str2Pos = 0;
// Copy characters from str1 to result
while (str1[str1Pos] != '\0') {
result[resultPos] = str1[str1Pos];
resultPos++;
str1Pos++;
}

// Copy characters from str2 to result


while (str2[str2Pos] != '\0') {
result[resultPos] = str2[str2Pos];
resultPos++;
str2Pos++;
}

// Add null character at the end to terminate the string


result[resultPos] = '\0';
}

int main() {
const char str1[] = "Hello, ";
const char str2[] = "world!";
char result[100]; // Assuming a maximum length for the result

concatStrings(result, str1, str2);


55
printf("Concatenated string: %s\n", result);

return 0;
}

Output:
Concatenated string: Hello, world!

iii) Reverse a string using built-in and without built-in string functions
Algorithm:

1. Initialize two pointers, start and end, to the beginning and end of the string,
respectively.
2. Swap the characters at the start and end positions.
3. Increment the start pointer and decrement the end pointer.
4. Repeat steps 2 and 3 until start is less than end. This means you're swapping
characters from both ends towards the middle of the string.
5. When start becomes greater than or equal to end, the entire string is reversed.

Pseudo code:

#include <stdio.h>

// Function to reverse a string without using built-in functions


void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;

while (start < end) {


// Swap characters at start and end positions
char temp = str[start];
str[start] = str[end];
str[end] = temp;

// Move the pointers towards each other


start++;
end--;
}
}
int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

reverseString(str);

printf("Reversed string: %s\n", str);

56
return 0;
}

Output:
Enter a string: hello
Reversed string: olleh

57
WEEK 9
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation &amp; 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 dereference.
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:

1. Ask the user for the number of elements in the array (array size).
2. Dynamically allocate memory for the array using malloc() based on the input size.
3. Initialize a variable sum to zero to store the sum of elements.
4. Iterate through the elements of the array using a loop.
5. For each element, prompt the user for its value and store it in the corresponding
position in the dynamically allocated array.
6. Add each element's value to the sum variable as you iterate through the array.
7. After processing all elements, the sum variable will contain the sum of all elements in
the array.
8. Finally, free the dynamically allocated memory using free() to prevent memory leaks

Pseudo code:

#include <stdio.h>
#include <stdlib.h> // for malloc and free functions

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

// Dynamically allocate memory for the array


int *arr = (int *)malloc(n * sizeof(int));

58
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}
// Input array elements and calculate the sum
int sum = 0;
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
sum += arr[i];
}
// Print the sum of array elements
printf("Sum of elements in the array: %d\n", sum);
// Free the dynamically allocated memory
free(arr);

return 0;
}

Output:
Enter the number of elements in the array: 5
Enter element 1: 5
Enter element 2: 6
Enter element 3: 7
Enter element 4: 8
Enter element 5: 9
Sum of elements in the array: 35

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

Algorithm:
1. Define a structure to represent student information. The structure can contain fields
like student name, roll number, and an array to store scores.
2. Ask the user for the number of students (n).
3. Dynamically allocate memory for an array of n student structures.
4. Iterate through each student and input their details, including name, roll number, and
scores.
5. Calculate the total score for each student and the average score for all students.
6. Print the total and average scores.

Pseudo code:

#include <stdio.h>
#include <stdlib.h> // for malloc and free functions
// Define a structure to represent a student

59
struct Student {
char name[50];
int rollNumber;
int scores[5]; // Assuming 5 scores per student
};

int main() {
int n;

printf("Enter the number of students: ");


scanf("%d", &n);

// Dynamically allocate memory for an array of student structures


struct Student *students = (struct Student *)malloc(n * sizeof(struct Student));

// Check if memory allocation was successful


if (students == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}

// Input student details and calculate total and average scores


for (int i = 0; i < n; i++) {
printf("Enter student %d name: ", i + 1);
scanf("%s", students[i].name);

printf("Enter student %d roll number: ", i + 1);


scanf("%d", &students[i].rollNumber);

printf("Enter %d scores for student %d: ", 5, i + 1);


for (int j = 0; j < 5; j++) {
scanf("%d", &students[i].scores[j]);
}
}

// Calculate total and average scores for all students


int totalScores = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < 5; j++) {
totalScores += students[i].scores[j];
}
}

double averageScore = (double)totalScores / (n * 5); // Total scores divided by (number of


students * number of scores)

60
// Print total and average scores
printf("Total scores of all students: %d\n", totalScores);
printf("Average score of all students: %.2lf\n", averageScore);

// Free the dynamically allocated memory


free(students);

return 0;
}

Output:
Enter the number of students: 2
Enter student 1 name: h
Enter student 1 roll number: 5
Enter 5 scores for student 1: 23 25 26 29 30
Enter student 2 name: k
Enter student 2 roll number: 6
Enter 5 scores for student 2: 29 24 26 30 28
Total scores of all students: 270
Average score of all students: 27.00
29

iii)Enter n students data using calloc() and display failed students list
Algorithm:
1. Define a structure to represent student information, including fields such as name, roll
number, and marks.
2. Ask the user for the number of students (n).
3. Allocate memory for an array of n student structures using calloc(). This ensures that
the memory is initialized to zero.
4. Input student details, including name, roll number, and marks for each student.
5. Calculate the average marks for each student.
6. Determine a passing threshold (e.g., passing marks could be 40).
7. Iterate through the student array and identify students whose average marks are below
the passing threshold.
8. Display the list of failed students.

Pseudo code:

#include <stdio.h>
#include <stdlib.h> // for calloc and free functions

// Define a structure to represent a student


struct Student {
char name[50];
int rollNumber;
int marks[5]; // Assuming 5 subjects' marks per student

61
double averageMarks;
};

int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);

// Allocate memory for an array of student structures using calloc


struct Student *students = (struct Student *)calloc(n, sizeof(struct Student));

// Check if memory allocation was successful


if (students == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}

// Input student details and calculate average marks


for (int i = 0; i < n; i++) {
printf("Enter student %d name: ", i + 1);
scanf("%s", students[i].name);

printf("Enter student %d roll number: ", i + 1);


scanf("%d", &students[i].rollNumber);

printf("Enter %d subject marks for student %d: ", 5, i + 1);


for (int j = 0; j < 5; j++) {
scanf("%d", &students[i].marks[j]);
students[i].averageMarks += students[i].marks[j];
}

students[i].averageMarks /= 5; // Calculate the average marks


}

// Determine the passing threshold (e.g., 40)


int passingMarks = 40;

// Display the list of failed students


printf("List of Failed Students:\n");
for (int i = 0; i < n; i++) {
if (students[i].averageMarks < passingMarks) {
printf("Name: %s, Roll Number: %d, Average Marks: %.2lf\n", students[i].name,
students[i].rollNumber, students[i].averageMarks);
}
}

62
// Free the dynamically allocated memory
free(students);

return 0;
}

Output:
Enter the number of students: 2
Enter student 1 name: j
Enter student 1 roll number: 5
Enter 5 subject marks for student 1: 21 35 36
32 65
Enter student 2 name: k
Enter student 2 roll number: 6
Enter 5 subject marks for student 2: 25 33 36 41 54 21
List of Failed Students:
Name: j, Roll Number: 5, Average Marks: 37.80
Name: k, Roll Number: 6, Average Marks: 37.80

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

1. Accept command line arguments for the student name and marks.
2. Initialize variables to store the student name, total marks, and individual subject
marks.
3. Iterate through the command line arguments, starting from the second argument (the
first argument is the program name).
4. Convert each argument to an integer (marks) using atoi() and add it to the total marks.
5. Print the student name and individual subject marks.
6. Print the total marks at the end.
Pseudo code:

#include <stdio.h>
#include <stdlib.h> // for atoi function

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


if (argc < 2) {
printf("Usage: %s <student_name> <marks1> <marks2> ... <marksN>\n", argv[0]);
return 1; // Exit with an error code
}
63
char *studentName = argv[1];
int totalMarks = 0;

printf("Student Name: %s\n", studentName);


printf("Individual Subject Marks:\n");

// Start from argv[2] to skip the program name and student name
for (int i = 2; i < argc; i++) {
int marks = atoi(argv[i]); // Convert argument to integer
totalMarks += marks;
printf("Subject %d: %d\n", i - 1, marks);
}

printf("Total Marks: %d\n", totalMarks);

return 0;
}

Output:

v) Write a C program to implement realloc()

Pseudo code:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr = NULL; // Declare a pointer to int
int initialSize = 5; // Initial size of the array
int newSize = 10; // New size to which we want to resize

// Allocate memory for the initial array


arr = (int *)malloc(initialSize * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program with an error code
}

printf("Initial array elements: ");


for (int i = 0; i < initialSize; i++) {
arr[i] = i * 2; // Initialize the array with some values
printf("%d ", arr[i]);

64
}
printf("\n");

// Use realloc() to resize the array to the new size


arr = (int *)realloc(arr, newSize * sizeof(int));

if (arr == NULL) {
printf("Memory reallocation failed.\n");
return 1; // Exit the program with an error code
}

printf("Resized array elements: ");


for (int i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Free the allocated memory when you're done using it


free(arr);

return 0; // Exit the program successfully


}
Output:
Initial array elements: 0 2 4 6 8
Resized array elements: 0 2 4 6 8 0 0 0 0 0

65
WEEK 10:

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:

Pseudo code:

#include <stdio.h>
#include <stdlib.h>
struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the next node
}*stnode;

void createNodeList(int n); // function to create the list


void displayList(); // function to display the list

int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf(" \n");

66
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));

if(stnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard

printf(" Input data for node 1 : ");


scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL; // links the address field to NULL
tmp = stnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);

fnNode->num = num; // links the num field of fnNode with num


fnNode->nextptr = NULL; // links the address field of fnNode with NULL

tmp->nextptr = fnNode; // links previous node i.e. tmp to the fnNode


tmp = tmp->nextptr;
}
}
}

67
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}

Output:
Input the number of nodes : 3
Input data for node 1 : 1
Input data for node 2 : 2
Input data for node 3 : 3
Data entered in the list :
Data = 1
Data = 2
Data = 3
ii)Demonstrate the differences between structures and unions using a C program.
Pseudo code:
#include <stdio.h>
#include <string.h>

// Define a structure
struct Student {
int roll_number;
char name[20];
};

// Define a union
union Money {
float dollars;
int euros;
};

int main() {
// Structure Example
struct Student student1;
student1.roll_number = 101;

68
strcpy(student1.name, "John");

printf("Structure - Student: Roll Number = %d, Name = %s\n", student1.roll_number,


student1.name);
printf("Size of Structure Student: %lu bytes\n", sizeof(student1));

// Union Example
union Money money1;
money1.dollars = 100.50;
money1.euros = 80;

// When using a union, only one member can have a value at a time
printf("Union - Money: Dollars = %.2f, Euros = %d\n", money1.dollars, money1.euros);
printf("Size of Union Money: %lu bytes\n", sizeof(money1));

return 0;
}
Output:
Structure - Student: Roll Number = 101, Name = John
Size of Structure Student: 24 bytes
Union - Money: Dollars = 0.00, Euros = 80
Size of Union Money: 4 bytes

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

Pseudo code:
#include <stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)

{
/* In n<<d, last d bits are 0. To put first 3 bits of n
at last, do bitwise or of n<<d with n >>(INT_BITS -
d) */
return (n << d) | (n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)

{
/* In n>>d, first d bits are 0. To put last 3 bits of at
first, do bitwise or of n>>d with n <<(INT_BITS
- d) */
return (n >> d) | (n << (INT_BITS - d));
}
/* Driver program to test above functions */
void main()

{
int n = 16;
69
int d = 2;

printf("Left Rotation of %d by %d is ", n, d);


printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
}

Output:
Left Rotation of 16 by 2 is 64 Right Rotation of 16 by 2 is 4

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

Pseudo code:

#include <stdio.h>

// Define a structure
struct Student
{
int roll_number;
char name[50];
float marks;
};
int main()
{
// Declare two structure variables
struct Student student1, student2;

// Initialize the first structure


student1.roll_number = 101;
strcpy(student1.name, "John");
student1.marks = 85.5;

// Copy the first structure to the second structure


student2 = student1;

// Display the contents of the second structure


printf("Copied Structure - Student 2:\n");
printf("Roll Number: %d\n", student2.roll_number);
printf("Name: %s\n", student2.name);
printf("Marks: %.2f\n", student2.marks);

return 0;
}
Output:
Copied Structure - Student 2:
Roll Number: 101

70
Name: John
Marks: 85.50

71
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 Eulers
method

1.Write a C function to calculate NCR value


Algorithm:
STEP 1: START
STEP 2: DEFINE n, r
STEP 3: ENTER n, r
STEP 4: PRINT nCr(n, r)
STEP 5: END

nCr(n r)
STEP 1: START
STEP 2: RETURN fact(n) / (fact(r)*fact (n-r))
STEP 3: END
fact(n)
STEP 1: START
STEP 2: SET res= 1
STEP 3: REPEAT STEP 3 and STEP 4 UNTIL i<=n
STEP 4: res = res*i
STEP 5: RETURN res
STEP 6: END

Flowchart:

72
Output:

2. Write a C function to find the length of a string.

73
Program :

#include <stdio.h>
int main()
{
char s[1000];
int c = 0;
printf("Input a string\n");
gets(s);
while (s[c] != '\0')
c++;
printf("Length of the string: %d\n", c);
return 0;
}

Output:
Input a string
vsm college
Length of the string: 11

74
3. Write a C function to transpose of a matrix

75
Program:

// C Program to find transpose


// of a square matrix
#include <stdio.h>
#define N 4

// This function stores transpose


// of A[][] in B[][]
void transpose(int A[][N], int B[][N])
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
// Assigns the transpose of element A[j][i] to
// B[i][j]
B[i][j] = A[j][i];
}

// Driver code
int main()
{
int A[N][N] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };

int B[N][N], i, j;

transpose(A, B);

printf("Result matrix is \n");


for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
printf("%d ", B[i][j]);
printf("\n");
}

return 0;
}
Output:
Result matrix is
1234
1234
1234
1234

76
4 . Write a C function to demonstrate numerical integration of differential equations using Euler’s
method

Algorithm:

1. Start
2. Define function
3. Get the values of x0, y0, h and xn
*Here x0 and y0 are the initial conditions
h is the interval
xn is the required value
4. n = (xn – x0)/h + 1
5. Start loop from i=1 to n
6. y = y0 + h*f(x0,y0)
x=x+h
7. Print values of y0 and x0
8. Check if x < xn
If yes, assign x0 = x and y0 = y
If no, goto 9.
9. End loop i
10. Stop

Flowchart:

Program:
#include<stdio.h>

77
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
Output:

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

1 Write a recursive function to generate Fibonacci series.

Algorithm:

1. START
2. Input the non-negative integer ‘n’
3. If (n==o || n==1)
return n;
else
return fib(n-1)+fib(n-2);
4. Print, nth Fibonacci number
5. END

FLOWCHART:

Program:

#include<stdio.h>

79
#include<conio.h>
void main()
{
int n, i;
int fibo(int);
printf("Enter n:");
scanf("%d",&n);
printf("Fibonacci numbers up to %d terms:\n",n);
for(i=1;i<=n;i++)
printf("%d\n",fibo(i));
getch();
}
int fibo(int k)
{
if(k == 0 || k == 1)
return k;
else
return fibo(k-1)+fibo(k-2);
}
Output:
Enter n:10
Fibonacci numbers up to 10 terms:
1
1
2
3
5
8
13
21
34
55

2 Write a recursive function to find the lcm of two numbers.


Algorithm:
 Define a recursive function LCM() with 3 integer parameters N, M, and K to
find LCM of N and M.
 The following base conditions need to be considered:
 If N or M is equal to 1, return N * M.
 If N is equal to M, return N.
 If K < min(N, M):
 If K divides both N and M, return K * LCM(N/K, M/K, 2).
 Otherwise, increment K by 1 and return LCM(N, M, K+1).
 Otherwise, return the product of N and M.
 Finally, print the result of the recursive function as the required LCM.

Flow Chart:

80
Program :

// C program for the above approach

#include <stdio.h>

// Function to return the


// minimum of two numbers
int Min(int Num1, int Num2)
{
return Num1 >= Num2
? Num2
: Num1;
}

// Utility function to calculate LCM


// of two numbers using recursion
int LCMUtil(int Num1, int Num2, int K)
{
// If either of the two numbers
// is 1, return their product
if (Num1 == 1 || Num2 == 1)
return Num1 * Num2;

81
// If both the numbers are equal
if (Num1 == Num2)
return Num1;

// If K is smaller than the


// minimum of the two numbers
if (K <= Min(Num1, Num2)) {

// Checks if both numbers are


// divisible by K or not
if (Num1 % K == 0 && Num2 % K == 0) {

// Recursively call LCM() function


return K * LCMUtil(
Num1 / K, Num2 / K, 2);
}

// Otherwise
else
return LCMUtil(Num1, Num2, K + 1);
}

// If K exceeds minimum
else
return Num1 * Num2;
}

// Function to calculate LCM


// of two numbers
void LCM(int N, int M)
{
// Stores LCM of two number
int lcm = LCMUtil(N, M, 2);

// Print LCM
printf("%d", lcm);
}

// Driver Code
int main()
{
// Given N & M
int N = 2, M = 4;

// Function Call
LCM(N, M);

return 0;

82
}

Output:

Enter two positive integers: 7


5
The LCM obtained from 7 and 5 is 35.

3 Write a recursive function to find the factorial of a number

Flowchart:

Program:

#include<stdio.h>

long factorial(int n)
{

83
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}

Output:

Enter a number: 6
Factorial of 5 is: 720

4 Write a C Program to implement Ackermann function using recursion

Algorithm:

Ackermann(m, n)

{next and goal are arrays indexed from 0 to m, initialized so that next[O] through next[m] are 0, goal[O]
through goal[m - l] are 1, and goal[m] is -1}

repeat

value ← next[O] + 1

transferring ← true

current ← O

while transferring do begin

if next[current] = goal[current] then goal[current] ← value

else transferring ← false

next[current] ← next[current]+l

current ← current + 1

84
end while

until next[m] = n + 1

return value {the value of A(m, n)}

end Ackermann

flowchart:

Program:

#include <stdio.h>

int ack(int m, int n)

if (m == 0){

return n+1;

else if((m > 0) && (n == 0)){

return ack(m-1, 1);

else if((m > 0) && (n > 0)){

return ack(m-1, ack(m, n-1));

int main(){

int A;

85
A = ack(1, 2);

printf("%d", A);

return 0;

Output: 4

5 Write a recursive function to find the sum of series.

Algorithm:

First printf statement will ask the user to enter any integer value and the scanf statement will assign the
user entered value to Number variable.

Next, we used For Loop to iterate between 1 and user entered value.

Within the For loop, we calculated the sum.

In the above example, user entered value is 5 it means, 1 + 2 + 3 + 4 + 5 = 15

Flowchart:

86
Program:

#include<stdio.h>
int series(int n);

int rseries(int n);

int main( )
{
int n;
printf("Enter number of terms : ");

scanf("%d", &n);
printf("\b\b Using Recursion :: \n");
printf("\b\b = %d\n", series(n)); /* \b to erase last +sign */
printf("\n\b\b Using Recursion :: \n");
printf("\b\b = %d\n\n\n", rseries(n));

return 0;
}/*End of main()*/

/*Iterative function*/
int series(int n)
{

int i, sum=0;
for(i=1; i<=n; i++)
{
printf("%d + ", i);
sum+=i;
}

return sum;
}/*End of series()*/

/*Recursive function*/

87
int rseries(int n)
{
int sum;
if(n == 0)
return 0;

sum = (n + rseries(n-1));
printf("%d + ",n);
return sum;
}/*End of rseries()*/

Output:

Enter number of terms : 15

Using Recursion ::
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120

Using Recursion ::
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120

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

1 Write a C program to swap two numbers using call by reference.

Flow Chart:

89
Program:

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramet
ers do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a =
20, b = 10
}

Output:

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

2 Demonstrate Dangling pointer problem using a C program.

Algorithm:

1. We allocate memory for an integer using malloc.


2. Check if the memory allocation was successful.
3. Assign a value to the allocated memory.
4. Print the value using the pointer.
5. Free the allocated memory.
6. Try to access the value using the pointer again, demonstrating the use of a dangling pointer.

90
Program:
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int *)malloc(sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

*ptr = 42;
printf("Value pointed to by 'ptr': %d\n", *ptr);

free(ptr); // Deallocate the memory

printf("Value pointed to by 'ptr' after deallocation: %d\n", *ptr); // Dangling pointer access

return 0;
}

Output:
Value pointed to by 'ptr': 42
Value pointed to by 'ptr' after deallocation: 0

3 Write a C program to copy one string into another using pointer.


Algorithm:

1. Here we've created a function named copystr() that has two pointer arguments.
2. The first argument is responsible for the target string, and the second one is for the source string.
3. After calling the function copystr(), the target string and source string get passed as arguments.
4. And we know that the source string holds the value that the user enters at runtime. But the target
string has some garbage values by default.
5. Now we've created a while loop inside the function that runs before the source string comes to its
null-terminated character, that is, '\0' (or runs until the last character of the string).
6. Inside the loop, we have copied each character (one by one) of the source string into the target
string.
7. After copying or initializing, we have incremented both the pointer variables for target and
source strings.
8. After completing the while loop, all the characters of the source string get copied to the target
variable.
9. As we have used a pointer here, we only have to output the value of both strings.
10. Never forget to end the targetString pointer variable with a null terminating character ('\0').

91
Program:

#include<stdio.h>

void copy_string(char*, char*);

main()
{
char source[100], target[100];
printf("Enter source string\n");
gets(source);
copy_string(target, source);
printf("Target string is \"%s\"\n", target);
return 0;
}

void copy_string(char *target, char *source)


{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}
Output:

Enter source string


w3schools.in
Target string is "w3schools.in"

4 Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.

Algorithm:

Declare a String variable with the char str[100] (a character array).

Declare and initialize an integer variable with the following values: int i, upper=0, lower=0, special=0.

The user was requested to type a string with upper and lower case letters and special characters.

The variable str is used to store the specified string.

A for-loop counts the total number of characters in a string.

92
It starts with i=0, checks whether str[i]!= '\0' in the test expression, and then executes the loop until the
supplied condition is met.

If if(str[i]>='A' && str[i]='Z') is true, use an if condition to test it. Upper is changed to upper+1 (or
upper=upper+1).

If it is false, control passes to the else-if portion, which evaluates the test expression of else-if. If true,
control passes to the else-if part, which examines the test expression of else-if. Lower becomes lower+1
(or lower=lower+1).

If it is false, control passes to the other part, which performs the other part's instructions. The special
becomes special+1.

Finally, the program displays the total amount of upper, lower, and special characters in the given string.

Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char str[100];
int i;
int upper=0,lower=0,special=0;;
printf("Please enter the string \n");
gets(str);

// For Uppercase
for(i=0; str[i] != '\0'; i++){
if(str[i]>='A' && str[i]<='Z') {
upper++;
}

// For Lowercase
else if(str[i]>='a' && str[i]<='z') {
lower++;
}

// For special
else{
special++;
}
}
printf("\nUpper case letters: %d",upper);
printf("\nLower case letters: %d",lower);
printf("\nSpecial characters: %d",special);
getch();

93
return 0;
}

Output:

94
WEEK14:
Objective: To understand data files and file handling with various file I/O functions. Explore the
differences between text and binary files.
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.

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

Algorithm:

 Creating variable of file pointer


 Opening/creating a file
 Write some of the characters in a file
 Reading one by one character from a file
 Closing a file
 And with second example
o Writing continuous text (complete paragraph until we do not press any special character
defined in program).
o Reading all text until EOF (End of the file) is not found.
 And closing the file

Flowchart:

95
Program:
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\nEnter file name to create :");
scanf("%s",fName);
/*creating (open) a file*/
fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);

printf("\nData written successfully.");


fclose(fp);

/*again open file to read data*/


fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}

printf("Contents of file is :\n");


printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));

fclose(fp);
return 0;
}
Output:
Enter file name to create :vsm
File created successfully.
Data written successfully.Contents of file is :ABC

96
2 Write a C program to write and read text into a binary file using fread() and fwrite()

Algorithm:

 open in write mode a file with name “out.bin”, in order to store in the file the vector of
structures
 written the file in a binary way by using the function fwrite
 close the file
 reopen the file for reading it
 read the file by using the function fread and fill the vector of structures with the read data
 print all the data contained in the vector of structures
 close the file

Program:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define LEN 50

#define N_STUD 2

typedef struct stud{

char name[LEN+1];

unsigned int id;

float average;

}stud_t;

int main() {

FILE *fp;

stud_t student[N_STUD];

int i;

char row[LEN+1];

unsigned int n_stud;

strcpy(student[0].name, "Steven");

student[0].id = 120000;

student[0].average = 25.5;

strcpy(student[1].name, "Julia");

97
student[1].id = 120001;

student[1].average = 28.5;

fp = fopen("out.bin", "w"); /* Open the file for writing */

if (fp == NULL){

printf("Error: file out.bin cannot be opened\n");

exit(1);

/* Write the file */

/* NOTE 2: a binary file sometimes cannot be readable

correctly in a PC that it is not the one which generates it,

because, for instance, integer numbers can be coded with a

different number of bytes.

*/

/* Write in binary all the data contained in the structure */

fwrite(student, sizeof(stud_t), N_STUD, fp);

/* DIMENSION OF THE GENERATED FILE

The dimension of the generated file will be:

n_stud*sizeof(stud_t)

in the case of the computer used to test the program:

2*60 = 120 byte

*/

fclose(fp); /* Close the file */

fp = fopen("out.bin", "r"); /* Open the file for reading */

if (fp == NULL){

printf("Error: file out.bin cannot be opened\n");

exit(1);

98
/* Read the file */

n_stud = 0;

while( fread(&student[n_stud], sizeof(stud_t), 1, fp) == 1 ) {

n_stud++;

fclose(fp); /* Close the file */

/* Print the read records */

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

printf("%s %d %f\n", student[i].name, student[i].id, student[i].average);

return 0;

Output:

Steven 120000 25.500000

Julia 120001 28.500000

3 Copy the contents of one file to another file.

99
Flowchart:

Program:
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{

100
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}

Output:
Enter the filename to open for readinga.txt
Enter the filename to open for writingb.txt
Contents copied to b.txt

4 Write a C program to merge two files into the third file using command-line arguments.

101
Flowchart:

Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)


{
puts("Could not open files");
exit(0);
}

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);

102
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");

fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Output:

Merged file1.txt and file2.txt into file3.txt

5 Find no. of lines, words and characters in a file

Algorithm:

1. Open source file in r (read) mode.


2. Initialize three variables characters = 0, words = 0 and lines = 0 to store counts.
3. Read a character from file and store it to some variable say ch.
4. Increment characters count.
Increment words count if current character is whitespace character i.e. if (ch == ' ' || ch ==
'\t' || ch == '\n' || ch == '\0').
Increment lines count if current character is new line character i.e. if (ch == '\n' || ch ==
'\0').
5. Repeat step 3-4 till file has reached end.
6. Finally after file has reached end increment words and lines count by one if
total characters > 0 to make sure you count last word and line.

103
Flowchart:

Program:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE * file;
char path[100];

char ch;
int characters, words, lines;

/* Input path of files to merge to third file */


printf("Enter source file path: ");
scanf("%s", path);

/* Open source files in 'r' mode */


file = fopen(path, "r");

104
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");

exit(EXIT_FAILURE);
}

/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;

/* Check new line */


if (ch == '\n' || ch == '\0')
lines++;

/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}

/* Increment words and lines for last word */


if (characters > 0)
{
words++;
lines++;
}

/* Print file statistics */


printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);

/* Close files to release resources */


fclose(file);

return 0;
}
Output:
I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.

Total characters = 106 Total words = 18 Total lines =3

105
6 Write a C program to print last n characters of a given file.
Algorithm:

The steps to read last N characters from file in C are as follows:


 Open the file as a file pointer in C

 Move pointer in the file to the N-th position from the last

 Read all characters till the end of file.

Program:
#include<stdio.h>
int main() {

FILE *fp;
char ch;
int num;
long length;

printf("Enter the value of num : ");


scanf("%d", &num);

fp = fopen("test.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}

fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);

do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return(0);
}

Output:

Enter the value of n : 4

Pritesh Abhiman TaralAuthor of c4learn.com


.com

106

You might also like