0% found this document useful (0 votes)
38 views95 pages

CP Lab Course File

The document outlines the Computer Programming Lab course for B.Tech in Computer Science & Engineering at Dadi Institute of Engineering & Technology for the academic year 2024-2025. It includes the institute's vision and mission, course syllabus, program outcomes, educational objectives, and lab timetable. The course aims to provide students with practical programming skills through various experiments and projects using the C programming language.
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)
38 views95 pages

CP Lab Course File

The document outlines the Computer Programming Lab course for B.Tech in Computer Science & Engineering at Dadi Institute of Engineering & Technology for the academic year 2024-2025. It includes the institute's vision and mission, course syllabus, program outcomes, educational objectives, and lab timetable. The course aims to provide students with practical programming skills through various experiments and projects using the C programming language.
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/ 95

Computer Programming Lab CSE-R23 DIET

DADI INSTITUTE OF ENGINEERING &TECHNOLOGY


(An Autonomous Institute)
(Approved by A.I.C.T.E., New Delhi &Permanently Affiliated to JNTUK, Kakinada)
Accredited by NAAC with ‘A’ Grade and Inclusion under Section 2(f) & 12(B) of UGC Act
An ISO 9001:2015, ISO 14001:2015 & ISO 45001:2018 Certified Institute.
NH-16, Anakapalle – 531002, Visakhapatnam, A.P.
Mobile: +91 9963981111, Website: www.diet.edu.in, E-mail: [email protected]

LAB COURSE FILE

Academic Year : 2024-2025

Year & Semester : I-I

Course : B.Tech

Branch : Computer Science & Engineering

Name of the Lab : Computer Programming Lab

Name of the Faculty : Mrs. P. Neeraja

Designation : Assistant Professor

Signature of Faculty Signature of the HOD

P. Neeraja Department of CSE Pg 1


Computer Programming Lab CSE-R23 DIET

Contents

1. Vision and Mission of the Institute and Department

2. Syllabus of the Course

3. PO, PEOs & PSO statements

4. Course Objectives & Outcomes

5. Lab Time Table

6. Lesson Plan

7. Roll List

8. Programs & Output

9. Internal Marks

10.External Marks

11. Result Analysis

12. CO-PO Attainment Sheet

P. Neeraja Department of CSE Pg 2


Computer Programming Lab CSE-R23 DIET

1. Vision and Mission of the Institute and Department

Vision of the Institute


To evolve into a premier technical institution ensuring academic excellence and promoting
innovational research.

Mission of the Institute


1. To impart high quality technical and professional education to uplift the living
standards of the youth by focusing on employability, higher education and research.
2. To bridge the gap between industry and academia by introducing add on courses
based on industrial and academic needs.
3. To develop responsible citizens through disciplined career and acceptance of ethical
values.
4. To be a student centric institute imbibing experiential, innovative and lifelong
learning skills addressing societal problems.

Vision of the Department


To contribute to the society through excellence in scientific and knowledge-based education
by utilizing the potential of Computer Science and Engineering with a deep passion for
Technology, Culture and Values.

Mission of the Department


1. To offer State-of-Art education in Computer Science and Engineering
2. To provide strong theoretical foundation complemented with extensive practical
training
3. To impart Software, Communication and Leadership Skills to the students for giving
solutions to the Global Challenges
4. To inculcate Value-based, Socially Committed Professionalism to the cause of overall
development of Students and Society

P. Neeraja Department of CSE Pg 3


Computer Programming Lab CSE-R23 DIET
2. Syllabus of the Course

I Year B. Tech CSE- L T P C


I Semester 0 0 3 1.5
Computer Programming Lab

List of Experiments:

UNIT I

WEEK 1

Tutorial 1: Problem-solving using Computers.


Lab1: Familiarization with programming environment

i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()

WEEK 2

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

WEEK 3

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

P. Neeraja Department of CSE Pg 4


Computer Programming Lab CSE-R23 DIET

UNIT II

WEEK 4

Tutorial4: Operators and the precedence and as associativity:


Lab4: Simple computational problems using the operator’ precedence and associativity

i) Evaluate the following expressions.


a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
iii) Take marks of 5 subjects in integers, and find the total, average in float

WEEK 5

Tutorial 5: Branching and logical expressions:


Lab 5: Problems involving if-then-else structures.

i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.

WEEK 6

Tutorial 6: Loops, while and for loops


Lab 6: Iterative problems e.g., the sum of series

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


ii) Find the given number is a prime or not.
iii) Compute sine and cos series
iv) Checking a number palindrome
v) Construct a pyramid of numbers.

UNIT III

WEEK 7:

Tutorial 7: 1 D Arrays: searching.


Lab 7:1D Array manipulation, linear search

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


ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
P. Neeraja Department of CSE Pg 5
Computer Programming Lab CSE-R23 DIET
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.

WEEK 8:

Tutorial 8: 2 D arrays, sorting and Strings.


Lab 8: Matrix problems, String operations, Bubble sort

i) Addition of two matrices


ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions

UNIT IV

WEEK 9:

Tutorial 9: Pointers, structures and dynamic memory allocation


Lab 9: Pointers and structures, memory dereference.

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


ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student details along
with the total.
v) Write a C program to implement realloc()

WEEK 10:

Tutorial 10: Bitfields, Self-Referential Structures, Linked lists


Lab10 : Bitfields, linked lists
Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same
without using bit- fields

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


ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the same type.

UNIT V

WEEK 11:

Tutorial 11: Functions, call by value, scope and extent,


Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.

i) Write a C function to calculate NCR value.


P. Neeraja Department of CSE Pg 6
Computer Programming Lab CSE-R23 DIET
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations using Euler’s
method

WEEK 12:

Tutorial 12: Recursion, the structure of recursive calls


Lab 12: Recursive functions

i) Write a recursive function to generate Fibonacci series.


ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement Ackermann function using recursion.
v) Write a recursive function to find the sum of series.

WEEK 13:

Tutorial 13: Call by reference, dangling pointers


Lab 13: Simple functions using Call by reference, Dangling pointers.

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


ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other
characters using pointers.

WEEK14:

Tutorial 14: File handling


Lab 14: File operations

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


ii) Write a C program to write and read text into a binary file using fread() and
fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line
arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.

Textbooks:
1. Ajay Mittal, Programming in C: A practical approach, Pearson.
2. Byron Gottfried, Schaum' s Outline of Programming with C, McGraw Hill
Reference Books:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice-
Hall of India
2. C Programming, A Problem-Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE

P. Neeraja Department of CSE Pg 7


Computer Programming Lab CSE-R23 DIET

3. PO, PEOs & PSO statements


PROGRAM OUTCOMES (POs) FOR UG COURSES

The program is targeted at developing the following competencies, skills and abilities
amongst students:

PO1: An ability to apply knowledge of Mathematics, Science and Engineering to give the
solution for Complex Engineering Problems

PO2: An ability to analyze and interpret data to design Efficient Algorithms

PO3: An ability to design a System, Component or Process to meet desired needs within
various realistic constraints of socio-economic sustainability

PO4: An ability to use research-based knowledge and research methods, including design,
analysis and interpretation of data and synthesis of the information to provide valid
conclusions to complex problems

PO5: An ability to use the Techniques, Skills and Modern Engineering Tools necessary for
engineering practice

PO6: An ability to apply reasoning informed by the contextual knowledge to assess


societal, health, safety and cultural issues and the consequent responsibilities relevant to the
professional engineering practice

PO7: An ability to obtain broad education necessary to understand the impact of


engineering solutions in global, economic, environmental, and societal context

PO8: An ability to understand professional and ethical responsibility while performing the
job responsibilities

PO9: An ability to collaborate with interdisciplinary teams efficiently

PO10: An ability to communicate effectively to ascertain best results

PO11: An ability to demonstrate knowledge and understanding of the engineering and


management principles to one’s own work as a member and leader in a team to manage
projects and in multidisciplinary environments

PO12: An ability to recognition the need for and ability to engage in Continual Learning

P. Neeraja Department of CSE Pg 8


Computer Programming Lab CSE-R23 DIET

Program Educational Objectives


Program Educational Objectives of the UG in COMPUTER SCIENCE & ENGINEERING
are:

PEO 1: Graduate shall be an efficient Software Developer in diverse fields and will be a
Successful Professional or pursue Higher Studies

PEO 2: Graduates shall be a Lifetime Learner, capable to adapt to new computing


technology for Professional Excellence and Research.

PEO 3: Graduates shall work productively exhibiting ethical qualities for the betterment of
Society

PEO 4: Graduates shall possess effective Leadership and Communication Skills to work
harmoniously with the team to achieve set goals

Program Specific outcomes


PSO 1. Problem Solving Skills: Ability to design and develop computing tools with moderate
complexity in the areas pertaining to database, data analytics, networking, web and app
design, IoT and information security with integration.

PSO 2. Professional Skills: Ability to apply standard practices and methods in software
project management and software development using suitable programming environments to
deliver quality product to the industry.

POs & PSO REFERENCE:

Engineering Environment & Problem Solving


PO1 PO7 PSO1
Knowledge Sustainability Skills
PO2 Problem Analysis PO8 Ethics PSO2 Professional Skills
Design &
Individual & Team
PO3 Development of PO9
Work
solutions
Conduct Investigations Communication
PO4 PO10
of Complex Problems Skills
Project
PO5 Modern Tools Usage PO11 Management &
Finance

PO6 Engineer & Society PO12 Life Long Learning

P. Neeraja Department of CSE Pg 9


Computer Programming Lab CSE-R23 DIET

4. Course Objectives & Outcomes


COURSE OBJECTIVES
The main objective of the course is to inculcate the basic understanding of Data Science
and it’s practicalimplementation using Python.

COURSE OUTCOMES (COs)


Upon successful completion of the course, the student will be able to:
● Perform various operations on numpy arrays
● Importing data from different file formats using pandas
● Draw different types of charts using matplotlib

COURSE ARTICULATION MATRIX (Correlation between Cos & POs, PSOs):

CO PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2
C411.1 3 3 2 1 - - - 1 2 1 - - 1
C411.2 3 2 1 2 2 1 1 1 2 - - 1 1
C411.3 3 3 2 2 2 1 1 1 3 - - 2
C411.4 3 3 2 1 2 1 1 - 1 1
C411.5 3 3 2 2 2 1 1 1 1 - - 2

1: Slight (Low) 2: Moderate (Medium) 3: Substantial (High) - :None

P. Neeraja Department of CSE Pg 10


Computer Programming Lab CSE-R23 DIET

5. Lab Timetable

Mrs P. Neeraja
Day 9.00- 9.50- 11.00- 11.50- 12.40- 1.30- 2.20- 3.10-
/Timings 9.50 10.40 11.50 12.40 1.30 2.20 3.10 4.00
MON
TUE
WED I CSE B CP LAB I CSE C CP LAB
Lunch
THU
FRI
SAT

Individual Time table

Mrs P. Neeraja
Day 9.00- 9.50- 11.00- 11.50- 12.40- 1.30- 2.20-
3.10-4.00
/Timings 9.50 10.40 11.50 12.40 1.30 2.20 3.10
I ECE- I CSE I CSE C I CSE
MON
B IP B IP IP C IP
I ECE- I ECE- I CSE
TUE
B IP B IP C IP
WED I CSE B CP LAB I CSE C CP LAB

I CSE I ECE- Lunch I CSE B I CSE MENTOR


THU
B IP B IP IP C IP II CSE B

I CSE I ECE- I CSE


FRI
B IP B IP B IP
I CSE I CSE
SAT LUNCH
C IP B IP

P. Neeraja Department of CSE Pg 11


Computer Programming Lab CSE-R23 DIET

6. Lesson Plan
Sl Programs List Proposed Date Actual Date
No.
1 Exercise - 1 Familiarization with
programming environment
1. a Basic Linux environment and its editors
like Vi, Vim & Emacs etc.
1. b Exposure to Turbo C, gcc
1. c Writing simple programs using printf(),
scanf()
2 Exercise - 2 Converting algorithms/flow
charts into C Source code.
2.a Sum and average of 3 numbers
2.b Conversion of Fahrenheit to Celsius and
vice versa
2.c iii) Simple interest calculation
3 Exercise - 3 Simple computational
problems using arithmetic expressions.
3.a Finding the square root of a given number
3.b Finding compound interest
3.c Area of a triangle using heron’s formulae
3.d Distance travelled by an object
4 Exercise - 4 Simple computational
problems using the operator’ precedence
and associativity
4.a i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
4.b ii) Find the maximum of three numbers
using conditional operator
4.c iii) Take marks of 5 subjects in integers, and
find the total, average in float
5 Exercise - 5 Problems involving if-then-
else structures.
5.a i) Write a C program to find the max and
min of four numbers using if-else.
5.b ii) Write a C program to generate electricity
bill.
5.c iii) Find the roots of the quadratic equation.

P. Neeraja Department of CSE Pg 12


Computer Programming Lab CSE-R23 DIET
5.d iv) Write a C program to simulate a
calculator using switch case.
6 Exercise - 6 Loops, while and for loops
6.a Find the factorial of given number using
any loop.
6.b Find the given number is a prime or not.
6.c Compute sine and cos series
6.d Checking a number palindrome
6.e Construct a pyramid of numbers.
Exercise - 7 1D Array manipulation, linear
7 search
7.a Find the min and max of a 1-D integer
array.
7.b Perform linear search on1D array.
7.c The reverse of a 1D integer array
7.d Find 2’s complement of the given binary
number.
7.e Eliminate duplicate elements in an array.
Exercise - 8 Matrix problems, String
8 operations, Bubble sort
8.a Addition of two matrices
8.b Multiplication two matrices
8.c Sort array elements using bubble sort
8.d Concatenate two strings without built-in
functions
8.e Reverse a string using built-in and without
built-in string functions
Exercise 9 Pointers and structures,
9 memory dereference.
9.a Write a C program to find the sum of a 1D
array using malloc()
9.b Write a C program to find the total,
average of n students using structures
9.c Enter n students data using calloc() and
display failed students list
9.d Read student name and marks from the
command line and display the student
details along with the total.
9.e Write a C program to implement realloc()
Exercise 10 Bitfields, Self-Referential
10 Structures, Linked lists
10.a Create and display a singly linked list
using self-referential structure.
10.b
Demonstrate the differences between
P. Neeraja Department of CSE Pg 13
Computer Programming Lab CSE-R23 DIET
structures and unions using a C program.

10.c Write a C program to shift/rotate using


bitfields.
10.d Write a C program to copy one structure
variable to another structure of the same
type.
Exercise 11 Simple functions using call by
value, solving differential equations
11 using Eulers theorem.
11.a Write a C function to calculate NCR value.
11.b Write a C function to find the length of a
string.
11.c Write a C function to transpose of a matrix.
11.d Write a C function to demonstrate
numerical integration of differential
equations using Euler’s method
Exercise 12 Recursion, the structure of
12 recursive calls
12.a Write a recursive function to generate
Fibonacci series.
12.b Write a recursive function to find the lcm of
two numbers.
12.c Write a recursive function to find the
factorial of a number.
12.d Write a C Program to implement
Ackermann function using recursion.
12.e Write a recursive function to find the sum
of series.
Exercise 13 Simple functions using Call
13 by reference, Dangling pointers.
13.a i) Write a C program to swap two numbers
using call by reference.
13.b ii) Demonstrate Dangling pointer problem
using a C program.
13.c iii) Write a C program to copy one string
into another using pointer.
13.d iv) Write a C program to find no of
lowercase, uppercase, digits and other
characters using pointers.
14 Exercise 14 File operations
14.a i) Write a C program to write and read text
into a file.
14.b ii) Write a C program to write and read text
into a binary file using fread() and fwrite()
P. Neeraja Department of CSE Pg 14
Computer Programming Lab CSE-R23 DIET
14.c iii) Copy the contents of one file to another
file.
14.d iv) Write a C program to merge two files
into the third file using command-line
arguments.
14.e v) Find no. of lines, words and characters in
a file
14.f vi) Write a C program to print last n
characters of a given file.

P. Neeraja Department of CSE Pg 15


Computer Programming Lab CSE-R23 DIET

7. Roll List

I CSE B

S.NO Roll No Name


1 24U41A0565 AKSHAY VARDHAN K V S P
2 24U41A0566 CHAVVAKULA SRINU
3 24U41A0567 CHELLI BHARGAVISRI
4 24U41A0568 CHINNI SURENDRA
5 24U41A0569 CHITRA MOUNIKA
6 24U41A0570 DADI KOWSALAYA
7 24U41A0571 DADI NAMRATHA
8 24U41A0572 DADI UDAYA DEEPIKA
9 24U41A0573 DASARI KUSUMA SAI PRASANTHI
10 24U41A0574 DEVUPALLI SHARMILA
11 24U41A0575 DONKADA HARITHA
12 24U41A0576 DUDI JHANSI
13 24U41A0577 EERLA GAYATHRI
14 24U41A0578 ESAMSETTI HEMAPRIYA
15 24U41A0579 GANDEM DEEPAK
16 24U41A0580 GANGUPAM RESMA
17 24U41A0581 GONTHINA MANOJ
18 24U41A0582 GORJI PUJITHA
19 24U41A0583 GORLI KAVITHA
20 24U41A0584 GUMMALA VENKATA THANAYA SREE
21 24U41A0585 GYPURI TEJAS
22 24U41A0586 IMMADISETTY VIGNESH
23 24U41A0587 IPPILI MOUNIKA
24 24U41A0588 KARRI NIHARIKA
25 24U41A0589 KESAR MISHRA
26 24U41A0590 KOLLA VIVEK
27 24U41A0591 KURMAPU MERY GOWRI
28 24U41A0592 KURMAPU VENNELA
29 24U41A0593 LEKKALA MOUNIKA
30 24U41A0594 MADAGALA DEEPIKA
P. Neeraja Department of CSE Pg 16
Computer Programming Lab CSE-R23 DIET
31 24U41A0595 MADDU PRADEEP KUMAR
32 24U41A0596 MALLA HARI SATYANARAYANA
33 24U41A0597 MATSA SAI SURAJ
34 24U41A0598 MULLU PRAVEEN KUMAR
35 24U41A0599 MUTTA KYATHI REKHA
36 24U41A05A0 NAGIREDDY DIVYA RAVI TEJA
37 24U41A05A1 NAKARABOYINA URVIK SAI PRUDHVI RAJ
38 24U41A05A2 NIMMADALA VIJAYA LAKSHMI
39 24U41A05A3 NUNNAM SWAMI SHIVA RAMESH
40 24U41A05A4 PADALA JAYA VARDHAN
41 24U41A05A5 PENIGOTA YADAV
42 24U41A05A6 PETHAKAMSETTY SRI HARSHINI
43 24U41A05A7 PUNYAMANTHULA TEJASWANTH
44 24U41A05A8 RAJANA TAPASWI
45 24U41A05A9 RAMPATNI TRILOCHANI
46 24U41A05B0 REYYI SATISH
47 24U41A05B1 SAMBANGI SWARNALATHA
48 24U41A05B2 SANAPATHI KIRANMAI
49 24U41A05B3 SHEIK HARSHAD
50 24U41A05B4 SIRIPURAPU JAHNAVI
51 24U41A05B5 SURAMPUDI SRI VINAYANI
52 24U41A05B6 TANGUDU MADHUMITHA
53 24U41A05B7 THOTA MOKSHITHA SAI
54 24U41A05B8 VADDI VAMSI
55 24U41A05B9 YARAVA KEERTHI CHOWDHARY
56 24U41A05C0 YELISETTI BHARGAVI
57 24U41A05C1 ALAJANGI BHARGAV
58 24U41A05C2 ALLA BHAVYASRI
59 24U41A05C3 ANAPARTHI SARAYU
60 24U41A05C4 ANUPOJU MANOJ
61 24U41A05C5 ASHIRBAD BEHERA
62 24U41A05C6 BAVIRIPUDI KARTHIKEYA NAIDU
63 24U41A05C7 BAYINA BHARATH
64 24U41A05C8 BODDU SUDHEER

P. Neeraja Department of CSE Pg 17


Computer Programming Lab CSE-R23 DIET

I CSE C

S.NO Roll No Name


1 24U41A05C9 BHOGIREDDY VIDHYA SAI SRI
2 24U41A05D0 BODDADA CHANDRA SEKHAR
3 24U41A05D1 BODDEPALLI AKHIL
4 24U41A05D2 BODDETI AKSHAYA LAVANYA
5 24U41A05D3 BESOI RAM KRISHNA CHARAN
6 24U41A05D4 CHERAPAKA SAI DEEPAK
7 24U41A05D5 CHILUKURI ASWANI KUMAR
8 24U41A05D6 CHIPPALA DURGA LOHITHA
9 24U41A05D7 CHENNAMSETTI JAYA SURYA
10 24U41A05D8 DOODI HIMA BINDU
11 24U41A05D9 GANDREDDY YERNAIDU
12 24U41A05E0 GANTYADA DIVYA SRI SYAMALA
13 24U41A05E1 GINNI SIRISHA
14 24U41A05E2 GORLE RESHMA
15 24U41A05E3 GUDELA VINEETHA
16 24U41A05E4 GUMMIDI DEVA HARSHA
17 24U41A05E5 JAYANTI VENKATA CHIKLEETA
18 24U41A05E6 JEEBA MOHAN RAO
19 24U41A05E7 KALEPU LIKHITA
20 24U41A05E8 KANDREGULA S G M K S LIKHITH
21 24U41A05E9 KARRI NEERAJA
22 24U41A05F0 KEDARISETTI AMRUTHA VARSHINI
23 24U41A05F1 KELLA HARISH
24 24U41A05F2 KODUKULA AKSHAYA TANMAYEE
25 24U41A05F3 KONA KESAVA
26 24U41A05F4 KOPPARTHI SUBHASHINI
27 24U41A05F5 LAKKAVARAPU HEMANTH KUMAR
28 24U41A05F6 MALLA VISHWANTH
29 24U41A05F7 MANTRI PRAGADA USHA GAYATRI
30 24U41A05F8 CHUKKA MARUTHI DURGA PRASAD REDDY
31 24U41A05F9 MOLLETI KUSUMA
32 24U41A05G0 NAKKANI DEEPAK CHARAN DEVA

P. Neeraja Department of CSE Pg 18


Computer Programming Lab CSE-R23 DIET
33 24U41A05G1 NARSUPALLI JAYA SREE
34 24U41A05G2 NIRUJOGI HARSHINI
35 24U41A05G3 PANTHAM ANAND KUMAR
36 24U41A05G4 PANTHAM APARNA JYOTHI SWAROOPA
37 24U41A05G5 PITTA HARSHA
38 24U41A05G6 POLISETTI LIKHITHA KUMARI
39 24U41A05G7 RAJAMANDRAPU DURGA JAHNAVI
40 24U41A05G8 RAJANA PRANEETH
41 24U41A05G9 SABBAVARAPU SAI SURYA
42 24U41A05H0 SANAPATHI DIVYA
43 24U41A05H1 SARVASUDDI DURGA RAO
44 24U41A05H2 TAMADA KRISHNA
45 24U41A05H3 TANDA GANESH
46 24U41A05H4 THUTA ROHITH
47 24U41A05H5 VAKADA PRADEEP
48 24U41A05H6 VASUPILLI SANDHYA
49 24U41A05H7 VEGI RAMAKOTESWARA RAO
50 24U41A05H8 VIGNESWARA TEJASWI
51 24U41A05H9 VILLURI KUMARI VAISHNAVI
52 24U41A05I0 YALALA HEMANTH
53 24U41A05I1 ANAKAPALLI BRAHMA
54 24U41A05I2 BODAPATI HARSHA SAI
55 24U41A05I3 BUDDHA KUSMITHA
56 24U41A05I4 CHEEKURUMELLI SAI CHARAN
57 24U41A05I5 DASARI RAJA
58 24U41A05I6 DEKKATHA BALA VIGNESH KUNDAN REDDY
59 24U41A05I7 DENDUKURI VARSHITH VARMA
60 24U41A05I8 DEVI PRIYA MAHAPATRO
61 24U41A05I9 DOLA HEMANTH KUMAR
62 24U41A05J0 GANDIPADALA JYOTHI SWAROOPA
63 24U41A05J1 GARA KIRAN
64 24U41A05J2 GULLA MOHAN GANESH

P. Neeraja Department of CSE Pg 19


8. Programs & Outputs

Experiment 1:

What do you mean by Basic Linux environment and its editors like Vi, Vim & Emacs etc.

A basic Linux environment in the context of C programming refers to the essential components and tools
that are typically available and required to develop, compile, and run C programs on a Linux-based
operating system. These components and tools include:

 Linux Operating System: A Linux distribution such as Ubuntu, Debian, CentOS, or Fedora forms
the foundation of the environment. Linux is open-source and widely used for software
development due to its robust command-line interface and development-friendly features.
 Terminal Emulator: The terminal emulator is a command-line interface that allows developers to
interact with the Linux system. It provides a text-based environment where you can execute
commands, navigate the file system, and compile and run C programs. Popular terminal
emulators include GNOME Terminal, Konsole, and xterm.
 C Compiler: The C programming language requires a compiler to translate human-readable C
code into machine-executable code. GCC (GNU Compiler Collection) is a commonly used C
compiler on Linux. You can install GCC with the package manager of your Linux distribution if it's
not already installed.
 Text Editor: A text editor is essential for writing and editing C source code. Commonly used text
editors for C programming in a Linux environment include Vi, Vim, Emacs, Nano, and graphical
editors like Visual Studio Code with C/C++ extensions.
 Development Libraries: Linux provides a set of development libraries and header files that are
necessary for compiling C programs. These libraries contain functions and resources that can be
utilized in your C code. The standard C library, glibc, is one of the most important libraries for C
programming on Linux.
 Version Control: Many C programmers use version control systems like Git to manage and track
changes in their source code. Git is commonly available on Linux and integrates well with the
development workflow.
 Debugger: A debugger, such as GDB (GNU Debugger), is useful for tracing and fixing issues in C
programs. It allows you to step through your code, inspect variables, and identify and resolve
errors.
 Build Tools: For more complex projects, build tools like Makefiles can be used to automate the
build process and manage dependencies in your C project.
 Documentation: Linux typically includes extensive documentation and man pages that provide
information about system calls, library functions, and command-line utilities. You can access
these resources from the terminal using commands like man or info.

Text Editors:

Vi: Vi is a terminal-based text editor that comes pre-installed on most Unix-based systems, including
Linux. It is a modal editor, meaning it has different modes for inserting text, navigating, and performing
other tasks.
Vim: Vim is an improved version of Vi and stands for "Vi IMproved." It offers additional features and a
more user-friendly interface while retaining Vi's powerful capabilities. Vim is highly configurable and
extensible. To open a file using Vim, you can type vim filename in the terminal. Once inside Vim, you can
switch between different modes (normal, insert, command) to perform various tasks like editing, saving,
and quitting.

Emacs: Emacs is another powerful and extensible text editor that can be used for C programming. It
provides a wide range of features and supports various programming languages. Emacs is known for its
extensibility; you can add different plugins and customize its behavior according to your needs. To open
a file using Emacs, you can type emacs filename in the terminal.

Exposure to Turbo C and GCC Compiler

Turbo C:

 TurboC is a legacy integrated development environment (IDE) and compiler for the C and C++
programming languages.
 It was developed by Borland and was particularly popular in the late 1980s and early 1990s.
 TurboC was primarily used in the MS-DOS and early Windows environments.
 It is considered a historic and influential tool in the realm of C and C++ programming.
 TurboC provided a simple and user-friendly integrated development environment with features
like a code editor, compiler, and linker bundled into one package. This made it accessible for
programmers, including beginners.
 TurboC was notable for its support of graphics programming, which was valuable for developing
applications and games in the DOS environment.
 TurboC used its own standard library, which had some differences compared to the standard
libraries used in modern C and C++ compilers. This means that code written in TurboC might
require modifications to compile with modern compilers like GCC.

GCC Compiler:

 The GCC (GNU Compiler Collection) is a widely-used open-source compiler system for various
programming languages, including C and C++.
 It is a powerful and versatile compiler that plays a significant role in the world of C
programming.
 GCC is available on a variety of platforms and operating systems, making it a versatile choice for
developing C and C++ applications on different environments.
 It is commonly used on Unix-like systems (e.g., Linux) but can be adapted to other platforms.
 GCC adheres to modern C language standards, such as ANSI C (C89), C99, and C11.
 This ensures that code written using GCC is compliant with industry-standard C language
specifications.
Write a sample Programs using printf() and scanf()

Sample Program 1: Input and Output of Floating-Point Numbers:

#include <stdio.h>

void main()

float num;

printf("Enter a floating-point number: ");

scanf("%f", &num);

printf("You entered: %f\n", num);

Output:

Enter a floating-point number: 25.5

You entered: 25.500000

Sample Program 2: Printing two integer values:

#include <stdio.h>
void main()
{
int num1, num2;
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
printf("You entered two integers: %d and %d\n", num1, num2);
}

Output:
Enter the first integer: 65
Enter the second integer: 45
You entered two integers: 65 and 45
2.1 Write a C program for Sum and average of 3 numbers

#include <stdio.h>

void main()
{
int num1, num2, num3, sum, average;

printf("Enter the first number: ");


scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

printf("Enter the third number: ");


scanf("%d", &num3);

sum = num1 + num2 + num3;

average = sum / 3.0;

printf("Sum of the three numbers: %d\n", sum);


printf("Average of the three numbers: %d\n", average);

Output:

Enter the first number: 48


Enter the second number: 56
Enter the third number: 47
Sum of the three numbers: 151.000000
Average of the three numbers: 50.333333
2.2 Write a C program for Conversion of Fahrenheit to Celsius and vice versa

#include<stdio.h>

Void main()

Float c,f;

printf(\n EnterTemperature in Fahrenit”);

scanf(“%f”,&f);

c=(f-32)*519;

printf(“\n Temperature in celsuis: %f”,c);

f=(915*c)+32;

printf(“\n Temperature in fahernhet: %2f”,f);

Output:

Temp in F: 89

Temp in C=31.6666

Temp in C: 76

Temp in F=108.00000

2.3: Write a C Program for Simple interest Calcuation:

#include <stdio.h>
void main()
{
double principal, rate, time, interest;
printf("Simple Interest Calculation\n");
printf("Enter the principal amount: $");
scanf("%lf", &principal);
printf("Enter the annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter the time period (in years): ");
scanf("%lf", &time);
interest = (principal * rate * time);
printf("Simple Interest: $%.2lf\n", interest)
}

Output:

Simple Interest Calculation


Enter the principal amount: $45
Enter the annual interest rate (as a decimal): 0.2
Enter the time period (in years): 2
Simple Interest: $18.00

Write a C Program to find the square root of a given number

#include <stdio.h>
#include <math.h>
void main()
{
double number, result;
printf("Enter a number to find its square root: ");
scanf("%lf", &number);
if (number >= 0)
{
result = sqrt(number);
printf("The square root of %.2lf is %.2lf\n", number, result);
}
else
{
printf("Cannot calculate the square root of a negative number.\n");
}
}

Output:
Enter a number to find its square root: 56
The square root of 56.00 is 7.48

Write a C Program to find Finding compound interest

#include <stdio.h>
#include <math.h>
void main()
{
double principal, rate, time, n, interest, amount;
printf("Compound Interest Calculation\n");
printf("Enter the principal amount: $");
scanf("%lf", &principal);
printf("Enter the annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter the time period (in years): ");
scanf("%lf", &time);
printf("Enter the number of times interest is compounded per year: ");
scanf("%lf", &n);
interest = principal * pow(1 + (rate / n), n * time) - principal;
amount = principal + interest;
printf("Compound Interest: $%.2lf\n", interest);
printf("Final Amount: $%.2lf\n", amount);
}

Output:

Compound Interest Calculation


Enter the principal amount: $4598
Enter the annual interest rate (as a decimal): 2.5
Enter the time period (in years): 5
Enter the number of times interest is compounded per year: 2.0
Compound Interest: $15284932.44
Final Amount: $15289530.44

Write a C program to calculate the area of a triangle using Heron's formula:

#include <stdio.h>

#include <math.h>

void main()

double a, b, c, s, area;

printf("Heron's Formula - Calculate the Area of a Triangle\n");

printf("Enter the length of side 'a': ");

scanf("%lf", &a);
printf("Enter the length of side 'b': ");

scanf("%lf", &b);

printf("Enter the length of side 'c': ");

scanf("%lf", &c);

s = (a + b + c) / 2;

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

printf("Area of the triangle: %.2lf square units\n", area);

Output:

Heron's Formula - Calculate the Area of a Triangle


Enter the length of side 'a': 54
Enter the length of side 'b': 48
Enter the length of side 'c': 14
Area of the triangle: 319.50 square units

Write a C program to find Distance travelled by an object

#include <stdio.h>
void main()
{
double initial_velocity, time, acceleration, distance;

printf("Distance Calculation for an Object with Constant Acceleration\n");


printf("Enter initial velocity (m/s): ");
scanf("%lf", &initial_velocity);
printf("Enter time (s): ");
scanf("%lf", &time);
printf("Enter acceleration (m/s^2): ");
scanf("%lf", &acceleration);
distance = (initial_velocity * time) + (0.5 * acceleration * time * time);
printf("Distance traveled: %.2f meters\n", distance);
}
Output:

Distance Calculation for an Object with Constant Acceleration


Enter initial velocity (m/s): 24
Enter time (s): 15
Enter acceleration (m/s^2): 45
Distance traveled: 5422.50 meters

Write a C Program to Find the maximum of three numbers using conditional operator

#include <stdio.h>
void main()
{
double num1, num2, num3, max;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &num1, &num2, &num3);
max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
printf("The maximum number is: %.2lf\n", max);
}

Output:
Enter three numbers: 654
558
145
The maximum number is: 654.00

Write a C Program to Take marks of 5 subjects in integers, and find the total, average in float

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

Output:
Enter marks for 5 subjects:
Subject 1: 86
Subject 2: 75
Subject 3: 86
Subject 4: 95
Subject 5: 86
Total Marks: 428
Average Marks: 85.60

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

#include <stdio.h>
void main()
{
int num1, num2, num3, num4;
int max, min;
printf("Enter four numbers: ");
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);
max = min = num1;
if (num2 > max)
{
max = num2;
}
else if (num2 < min)
{
min = num2;
}
if (num3 > max)
{
max = num3;
}
else if (num3 < min)
{
min = num3;
}
if (num4 > max)
{
max = num4;
}
else if (num4 < min)
{
min = num4;
}
printf("Maximum number: %d\n", max);
printf("Minimum number: %d\n", min);
}

Output:

Enter four numbers: 75


84
95
486
Maximum number: 486
Minimum number: 75

Write a C program to generate electricity bill.

#include <stdio.h>
void main()
{
double unitRate = 7.5; // Tariff rate per unit (in dollars)
double unitsConsumed;
double totalBill;
printf("Electricity Bill Generator\n");
printf("Enter the number of units consumed: ");
scanf("%lf", &unitsConsumed);
totalBill = unitsConsumed * unitRate;
printf("Electricity Bill: $%.2lf\n", totalBill);
}

Output:

Electricity Bill Generator


Enter the number of units consumed: 476
Electricity Bill: $3570.00
Write a C program to Find the roots of the quadratic equation.

#include <stdio.h>
#include <math.h>
void main()
{
double a, b, c;
double discriminant, root1, root2;
printf("Quadratic Equation Solver\n");
printf("Enter the coefficients (a, b, 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("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
}
else if (discriminant == 0)
{
root1 = -b / (2 * a);
printf("Root = %.2lf\n", root1);
}
else
{
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Root 1 = %.2lf + %.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf - %.2lfi\n", realPart, imaginaryPart);
}
}

Output:
Quadratic Equation Solver
Enter the coefficients (a, b, c): 458
54
56
Root 1 = -0.06 + 0.34i
Root 2 = -0.06 - 0.34i

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


#include <stdio.h>
void main()
{
int choice;
double num1, num2, result;
printf("Calculator Menu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Enter your choice (1/2/3/4): ");
scanf("%d", &choice);
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
switch (choice) {
case 1:
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case 2:
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case 3:
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice. Please enter 1, 2, 3, or 4.\n");
break;
}
}

Output:

Calculator Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1/2/3/4): 1
Enter the first number: 545
Enter the second number: 854
Result: 1399.00

#include <stdio.h>

int main() {
int year;

// Prompt the user to enter a year


printf("Enter a year: ");
scanf("%d", &year);

// Check if it's a leap 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;
}

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

#include <stdio.h>
void 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);
}
}

Output:
Enter a year: 2024
2024 is a leap year.

Write a C program to Find the factorial of given number using any loop.

#include <stdio.h>
void main()
{
int number;
unsigned long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0)
{
printf("Factorial is not defined for negative numbers.\n");
}
else
{
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
printf("Factorial of %d = %llu\n", number, factorial);
}
}

Output:
Enter a positive integer: 64
Factorial of 64 = 9223372036854775808

Write a C Program to Find the given number is a prime or not.

#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

void main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (isPrime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}
}

Output:
Enter a positive integer: 74
74 is not a prime number.

Write a C Program to Compute sine and cos series

#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
void main ( ) {
int angle;
float x,y,z;
angle = 0;
printf("Angle cos(angle)");
while(angle <= MAX) {
x = (PI/MAX)*angle;
y = cos(x);
printf("\n %d %.2lf", angle, y);
angle = angle + 10;
}
}

Output:
Angle cos(angle)
0 1.00
10 0.98
20 0.91
30 0.81
40 0.67
50 0.50
60 0.31
70 0.10
80 -0.10
90 -0.31
100 -0.50
110 -0.67
120 -0.81
130 -0.91
140 -0.98
150 -1.00

Write a C Program to Checking a number palindrome

#include <stdio.h>

int main() {
int number, originalNumber, reverseNumber = 0, remainder;
printf("Enter a number: ");
scanf("%d", &number);
originalNumber = number;
while (number > 0) {
remainder = number % 10;
reverseNumber = reverseNumber * 10 + remainder;
number /= 10;
}
if (originalNumber == reverseNumber) {
printf("%d is a palindrome.\n", originalNumber);
} else {
printf("%d is not a palindrome.\n", originalNumber);
}
}
Output:
Enter a number: 475
475 is not a palindrome.

Write a C program to Construct a pyramid of numbers.

#include <stdio.h>

int main() {
int rows, i, j, number = 1;

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


scanf("%d", &rows);

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


for (j = i; j < rows; j++) {
printf(" ");
}

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


printf("%2d ", number++);
}

for (j = i - 1; j >= 1; j--) {


printf("%2d ", number++);
}

printf("\n");
}

Output:
Enter the number of rows for the pyramid: 4
1
2 3 4
5 6 7 8 9
10 11 12 13 14 15 16
Write a C Program to Find the min and max of a 1-D integer array.

#include <stdio.h>
void main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n]; // Declare an array of size 'n'
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min = arr[0];
int max = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
printf("Minimum element: %d\n", min);
printf("Maximum element: %d\n", max);
}
Output:
Enter the number of elements: 4
Enter the elements of the array:
25
5
5
56
54
Minimum element: 5
Maximum element: 56

Write a C program to Perform linear search on1D array.

#include <stdio.h>

int linearSearch(int arr[], int n, int target) {


for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Return the index where the target element was found
}
}
return -1; // Return -1 if the target element was not found in the array
}

int main() {
int n, target;

// Prompt the user to enter the number of elements in the array


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size 'n'

// Prompt the user to enter the elements of the array


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

// Prompt the user to enter the element to be searched


printf("Enter the element to search for: ");
scanf("%d", &target);

int result = linearSearch(arr, n, target);

if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

Output: Enter the number of elements: 5


Enter the elements of the array:
15
47
54
656
52
Enter the element to search for: 47
Element 47 found at index 1.

Write a C Program to The reverse of a 1D integer array

#include <stdio.h>

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


int start = 0;
int end = n - 1;

while (start < end) {


// Swap elements at the start and end
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

// Move the start and end pointers


start++;
end--;
}
}

int main() {
int n;

// Prompt the user to enter the number of elements in the array


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size 'n'

// Prompt the user to enter the elements of the array


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

// Reverse the array


reverseArray(arr, n);
// Display the reversed array
printf("Reversed array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements of the array:
84
54
52
62
51
Reversed array: 51 62 2 4 84

Write a C Program to find 2’s complement of the given binary number.

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

// Function to perform ones' complement


void onesComplement(char binary[]) {
for (int i = 0; i < strlen(binary); i++) {
if (binary[i] == '0') {
binary[i] = '1';
} else {
binary[i] = '0';
}
}
}

// Function to add 1 to a binary number


void addOne(char binary[]) {
int carry = 1;
for (int i = strlen(binary) - 1; i >= 0; i--) {
if (binary[i] == '0' && carry == 1) {
binary[i] = '1';
carry = 0;
} else if (binary[i] == '1' && carry == 1) {
binary[i] = '0';
}
}
}

int main() {
char binary[32]; // Assume a maximum of 32-bit binary number

// Prompt the user to enter a binary number


printf("Enter a binary number: ");
scanf("%s", binary);

// Perform ones' complement


onesComplement(binary);

// Add 1 to get the two's complement


addOne(binary);

// Display the two's complement


printf("Two's complement: %s\n", binary);

return 0;
}

Output:
Enter a binary number: 5
Two's complement: 1

Write a C Program to Eliminate duplicate elements in an array.

#include <stdio.h>

int main() {
int n;
// Prompt the user to enter the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size 'n'

// Prompt the user to enter the elements of the array


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

// Eliminate duplicate elements


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n;) {
if (arr[i] == arr[j]) {
// Shift elements to overwrite the duplicate
for (int k = j; k < n - 1; k++) {
arr[k] = arr[k + 1];
}
n--; // Reduce the size of the array
} else {
j++;
}
}
}

// Display the array with duplicates removed


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

return 0;
}

Output:

Enter the number of elements: 6


Enter the elements of the array:
145
15
145
25
26
25
Array with duplicates removed: 145 15 25 26

Write a C Program to Addition of two matrices

#include <stdio.h>

int main() {
int row, col, i, j;

// Define the dimensions of the matrices


printf("Enter the number of rows: ");
scanf("%d", &row);
printf("Enter the number of columns: ");
scanf("%d", &col);

// Initialize two matrices


int matrix1[row][col], matrix2[row][col], sum[row][col];

// Input the elements of the first matrix


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

// Input the elements of the second matrix


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

// Add the matrices


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result


printf("The sum of the two matrices is:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d\t", sum[i][j]);
}
printf("\n");
}

return 0;
}

Output:
Enter the number of rows: 2
Enter the number of columns: 1
Enter elements of the first matrix:
54
84
7Enter elements of the second matrix:
5
54
The sum of the two matrices is:
59
138

Write a C Program for Multiplication two matrices

#include <stdio.h>

int main() {
int row1, col1, row2, col2, i, j, k;

// Input the dimensions of the first matrix


printf("Enter the number of rows of the first matrix: ");
scanf("%d", &row1);
printf("Enter the number of columns of the first matrix: ");
scanf("%d", &col1);
// Input the dimensions of the second matrix
printf("Enter the number of rows of the second matrix: ");
scanf("%d", &row2);
printf("Enter the number of columns of the second matrix: ");
scanf("%d", &col2);

// Check if matrix multiplication is possible


if (col1 != row2) {
printf("Matrix multiplication is not possible. Number of columns in the first matrix must be equal to
the number of rows in the second matrix.\n");
return 1;
}

// Initialize matrices
int matrix1[row1][col1], matrix2[row2][col2], result[row1][col2];

// Input elements of the first matrix


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

// Input elements of the second matrix


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

// Initialize the result matrix with zeros


for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
result[i][j] = 0;
}
}

// Multiply the matrices


for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < col1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the result


printf("The result of matrix multiplication is:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}

Output:

Enter the number of rows of the first matrix: 2


Enter the number of columns of the first matrix: 2
Enter the number of rows of the second matrix: 2
Enter the number of columns of the second matrix: 1
Enter elements of the first matrix:
14
18
16
14
Enter elements of the second matrix:
19
16
The result of matrix multiplication is:
554
528
Write a C Program to

#include <stdio.h>

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


int temp;
int swapped;
for (int i = 0; i < n - 1; i++) {
swapped = 0; // Flag to check if any swap is made in this pass

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


if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1; // Set the flag to true
}
}

// If no two elements were swapped in the inner loop, the array is already sorted
if (swapped == 0) {
break;
}
}
}

int main() {
int n;

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


scanf("%d", &n);

int arr[n];

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


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

// Sort the array using bubble sort


bubbleSort(arr, n);

printf("Sorted array in ascending order:\n");


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

Output:
Enter the number of elements in the array: 2
Enter the elements of the array:
4
6
Sorted array in ascending order:
4 6 58

Write a C Program to Concatenate two strings without built-in functions

#include <stdio.h>

void stringConcatenate(char str1[], char str2[]) {


int i, j;

// Find the length of the first string


for (i = 0; str1[i] != '\0'; i++)
;

// Concatenate the second string to the first


for (j = 0; str2[j] != '\0'; j++) {
str1[i] = str2[j];
i++;
}

// Null-terminate the concatenated string


str1[i] = '\0';
}

int main() {
char str1[100], str2[100];

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


scanf("%s", str2);

// Concatenate the two strings


stringConcatenate(str1, str2);

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

return 0;
}

Output:
Enter the first string: 16
Enter the second string: 14
Concatenated string: 1614

Write a C Program to Reverse a string using built-in and without built-in string functions

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

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

// Using built-in string functions to reverse the string


strrev(str);

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

return 0;
}

Without Built-In String Functions:

#include <stdio.h>

void reverseString(char str[]) {


int length = 0;
while (str[length] != '\0') {
length++;
}
int start = 0;
int end = length - 1;

while (start < end) {


char temp = str[start];
str[start] = str[end];
str[end] = temp;

start++;
end--;
}
}

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

// Reverse the string without built-in string functions


reverseString(str);

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

return 0;
}

Output:
Enter a string: 15
Reversed string: 51

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

#include <stdio.h>

#include <stdlib.h>
int main() {

int n;

int *arr;

int sum = 0;

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

scanf("%d", &n);

// Allocate memory for the array

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

if (arr == NULL) {

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

return 1;

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

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

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

sum += arr[i];

// Display the sum of the array

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


// Free the allocated memory

free(arr);

return 0;

Output:

Enter the number of elements in the array: 4

Enter the elements of the array:

16

19

13

17

Sum of the elements in the array: 65

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

#include <stdio.h>

struct Student {

char name[50];

int scores[5]; // Assuming 5 scores per student

};

int main() {

int n;

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

scanf("%d", &n);
// Create an array of Student structures

struct Student students[n];

// Input data for each student

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

printf("Enter the name of student %d: ", i + 1);

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

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

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

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

// Calculate the total and average scores for each student

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

int total = 0;

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

total += students[i].scores[j];

float average = (float)total / 5.0;

printf("Student %d: %s\n", i + 1, students[i].name);

printf("Total Score: %d\n", total);


printf("Average Score: %.2f\n", average);

return 0;

Output:

Enter the number of students: 2

Enter the name of student 1: hgtuhji

Enter scores (5 scores) for student 1: 2

1546

154

454

1545

Enter the name of student 2: bjshhbvghn

Enter scores (5 scores) for student 2: 2

54

51

15

Student 1: hgtuhji

Total Score: 3701

Average Score: 740.20

Student 2: bjshhbvghn

Total Score: 77

Average Score: 15.40


write a C Program Enter n students data using calloc() and display failed students list

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

// Define a structure to represent a student


struct Student {
char name[50];
int rollNumber;
float marks;
};

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

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


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

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

// Input data for each student


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

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


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

printf("Enter the marks of student %d: ", i + 1);


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

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


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

// Free the allocated memory


free(students);

return 0;
}

Output:
Enter the number of students: 2
Enter the name of student 1: nhsbxahsdb
Enter the roll number of student 1: 154789
Enter the marks of student 1: 145956
Enter the name of student 2: njshbjhbh
Enter the roll number of student 2: 266685
Enter the marks of student 2: 26965
List of Failed Students:
26965

Write a C Program Read student name and marks from the command line and display the student
details along with the total.

#include <stdio.h>
#include <conio.h>

int main() {
char studentName[50];
int totalMarks = 0;
int marks;

// Prompt for student name


printf("Enter student name: ");
gets(studentName);

// Loop to input marks


printf("Enter marks for each subject (enter -1 to finish):\n");
do {
printf("Enter marks (or -1 to finish): ");
scanf("%d", &marks);

// Check if marks are not -1 before adding to the total


if (marks != -1) {
totalMarks += marks;
}
} while (marks != -1);

// Display student details along with the total marks


clrscr(); // Clear the screen
printf("Student Name: %s\n", studentName);
printf("Total Marks: %d\n", totalMarks);

getch(); // Wait for a key press before closing the console

return 0;
}
Output:
Usage: /tmp/uvBKgFQOzV.o <name1> <marks1> <name2> <marks2> ...
arun 26548 bhasdj 65894

Write a C program to implement realloc()

#include <stdio.h>

#include <stdlib.h>

void* my_realloc(void* ptr, size_t size) {

if (ptr == NULL) {

// If ptr is NULL, treat it as equivalent to malloc(size)

return malloc(size);

if (size == 0) {

// If size is 0, treat it as equivalent to free(ptr)

free(ptr);

return NULL;

}
// Allocate a new block of memory with the desired size

void* new_ptr = malloc(size);

if (new_ptr == NULL) {

// Allocation failed, return the original pointer

return ptr;

// Copy the contents from the old block to the new block

size_t min_size = size; // Minimum size between old and new block

size_t old_size = *((size_t*)ptr - 1); // Get the size of the old block

if (old_size < size) {

min_size = old_size;

memcpy(new_ptr, ptr, min_size);

// Free the old block

free(ptr);

return new_ptr;

int main() {

// Example usage of my_realloc


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

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

arr[i] = i;

printf("Original array: ");

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

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

printf("\n");

// Resize the array to hold 8 integers

arr = (int*)my_realloc(arr, 8 * sizeof(int));

// Initialize the new elements

for (int i = 5; i < 8; i++) {

arr[i] = i;

printf("Resized array: ");

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

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

printf("\n");
// Free the memory

free(arr);

return 0;

Output:

Original array: 0 10 20

Modified array: 0 10 20 30 40

Write a C program that demonstrates the differences between structures and unions:

#include <stdio.h>

#include <string.h>

// Define a structure to represent a student with name and age

struct Student {

char name[50];

int age;

};

// Define a union to represent a person with name and age

union Person {

char name[50];

int age;

};

int main() {
// Declare and initialize a structure variable

struct Student student;

strcpy(student.name, "John");

student.age = 20;

// Declare and initialize a union variable

union Person person;

strcpy(person.name, "Alice");

// Union can store either a name or an age, not both

person.age = 25;

// Print structure and union values

printf("Student: Name = %s, Age = %d\n", student.name, student.age);

printf("Person: Name = %s, Age = %d\n", person.name, person.age);

return 0;

Output:

Student: Name = John, Age = 20

Person: Name = Alice, Age = 25

Write a C program to shift/rotate using bitfields.

#include <stdio.h>

// Define a structure with bitfields for demonstration

struct BitfieldExample {
unsigned int a : 4; // 4-bit bitfield

unsigned int b : 4; // 4-bit bitfield

};

// Function to display the bitfields

void displayBitfields(struct BitfieldExample bf) {

printf("a: %u, b: %u\n", bf.a, bf.b);

int main() {

struct BitfieldExample bf;

bf.a = 3; // 0011 in binary

bf.b = 6; // 0110 in binary

printf("Original Bitfields:\n");

displayBitfields(bf);

// Perform a left shift on bitfield 'a'

bf.a <<= 2; // Left shift 'a' by 2 positions

printf("After left shift (a <<= 2):\n");

displayBitfields(bf);

// Perform a right shift on bitfield 'b'

bf.b >>= 1; // Right shift 'b' by 1 position

printf("After right shift (b >>= 1):\n");


displayBitfields(bf);

// Perform a bitwise rotation on bitfield 'a'

unsigned int mask = (1 << 4) - 1; // Mask with 4 bits (1111)

bf.a = (bf.a << 2) | ((bf.a >> 2) & mask); // Rotate 'a' left by 2 positions

printf("After bitwise rotation (a rotated left by 2):\n");

displayBitfields(bf);

return 0;

Output:

Original Bitfields:

a: 3, b: 6After left shift (a <<= 2):

a: 12, b: 6

After right shift (b >>= 1):

a: 12, b: 3

After bitwise rotation (a rotated left by 2):

a: 3, b: 3

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

#include <stdio.h>

#include <string.h>

// Define a structure to represent a person

struct Person {

char name[50];
int age;

};

int main() {

// Create two structure variables of the same type

struct Person person1;

struct Person person2;

// Initialize person1

strcpy(person1.name, "Alice");

person1.age = 25;

// Copy the contents of person1 to person2

person2 = person1;

// Display the contents of person1 and person2

printf("Person 1: Name = %s, Age = %d\n", person1.name, person1.age);

printf("Person 2: Name = %s, Age = %d\n", person2.name, person2.age);

return 0;

Output:

Person 1: Name = Alice, Age = 25

Person 2: Name = Alice, Age = 25

Write a C function to calculate NCR value.


#include <stdio.h>

// Function to calculate the factorial of a number

unsigned long long factorial(int n) {

unsigned long long result = 1;

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

result *= i;

return result;

// Function to calculate the N choose R (NCR) value

unsigned long long calculateNCR(int N, int R) {

if (R < 0 || R > N) {

return 0; // Invalid input, NCR is not defined

unsigned long long numerator = factorial(N);

unsigned long long denominator = factorial(R) * factorial(N - R);

return numerator / denominator;

int main() {

int N, R;
printf("Enter the values of N and R: ");

scanf("%d %d", &N, &R);

if (R > N) {

printf("Invalid input: R should be less than or equal to N.\n");

} else {

unsigned long long result = calculateNCR(N, R);

printf("C(%d, %d) = %llu\n", N, R, result);

return 0;

Output:

Enter the values of N and R: 57

48

C(57, 48) = 2

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

#include <stdio.h>

// Function to find the length of a string

int stringLength(const char *str) {

int length = 0;

while (str[length] != '\0') {


length++;

return length;

int main() {

const char *text = "Hello, World!";

int length = stringLength(text);

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

return 0;

Output: The length of the string is: 13

Write a C function to transpose of a matrix.

#include <stdio.h>

// Function to transpose a matrix

void transposeMatrix(int original[][100], int rows, int cols, int transposed[][100]) {

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

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

transposed[j][i] = original[i][j];

}
}

// Function to display a matrix

void displayMatrix(int matrix[][100], int rows, int cols) {

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

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

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

printf("\n");

int main() {

int rows, cols;

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

scanf("%d %d", &rows, &cols);

int originalMatrix[100][100];

int transposedMatrix[100][100];

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

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

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

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

printf("Original Matrix:\n");

displayMatrix(originalMatrix, rows, cols);

// Transpose the matrix

transposeMatrix(originalMatrix, rows, cols, transposedMatrix);

printf("Transposed Matrix:\n");

displayMatrix(transposedMatrix, cols, rows);

return 0;

Output: Enter the number of rows and columns: 1

Enter the elements of the matrix:

16

Original Matrix:

16

Transposed Matrix:

16

Write a C function to demonstrate numerical integration of differential equations using


Euler’s method

#include <stdio.h>
// Function representing the derivative of the function to be integrated

double derivative(double x, double y) {

// Example: dy/dx = x + y

return x + y;

// Function to perform numerical integration using Euler's method

void eulerIntegration(double x0, double y0, double h, double xn) {

double x = x0;

double y = y0;

while (x < xn) {

printf("x = %.4f, y = %.4f\n", x, y);

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

x = x + h;

int main() {

double x0 = 0.0; // Initial x

double y0 = 1.0; // Initial y

double h = 0.1; // Step size

double xn = 2.0; // Final x


printf("Numerical Integration using Euler's Method:\n");

eulerIntegration(x0, y0, h, xn);

return 0;

Output: Numerical Integration using Euler's Method:

x = 0.0000, y = 1.0000

x = 0.1000, y = 1.1000

x = 0.2000, y = 1.2200

x = 0.3000, y = 1.3620

x = 0.4000, y = 1.5282

x = 0.5000, y = 1.7210

x = 0.6000, y = 1.9431

x = 0.7000, y = 2.1974

x = 0.8000, y = 2.4872

x = 0.9000, y = 2.8159

x = 1.0000, y = 3.1875

x = 1.1000, y = 3.6062

x = 1.2000, y = 4.0769

x = 1.3000, y = 4.6045

x = 1.4000, y = 5.1950

x = 1.5000, y = 5.8545

x = 1.6000, y = 6.5899

x = 1.7000, y = 7.4089

x = 1.8000, y = 8.3198
x = 1.9000, y = 9.3318

Write a recursive function to generate Fibonacci series.

#include <stdio.h>

// Recursive function to generate Fibonacci series

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 for the Fibonacci series: ");

scanf("%d", &n);

if (n < 1) {

printf("Invalid input. Please enter a positive integer.\n");

} else {

printf("Fibonacci series for the first %d terms:\n", n);

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

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


}

printf("\n");

return 0;

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

#include <stdio.h>

// Recursive function to calculate the greatest common divisor (GCD)

int gcd(int a, int b) {

if (b == 0) {

return a;

return gcd(b, a % b);

// Recursive function to calculate the least common multiple (LCM)

int lcm(int a, int b) {

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

int main() {

int num1, num2;


printf("Enter two numbers to find their LCM: ");

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

if (num1 <= 0 || num2 <= 0) {

printf("Invalid input. Please enter positive integers.\n");

} else {

int result = lcm(num1, num2);

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

return 0;

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

#include <stdio.h>

unsigned long long factorial(int n) {

if (n == 0) {

return 1; // Base case: 0! is defined as 1

} else {

return n * factorial(n - 1); // Recursive call to find (n-1)!

int main() {

int num;
printf("Enter a non-negative integer to find its factorial: ");

scanf("%d", &num);

if (num < 0) {

printf("Invalid input. Please enter a non-negative integer.\n");

} else {

unsigned long long result = factorial(num);

printf("%d! = %llu\n", num, result);

return 0;

Write a C Program to implement Ackermann function using recursion.

#include <stdio.h>

int ackermann(int m, int n) {

if (m == 0) {

return n + 1;

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

return ackermann(m - 1, 1);

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

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

}
int main() {

int m, n;

printf("Enter values for m and n: ");

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

if (m < 0 || n < 0) {

printf("Invalid input. Please enter non-negative integers.\n");

} else {

int result = ackermann(m, n);

printf("A(%d, %d) = %d\n", m, n, result);

return 0;

Write a recursive function to find the sum of series.

#include <stdio.h>

// Recursive function to find the sum of a series

double seriesSum(int n) {

if (n == 0) {

return 0.0; // Base case: sum of an empty series is 0

} else {

return 1.0 / n + seriesSum(n - 1); // Recursive call for the sum

}
}

int main() {

int terms;

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

scanf("%d", &terms);

if (terms < 0) {

printf("Invalid input. Please enter a non-negative integer.\n");

} else {

double result = seriesSum(terms);

printf("Sum of the series for %d terms: %.4f\n", terms, result);

return 0;

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

#include <stdio.h>

// Function to swap two numbers using call by reference

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

int temp = *a;

*a = *b;

*b = temp;
}

int main() {

int num1, num2;

printf("Enter two numbers to swap: ");

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

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

// Call the swap function to swap num1 and num2

swap(&num1, &num2);

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

return 0;

Demonstrate Dangling pointer problem using a C program.

#include <stdio.h>

#include <stdlib.h>

int main() {

int *danglingPtr;

// Dynamically allocate memory


danglingPtr = (int *)malloc(sizeof(int));

if (danglingPtr == NULL) {

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

return 1;

*danglingPtr = 42; // Assign a value

// Deallocate memory

free(danglingPtr);

// Dangling pointer issue: accessing memory after deallocation

printf("Value of the dangling pointer: %d\n", *danglingPtr);

return 0;

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

#include <stdio.h>

// Function to copy one string into another using pointers

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

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

*dest = *src;

dest++;
src++;

*dest = '\0'; // Null-terminate the destination string

int main() {

char source[] = "Hello, World!";

char destination[50]; // Make sure the destination buffer is large enough

// Call the stringCopy function to copy source into destination

stringCopy(destination, source);

printf("Source: %s\n", source);

printf("Destination: %s\n", destination);

return 0;

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

#include <stdio.h>

#include <ctype.h> // For islower, isupper, isdigit

void countCharacters(const char *str, int *lower, int *upper, int *digits, int *others) {

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

if (islower(*str)) {
(*lower)++;

} else if (isupper(*str)) {

(*upper)++;

} else if (isdigit(*str)) {

(*digits)++;

} else {

(*others)++;

str++;

int main() {

char inputString[100];

int lowercase = 0, uppercase = 0, digitCount = 0, otherCount = 0;

printf("Enter a string: ");

gets(inputString); // Note: gets() is not safe and should be used carefully

countCharacters(inputString, &lowercase, &uppercase, &digitCount, &otherCount);

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

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

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

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


return 0;

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

#include <stdio.h>

int main() {

// Create a file pointer for writing

FILE *file;

// Open a file for writing

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

if (file == NULL) {

printf("Unable to open the file.\n");

return 1;

// Write text to the file

fprintf(file, "Hello, World!\nThis is a sample text.");

// Close the file

fclose(file);

// Reopen the file for reading

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


if (file == NULL) {

printf("Unable to open the file for reading.\n");

return 1;

// Read and print the contents of the file

char ch;

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

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

printf("%c", ch);

// Close the file

fclose(file);

return 0;

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

#include <stdio.h>

#include <string.h>

int main() {

// Create a file pointer for writing


FILE *file;

// Open a binary file for writing

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

if (file == NULL) {

printf("Unable to open the file for writing.\n");

return 1;

// Write text to the binary file

const char text[] = "Hello, World!\nThis is a sample text.";

int textLength = strlen(text);

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

// Close the file

fclose(file);

// Reopen the file for reading

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

if (file == NULL) {

printf("Unable to open the file for reading.\n");

return 1;
}

// Read and print the contents of the binary file

char buffer[100]; // Allocate a buffer to read data

printf("Contents of the binary file:\n");

size_t bytesRead;

while ((bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) {

fwrite(buffer, sizeof(char), bytesRead, stdout); // Print to console

// Close the file

fclose(file);

return 0;

Copy the contents of one file to another file.

#include <stdio.h>

int main() {

FILE *sourceFile, *destinationFile;

char ch;

// Open the source file for reading


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

if (sourceFile == NULL) {

printf("Unable to open the source file for reading.\n");

return 1;

// Open the destination file for writing

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

if (destinationFile == NULL) {

printf("Unable to open the destination file for writing.\n");

fclose(sourceFile); // Close the source file before exiting

return 1;

// Copy the contents from the source file to the destination file

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

fputc(ch, destinationFile);

// Close both files

fclose(sourceFile);

fclose(destinationFile);
printf("File copied successfully.\n");

return 0;

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

#include <stdio.h>

#include <stdlib.h>

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

// Check for the correct number of command-line arguments

if (argc != 4) {

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

return 1;

FILE *file1, *file2, *mergedFile;

char ch;

// Open the first input file for reading

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

if (file1 == NULL) {

printf("Unable to open %s for reading.\n", argv[1]);

return 1;

}
// Open the second input file for reading

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

if (file2 == NULL) {

printf("Unable to open %s for reading.\n", argv[2]);

fclose(file1); // Close the first file before exiting

return 1;

// Open the merged file for writing

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

if (mergedFile == NULL) {

printf("Unable to open %s for writing.\n", argv[3]);

fclose(file1);

fclose(file2);

return 1;

// Copy the contents of the first file to the merged file

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

fputc(ch, mergedFile);

}
// Copy the contents of the second file to the merged file

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

fputc(ch, mergedFile);

// Close all files

fclose(file1);

fclose(file2);

fclose(mergedFile);

printf("Files merged successfully.\n");

return 0;

write a C program to Find no. of lines, words and characters in a file

#include <stdio.h>

int main() {

FILE *file;

char filename[100];

char ch;

int lineCount = 0, wordCount = 0, charCount = 0, inWord = 0;

printf("Enter the name of the file: ");

scanf("%s", filename);
// Open the file for reading

file = fopen(filename, "r");

if (file == NULL) {

printf("Unable to open the file.\n");

return 1;

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

charCount++;

// Count lines

if (ch == '\n') {

lineCount++;

// Count words

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

inWord = 0;

} else if (inWord == 0) {

inWord = 1;

wordCount++;

}
// Close the file

fclose(file);

printf("Number of lines: %d\n", lineCount);

printf("Number of words: %d\n", wordCount);

printf("Number of characters: %d\n", charCount);

return 0;

Write a C program to print last n characters of a given file.

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *file;

char filename[100];

int n, charCount = 0;

char *buffer;

printf("Enter the name of the file: ");

scanf("%s", filename);

printf("Enter the number of characters to print from the end: ");

scanf("%d", &n);
if (n <= 0) {

printf("Invalid input. Please enter a positive number.\n");

return 1;

// Open the file for reading

file = fopen(filename, "r");

if (file == NULL) {

printf("Unable to open the file.\n");

return 1;

// Calculate the file size

fseek(file, 0, SEEK_END);

charCount = ftell(file);

if (charCount < n) {

// If the file is smaller than n characters, print the entire file

n = charCount;

// Allocate memory for the buffer

buffer = (char *)malloc(n + 1);


// Move the file pointer to the appropriate position from the end

fseek(file, -n, SEEK_END);

// Read the last n characters into the buffer

fread(buffer, 1, n, file);

// Null-terminate the buffer

buffer[n] = '\0';

// Close the file

fclose(file);

// Print the last n characters

printf("Last %d characters:\n%s\n", n, buffer);

// Free allocated memory

free(buffer);

return 0;

You might also like