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

CP Lab Record (2024)

Uploaded by

parru258037
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)
275 views

CP Lab Record (2024)

Uploaded by

parru258037
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/ 141

C PROGRAMMING LAB-R23

SESHADRI RAO GUDLAVALLERU ENGINEERING


COLLEGE
(An Autonomous Institute with Permanent Affiliation to JNTUK, Kakinada)
Seshadri Rao Knowledge Village, Krishna District, Andhra Pradesh, GUDLAVALLERU - 521 356.

Department of Computer Science and Engineering

LAB MANUAL

ON

COMPUTER PROGRAMMING LAB

I B.Tech I Sem – R23

Department of Computer Science and Engineering SRGEC Page 1


C PROGRAMMING LAB-R23

Vision
To be a Centre of Excellence in computer science and engineering education and training to
meet the challenging needs of the industry and society.

Mission
• To impart quality education through well-designed curriculum in tune with the growing
software needs of the industry.
• To be a Centre of Excellence in computer science and engineering education and training to
meet the challenging needs of the industry and society.
• To serve our students by inculcating in them problem solving, leadership, teamwork skills and
the value of commitment to quality, ethical behavior & respect for others.
• To foster industry-academia relationship for mutual benefit and growth.

Program Educational Objectives


• Identify, analyze, formulate and solve Computer Science and Engineering problems both
independently and in a team environment by using the appropriate modern tools.
• Manage software projects with significant technical, legal, ethical, social, environmental and
economic considerations
• Demonstrate commitment and progress in lifelong learning, professional development,
leadership and Communicate effectively with professional clients and the public.

Department of Computer Science and Engineering SRGEC Page 2


C PROGRAMMING LAB-R23

Week No Experiments Page No


Procedural Manual For Conducting Experiments In
Programming Lab
Week 1:
1. *Basic Linux environment and its editors like Vi,
Familiarization Vim & Emacs etc.
with
8-11
programming 2. Exposure to Turbo C, gcc.
environment
3. Writing simple programs using printf(), scanf()

Week 2:
1. Sumandaverageof3numbers
Problem-solving 2. Conversion of Fahrenheit to Celsius and vice
versa 12-16
using
Algorithms and 3. Simple interest calculation
Flow charts

Week 3: 1. Finding the square root of a given number


2. Finding compound interest
Simple
3. Area of a triangle using heron’s formulae
computational 17-22
problems using 4. Distance travelled by an object
arithmetic
expressions.
Week 4: 1. Evaluate the following expressions.
a. A+B*C+(D*E)+F*G
Simple b. A/B*C-B+A*D/3
computational c. A+++B---A
problems using d. J=(i++) +(++i) 23-30
the operator’s 2. Find the maximum of three numbers using
conditional operator
precedence and
3. Takemarksof5subjectsinintegers,andfindthetotal,
associativity
averageinfloat
Week 5: 1. Write a C program to find the max and min of four
numbers using if-else.
Problems 2. Write a C program to generate electricity bill.
involving if- 3. Find the roots of the quadratic equation.
31-39
then-else 4. Write a C program to simulate a calculator using switch
structures. case.
5. Write a C program to find the given year is a leap year
or not.
Week 6: 1. Find the factorial of given number using any loop.
2. Find the given number is a prime or not.
40-49
Iterative 3. Compute sine and cos series
problems 4. Checking a number palindrome

Department of Computer Science and Engineering SRGEC Page 3


C PROGRAMMING LAB-R23

e.g.,the sum of 5. Construct a pyramid of numbers.


series

Week 7: 1. Find the min and max of a 1-D integer array.


2. Perform linear search on1D array.
1-DArray 3. The reverse of a 1D integer array
50-61
manipulation, 4. Find 2’s complement of the given binary number.
linear search 5. Eliminate duplicate elements in an array.

Week 8: 1. Addition of two matrices


2. Multiplication two matrices
Matrix 3. Sort array elements using bubble sort
problems,String 4. Concatenate two strings without built-in functions 62-73
operations,Bubb 5. Reverse a string using built-in and without built-
lesort in string functions
1. Write a C program to find the sum of a 1D array
using malloc()
WEEK9:
2. Write a C program to find the total, average of n
students using structures
Pointers and
3. Enter n students data using calloc() and display
structures, 74-88
failed students list
memory
4. Read student name and marks from the command
dereference.
line and display the student details along with the
total.
5. Write a C program to implement realloc()
WEEK 10: 1. Create and display a singly linked list using self-
referential structure.
Bitfields,
2. Demonstrate the differences between structures and
linkedlists Read
and print a unions using a C program.
date using 3. Write a C program to shift/rotate using bitfields.
dd/mm/yyyy 4. Write a C program to copy one structure variable to 89-97
format using another structure of the same type.
bit-fields and
differentiate
the same with
out using bit-
fields
WEEK11: 1. Write a C function to calculate NCR value.
2. Write a C function to find the length of a string.
Simple 3. Write a C function to transpose of a matrix.
functions using 4. Write a C function to demonstrate numerical
call by value, integration of differential equations using Euler’s 98-106
solving method
differential
equations using
Eulers theorem.

Department of Computer Science and Engineering SRGEC Page 4


C PROGRAMMING LAB-R23

1. Write a recursive function to generate Fibonacci


series.
2. Write a recursive function to find the lcm of two
WEEK 12: numbers.
Recursive 3. Write a recursive function to find the factorial of a 107-115
functions number.
4. Write a C Program to implement Ackermann
function using recursion.
5. Write a recursive function to find the sum of series.
WEEK 13: 1. Write a C program to swap two numbers using call
by reference.
Simple functions 2. Demonstrate Dangling pointer problem using a C
using Call by program.
reference, 3. Write a C program to copy one string into another 116-124
Dangling using pointer.
pointers. 4. Write a C program to find no of lowercase,
uppercase, digits and other characters using pointers.
1. Write a C program to write and read text into a
file.
2. Write a C program to write and read text into a
WEEK 14:
binary file using fread() and fwrite()
3. Copy the contents of one file to another file.
4. Write a C program to merge two files into the 125-141
third file using command-line arguments.
5. Find no. of lines, words and characters in a file
File operations
6. Write a C program to print last n characters of a
given file.

Department of Computer Science and Engineering SRGEC Page 5


C PROGRAMMING LAB-R23

EQUIPMENT REQUIRED FOR CONDUCTING THE LAB


EXPERIMENTS
HARDWARE AND SOFTWARE REQUIRED:
1. A working computer system with either Windows XP or Windows 2003.
2. Every student should be provided with a separate Cabinet for assembling and dissembling the
components of a Cabinet.
3. Windows XP Installation Software.
4. Pentium IV Processor and Motherboard will all its components,
5. 1GB RAM
6. 250 GB Hard Disk
7. CD ROM,CD Writer and Floppy Disk Drives
8. Keyboard & Mouse
9. Microsoft Office Suite 2007 (Including PowerPoint, Word, Excel)

COURSE OBJECTIVES

▪ To design algorithms and flowcharts for problem solving.

▪ To develop C programs using arrays, strings, pointers and functions.

COURSE OUTCOMES

CO1: Read, understand, and trace the execution of programs written in C language.
CO2: Select the right control structure for solving the problem.
CO3: Develop C programs which utilize memory efficiently using programming constructs like
pointers.
CO4: Develop Debug and Execute programs to demonstrate the applications of arrays, functions,
basic concepts of pointers in C.

Department of Computer Science and Engineering SRGEC Page 6


C PROGRAMMING LAB-R23

REFERENCES

1. Introduction to Information Technology, ITL Education Solutions limited, Pearson Education.


2. Introduction to Computers, Peter Norton, 6/e Mc Graw Hill
3. Comdex Information Technology course tool kit Vikas Gupta, WILEY Dreamtech
4. IT Essentials PC Hardware and Software Companion Guide Third Edition by David Anfinson and
KenQuamme. – CISCO Press, Pearson Education.
5. PC Hardware and A+Handbook – Kate J. Chase PHI (Microsoft)
6. C Programming, A Problem Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE.
7. Programming in C, Second Edition Pradip Dey and Manas Ghosh, OXFORD Higher Education
8. Programming for Problem Solving, Behrouz A. Forouzan, Richard F.Gilberg, Cengage, 2020.
9. Programming in C, 2nd Edition Pradip Dey and Manas Ghosh, OXFORD Higher Education.
10. . C Programming, E Balaguruswamy, 3rd edition, TMH
11. R G Dromey, How to Solve it by Computer, Prentice-Hall of India, 1999.

GUIDELINES TO STUDENTS
• Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab.

• Students must use the equipment including PCs, Keyboard and Mouse with care. Any damage
is caused is punishable.

• Students are required to carry their observation and record books with completed exercises
while entering the lab.

• Students are supposed to occupy the machines allotted to them and are not supposed to talk or
make noise in the lab.

• Lab can be used in free time / lunch hours by the students. Students who need to use the
systems should take prior permission from the lab in-charge.

• Lab records need to be submitted on or before date of submission.

• Students are not supposed to use floppy disks/CDs/Pen drives etc during the Lab session.

• Use of computer network is not encouraged.

Department of Computer Science and Engineering SRGEC Page 7


C PROGRAMMING LAB-R23

WEEK 1:

Objective: Getting familiar with the programming environment on the computer and writing the first
program.

Suggested Experiments/Activities:

Tutorial 1: Problem-solving using Computers.


Lab1: Familiarization with programming environment
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.

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 vim editor.
The vi editor has two modes:
o Command Mode: In command mode, actions are taken on the file. The vi editor starts in
command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will take
you to the command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert
mode, just type 'i' and you'll be in insert mode. Although, after typing i nothing will appear on the
screen but you'll be in insert mode. Now you can type anything.
To exit from insert mode press Esc key, you'll be directed to command mode.
How to open VI editor?
To open vi editors, we just need to type the command mentioned below.
vi [file_name]
Here, [file_name] = this is the file name we want to create or to open the pre-existing file.

Vim:
Vim is a free and open-source, screen-based text editor program. It is an improved clone
of Bill Joy's vi. Vim's author, Bram Moolenaar, derived Vim from a port of the Stevie editor
for Amiga and released a version to the public in 1991. Vim is designed for use both from a command-
line interface and as a standalone application in a graphical user interface.

Department of Computer Science and Engineering SRGEC Page 8


C PROGRAMMING LAB-R23

Since its release for the Amiga, cross-platform development has made it available on many
other systems. In 2018, it was voted the most popular editor amongst Linux Journal readers; in 2015
the Stack Overflow developer survey found it to be the third most popular text editor, and in 2019 the
fifth most popular development environment.
Emacs:
GNU Emacs is a free software text editor. It was created by GNU Project founder Richard
Stallman, based on the Emacs editor developed for Unix operating systems. GNU Emacs has been
acentral component of the GNU project and a flagship project of the free software movement. Its tag
line is "the extensible self-documenting text editor."
GNU Emacs was later ported to the Unix operating system. It offered more features than
Gosling Emacs, in particular a full-featured Lisp as its extension language, and soon replaced Gosling
Emacs as the de facto Unix Emacs editor. Markus Hess exploited a security flaw in GNU Emacs's
email subsystem in his 1986 cracking spree, in which he gained superuser access to Unix computers.

ii) Exposure to Turbo C, gcc:


Turbo C:
Turbo C is a discontinued integrated development environment (IDE) and compiler for the C
programming language from Borland. First introduced in 1987, it was noted for its integrated
development environment, small size, fast compile speed, comprehensive manuals and low price.
In May 1990, Borland replaced Turbo C with Turbo C++. In 2006, Borland reintroduced
the Turbo moniker.
Version history:
Version 1.0 (May 13, 1987) offered the first integrated development environment for C
on IBM PCs. Like many Borland products of the time, the software was bought from another company
and branded with the "Turbo" name. It ran in 384 kB of memory. It allowed inline assembly with full
access to C symbolic names and structures, supported all memory models, and offered optimizations
for speed, size, constant folding.
Version 1.5 (January 1988) was an incremental improvement over version 1.0. It included
more sample programs, improved manuals and bug fixes. It was shipped on five 360 KB diskettes of
uncompressed files, and came with sample C programs, including a stripped down spreadsheet
called mcalc. This version introduced the <conio.h> header file (which provided fast, PC-specific
console I/O routines).
Version 2.0 (late 1988) featured the first "blue screen" version, which would be typical of all
future Borland releases for MS-DOS. It was also available bundled with Turbo Assembler and Turbo
Debugger. Turbo C 2.0 was also released (in Germany only) for the Atari ST; the program was not
maintained by Borland, but sold and renamed PureC. This version introduced the <graphics.h> header
file, which provided the Borland Graphics Interface already included in Turbo Pascal.

gcc:
The GNU Compiler Collection (GCC) is an optimizing compiler produced by the GNU
Project supporting various programming languages, hardware architectures and operating systems.
The Free Software Foundation (FSF) distributes GCC as free software under the GNU General Public

Department of Computer Science and Engineering SRGEC Page 9


C PROGRAMMING LAB-R23

License (GNU GPL). GCC is a key component of the GNU toolchain and the standard compiler for
most projects related to GNU and the Linux kernel. With roughly 15 million lines of code in 2019,
GCC is one of the biggest free programs in existence. It has played an important role in the growth
of free software, as both a tool and an example.
When it was first released in 1987 by Richard Stallman, GCC 1.0 was named the GNU C
Compiler since it only handled the C programming language. It was extended to compile C++ in
December of that year. Front ends were later developed for Objective-C, Objective-
C++, Fortran, Ada, D, Go and Rust, among others. The OpenMP and OpenACC specifications are also
supported in the C and C++ compilers.
GCC has been ported to more platforms and instruction set architectures than any other
compiler, and is widely deployed as a tool in the development of both free and proprietary software.
GCC is also available for many embedded systems, including ARM-based and Power ISA-based
chips.

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

Program to Display "Hello, World!"

#include <stdio.h>
intmain()
{
printf("Hello World");
return0;
}

OUTPUT: Hello World

Print an Integer Value in C

#include <stdio.h>
intmain()
{
intx = 5;
printf("Printing Integer value %d", x);
return0;
}

OUTPUT: Printing Integer value 5

C Program to Add Two Integers

Department of Computer Science and Engineering SRGEC Page 10


C PROGRAMMING LAB-R23

#include <stdio.h>
intmain()
{
intA, B, sum = 0;
printf("Enter two numbers A and B : \n");
scanf("%d,%d", &A, &B);
sum = A + B;
printf("Sum of A and B is: %d", sum);
return0;
}
OUTPUT: Enter two numbers A and B :
15,10
Sum of A and B is:25

C Program to Swap two Numbers

#include <stdio.h>
intmain()
{
intx, y;
printf("\nEnter Value of x\t ");
scanf("%d", &x);
printf("\nEnter Value of y\t ");
scanf("%d", &y);
inttemp = x;
x = y;
y = temp;
printf("\nAfter Swapping: x = %d, y = %d", x, y);
return0;
}

OUTPUT: Enter Value of x 15


Enter Value of y 10
After Swapping: x=10,y=15

Department of Computer Science and Engineering SRGEC Page 11


C PROGRAMMING LAB-R23

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 2: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

Sum and Average of 3 numbers

Algorithm:
1. Start
2. Declaring Variables
3. Input Three Numbers from User
4. Calculating Sum of Three Numbers (sum = num1+num2+num3)
5. Displaying the Sum of Three Numbers
6. Calculating Average of Three Numbers (average = sum/3)
7. Displaying the Average of Three Numbers
8. Stop
Flowchart:

Department of Computer Science and Engineering SRGEC Page 12


C PROGRAMMING LAB-R23

Program:
#include<stdio.h>
int main()
{
int num1, num2, num3, sum;
float avg;
printf("Enter Three Numbers : \n");
scanf("%d %d %d",&num1,&nnum2,&num2);
sum = num1 + num2 + num3;
printf("Sum of Three Numbers is : %d", sum);
avg=sum/3;
printf("\n Average of Three Numbers is : %f", avg);
return0;
}
OUTPUT: Enter Three Numbers :
12
14
16
Sum of Three Numbers is : 42
Average of Three Numbers is : 14

Conversion of Fahrenheit to Celsius and vice versa

Department of Computer Science and Engineering SRGEC Page 13


C PROGRAMMING LAB-R23

Algorithm for Fahrenheit to Celsius:


Step 1: Start.
Step 2: Read F.
Step 3: C=(5(F-32))/9.
Step 4: Print C.
Step 5: Stop.

Algorithm for Celsius to Fahrenheit:

Step 1: Start
Step 2: Read the value of temperature to be converted from the user
Step 3: Assign the value to a variable, say ‘cel’
Step 4: Initialize f = 0
Step 5: f = ((9/5) * cel ) + 32
Step 6: Display f
Step 7: Stop

Flowchart for Celsius to Fahrenheit:

Program for Conversion of Fahrenheit to Celsius and vice versa:

Department of Computer Science and Engineering SRGEC Page 14


C PROGRAMMING LAB-R23

Program for Conversion of Fahrenheit to Celsius:


# include<stdio.h>
#include<conio.h>
void main()
{
float c, f;
clrscr();
printf("\n Enter Temp in Fahrenheit : ");
scanf("%f", &f);
c = ((f-32)*5) / 9;
printf("\n Temperature in Celsius : %.2f ", c);
getch();
}
Output: Enter Temp in Fahrenheit : 98
Temperature in Celsius : 36.67

Program for Celsius to Fahrenheit:


#include<stdio.h>
#include<conio.h>
void main()
{
float c, f;
clrscr();
printf("\n Enter Temp in Celsius : ");
scanf("%f", &c);
f = ((9/5) * c) + 32;
printf("\n Temperature in Fahrenheit : %.2f ", f);
getch();
}
Output: Enter Temp in Celsius : 56
Temperature in Fahrenheit : 132.80

simple interest calculation

Simple interest calculation:


Algorithm:
Step 1 : START
Step 2 : Declare variables p , t , r and si .
Step 3 : Read the values of variable p ( principal ) , t ( Number of years ) , r ( Rate of Interest ) .
Step 4 : calculate the values of “ si = ( p * t * r )/100 “ .
Step 5 : Display si ( simple interest ) .
Step 6 : STOP

Department of Computer Science and Engineering SRGEC Page 15


C PROGRAMMING LAB-R23

Flowchart:

Program:
#include<stdio.h>
int main()
{
int p,r,t,si;
printf("Enter principle, Rate of interest & time to find simple interest: \n");
scanf("%d%d%d",&p,&r,&t);
si=(p*r*t)/100;
printf("Simple interest = %d",si);
return 0;
}
Output: Enter printciple, Rate of interest & time to find simple interest:
15000
5
12
Simple interest = 9000

Department of Computer Science and Engineering SRGEC Page 16


C PROGRAMMING LAB-R23

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.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv)Distance travelled by an object

Square Root of a Given Number


Algorithm:
Step 1: START
Step 2: Declare variables num and root.
Step 3: Read value of variable num(number).
Step 4: Calculate “root = sqrt(num)”.
Step 5: Display root ( square root of the given number).
Step 6: STOP

Program for finding the square root of a given number:


#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%d", &num);
root = sqrt(num);
printf("The Square Root of %f is %f", num, root);
return 0;
}
Output:
Enter a number: 12
The Square Root of 12.000000 is 3.464102

Flowchart:

Department of Computer Science and Engineering SRGEC Page 17


C PROGRAMMING LAB-R23

Compound Interest:

Algorithm:
Step 1: START
Step 2: Declare variables principal,rate,time,Amount and CI
Step 3: Read values of principal,rate and time.
Step 4: Calculate “Amount = principal*(pow(1+(rate/100),time))”.
Step 5: Calculate “CI = Amount-principal”.
Step 6: Display CI(Compound Interest).
Step 7: STOP

Program for finding compound interest:

#include <stdio.h>
#include<math.h>
int main()
{
double principal = 10000;
double rate = 5;
double time= 2;
double Amount = principal * ((pow((1 + rate / 100), time)));
double CI = Amount - principal;
printf("Compound Interest is : %lf",CI);
return 0;
}

Output: Compound Interest is : 1025.000000

Department of Computer Science and Engineering SRGEC Page 18


C PROGRAMMING LAB-R23

Flowchart:

Area of Triangle using Heron’s Formula

Algorithm:
Step 1: START
Step2 : Declare variables a,b,c,s and area.
Step 3: Read sides of triangles a,b,c.
Step 4: Calculate “ s = (a+b+c)/2”.
Step 5: Calculate “area = sqrt(s*(s-a)*(s-b)*(s-c))”.
Step 6: Display area(Area of the triangle).
Step 7: STOP

Program for Area of a triangle using heron’s formulae:

# include<stdio.h>
# include <math.h>
int main()
{
int a,b,c,s;
float area;
printf("Enter the length of three sides of a triangle:\n");
scanf("%d%d%d", &a,&b,&c);
s = (a+b+c)/2;
printf("The value of S is %d\n",s);

Department of Computer Science and Engineering SRGEC Page 19


C PROGRAMMING LAB-R23

area = sqrt(s*(s-a) * (s-b) * (s-c));


printf("The area of the triangle is:%f\n", area);
return 0;
}
Output:
Enter the length of three sides of a triangle:
12
13
15
The value of S is 20
The area of the triangle is: 74.833145

Flowchart:

Program for Distance travelled by an object:

Distance traveled by an Object


Algorithm:
Step 1: START
Step 2: Declare u,a,t,v and s.
Step 3: Read u,a,t values.
Step 4: Calculate “ v = u+(a*t)”
Step 5: Calculate “s = (u*t) +( (1/2)(a*t*t))”.
Step 6: Display v (velocity) and s (distance travelled by object)
Step 7: STOP
Program:
#include<stdio.h>
void main()

Department of Computer Science and Engineering SRGEC Page 20


C PROGRAMMING LAB-R23

{
float u,a,t,v,s;
printf("\n Enter initial velocity: ");
scanf("%f",&u);
printf("\n Enter acceleration: ");
scanf("%f",&a);
printf("\n Enter time required: ");
scanf("%f",&t);
v=u+a*t;
s=u*t+(1/2)*a*t*t;
printf("\n The final Velocity is : %f",v);
printf("\n \n The distance traveled is : %f \n \n",s);
getch();
}
Output:
Enter initial velocity: 18
Enter acceleration: 5
Enter time required:60
The final Velocity is :318.000000
The distance traveled is :1080.000000

Department of Computer Science and Engineering SRGEC Page 21


C PROGRAMMING LAB-R23

Flowchart:

Department of Computer Science and Engineering SRGEC Page 22


C PROGRAMMING LAB-R23

WEEK 4:

Simple computational problems using the operator precedence and associativity.


Associativity of operators: Associativity rule decides the order in which multiple occurrences of the
same level operator are applied.

Operator Precedence(rank) Associativity


() 1 Left to right
[]
Unary operators 2 Right to left
+
-
++
--
!
~
*
sizeof
(type)
(Binary) 3 Left to right
*
/
%
+ 4 Left to right
-
<< 5 Left to right
>>
< 6 Left to right
<=
>
>=
== 7 Left to right
|=
& 8 Left to right
^ 9 Left to right
| 10 Left to right
&& 11 Left to right
|| 12 Left to right
? : 13 Left to right

Department of Computer Science and Engineering SRGEC Page 23


C PROGRAMMING LAB-R23

= 14 Right to left
*= /= %=
+= -= &=
^= |= <<=
>>=
, 15 Left to right

i) Evaluate the following expressions.

A+B*C+(D*E) + F*G

Algorithm:
1. Start
2. Input A,B,C,D,E,F,G
3. Calculate D * E
4. Calculate B * C
5. Calculate F * G
6. Calculate A + (B * C)
7. Calculate (D * E) + F * G
8. Calculate A + (B * C) + (D * E) + F * G
9. Output the result
10. End

Flow chart:

Department of Computer Science and Engineering SRGEC Page 24


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>
int main() {
int A,B,C,D,E,F,G,X;
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);
X=A+B*C+(D*E)+F*G;
printf("X=%d",X);
return 0;
}
Output:
Enter A,B,C,D,E,F,G values: 1
3
5
7
9
11
2
X=101

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

Department of Computer Science and Engineering SRGEC Page 25


C PROGRAMMING LAB-R23

Algorithm:
1. Start
2. Read A,B,C,D
3. Calculate X= A/B*C-B+A*D/3
4. Display X
5. Stop

Flow chart:

Program:

#include <stdio.h>
int main( )
{
float A,B,C,D,X;
printf("enter A,B,C,D values:");
scanf("%f%f%f%f",&A,&B,&C,&D);
X=A/B*C-B+A*D/3;
printf("X=%f",X);
return 0;
}
Output: enter A,B,C,D values:4
3
7
8
X=17.000000

A+++B---A

Department of Computer Science and Engineering SRGEC Page 26


C PROGRAMMING LAB-R23

Algorithm:
1. Start
2. Read A,B
3. Calculate X= A+++B---A
4. Display X
5. Stop

Flow chart:

Program:
#include <stdio.h>
int main()
{
int A,B,X;
printf("enter A,B values:");
scanf("%d%d",&A,&B);
X=A+++B---A;
printf("X=%d",X);
return 0;
}
Output: enter A,B values:12
18
X=17

J= (i++) + (++i)

Algorithm:
1. Start
2. Read i,j (values)
3. Declare J(variable)
4. Calculate J=(i++)+(++i)
5. Display J
6. Stop

Department of Computer Science and Engineering SRGEC Page 27


C PROGRAMMING LAB-R23

Flow chart:

Program:
#include <stdio.h>
int main()
{
int i,j,J;
printf("enter i,j values:");
scanf("%d%d",&i,&j);
J=(i++)+(++i);
printf("X=%d",J);
return 0;
}
Output: enter i,j values:9
8
X=20

Find the maximum of three numbers using conditional operator

ALGORITHM:

1. start
2. Input: take three numbers as input and store them in variables 'a','b','c'.
3. compare: use the conditional operator to compare the numbers and find maximum:
a. a) if 'a' is greater than both 'b' and 'c' set 'maximum to 'a'.
b. b) else if 'b' is greater than 'c',set 'maximum' to 'b'.
c. c) else set 'maximum' to'c'
4. stop

Department of Computer Science and Engineering SRGEC Page 28


C PROGRAMMING LAB-R23

Flowchart

Program:
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("Enter Three Integers\n");
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 Integers 4
5
7
Maximum Number is =7
iii)Take marks of 5 subjects in integers ,and find the total ,average in float
ALGORITHEM:
1. START
2. Read marks of five subjects and store it in some variables say eng,phy,chem.,math and comp.
3. Calculate sum of all subjects and store in total=eng+phy+chem.+math+comp.
4. Divide sum of all subjects by total number of subjects to find average i.e., average =total/5
5. Calculate percentage using percentage=(total/500)*100
6. Display Resultant values.
7.Stop.

Department of Computer Science and Engineering SRGEC Page 29


C PROGRAMMING LAB-R23

FLOWCHART:

PROGRAM:
#include <stdio.h>
int main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f",percentage);
return 0;
}
Output: Enter marks of five subjects: 87
88
89
92
95
Total marks = 451
Average marks = 90.20
Percentage = 90.20

Department of Computer Science and Engineering SRGEC Page 30


C PROGRAMMING LAB-R23

WEEK 5:

LAB 5: Problems involving if - then - else structures


1) Write a C program to find the max and min of four numbers using if-else

ALGORITHM:

1. Start
2. Read num1,num2,num3,num 4 (values).
3. Read ‘max’,’min’(variables).
4. Set ‘max’ and ‘min’ initially to num1.
5. Use if-else statements to compare num2,num3 and num 4 with ‘max’,’min’
6. If num 2 is greater than ‘max’,update ‘max’ to num2.If num 2 is smaller than ‘min’,update ‘min’ to
num 2.
7. Repeat step 6 for num 3 and num4
8. Display ‘max’ as the maximum number and ‘min’ as minimum number.

Flowchart:

Department of Computer Science and Engineering SRGEC Page 31


C PROGRAMMING LAB-R23

PROGRAM:
#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);
if (num1 >= num2 && num1 >= num3 && num1 >= num4)
{
max = num1;
} else if (num2 >= num1 && num2 >= num3 && num2 >= num4)
{
max = num2;
} else if (num3 >= num1 && num3 >= num2 && num3 >= num4)
{
max = num3;
} else {
max = num4;
}
if (num1 <= num2 && num1 <= num3 && num1 <= num4)
{
min = num1;
} else if (num2 <= num1 && num2 <= num3 && num2 <= num4)
{
min = num2;
} else if (num3 <= num1 && num3 <= num2 && num3 <= num4)
{
min = num3;
}
else {
min = num4;
}
printf("Maximum number is: %d\n", max);
printf("Minimum number is: %d\n", min);
return 0;
}
Output:
Enter four numbers:12
15
9
3
Maximum number is: 15
Minimum number is: 3

Department of Computer Science and Engineering SRGEC Page 32


C PROGRAMMING LAB-R23

2) Write a c program to generate electricity bill

ALGORITHEM:

1) START
2) Input unit consumed by customer in some variable say unit.
3) If unit consumed less or equal to 50 units. Then amt = unit * 0.50.
4) If unit consumed more than 50 units but less than 100 units. Then add the first 50 units amount
i.e. 25 to final amount and compute the rest 50 units amount. Which is given by amt = 25 + (unit-
50) * 0.75. I have used units-50, since I already calculated first 50 units which is 25.
5) Similarly check rest of the conditions and calculate total amount.
6) After calculating total amount. Calculate the surcharge amount i.e. sur_charge = total_amt * 0.20. Add
surcharge amount to net amount. Which is given by net_amt = total_amt + sur_charge.
7) STOP
Flowchart:

Department of Computer Science and Engineering SRGEC Page 33


C PROGRAMMING LAB-R23

PROGRAM:
#include <stdio.h>
int main() {
int units;
float totalBill;
printf("Enter the number of units consumed: ");
scanf("%d", &units);
if(units <= 50) {
totalBill = units * 0.50; // Rate for first 50 units: 0.50 per unit
} else if(units <= 150) {
totalBill = 50 * 0.50 + (units - 50) * 0.75; // Rate for next 100 units: 0.75 per unit
} else if(units <= 250) {
totalBill = 50 * 0.50 + 100 * 0.75 + (units - 150) * 1.20; // Rate for next 100 units: 1.20 per unit
} else {
totalBill = 50 * 0.50 + 100 * 0.75 + 100 * 1.20 + (units - 250) * 1.50; // Rate for above 250 units:
1.50 per unit
}

Department of Computer Science and Engineering SRGEC Page 34


C PROGRAMMING LAB-R23

printf("Electricity Bill: $%.2f\n", totalBill);


return 0;
}
Output: Enter the number of units consumed: 123
Electricity Bill: $95.70

3)Find the roots of the quadratic equation.

ALGORITHEM:
1. START
2. Read a, b, c values
3. Compute d = b^2- 4ac
if d > 0 then
r1 = b+ sqrt (d)/(2*a)
r2 = b sqrt(d)/(2*a)
4. Otherwise if d = 0 then
compute r1 = -b/2a, r2=-b/2a
print r1,r2 values
5. Otherwise if d < 0 then print roots are imaginary
6. Stop"

Flowchart:

Department of Computer Science and Engineering SRGEC Page 35


C PROGRAMMING LAB-R23

PROGRAM:
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b, and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: %.2lf and %.2lf\n", root1, root2);
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal: %.2lf\n", root1);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex: %.2lf + %.2lfi and %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart,
imaginaryPart);
}
return 0;
}
Output: Enter coefficients a, b, and c: 1
4
3
Roots are real and distinct:-3.000000 and -5.000000

4) Write a C program to simulate a calculation using a switch case.

ALGORITHM:
1. Start:
- Begin the program.

2. Declare Variables:
- Declare variables `operator`, `num1`, `num2`, and `result` of appropriate data types.

3. User Input:
- Prompt the user to enter an operator (`+, -, *, /`).
- Read the entered operator and store it in the variable `operator`.

Department of Computer Science and Engineering SRGEC Page 36


C PROGRAMMING LAB-R23

4. User Input for Numbers:


- Prompt the user to enter two numbers.
- Read the entered numbers and store them in the variables `num1` and `num2`.

5. Switch-Case:
- Use a switch-case statement on the variable `operator` to determine the operation to be performed.
- For addition (`+`), add `num1` and `num2`, store the result in `result`, and print the result.
- For subtraction (`-`), subtract `num2` from `num1`, store the result in `result`, and print the result.
- For multiplication (`*`), multiply `num1` and `num2`, store the result in `result`, and print the
result.
- For division (`/`), check if `num2` is not zero. If true, divide `num1` by `num2`, store the result in
`result`, and print the result. If `num2` is zero, print an error message for division by zero.
- For any other operator, print an error message for an invalid operator.

6. End:
- End the program

PROGRAM:
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case '/':
if(num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
}

Department of Computer Science and Engineering SRGEC Page 37


C PROGRAMMING LAB-R23

else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator\n");
}
return 0;
}
Output: Enter an operator (+, -, *, /): *
Enter two numbers: 4
5
Result: 20.0

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

ALGORITHM:

1. Start:
- Begin the program.
2. Declare Variable:
- Declare a variable `year` of type integer.
3. User Input:

Department of Computer Science and Engineering SRGEC Page 38


C PROGRAMMING LAB-R23

- Prompt the user to enter a year.


- Read the entered year and store it in the variable `year`.
4. Leap Year Check:
- Use an if statement to check if the entered year is a leap year.
- Check if the year is divisible by 4 and not divisible by 100, or if it is divisible by 400.
- If the conditions are true, the year is a leap year.
5. Output:
- If the year is a leap year, print a message indicating that the year is a leap year.
- If the year is not a leap year, print a message indicating that the year is not a leap year.

6. End:
- End the program.

FLOWCHART:

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

Department of Computer Science and Engineering SRGEC Page 39


C PROGRAMMING LAB-R23

WEEK 6:
LAB-6: Iterative problems --the sum of series

1)Find the factorial of given number using any loop


Algorithm:
Step 1: START
Step 2: Declare variables n, factorial and i.
Step 3: Initialize variables factorial as 1 and i as 1.
Step 4: Read n value
Step 5: Repeat the steps until i=n
5.1: factorial = factorial*i
5.2: I = i+1
Step 6: Display factorial
Step 7: STOP

FlowChart:

PROGRAM:
#include <stdio.h>
int main()
{
int number, i;
unsigned long long factorial = 1;

Department of Computer Science and Engineering SRGEC Page 40


C PROGRAMMING LAB-R23

printf("Enter a positive integer: ");


scanf("%d", &number);
if (number < 0)
{
printf("Error: Factorial is not defined for negative numbers.\n");
}
else
{
for (i = 1; i <= number; ++i)
{
factorial *= i; // Multiply factorial by current loop variable
}
printf("Factorial of %d = %llu\n", number, factorial);
}
return 0;
}
Output:
Enter a positive integer: 5
120

2)Find the given number is a prime or not

Algorithm:
STEP 1: Take num as input.

STEP 2: Initialize a variable temp to 0.

STEP 3: Iterate a “for” loop from 2 to num/2.

STEP 4: If num is divisible by loop iterator, then increment temp.

STEP 5: If the temp is equal to 0,Return “Num IS PRIME”.else, Return “Num IS NOT PRIME”.

STEP6: STOP

FLOWCHART:

Department of Computer Science and Engineering SRGEC Page 41


C PROGRAMMING LAB-R23

PROGRAM:
#include <stdio.h>
int isPrime(int num)
{
if (num <= 1)
{
return 0; // Not a prime number
}
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
return 0;
}
}
return 1;
}

int main()
{
int number;
printf("Enter a number: ");

Department of Computer Science and Engineering SRGEC Page 42


C PROGRAMMING LAB-R23

scanf("%d", &number);
if (isPrime(number))
{
printf("%d is a prime number.\n", number);
}
else
{
printf("%d is not a prime number.\n", number);
}
return 0;
}
Output:
Enter a number: 31
31 is a prime number

3) Compute sine and cos series


Algorithm:
1. Start
2. Read x in degrees
3. For i🡨1 to n+1 do
t=t*pow((double)(-1),(double)(2*i-1))*x*x/(2*i*(2*i-1))
sum=sum+t
end loop
4. print cos(x)=sum
5. stop

FlowChart:

Department of Computer Science and Engineering SRGEC Page 43


C PROGRAMMING LAB-R23

PROGRAM
#include <stdio.h>
#include <math.h>
double calculateSine(int x, int n)
{
double sine = 0;
for (int i = 0; i < n; i++)
{
sine += (pow(-1, i) * pow(x, 2 * i + 1)) / factorial(2 * i + 1);
}
return sine;
}
double calculateCosine(int x, int n)
{
double cosine = 0;
for (int i = 0; i < n; i++)
{
cosine += (pow(-1, i) * pow(x, 2 * i)) / factorial(2 * i);
}
return cosine;

Department of Computer Science and Engineering SRGEC Page 44


C PROGRAMMING LAB-R23

}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
return num * factorial(num - 1);
}

int main()
{
int angle, n;
printf("Enter the angle in radians: ");
scanf("%d", &angle);
printf("Enter the number of terms in the series: ");
scanf("%d", &n);
double sineValue = calculateSine(angle, n);
double cosineValue = calculateCosine(angle, n);
printf("Sine(%d) = %.4lf\n", angle, sineValue);
printf("Cosine(%d) = %.4lf\n", angle, cosineValue);
return 0;
}

Output:
Enter the angle in radians: 60
Enter the number of terms in the series: 2
Sine(60) = -35940.0000
Cosine(60) = -1799.0000

4) Checking a number palindrome

Algorithm:

Step 1: Start
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

Department of Computer Science and Engineering SRGEC Page 45


C PROGRAMMING LAB-R23

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


Step 8: stop

FLOW CHART:

PROGRAM:
#include <stdio.h>
int main()
{
int num, reversedNum = 0, originalNum, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
while (num != 0)
{
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}

if (originalNum == reversedNum)
{
printf("%d is a palindrome.\n", originalNum);

Department of Computer Science and Engineering SRGEC Page 46


C PROGRAMMING LAB-R23

}
else
{
printf("%d is not a palindrome.\n", originalNum);
}
return 0;
}
Output:
Enter an integer: 1285821
1285821 is a palindrome.

5)Construct a pyramid of numbers


Algorithm:
Step 1: Start
Step 2: Read n value as integer
Step 3: for p:1 to n increment p by 1
begin
for q:1 to n increment q by 1
m = p;
for q:1 to p increment q by 1
print m++
m = m - 2;
for q:1 to p increment q by 1
print m--
end
Step 4: Stop"

Department of Computer Science and Engineering SRGEC Page 47


C PROGRAMMING LAB-R23

FLOWCHART:

Department of Computer Science and Engineering SRGEC Page 48


C PROGRAMMING LAB-R23

PROGRM:
#include <stdio.h>
int main()
{
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (space = 1; space <= rows - i; ++space)
{
printf(" ");
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
printf("%d ", i + k);
++count;
}
else
{
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 5
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

Department of Computer Science and Engineering SRGEC Page 49


C PROGRAMMING LAB-R23

Week 7:
(1)Find the min and max of a 1-D integer array
Algorithm:
1. Declaration of variables:
2. User input:
3. Initialization:
4. Finding maximum and minimum:
In this loop, the program iterates through the array, comparing each element with the current
maximum and minimum. If the current element is greater than the current maximum, it updates the
maximum. If the current element is smaller than the current minimum, it updates the minimum.
5. Printing the result:
The algorithm is straightforward: it initializes the maximum and minimum with the first element of the
array, then iterates through the array to find the actual maximum and minimum values. Finally, it
prints the results.
Flowchart:

Department of Computer Science and Engineering SRGEC Page 50


C PROGRAMMING LAB-R23

program:
#include <stdio.h>
void main()
{
int arr1[100];
int i, mx, mn, n;
printf("\n\nFind maximum and minimum element in an array :\n");
printf("the number of elements wants to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
mx = arr1[0];
mn = arr1[0];
for(i=1; i<n; i++)
{
if(arr1[i]>mx)
{
mx = arr1[i];
}
if(arr1[i]<mn)
{
mn = arr1[i];
}
}

Department of Computer Science and Engineering SRGEC Page 51


C PROGRAMMING LAB-R23

printf("Maximum element is : %d\n", mx);


printf("Minimum element is : %d\n\n", mn);
}
Output:

Find maximum and minimum element in an array :


the number of elements wants to be stored in the array :2
Input 2 elements in the array :
element - 0 : 5
element - 1 : 5
Maximum element is : 5
Minimum element is : 5

2. Perform linear search on1D array

Algorithm:

1. Start
2. Initialize the array and the target value.
3. Set a flag to indicate whether the target is found (flag = 0).
4. For each element in the array:
a. If the element is equal to the target value:
i. Set the flag to 1.
ii. Print the index of the element.
iii. Break out of the loop.
5. If the flag is still 0, print that the target value is not found.
6. End

Department of Computer Science and Engineering SRGEC Page 52


C PROGRAMMING LAB-R23

Flowchart:

Program:
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
printf("Element found at index %d\n", i);
return 1;
}
}
return 0;
}
int main() {

Department of Computer Science and Engineering SRGEC Page 53


C PROGRAMMING LAB-R23

int arr[] = {2, 5, 8, 12, 16, 23, 38, 42, 50};


int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
if (linearSearch(arr, n, target) == 0) {
printf("Element not found in the array.\n");
}
return 0;
}
output:
Element found at index 5

3.The reverse of a 1D integer array


Algorithm:
1. Initialize two pointers, start and end, pointing to the first and last elements of the array,
respectively.
2. Swap the elements at the start and end positions.
3. Move the start pointer one step forward and the end pointer one step backward.
4. Repeat steps 2-3 until the start pointer is greater than or equal to the end pointer.
5. The array is now reversed.
Flowchart:

Department of Computer Science and Engineering SRGEC Page 54


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
while (start < end) {
// Swap elements at start and end positions
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move the pointers
start++;
end--;
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};

Department of Computer Science and Engineering SRGEC Page 55


C PROGRAMMING LAB-R23

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


printf("Original Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
reverseArray(myArray, size);
printf("\nReversed Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
Output:
Original Array: 1 2 3 4 5
Reversed Array: 5 4 3 2 1

(4) Find 2’s complement of the given binary number in c


Algorithm:
1. Read the Binary Number:
- Input the binary number that you want to find the 2's complement of.
2. Reverse the Bits:
- Reverse all the bits of the binary number.
3. Add 1 to the Reversed Binary Number:
- Add 1 to the reversed binary number obtained in the previous step.
Flowchart:

Department of Computer Science and Engineering SRGEC Page 56


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>
void findTwosComplement(int binaryNumber[], int n) {
int i;
for (i = 0; i < n; i++) {
binaryNumber[i] = (binaryNumber[i] == 0) ? 1 : 0;
}
int carry = 1;
for (i = 0; i < n; i++) {

Department of Computer Science and Engineering SRGEC Page 57


C PROGRAMMING LAB-R23

int sum = binaryNumber[i] + carry;


binaryNumber[i] = sum % 2;
carry = sum / 2;
}
printf("2's complement: ");
if (carry) {
printf("1 ");
}
for (i = n - 1; i >= 0; i--) {
printf("%d ", binaryNumber[i]);
}
printf("\n");
}
int main() {
int binaryNumber[] = {1, 0, 1, 1, 0};
int n = sizeof(binaryNumber) / sizeof(binaryNumber[0]);
findTwosComplement(binaryNumber, n);
return 0;
}
Output:
2's complement: 1 0 0 1 1

Department of Computer Science and Engineering SRGEC Page 58


C PROGRAMMING LAB-R23

(5)Eliminate duplicate elements in an array


Algorithm:
1. Initialize an empty array to store unique elements.
2. Iterate through the original array.
- For each element, check if it already exists in the new array.
- If it does not exist, add it to the new array.
3. The new array now contains only unique elements.
Flowchart:

Program:
#include <stdio.h>
void removeDuplicates(int arr[], int *n) {
int uniqueArr[*n];
int uniqueCount = 0;

Department of Computer Science and Engineering SRGEC Page 59


C PROGRAMMING LAB-R23

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


int isDuplicate = 0;
for (int j = 0; j < uniqueCount; j++) {
if (arr[i] == uniqueArr[j]) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
uniqueArr[uniqueCount] = arr[i];
uniqueCount++;
}
}
for (int i = 0; i < uniqueCount; i++) {
arr[i] = uniqueArr[i];
}
*n = uniqueCount;
}
int main() {
int arr[] = {1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
removeDuplicates(arr, &n);
printf("Array after removing duplicates: ");

Department of Computer Science and Engineering SRGEC Page 60


C PROGRAMMING LAB-R23

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


printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Original Array: 1 2 3 4 2 5 6 3 7 8 1
Array after removing duplicates: 1 2 3 4 5 6 7 8

Department of Computer Science and Engineering SRGEC Page 61


C PROGRAMMING LAB-R23

WEEK – 8:
Objective: Explore the difference between other arrays and character arrays that can be used as
Strings by using null character and get comfortable with string by doing experiments that will
reverse a string and concatenate two strings. Explore sorting solution bubble sort using integer
arrays.

Tutorial 8: 2-D arrays, sorting and Strings.

Lab 8: Matrix problems, String operations, Bubble sort

i) Addition of two matrices

Step 1: Start

Step 2: Declare matrix mat1[row][col];


and matrix mat2[row][col];
and matrix sum[row][col]; row= no. of rows, col= no. of columns

Step 3: Read row, col, mat1[][] and mat2[][]

Step 4: Declare variable i=0, j=0

Step 5: Repeat until i < row

5.1: Repeat until j < col

sum[i][j]=mat1[i][j] + mat2[i][j]

Set j=j+1

5.2: Set i=i+1

Step 6: sum is the required matrix after addition

Step 7: Stop

FLOWCHART

Department of Computer Science and Engineering SRGEC Page 62


C PROGRAMMING LAB-R23

PROGRAM:

#include <stdio.h>

int main ()

int mat1[3][3] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };

int mat2[3][3] = { {9, 10, 11}, {12, 13, 14}, {15, 16, 17} };

int sum[3][3], i, j;

printf ("matrix 1 is :\n");

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf ("%d ", mat1[i][j]);

if (j == 3 - 1)

printf ("\n\n");

Department of Computer Science and Engineering SRGEC Page 63


C PROGRAMMING LAB-R23

printf ("matrix 2 is :\n");

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf ("%d ", mat2[i][j]);

if (j == 3 - 1)

printf ("\n\n");

// adding two matrices

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

sum[i][j] = mat1[i][j] + mat2[i][j];

// printing the sum 0f two matrices

printf ("\nSum of two matrices: \n");

for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf ("%d ", sum[i][j]);

if (j == 3 - 1)

printf ("\n\n");

Department of Computer Science and Engineering SRGEC Page 64


C PROGRAMMING LAB-R23

return 0;

OUTPUT:

matrix 1 is :

0 1 2

3 4 5

6 7 8

matrix 2 is :

9 10 11

12 13 14

15 16 17

Sum of two matrices:

9 11 13

15 17 19

21 23 25

ii) Multiplication two matrices

Step 1: Start

Step 2: Declare matrix mat1[row1][col1]; and matrix mat2[row2][col2]; and matrix mul[row1][col2]; row= no. of
rows, col= no. of columns

Step 3: Read mat1[row1][col1] and mat2[row2][col2]

Step 4: Declare variable i=0, j=0

Step 5: Set a loop from i=0 to i=row1.

Step 6: Set an inner loop for the above loop from j=0 to j=col2

• Initialise the value of the element (i, j) of the new matrix (mul[row1][col2]) to 0.
• Set an inner loop inside the above loop from k=0 to k=row1.
• Using the add and assign operator (+=) store the value of mat1[i][k] * mat2[k][j] in the third matrix,
mul[i][j].
• Print the third matrix.

Department of Computer Science and Engineering SRGEC Page 65


C PROGRAMMING LAB-R23

Step 7: Stop

FLOWCHART:

Department of Computer Science and Engineering SRGEC Page 66


C PROGRAMMING LAB-R23

PROGRAM:
#include<stdio.h>
int main ()
{
int mat1[2][3] = { {0, 1, 2}, {3, 4, 5} };
int mat2[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[2][2], i, j, k;
printf ("matrix 1 is :\n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf ("%d ", mat1[i][j]);
if (j == 3 - 1)
{
printf ("\n\n");
}
}
}
printf ("matrix 2 is :\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d ", mat2[i][j]);
if (j == 2 - 1)
{
printf ("\n\n");
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (k = 0; k < 3; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
printf ("The product of the two matrices is: \n");

Department of Computer Science and Engineering SRGEC Page 67


C PROGRAMMING LAB-R23

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


{
for (j = 0; j < 2; j++)
{
printf ("%d\t", mul[i][j]);
}
printf ("\n");
}
return 0;
}

OUTPUT:
matrix 1 is :
0 1 2
3 4 5

matrix 2 is :
1 2
3 4
5 6

The product of the two matrices is:


13 16
40 52

iii) Sort array elements using bubble sort

ALGORITHM:

1. Start
2. Initialize an array of elements.
3. Repeat the following steps until no swaps are performed in a pass:
● Set a flag to indicate whether a swap is performed in the current pass.
● Iterate through the array from the first element to the second-to-last element.
o Compare each element with its adjacent element.
o If the current element is greater than the next element, swap them and set the
swap flag to true.
● If no swaps were performed in the pass, the array is sorted, and you can exit the loop.
4. Display the sorted array.
5. End

Department of Computer Science and Engineering SRGEC Page 68


C PROGRAMMING LAB-R23

FLOWCHART:

Department of Computer Science and Engineering SRGEC Page 69


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>

void bubbleSort(int arr[], int n) {


int temp;
int swapped; // Flag to track whether a swap is performed in a pass

// Iterate through the array until no swaps are performed in a pass


for (int i = 0; i < n - 1; ++i) {
swapped = 0; // Initialize swap flag for the current pass

// Compare and swap elements


for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;

swapped = 1; // Set the swap flag to true


}
}

// If no swaps were performed, the array is sorted


if (swapped == 0) {
break;
}
}
}

void displayArray(int arr[], int n) {


// Display the elements of the array
for (int i = 0; i < n; ++i) {
printf("%d\t", arr[i]);
}
printf("\n");
}

int main() {
int n;

// Input array size


printf("Enter the size of the array: ");
scanf("%d", &n);

Department of Computer Science and Engineering SRGEC Page 70


C PROGRAMMING LAB-R23

int arr[n];

// Input elements of the array


printf("Enter elements of the array:\n");
for (int i = 0; i < n; ++i) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
}

// Sort the array using Bubble Sort


bubbleSort(arr, n);

// Display the sorted array


printf("Sorted array:\n");
displayArray(arr, n);

return 0;
}
OUTPUT:
Enter the size of the array: 6
Enter elements of the array:
Enter element 1: 42
Enter element 2: 11
Enter element 3: 7
Enter element 4: 23
Enter element 5: 16
Enter element 6: 35
Sorted array:
7 11 16 23 35 42

IV) Reverse a string using built-in and without built-in string functions

ALGORITHM:
1. Start
2. Initialize a string.
3. Reverse with Built-in Functions:
● Use a built-in string reversal function (e.g., strrev in C).
4. Display the reversed string.
5. Reverse without Built-in Functions:
● Find the length of the string.
● Iterate from the end of the string to the beginning.
o Print each character in reverse order.
6. Display the reversed string.

Department of Computer Science and Engineering SRGEC Page 71


C PROGRAMMING LAB-R23

7. End

FLOWCHART:

PROGRAM:

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

// Function to reverse a string using built-in function


void reverseWithBuiltIn(char str[]) {
// Use the strrev function from the string.h library
strrev(str);
}

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


void reverseWithoutBuiltIn(char str[]) {
int length = strlen(str);

Department of Computer Science and Engineering SRGEC Page 72


C PROGRAMMING LAB-R23

// Iterate from the end of the string to the beginning


for (int i = length - 1; i >= 0; --i) {
// Print each character in reverse order
printf("%c", str[i]);
}
printf("\n");
}

int main() {
char inputString[100];

// Input a string
printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);

// Remove the newline character from inputString if present


inputString[strcspn(inputString, "\n")] = '\0';

// Reverse the string using built-in function


printf("Reversed string using built-in function: ");
reverseWithBuiltIn(inputString);
printf("%s\n", inputString);

// Reverse the string without using built-in function


printf("Reversed string without built-in function: ");
reverseWithoutBuiltIn(inputString);

return 0;
}

OUTPUT:

Enter a string: Hello, World!


Reversed string using built-in function: !dlroW ,olleH
Reversed string without built-in function: !dlroW ,olleH

Department of Computer Science and Engineering SRGEC Page 73


C PROGRAMMING LAB-R23

Week-9:

9. DEVELOP A C PROGRAM FOR THE FOLLOWING STATEMENTS

(1) write a simple c program to find the sum of 1D array using malloc()

Algorithm:

This program performs the following steps:

1. Gets the size of the array (`n`) from the user.

2. Allocates memory for the array using `malloc`.

3. Asks the user to input the array elements.

4. Calculates the sum of the array elements.

5. Prints the sum.

6. Frees the dynamically allocated memory using `free()` to avoid memory leaks.

Flow chart:

Department of Computer Science and Engineering SRGEC Page 74


C PROGRAMMING LAB-R23

Program:

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, *arr, sum = 0;

printf("Enter the size of the array: ");

scanf("%d", &n);

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

if (arr == NULL) {

printf("Memory allocation failed.\n");

return 1;

printf("Enter the %d elements:\n", n);

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

scanf("%d", &arr[i]);

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

sum += arr[i];

} printf("Sum of the array elements: %d\n", sum);

free(arr);

return 0;

Output:

Enter the size of the array: 2

Enter the 2 elements:

12

10

Department of Computer Science and Engineering SRGEC Page 75


C PROGRAMMING LAB-R23

Sum of the array elements: 22

2.write a c program to find the total,average of n students using structures

Algorithm:

1. Include necessary header files:

- `#include <stdio.h>` is included for standard input and output functions.

2. Define a structure:

- `struct Student` is defined to represent a student, containing the student's name and marks.

3. Declare variables:

- `n` is used to store the number of students.

- `i` is used as a loop variable.

4. Prompt user for input:

- Ask the user to enter the number of students (`n`).

5. Declare an array of structures:

- An array `students` of type `struct Student` is declared to store information about each student.

6. Input information about each student:

- Use a `for` loop to iterate over each student and input their name and marks.

7. Calculate total and average:

- Use another `for` loop to calculate the total marks of all students.

- Calculate the average by dividing the total by the number of students (`n`).

8. Display total and average marks:

- Print the total and average marks on the console.

9. Return 0:

- Indicate successful execution by returning 0 from the `main` function.

Department of Computer Science and Engineering SRGEC Page 76


C PROGRAMMING LAB-R23

Flow chart:

Program:

#include <stdio.h>
struct Student {
char name[50];
int marks;
};
int main() {
int n, i;
printf("Enter the number of students: ");
scanf("%d", &n);

Department of Computer Science and Engineering SRGEC Page 77


C PROGRAMMING LAB-R23

struct Student students[n];


for (i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Enter name: ");
scanf("%s", students[i].name);
printf("Enter marks: ");
scanf("%d", &students[i].marks);
}
int total = 0;
for (i = 0; i < n; i++) {
total += students[i].marks;
}
double average = (double)total / n;
printf("\nTotal marks: %d\n", total);
printf("Average marks: %.2f\n", average);
return 0;
}

Output:

Enter number of students: 2

Enter details for student 1:

Name: yaseer

Marks: 80

Enter details for student 2:

Name: irfan

Marks: 50

Total Marks: 130.00

Average Marks: 65.00

Department of Computer Science and Engineering SRGEC Page 78


C PROGRAMMING LAB-R23

3. Enter n students data using calloc () and display failed students list

Algorithm:

1. We define a `struct Student` to store information about each student.

2. The `main` function takes the number of students as input and allocates memory for an array of
student structures using `calloc()`.

3. We then use a loop to input details for each student.

4. After inputting the data, we call the `displayFailedStudents` function to identify and display the list
of failed students based on a passing marks threshold (40 in this example).

5. Finally, we free the dynamically allocated memory using `free()`

Flow chart:

Program:

#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int rollNumber;
float marks;
};
void displayFailedStudents(struct Student* students, int n, float passingMarks) {

Department of Computer Science and Engineering SRGEC Page 79


C PROGRAMMING LAB-R23

printf("\nList of Failed Students:\n");


printf("========================\n");
for (int i = 0; i < n; i++) {
if (students[i].marks < passingMarks) {
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Marks: %.2f\n", students[i].marks);
printf("------------------------\n");
}
}
}

int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student* students = (struct Student*)calloc(n, sizeof(struct Student));
for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
displayFailedStudents(students, n, 40.0);
free(students);
return 0;
}

Department of Computer Science and Engineering SRGEC Page 80


C PROGRAMMING LAB-R23

Output:

Enter the number of students: 2

Enter details for student 1:

Name: Boy

Roll Number: 89441248474

Marks: 25

Enter details for student 2:

Name: sana

Roll Number: 1214874154

Marks: 41

List of Failed Students:

========================

Name: Nice one

Roll Number: -753064742

Marks: 25.00

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

Algorithm:

1. It takes student names and marks as command line arguments. The program assumes that each
student has a name followed by marks.
2. It allocates memory for an array of `num Students` based on the number of command line
arguments.
3. It then copies the name and converts the marks from the command line arguments into the array of
`struct Student`.
4. Finally, it displays the student details along with the total marks.
5. compile and run the program,

Department of Computer Science and Engineering SRGEC Page 81


C PROGRAMMING LAB-R23

Flowchart:

Program;

#include <stdio.h>

#include <stdlib.h>

struct Student {

char name[50];

float marks;

};

int main() {

int n;

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

scanf("%d", &n);

Department of Computer Science and Engineering SRGEC Page 82


C PROGRAMMING LAB-R23

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

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

printf("Enter details for student %d:\n", i + 1);

printf("Name: ");

scanf("%s", students[i].name);

printf("Marks: ");

scanf("%f", &students[i].marks);

printf("\nStudent Details and Total Marks:\n");

printf("----------------------------\n");

printf("Name\t\tMarks\n");

printf("----------------------------\n");

float totalMarks = 0.0;

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

printf("%s\t\t%.2f\n", students[i].name, students[i].marks);

totalMarks += students[i].marks;

printf("----------------------------\n");

printf("Total\t\t%.2f\n", totalMarks);

free(students);

return 0;

Output:

Enter the number of students: 2

Enter details for student 1:

Name: Girl

Marks: 50

Department of Computer Science and Engineering SRGEC Page 83


C PROGRAMMING LAB-R23

Enter details for student 2:

Name: saNA

Marks: 60

Student Details and Total Marks:

----------------------------

Name Marks

----------------------------

Girl 50.00

saNA 60.00

----------------------------

Total 110.00

(5)Write a C program to implement realloc()

Algorithm:

1. Initialize Variables:

- Set `initialSize` to the desired initial size (e.g., 2).

- Declare an integer pointer `arr` and allocate memory for an array of size `initialSize` using
`malloc`.

- Check if memory allocation is successful. If not, print an error message and exit.

2. Input Initial Integers:

- Display a prompt to the user to enter `initialSize` integers.

- Use a loop to input integers and store them in the allocated memory.

3. Display Original Array:

- Display a message indicating the original array.

- Use a loop to print each element of the array.

4. Input New Size:

- Prompt the user to enter the new size of the array.

Department of Computer Science and Engineering SRGEC Page 84


C PROGRAMMING LAB-R23

- Read the value into the variable `newSize`.

5. Reallocate Memory:

- Use `realloc` to reallocate memory for the array based on the new size (`newSize`).

- Check if reallocation is successful. If not, print an error message and exit.

6. Input Additional Integers:

- Display a prompt to the user to enter additional integers (`newSize - initialSize`).

- Use a loop to input integers and store them in the newly allocated memory.

7. Display Updated Array:

- Display a message indicating the updated array.

- Use a loop to print each element of the array.

8. Free Allocated Memory:

- Use `free` to release the allocated memory.

9. Exit Program:

- Return 0 to indicate successful execution

Flowchart:

Department of Computer Science and Engineering SRGEC Page 85


C PROGRAMMING LAB-R23

Program:

#include <stdio.h>

#include <stdlib.h>

int main() {

int initialSize = 2;

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

if (arr == NULL) {

printf("Memory allocation failed.\n");

return 1;

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

for (int i = 0; i < initialSize; ++i) {

scanf("%d", &arr[i]);

Department of Computer Science and Engineering SRGEC Page 86


C PROGRAMMING LAB-R23

printf("Original Array:\n");

for (int i = 0; i < initialSize; ++i) {

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

printf("\n");

int newSize;

printf("Enter the new size of the array: ");

scanf("%d", &newSize);

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

if (arr == NULL) {

printf("Memory reallocation failed.\n");

return 1;

printf("Enter additional %d integers:\n", newSize - initialSize);

for (int i = initialSize; i < newSize; ++i) {

scanf("%d", &arr[i]);

printf("Updated Array:\n");

for (int i = 0; i < newSize; ++i) {

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

printf("\n");

free(arr);

return 0;

Department of Computer Science and Engineering SRGEC Page 87


C PROGRAMMING LAB-R23

Output:

Enter 2 integers:

15

20

Original Array:

15 20

Enter the new size of the array: 3

Enter additional 1 integers:

12

Updated Array:

15 20 12

Department of Computer Science and Engineering SRGEC Page 88


C PROGRAMMING LAB-R23

Week 10:
(1) Create and display a singly linked list using self-referential structure in c .

Algorithm:

1.Define the Structure:

Start by defining a structure that represents a node in the linked list. Each node should contain a
data element and a pointer to the next node in the list.

2. Initialize an Empty List:

Create a function to initialize an empty linked list. This function should return a pointer to the head
of the list, which is initially set to `NULL`.

3. Insert a Node at the Beginning:

Write a function to insert a new node at the beginning of the linked list. This involves creating a new
node, setting its data, and updating the next pointer to point to the current head of the list.

4. Display the Linked List:

Create a function to display the elements of the linked list. Traverse the list from the head, printing
the data of each node.

5. Test the Linked List:

In the `main` function, you can test the linked list operations. Initialize an empty list, insert some
elements, and display the list

Flowchart:

Department of Computer Science and Engineering SRGEC Page 89


C PROGRAMMING LAB-R23

Program:

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

void insertAtEnd(struct Node** head, int value) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = value;

newNode->next = NULL;

if (*head == NULL) {

*head = newNode;

} else {

struct Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

void displayList(struct Node* head) {

printf("Linked List: ");

while (head != NULL) {

printf("%d -> ", head->data);

head = head->next;

Department of Computer Science and Engineering SRGEC Page 90


C PROGRAMMING LAB-R23

printf("NULL\n");

int main() {

struct Node* head = NULL;

insertAtEnd(&head, 1);

insertAtEnd(&head, 2);

insertAtEnd(&head, 3);

displayList(head);

return 0;

Output:

Linked List: 1 -> 2 -> 3 -> NULL

2.Demonstrate the differences between structures and unions using a C program

Algorithm:

1. Define a Structure (`struct Point`)

- The structure `Point` has two members, `x` and `y`, each of type `int`.

2. Define a Union (`union Coordinate`):**

- The union `Coordinate` also has two members, `x` and `y`, each of type `int`.

3. Main Function:

- Declare an instance of the structure (`pointStruct`) and an instance of the union


(`coordinateUnion`).

- Set values for both the structure and the union.

- Print the values from both the structure and the union.

4. Size Comparison:.

Department of Computer Science and Engineering SRGEC Page 91


C PROGRAMMING LAB-R23

Flowchart:

Program:

#include <stdio.h>

struct Point {

int x;

int y;

};

union Coordinate {

int x;

int y;

};

int main() {

// Using a structure

struct Point pointStruct;

Department of Computer Science and Engineering SRGEC Page 92


C PROGRAMMING LAB-R23

pointStruct.x = 10;

pointStruct.y = 20;

union Coordinate coordinateUnion;

coordinateUnion.x = 30;

coordinateUnion.y = 40;

printf("Structure values: x = %d, y = %d\n", pointStruct.x, pointStruct.y);

printf("Union values: x = %d, y = %d\n", coordinateUnion.x, coordinateUnion.y);

printf("Size of Structure: %zu bytes\n", sizeof(struct Point));

printf("Size of Union: %zu bytes\n", sizeof(union Coordinate));

return 0;

Output:

Structure values: x = 10, y = 20

Union values: x = 40, y = 40

Size of Structure: 8 bytes

Size of Union: 4 bytes

3. Write a C program to shift/rotate using bit fields.

Algorithm:

1. Define a bitfield structure (`struct BitField`) with an 8-bit data field.

2. Implement a function (`rotateBits`) that takes a `BitField` structure and the number of positions to
rotate. It performs a left rotation operation on the bitfield.

3. In the `main` function, create an instance of the bitfield (`bf1`) with some initial data (in this case,
`0b10101010`).

4. Display the original bitfield.

5. Call the `rotateBits` function to rotate the bits of `bf1` by a specified number of positions (in this
case, 3 positions to the left).

6. Display the rotated bitfield.

Department of Computer Science and Engineering SRGEC Page 93


C PROGRAMMING LAB-R23

Flowchart:

Program:

#include <stdio.h>
struct BitField {
unsigned int data : 8;
};
struct BitField rotateBits(struct BitField bf, int positions) {
positions = positions % 8;
bf.data = (bf.data << positions) | (bf.data >> (8 - positions));
return bf;
}
int main() {
struct BitField bf1 = { 0b10101010 };

Department of Computer Science and Engineering SRGEC Page 94


C PROGRAMMING LAB-R23

printf("Original BitField: %X\n", bf1.data);


struct BitField rotatedBf = rotateBits(bf1, 3);
printf("Rotated BitField: %X\n", rotatedBf.data);
return 0;
}
Output:

Original BitField: AA

Rotated BitField: 55

(4)Write a C program to copy one structure variable to another structure of the same type.
Algorithm:

1. Define a structure:

- Define a structure `Person` with fields like name, age, and height.

2. Copy Function:

- Create a function `copyStruct` that takes two parameters: a pointer to the destination structure and a
pointer to the source structure.

- Use `memcpy` to copy the content of the source structure to the destination structure.

3. Main Function:

- Create two instances of the `Person` structure (`person1` and `person2`).

- Display the original values of `person1`.

4. Copy and Display:

- Call the `copyStruct` function to copy the contents of `person1` to `person2`.

- Display the copied values of `person2`.

Department of Computer Science and Engineering SRGEC Page 95


C PROGRAMMING LAB-R23

Flowchart:

Program:

#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
void copyStruct(struct Person *dest, const struct Person *src) {
memcpy(dest, src, sizeof(struct Person));
}

Department of Computer Science and Engineering SRGEC Page 96


C PROGRAMMING LAB-R23

int main() {
struct Person person1 = {"yaseer", 25, 5.8};
struct Person person2;
printf("Original Person 1:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n\n", person1.height);
copyStruct(&person2, &person1);
printf("Copied Person 2:\n");
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.2f\n", person2.height);
return 0;
}
Output:

Original Person 1:

Name: Perfect

Age: 25

Height: 5.80

Copied Person 2:

Name: Hancy

Age: 25

Height: 5.80

Department of Computer Science and Engineering SRGEC Page 97


C PROGRAMMING LAB-R23

Week-11:

11(a). Function to calculate factorial

Algorithm:
1. Start

2. Read n and r

3. Calculate n! using a factorial function

4. Calculate r! using a factorial function

5. Calculate (n−r)! using a factorial function

6. Calculate nCr using the formula: n!/r!(n-r)!

7. Display the result

8. End

Program:

#include <stdio.h>

// Function to calculate factorial

unsigned long long factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1);

// Function to calculate nCr

unsigned long long nCr(int n, int r) {

if (r > n)

return 0;

return factorial(n) / (factorial(r) * factorial(n - r));

int main() {

Department of Computer Science and Engineering SRGEC Page 98


C PROGRAMMING LAB-R23

int n, r;

// Input values for n and r

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

scanf("%d", &n);

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

scanf("%d", &r);

// Calculate and display the result

printf("%dC%d = %llu\n", n, r, nCr(n, r));

return 0;

Output:
Enter the value of n: 55

Enter the value of r: 45

55C45 = 1

Flow chart:

Department of Computer Science and Engineering SRGEC Page 99


C PROGRAMMING LAB-R23

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


Algorithm:
1. Start
2. Declare a function stringLength that takes a string as input.
3. Initialize a variable length to 0.
4. Iterate through the string using a loop until the null character ('\0') is encountered.
5. Inside the loop, increment the length variable.
6. Return the final value of length.
7. In the main function:
● Declare a character array inputString to store the user input.
● Input a string from the user.
● Call the stringLength function with the input string.
● Display the length of the string.
8. End
program:

#include <stdio.h>
int stringLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
char inputString[100];
printf("Enter a string: ");
scanf("%s", inputString);
int length = stringLength(inputString);

Department of Computer Science and Engineering SRGEC Page 100


C PROGRAMMING LAB-R23

printf("Length of the string: %d\n", length);


return 0;
}

Output:

Enter a string: 3

Length of the string: 1

Flow chart:

11.c) Write a C function to transpose a matrix.

Algorithm:
1. Start

2. Declare a function transposeMatrix that takes the number of rows, number of columns, and a matrix as
input.

3. Declare a new matrix transpose to store the transposed elements.

4. Perform the transpose operation using nested loops.

5. Display the original matrix.

6. Display the transposed matrix.

Department of Computer Science and Engineering SRGEC Page 101


C PROGRAMMING LAB-R23

7. In the main function:

● Input the dimensions of the matrix.

● Declare a matrix and input its elements.

● Call the transposeMatrix function with the matrix as input.

8. End

Program:
#include <stdio.h>

void transposeMatrix(int rows, int cols, int matrix[rows][cols]) {

int transpose[cols][rows];

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

transpose[j][i] = matrix[i][j];

printf("Original Matrix:\n");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

printf("%d\t", matrix[i][j]);

printf("\n");

printf("\nTransposed Matrix:\n");

for (int i = 0; i < cols; i++) {

for (int j = 0; j < rows; j++) {

printf("%d\t", transpose[i][j]);

printf("\n");

Department of Computer Science and Engineering SRGEC Page 102


C PROGRAMMING LAB-R23

int main() {

int rows, cols;

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

scanf("%d", &rows);

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

scanf("%d", &cols);

int matrix[rows][cols];

printf("Enter the elements of the matrix:\n");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

scanf("%d", &matrix[i][j]);

transposeMatrix(rows, cols, matrix);

return 0;

Output:
Enter the number of rows: 3

Enter the number of columns: 2

Enter the elements of the matrix:

12

34

56

Original Matrix:

1 2

3 4

5 6

Transposed Matrix:

1 3 5

Department of Computer Science and Engineering SRGEC Page 103


C PROGRAMMING LAB-R23

2 4 6

Flowchart:

Department of Computer Science and Engineering SRGEC Page 104


C PROGRAMMING LAB-R23

11.d) Write a C function to demonstrate numerical integration of differential equations

using Euler’s method.

Algorithm:
1. Start

2. Declare a function eulerMethod that takes initial x and y values, step size (h), and the target x-value for
integration.

3. Initialize variables x and y to the initial values.

4. Use a while loop to iteratively apply Euler's method until the target x-value is reached.

5. In each iteration, update the value of y using the differential equation ��/��=�+�dy/dx=x+y.

6. Display the result of numerical integration at the target x-value.

7. In the main function:

● Specify initial conditions, step size, and the target x-value.

● Call the eulerMethod function.

8. End

Program:

#include <stdio.h>

void eulerMethod(double x0, double y0, double h, double target_x) {

double x = x0;

double y = y0;

while (x < target_x) {

y = y + h * (x + y);

x += h;

printf("Numerical integration using Euler's method:\n");

printf("At x = %.2f, y = %.6f\n", target_x, y);

int main() {

double x0 = 0.0; // Initial x-value

Department of Computer Science and Engineering SRGEC Page 105


C PROGRAMMING LAB-R23

double y0 = 1.0; // Initial y-value

double h = 0.1;

double target_x = 1.0;

eulerMethod(x0, y0, h, target_x);

return 0;

Output:
Numerical integration using Euler's method:

At x = 1.00, y = 3.161051

Flowchart:

Department of Computer Science and Engineering SRGEC Page 106


C PROGRAMMING LAB-R23

Week-12:
12.a)Write a recursive function to generate Fibonacci series.

Algorithm:
1. Start

2. Declare a recursive function fibonacci that takes an integer n.

3. If n is less than or equal to 1, return n.

4. Otherwise, return the sum of fibonacci(n-1) and fibonacci(n-2).

5. In the main function:

● Input the number of terms in the Fibonacci series.

● Display the Fibonacci series using the fibonacci function.

6. End

Program:
#include <stdio.h>

int fibonacci(int n) {

if (n <= 1) {

return n;

} else {

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int n;

printf("Enter the number of terms in the Fibonacci series: ");

scanf("%d", &n);

printf("Fibonacci Series up to %d terms:\n", n);

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

printf("%d ", fibonacci(i));

Department of Computer Science and Engineering SRGEC Page 107


C PROGRAMMING LAB-R23

return 0; }

Output:
Enter the number of terms in the Fibonacci series: 10

Fibonacci Series up to 10 terms:

0 1 1 2 3 5 8 13 21 34

flowchart:

12.b)Write a recursive function to find the lcm of two numbers

Algorithm:
Input: Two integers a and b

1. Define a function gcd(a, b) to calculate the greatest common divisor using the Euclidean algorithm:

a. If b is 0, return a.

Department of Computer Science and Engineering SRGEC Page 108


C PROGRAMMING LAB-R23

b. Otherwise, return gcd(b, a % b).

2. Define a function lcm(a, b) to calculate the least common multiple:

a. Return (a * b) / gcd(a, b).

3. Read the input values for num1 and num2.

4. Calculate the LCM using the lcm function: result = lcm(num1, num2).

5. Display the result: "LCM of num1 and num2 is: result".

6. End.

Program:
#include <stdio.h>

int gcd(int a, int b) {

if (b == 0) {

return a;

} else {

return gcd(b, a % b);

int lcm(int a, int b) {

return (a * b) / gcd(a, b);

int main() {

int num1, num2;

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

printf("LCM of %d and %d is: %d\n", num1, num2, lcm(num1, num2));

return 0;

Department of Computer Science and Engineering SRGEC Page 109


C PROGRAMMING LAB-R23

Output:
Enter the first number: 12

Enter the second number: 18

LCM of 12 and 18 is: 36

Flow chart:

12.c)Write a recursive function to find the factorial of a number.

Algorithm:

1. Start

2. Declare a recursive function factorial that takes an integer n.

3. If n is 0 or 1, return 1.

4. Otherwise, return n * factorial(n - 1).

5. In the main function:

Department of Computer Science and Engineering SRGEC Page 110


C PROGRAMMING LAB-R23

● Input a number.

● Display the factorial using the factorial function.

6. End

Program:
#include <stdio.h>

unsigned long long factorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

printf("Factorial of %d is: %llu\n", num, factorial(num));

return 0;

Output:

Enter a number: 5

Factorial of 5 is: 120

Department of Computer Science and Engineering SRGEC Page 111


C PROGRAMMING LAB-R23

FLow chart:

12.d)Write a C Program to implement the Ackermann function using recursion.

Algorithm:
1. Start

2. Declare a recursive function ackermann that takes two integers m and n.

3. If m is 0, return n + 1.

4. If n is 0, return ackermann(m - 1, 1).

5. Otherwise, return ackermann(m - 1, ackermann(m, n - 1)).

6. In the main function:

● Input values for m and n.

● Display the result of the Ackermann function using the ackermann function.

7. End

Department of Computer Science and Engineering SRGEC Page 112


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>

int ackermann(int m, int n) {

if (m == 0) {

return n + 1;

} else if (n == 0) {

return ackermann(m - 1, 1);

} else {

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

int main() {

int m, n;

printf("Enter the values of m and n: ");

scanf("%d %d", &m, &n);

printf("Ackermann(%d, %d) = %d\n", m, n, ackermann(m, n));

return 0;

Output:
Enter the values of m and n: 2 3

Ackermann(2, 3) = 9

Department of Computer Science and Engineering SRGEC Page 113


C PROGRAMMING LAB-R23

Flowchart:

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

Algorithm:
1. Start

2. Declare a recursive function sumOfSeries that takes an integer n.

3. If n is 0, return 0.

4. Otherwise, return n + sumOfSeries(n - 1).

5. In the main function:

● Input the number of terms in the series.

● Display the sum of the series using the sumOfSeries function.

6. End

Program:
#include <stdio.h>

int sumOfSeries(int n) {

if (n == 0) {

return 0;

} else {

Department of Computer Science and Engineering SRGEC Page 114


C PROGRAMMING LAB-R23

return n + sumOfSeries(n - 1);

int main() {

int num;

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

scanf("%d", &num);

printf("Sum of the series up to %d terms: %d\n", num, sumOfSeries(num));

return 0;

Output:
Enter the number of terms in the series: 5

Sum of the series up to 5 terms: 15

Flowchart:

Department of Computer Science and Engineering SRGEC Page 115


C PROGRAMMING LAB-R23

Week-13
13.a)Write a C program to swap two numbers using call by reference.

Algorithm:
1. Start

2. Declare a function swapNumbers that takes two integer pointers (a and b) as parameters.

3. Inside the function, use a temporary variable to swap the values pointed to by a and b.

4. In the main function:

● Input two numbers (num1 and num2).

● Display the numbers before swapping.

● Call the swapNumbers function by passing the addresses of num1 and num2.

● Display the numbers after swapping.

5. End

Program:
#include <stdio.h>

void swapNumbers(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

int main() {

int num1, num2;

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

Department of Computer Science and Engineering SRGEC Page 116


C PROGRAMMING LAB-R23

swapNumbers(&num1, &num2);

printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

return 0;

Output:
Enter the first number: 10

Enter the second number: 20

Before swapping: num1 = 10, num2 = 20

After swapping: num1 = 20, num2 = 10

Flowchart:

13.b)Demonstrate Dangling pointer problem using a C program.

Algorithm:
1. Start

2. Declare a function createDanglingPointer that creates a local variable num, assigns its address to a
pointer ptr, and returns the pointer.

3. In the main function:

● Declare a pointer danglingPtr.

● Call createDanglingPointer and assign the returned pointer to danglingPtr.

● Attempt to access the value through the dangling pointer (which is undefined behavior).

Department of Computer Science and Engineering SRGEC Page 117


C PROGRAMMING LAB-R23

4. End

Program:
#include <stdio.h>

int* createDanglingPointer() {

int num = 42;

int *ptr = &num;

return ptr;

int main() {

int *danglingPtr;

danglingPtr = createDanglingPointer();

printf("Dangling pointer value: %d\n", *danglingPtr);

return 0;

Output:
Dangling pointer value: 42

Flowchart:

Department of Computer Science and Engineering SRGEC Page 118


C PROGRAMMING LAB-R23

13.c)Write a C program to copy one string into another using a pointer.

Algorithm:
1. Start

2. Declare a function copyString that takes two character pointers (dest and src).

3. Use a while loop to copy characters from src to dest until a null character ('\0') is encountered.

4. In the main function:

● Declare two character arrays (sourceString and destinationString).

Department of Computer Science and Engineering SRGEC Page 119


C PROGRAMMING LAB-R23

● Input a string into sourceString.

● Call copyString to copy sourceString into destinationString.

● Display the original and copied strings.

5. End

Program:
#include <stdio.h>

void copyString(char *dest, const char *src) {

while ((*dest++ = *src++));

int main() {

char sourceString[100], destinationString[100];

printf("Enter a string: ");

scanf("%s", sourceString);

copyString(destinationString, sourceString);

printf("Original String: %s\n", sourceString);

printf("Copied String: %s\n", destinationString);

return 0;

Output:
Enter a string: Hello, World!

Original String: Hello, World!

Copied String: Hello, World!

Flowchart:

Department of Computer Science and Engineering SRGEC Page 120


C PROGRAMMING LAB-R23

13.d) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.
Algorithm:
1. Start

2. Declare a function countCharacters that takes a string and four integer pointers (lowercase,
uppercase, digits, and others).

3. Use a while loop to iterate through the string and count lowercase, uppercase, digits, and other
characters.

4. In the main function:

● Declare a character array (inputString) and four integers (lowercase, uppercase, digits, and
others).

● Input a string into inputString.

● Call countCharacters to count characters in the string.

● Display the counts of lowercase, uppercase, digits, and other characters.

5. End

Department of Computer Science and Engineering SRGEC Page 121


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>

void countCharacters(const char *str, int *lowercase, int *uppercase, int *digits, int *others) {

while (*str != '\0') {

if (*str >= 'a' && *str <= 'z') {

(*lowercase)++;

} else if (*str >= 'A' && *str <= 'Z') {

(*uppercase)++;

} else if (*str >= '0' && *str <= '9') {

(*digits)++;

} else {

(*others)++;

str++;

int main() {

char inputString[100];

int lowercase = 0, uppercase = 0, digits = 0, others = 0;

printf("Enter a string: ");

scanf("%s", inputString);

countCharacters(inputString, &lowercase, &uppercase, &digits, &others);

printf("Lowercase characters: %d\n", lowercase);

printf("Uppercase characters: %d\n", uppercase);

printf("Digits: %d\n", digits);

printf("Other characters: %d\n", others);

return 0;

Department of Computer Science and Engineering SRGEC Page 122


C PROGRAMMING LAB-R23

Output:
Enter a string: Hello123World!

Lowercase characters: 8

Uppercase characters: 3

Digits: 3

Other characters: 1

Flowchart:

Department of Computer Science and Engineering SRGEC Page 123


C PROGRAMMING LAB-R23

Department of Computer Science and Engineering SRGEC Page 124


C PROGRAMMING LAB-R23

Week-14
14.a)Write a C program to write and read text into a file.
Algorithm:
1. Start

2. Open a file for writing using fopen in write mode ("w").

3. If the file opening is unsuccessful, display an error message and exit.

4. Input text from the user and write it to the file using fprintf.

5. Close the file using fclose.

6. Display a success message for writing to the file.

7. Open the same file for reading using fopen in read mode ("r").

8. If the file opening is unsuccessful, display an error message and exit.

9. Read and display the text from the file using fgets.

10. Close the file using fclose.

11. End

Program:
#include <stdio.h>

int main() {

FILE *file;

char text[100];

file = fopen("sample.txt", "w");

if (file == NULL) {

printf("Error opening the file for writing.\n");

return 1;

printf("Enter text to write into the file: ");

fgets(text, sizeof(text), stdin);

fprintf(file, "%s", text);

fclose(file);

printf("Text written to the file successfully.\n");

Department of Computer Science and Engineering SRGEC Page 125


C PROGRAMMING LAB-R23

file = fopen("sample.txt", "r");

if (file == NULL) {

printf("Error opening the file for reading.\n");

return 1;

printf("Reading text from the file:\n");

while (fgets(text, sizeof(text), file) != NULL) {

printf("%s", text);

fclose(file);

return 0;

Output:
Enter text to write into the file: This is a sample text for file operations.

Text written to the file successfully.

Reading text from the file:

This is a sample text for file operations.

Department of Computer Science and Engineering SRGEC Page 126


C PROGRAMMING LAB-R23

Flowchart:

Department of Computer Science and Engineering SRGEC Page 127


C PROGRAMMING LAB-R23

14.b)Write a C program to write and read text into a binary file using fread() and fwrite().

Algorithm:
1. Start

2. Open a binary file for writing using fopen in binary write mode ("wb").

3. If the file opening is unsuccessful, display an error message and exit.

4. Input text from the user and write it to the binary file using fwrite.

5. Close the binary file using fclose.

6. Display a success message for writing to the binary file.

7. Open the same binary file for reading using fopen in binary read mode ("rb").

8. If the file opening is unsuccessful, display an error message and exit.

9. Read and display the text from the binary file using fread.

10. Close the binary file using fclose.

11. EnD

Program:
#include <stdio.h>

int main() {

FILE *file;

char text[100];

file = fopen("binary_file.bin", "wb");

if (file == NULL) {

printf("Error opening the binary file for writing.\n");

return 1;

printf("Enter text to write into the binary file: ");

fgets(text, sizeof(text), stdin);

fwrite(text, sizeof(char), sizeof(text), file);

Department of Computer Science and Engineering SRGEC Page 128


C PROGRAMMING LAB-R23

fclose(file);

printf("Text written to the binary file successfully.\n");

file = fopen("binary_file.bin", "rb");

if (file == NULL) {

printf("Error opening the binary file for reading.\n");

return 1;

printf("Reading text from the binary file:\n");

fread(text, sizeof(char), sizeof(text), file);

printf("%s", text);

fclose(file);

return 0;

Output:
Enter text to write into the binary file: hello

Text written to the binary file successfully.

Reading text from the binary file:Hello

Department of Computer Science and Engineering SRGEC Page 129


C PROGRAMMING LAB-R23

Flowchart:

14.c)Copy the contents of one file to another file.

Algorithm:
1. Start

2. Open the source file for reading using fopen in read mode ("r").

3. If the source file opening is unsuccessful, display an error message and exit.

4. Open the destination file for writing using fopen in write mode ("w").

5. If the destination file opening is unsuccessful, display an error message, close the source file, and exit.

6. Copy contents from the source file to the destination file using fgetc and fputc in a loop until EOF is
encountered.

7. Close both the source and destination files using fclose.

8. Display a success message for copying contents.

9. End

Department of Computer Science and Engineering SRGEC Page 130


C PROGRAMMING LAB-R23

Program:
#include <stdio.h>

int main() {

FILE *sourceFile, *destinationFile;

char ch;

sourceFile = fopen("source.txt", "r");

if (sourceFile == NULL) {

printf("Error opening the source file.\n");

return 1;

destinationFile = fopen("destination.txt", "w");

if (destinationFile == NULL) {

printf("Error opening the destination file.\n");

fclose(sourceFile);

return 1;

while ((ch = fgetc(sourceFile)) != EOF) {

fputc(ch, destinationFile);

fclose(sourceFile);

fclose(destinationFile);

printf("Contents copied successfully from source to destination.\n");

return 0;

Output:
If the content of the source.txt file is:
This is a sample text for file copying.

After running the program, the content of the destination.txt file will be:

Department of Computer Science and Engineering SRGEC Page 131


C PROGRAMMING LAB-R23

This is a sample text for file copying.

Department of Computer Science and Engineering SRGEC Page 132


C PROGRAMMING LAB-R23

14.d)Write a C program to merge two files into the third file using command-line

arguments.

Algorithm:
1. Start

2. Check if the correct number of command-line arguments are provided (3 file names).

3. Open the first file for reading (file1).

4. If the first file opening is unsuccessful, display an error message and exit.

5. Open the second file for reading (file2).

6. If the second file opening is unsuccessful, display an error message, close the first file, and exit.

7. Open the merged file for writing (mergedFile).

8. If the merged file opening is unsuccessful, display an error message, close both the first and second
files, and exit.

9. Copy contents from the first file to the merged file using fgetc and fputc in a loop until EOF is
encountered.

10. Copy contents from the second file to the merged file using fgetc and fputc in a loop until EOF is
encountered.

11. Close all files using fclose.

12. Display a success message for merging files.

13. End

Program:
#include <stdio.h>

#include <stdlib.h>

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

FILE *file1, *file2, *mergedFile;

char ch;

if (argc != 4) {

printf("Usage: %s <file1> <file2> <mergedFile>\n", argv[0]);

return 1;

Department of Computer Science and Engineering SRGEC Page 133


C PROGRAMMING LAB-R23

file1 = fopen(argv[1], "r");

if (file1 == NULL) {

printf("Error opening %s for reading.\n", argv[1]);

return 1;

file2 = fopen(argv[2], "r");

if (file2 == NULL) {

printf("Error opening %s for reading.\n", argv[2]);

fclose(file1);

return 1;

mergedFile = fopen(argv[3], "w");

if (mergedFile == NULL) {

printf("Error opening %s for writing.\n", argv[3]);

fclose(file1);

fclose(file2);

return 1;

while ((ch = fgetc(file1)) != EOF) {

fputc(ch, mergedFile);

while ((ch = fgetc(file2)) != EOF) {

fputc(ch, mergedFile);

fclose(file1);

fclose(file2);

fclose(mergedFile);

printf("Files %s and %s merged into %s successfully.\n", argv[1], argv[2], argv[3]);

Department of Computer Science and Engineering SRGEC Page 134


C PROGRAMMING LAB-R23

return 0;

Output:
Assuming the program is named merge_files:
$ ./merge_files file1.txt file2.txt merged_file.txt

Files file1.txt and file2.txt merged into merged_file.txt successfully.

FLowchart:

Department of Computer Science and Engineering SRGEC Page 135


C PROGRAMMING LAB-R23

14.e)Find no. of lines, words and characters in a file.

Algorithm:
1. Start

2. Declare a function countLinesWordsCharacters that takes a file pointer and three integer pointers
(lines, words, and characters).

3. Initialize variables ch and inWord.

4. Use a while loop to read characters from the file until EOF is encountered.

5. Increment the characters count for each character read.

6. Check for newline characters ('\n') to count lines.

7. Check for space, tab, or newline characters to detect word boundaries and update the words count
accordingly.

8. In the main function:

● Open the file for reading.

● If the file opening is unsuccessful, display an error message and exit.

● Call countLinesWordsCharacters to count lines, words, and characters in the file.

● Close the file.

● Display the counts of lines, words, and characters.

9. End

Program:
#include <stdio.h>

void countLinesWordsCharacters(FILE *file, int *lines, int *words, int *characters) {

char ch;

int inWord = 0;

while ((ch = fgetc(file)) != EOF) {

(*characters)++;

if (ch == '\n') {

(*lines)++;

if (ch == ' ' || ch == '\t' || ch == '\n') {

Department of Computer Science and Engineering SRGEC Page 136


C PROGRAMMING LAB-R23

inWord = 0;

} else if (inWord == 0) {

inWord = 1;

(*words)++;

int main() {

FILE *file;

int lines = 0, words = 0, characters = 0;

file = fopen("sample_text.txt", "r");

if (file == NULL) {

printf("Error opening the file for reading.\n");

return 1;

countLinesWordsCharacters(file, &lines, &words, &characters);

fclose(file);

printf("Lines: %d\n", lines);

printf("Words: %d\n", words);

printf("Characters: %d\n", characters);

return 0;

Output:
Assuming the program is reading from a file named sample_text.txt with the following
content:
This is a sample text file.

It has multiple lines and words.

Counting lines, words, and characters.

Department of Computer Science and Engineering SRGEC Page 137


C PROGRAMMING LAB-R23

The expected output would be:


Lines: 3

Words: 15

Characters: 96

Flowchart:

Department of Computer Science and Engineering SRGEC Page 138


C PROGRAMMING LAB-R23

14.f)Write a C program to print the last n characters of a given file.

Algorithm:
1. Start

2. Declare a function printLastNCharacters that takes a file pointer and an integer n.

3. Use fseek to move the file pointer to the end of the file (SEEK_END).

4. Use ftell to get the current position, which is the file size.

5. Move the file pointer to the start of the last n characters from the end of the file.

6. Print the last n characters using fgetc.

7. In the main function:

● Open the file for reading.

● If the file opening is unsuccessful, display an error message and exit.

● Input the value of n.

● Call printLastNCharacters to print the last n characters of the file.

● Close the file.

8. End

Program:
#include <stdio.h>

void printLastNCharacters(FILE *file, int n) {

fseek(file, 0, SEEK_END); // Move file pointer to the end of the file

long fileSize = ftell(file); // Get the current position, which is the file size

if (fileSize == -1) {

printf("Error getting file size.\n");

return;

fseek(file, -n, SEEK_END);

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

Department of Computer Science and Engineering SRGEC Page 139


C PROGRAMMING LAB-R23

int ch = fgetc(file);

if (ch == EOF) {

break;

putchar(ch);

printf("\n");

int main() {

FILE *file;

int n;

file = fopen("sample_text.txt", "r");

if (file == NULL) {

printf("Error opening the file for reading.\n");

return 1;

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

scanf("%d", &n);

printf("Last %d characters of the file:\n", n);

printLastNCharacters(file, n);

fclose(file);

return 0;

Output:
Assuming the program is reading from a file named sample_text.txt with the following
content:
This is a sample text file.

It has multiple lines and words.

Department of Computer Science and Engineering SRGEC Page 140


C PROGRAMMING LAB-R23

Counting lines, words, and characters.

If n is set to 20, the expected output would be:

Last 20 characters of the file:

g lines, words, and characters.

Flowchart:

Department of Computer Science and Engineering SRGEC Page 141

You might also like