(23CS0502) COMPUTER PROGRAMMING LAB MANUAL
(23CS0502) COMPUTER PROGRAMMING LAB MANUAL
Name : ____________________________________________
Specialization : _____________________________________________
INSTITUTE VISION
To emerge as one of the premier institutions through excellence in education and research,
producing globally competent and ethically strong professionals and entrepreneurs
INSTITUTE MISSION
M1: Imparting high-quality technical and management education through the state-of-
the- art resources.
M2: Creating an eco-system to conduct independent and collaborative research for the
betterment of the society
M3: Promoting entrepreneurial skills and inculcating ethics for the socio-economic
development of the nation.
DEPARTMENT VISION
To impart quality education and research in Computer Science and Engineering for producing
technically competent and ethically strong IT professionals with contemporary knowledge
DEPARTMENT MISSION
M1: Achieving academic excellence in computer science through effective pedagogy,
modern curriculum and state-of-art computing facilities.
M2: Encouraging innovative research in Computer Science and Engineering by
collaborating with Industry and Premier Institutions to serve the nation.
M3: Empowering the students by inculcating professional behavior, strong ethical
values and leadership abilities
Program Outcomes
PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2: Problem Analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to provide
valid conclusions.
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding of the
limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9: Individual and Team Work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE OBJECTIVES
The Objectives of this course:
1. The course aims to give students hands – on experience and train them on the
concepts of the C- programming language.
List of Experiments:
UNIT I
WEEK 1 - Objective: Getting familiar with the programming environment on the computer
and writing the first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()
WEEK 2 - Objective: Getting familiar with how to formally describe a solution to a problem
in a series of finite steps both using textual notation and graphic notation.
Suggested Experiments /Activities:
Tutorial 2: Problem-solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code. Developing the
algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation
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
UNIT II
WEEK 4 - Objective: Explore the full scope of expressions, type-compatibility of variables
& constants and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial 4: Operators and the precedence and as associativity:
Lab 4: 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 - Objective: Explore the full scope of different variants of “if construct” namely if-
else, nullelse, if-else if*-else, switch and nested-if including in what scenario each one of
them can be used and how to use them. Explore all relational and logical operators while
writing conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.
WEEK 6 - Objective: Explore the full scope of iterative constructs namely while loop, do-
while loop and for loop in addition to structured jump constructs like break and continue
including when each of these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
i) Find the factorial of given number using any loop.
ii) Find the given number is a prime or not.
iii) Compute sine and cos series
iv) Checking a number palindrome
UNIT III
WEEK 7 - Objective: Explore the full scope of Arrays construct namely defining and
initializing 1-D and 2-D and more generically n-D arrays and referencing individual array
elements from the defined array. Using integer 1-D arrays, explore search solution linear
search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7: 1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.
WEEK 8 - Objective: Explore the difference between other arrays and character arrays that
can be used as Strings by using null character and get comfortable with string by doing
experiments that will reverse a string and concatenate two strings. Explore sorting solution
bubble sort using integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions
UNIT IV
WEEK 9 - Objective: Explore pointers to manage a dynamic array of integers, including
memory allocation & value initialization, resizing changing and reordering the contents of an
array and memory de-allocation using malloc (), calloc (), realloc () and free () functions.
Gain experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory 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 - Objective: Experiment with C Structures, Unions, bit fields and self-referential
structures (Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10: Bitfields, linked lists Read and print a date using dd/mm/yyyy format using bit-fields
and differentiate the same without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the same
type.
UNIT V
WEEK 11 - Objective: Explore the Functions, sub-routines, scope and extent of variables,
doing some experiments by parameter passing using call by value. Basic methods of
numerical integration.
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent.
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations
using Euler’s method
WEEK 13 - Objective: Explore the basic difference between normal and pointer variables,
Arithmetic operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
Lab 13: Simple functions using Call by reference, Dangling pointers.
i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other characters
using pointers.
WEEK 14 - Objective: To understand data files and file handling with various file I/O
functions. Explore the differences between text and binary files.
Suggested Experiments/Activities:
Tutorial 14: File handling
Lab 14: File operations
i) Write a C program to write and read text into a file.
ii) Write a C program to write and read text into a binary file using fread() and fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line
arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.
INDEX
Page Faculty
S.No. Name of the experiment
No. Signature
10
11
12
13
14
Objective: Getting familiar with the programming environment on the computer and writing
the first program
i) Aim: TO Basic Linux environment and its editors like Vi, Vim & Emacs
1. Vi: Vi is one of the oldest and most basic text editors available on Unix-like systems. It has
two modes: command mode and insert mode. To open a file in Vi, you typically use the
command vi filename. Here are some basic commands:
i: Enter insert mode (for editing).
Esc: Return to command mode.
:w: Save changes.
:q: Quit Vi.
:wq: Save and quit.
2. Vim (Vi Improved): Vim is an enhanced version of Vi, retaining its basic functionality
but adding numerous features and improvements. Vim is known for its extensibility and
efficient text editing. You can open Vim with the command vim filename. Some basic
commands:
i: Enter insert mode.
Esc: Return to normal mode.
:w: Save changes.
:q: Quit Vim.
:wq: Save and quit.
3. Emacs: Emacs is a highly extensible text editor with its own ecosystem of extensions and
plugins. It's known for its powerful features and customization options. To open Emacs, you
use the command emacs filename. Some basic commands:
Ctrl + X, Ctrl + S: Save changes.
Ctrl + X, Ctrl + C: Quit Emacs.
Ctrl + K: Cut text (kill).
Ctrl + Y: Paste text (yank).
Ctrl + S: Search forward.
Ctrl + R: Search backward.
Turbo C was a popular Integrated Development Environment (IDE) and compiler for the
C and C++ programming languages developed by Borland. It was widely used during the
MS-DOS era and was known for its ease of use. Here are some key points about Turbo C:
IDE: Turbo C provided an integrated development environment that included a code editor,
compiler, debugger, and other tools in a single package.
DOS Environment: Turbo C was primarily designed for MS-DOS (Microsoft Disk Operating
System) environments. It utilized a text-based interface.
Ease of Use: Turbo C was known for its simplicity and user-friendly interface, making it
accessible to beginners.
Graphics Support: It included libraries for graphics programming, which was a significant
feature at the time for creating simple graphical applications and games.
Legacy: Turbo C is considered a legacy compiler and is not commonly used for modern
development due to its outdated technology and lack of support for modern operating
systems.
2. GCC (GNU Compiler Collection):
PROGRAM:
#include <stdio.h>
void main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.\n", age);
}
Expected Input:
Enter your age: 43
Expected Output:
You are 43 years old.
Actual Input:
Actual Output:
Result:
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
PROGRAM:
#include<stdio.h>
void main()
{
int num1, num2, num3;
float sum, average;
printf("Enter three numbers separated by spaces: ");
scanf("%d %d %d", &num1, &num2, &num3);
sum=num1+num2+num3;
average=sum/3;
printf("Sum of three number %.2lf", sum);
printf("Average: %.2lf\n", average);
}
Expected Input:
Enter three numbers separated by spaces: 2 2 2
Expected Output:
Sum of three number 6.00 Average: 2.00
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
void main()
{
float celsius, fahrenheit;
printf("\n Enter Temp in Fahrenheit : ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit-32) / 1.8;
printf("\n Temperature in Celsius : %.2f ", celsius);
}
Expected Input:
Enter Temp in Fahrenheit: 98
Expected Output:
Temperature in Celsius: 36.67
Actual Input:
Actual Output:
Result:
PROGRAM:
# include <stdio.h>
void main()
{
int principal, rate, time, interest;
printf("Enter the principal: ");
scanf("%d", &principal);
printf("Enter the rate: ");
scanf("%d", &rate);
printf("Enter the time: ");
scanf("%d", &time);
interest = principal * rate * time / 100;
printf("The Simple interest is %d", interest);
Expected Input:
Enter the principal: 5000
Enter the rate: 2
Enter the time: 12
Expected Output:
The Simple interest is 1200
Actual Input:
Actual Output:
Result:
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.
if (number < 0) {
printf("Square root is not defined for negative numbers.\n");
} else {
squareRoot = sqrt(number);
printf("The square root of %.2lf is %.2lf\n", number, squareRoot);
}
return 0;
}
Expected Input:
Enter a number: 25
Expected Output:
The square root of 25.00 is 5.00
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
void main()
{
float principle, rate, time, CI;
printf("Enter principle (amount): ");
scanf("%f", &principle);
printf("Enter time: ");
scanf("%f", &time);
printf("Enter rate: ");
scanf("%f", &rate);
CI = principle* (pow((1 + rate / 100), time));
printf("Compound Interest = %.2f", CI);
}
Expected Input:
Enter principle (amount): 50000
Enter time: 1
Enter rate: 2
Expected Output:
Compound Interest = 51000.00
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
#include <math.h>
void main()
{
float sideOne, sideTwo, sideThree, s, area;
printf("Enter the length of three sides of triangle\n");
scanf("%f %f %f", &sideOne,&sideTwo, &sideThree);
s = (sideOne + sideTwo + sideThree)/2;
area = sqrt(s*(s-sideOne)*(s-sideTwo)*(s-sideThree));
printf("Area of triangle : %0.4f\n", area);
}
Expected Input:
Expected Output:
Area of triangle: 2.9047
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
void main()
{
float speed, time, distance;
printf("Enter the speed (in meters per second): ");
scanf("%f", &speed);
printf("Enter the time (in seconds): ");
scanf("%f", &time);
distance = speed * time;
printf("Distance traveled: %.2f meters\n", distance);
}
Expected Input:
Enter the speed (in meters per second): 60
Enter the time (in seconds): 10
Expected Output:
Distance traveled: 600.00 meters
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
char operator;
double A, B, C, D, E, F, G, J;
int i;
switch (operator)
{
case 'a':
printf("Enter the values of A, B, C, D, E, F, and G separated by spaces: ");
scanf("%lf %lf %lf %lf %lf %lf %lf", &A, &B, &C, &D, &E, &F, &G);
J = A + B * C + (D * E) + F * G;
printf("Result: %.2lf\n", J);
break;
case 'b':
printf("Enter the values of A, B, and D separated by spaces: ");
scanf("%lf %lf %lf", &A, &B, &D);
J = (A / B) * C - B + (A * D / 3);
printf("Result: %.2lf\n", J);
break;
case 'c':
printf("Enter the values of A and B: ");
scanf("%lf %lf", &A, &B);
J = (A++) + (++B);
printf("Result: %.2lf\n", J);
break;
case 'd':
printf("Enter the initial value of i: ");
scanf("%d", &i);
J = (i++) + (++i);
printf("Result: %d\n", i);
break;
default:
printf("Invalid operator!\n");
break;
}
return 0;
}
Expected Input:
Expected Output:
Result: 69.00
Result: 3.67
Actual Input:
Actual Output:
Result:
ii) To write a C program to find the maximum of three numbers using conditional operator
PROGRAM:
#include<stdio.h>
void main()
{
int a, b, c, big ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
}
Expected Input:
Enter three numbers : 10
90
60
Expected Output:
The biggest number is : 90
Actual Input:
Actual Output:
Result:
iii) Aim: To write a C program to take marks of 5 subjects in integers, and find the total,
average in float
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;
}
Expected Input:
Enter marks of five subjects: 55 80 90 70 60
Expected Output:
Total marks = 355.00
Average marks = 71.00
Percentage = 71.00
Actual Input:
Actual Output:
Result:
i) Aim: To write a C program to write a C program to find the max and min of four numbers
using if-else
PROGRAM:
#include<stdio.h>
int main ()
{
int num1, num2, num3, num4;
int minimum;
printf("Enter 4 numbers here...\n");
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);
minimum = num1;
if (num2 < minimum)
{
minimum = num2;
}
if (num3 < minimum)
{
minimum = num3;
}
if (num4 < minimum)
{
minimum = num4;
}
printf("%d minimum number:", minimum);
if(num1>num2&&num1>num3&&num1>num4)
{
printf("(num1) is maximum %d", num1);
}
else if(num2>num3&&num2>num4)
{
printf(" (num2) is maximum %d",num2);
}
else if(num3>num4)
{
printf("(num3) is maximum %d", num3);
}
else
{
printf("(num4) is maximum %d", num4);
}
return 0;
}
Expected Input:
Enter 4 numbers here...
4
5
6
1
Expected Output:
1 minimum number: (num3) is maximum 6
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
printf("Enter total units consumed: ");
scanf("%d", &unit);
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
return 0;
}
Expected Input:
Enter total units consumed: 1000
Expected Output:
Electricity Bill = Rs. 1614.00
Actual Input:
Actual Output:
Result:
iii) Aim: To write a C program to find the roots of the quadratic equation
PROGRAM:
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
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("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart,
imagPart, realPart, imagPart);
}
return 0;
Expected Input:
Enter coefficients a, b and c:
2.3
4
5.6
Expected Output:
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (op)
{
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
Expected Input:
Enter an operator (+, -, *, /): /
Enter two operands: 6
5
Expected Output:
6.0 / 5.0 = 1.2
Actual Input:
Actual Output:
Result:
v) Aim: To write a C program to find the given year is a leap year or not
PROGRAM:
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 400 == 0)
{
printf("%d is a leap year.", year);
}
else if (year % 100 == 0)
{
printf("%d is not a leap year.", year);
}
else if (year % 4 == 0)
{
printf("%d is a leap year.", year);
}
else
{
printf("%d is not a leap year.", year);
}
return 0;
}
Expected Input:
Enter a year: 1900
Expected Output:
1900 is not a leap year
Actual Input:
Actual Output:
Result:
i) Aim: To write a C program to find the factorial of given number using any loop
PROGRAM:
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Expected Input:
Enter a number: 6
Expected Output:
Factorial of 6 is: 720
Actual Input:
Actual Output:
Result:
ii) Aim: To write a C program to find the given number is a prime or not
PROGRAM:
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if(n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
Expected Input:
Expected Output
29 is a prime number
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
void main()
{
int angle;
float x,y;
angle = 0;
printf("Angle cos(angle)");
while(angle <= MAX)
{
x = (PI/MAX)*angle;
y = cos(x);
printf("%15d %13.4f", angle, y);
angle = angle + 10;
}
}
Expected Input:
Expected Output:
Angle cos(angle)
0 1.0000 10 0.9781 20 0.9135 30 0.8090 40 0.6691 50 0.5000 60 0.3090 70 0.1045
80 -0.1045 90 -0.3090 100 -0.5000 110 -0.6691 120 -0.8090 130 -0.9135 140 -0.9781
150 -1.0000
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while(n!= 0)
{
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
Expected Input:
Enter an integer: 1001
Expected Output
1001 is a palindrome
Actual Input:
Actual Output:
Result:
PROGRAM:
#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;
}
Expected Input:
Enter the number of rows: 5
Expected Output:
1
232
34543
4567654
567898765
Actual Input:
Actual Output:
Result:
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D
and 2-D and more generically n-D arrays and referencing individual array elements from the
defined array. Using integer 1-D arrays, explore search solution linear search.
i) Aim: To write a C program Find the min and max of a 1-D integer array
PROGRAM:
#include <stdio.h>
int main()
{
int a[1000],i,n,min,max;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
return 0;
}
Expected Input:
Enter size of the array : 5
Enter elements in array : 10 20 90 50 60
Expected Output:
minimum of array is : 10
maximum of array is : 90
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
int array[100], search, c, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for ( c = 0 ; c < number ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
for ( c = 0 ; c < number ; c++ )
{
if ( array[c] == search ) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if ( c == number )
printf("%d is not present in array.\n", search);
return 0;
}
Expected Input:
Enter the number of elements in array 5
Enter 5 numbers 12 23 22 10 45
Enter the number to search
22
Expected Output:
22 is present at location 3.
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
int main()
{
int i,j,n,a[10],m,o,b[10];
printf("\nEnter the Limit:");
scanf("%d",&n);
printf("\nEnter the values:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nGiven values are:");
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
for(i=0;i<n;i++)
{
b[i]=a[n-i-1];
}
printf("\nReverse values are :");
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,b[i]);
}
return 0;
}
Expected Input:
Enter the Limit:5
Enter the values:1 2 3 4 5
Given values are:
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
Expected Output:
Reverse values are :
a[0]=5
a[1]=4
a[2]=3
a[3]=2
a[4]=1
Actual Input:
Actual Output:
Result:
iv) Aim: To write a C program to find 2’s complement of the given binary number
PROGRAM:
#include<stdio.h>
#define SIZE 8
int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1];
int i, carry=1;
printf("Enter %d bit binary value: ", SIZE);
gets(binary);
for(i=0; i<SIZE; i++)
{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[SIZE] = '\0';
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
printf("Original binary = %s\n", binary);
printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n", twosComp);
return 0;
}
Expected Input:
Enter 8 bit binary value: 01101100
Original binary = 01101100
Expected output:
Ones complement = 10010011
Twos complement = 10010100
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[50],i,j,k, count = 0, dup[50], number;
printf("Enter size of the array :");
scanf("%d",&number);
printf("Enter Elements of the array:");
for(i=0;i<number;i++)
{
scanf("%d",&a[i]);
dup[i] = -1;
}
printf("Entered element are:");
for(i=0;i<number;i++)
{
printf("%d ",a[i]);
}
for(i=0;i<number;i++)
{
for(j = i+1; j < number; j++)
{
if(a[i] == a[j])
{
for(k = j; k <number; k++)
{
a[k] = a[k+1];
}
j--;
number--;
}
}
}
Expected Output:
After deleting the duplicate element, the Array is:
1243567
Actual Input:
Actual Output:
Result:
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.
PROGRAM:
#include <stdio.h>
int main()
{
int a[3][3], b[3][3], result[3][3];
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
{
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
{
scanf("%d", &b[i][j]);
}
}
printf("\n");
}
return 0;
}
Expected Input:
Enter elements of 1st matrix
Enter elements of 1st matrix
123456789
Enter elements of 2nd matrix
1 2 3 4 5 6 7 8 9 10
Expected Output:
Sum Of Matrix:
2 4 6
8 10 12
14 17 19
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first 3*3 matrix element: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat1[i][j]);
}
printf("Enter second 3*3 matrix element: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat2[i][j]);
}
printf("\nMultiplying two matrices...");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum=0;
for(k=0; k<3; k++)
sum = sum + mat1[i][k] * mat2[k][j];
mat3[i][j] = sum;
}
}
printf("\nMultiplication result of the two given Matrix is: \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d\t", mat3[i][j]);
printf("\n");
}
getch();
return 0;
}
Expected Input:
Expected Output:
30 24 18
84 69 54
138 114 90
Actual Input:
Actual Output:
Result:
iii) Aim: To write a C program to sort array elements using bubble sort
PROGRAM:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
Expected Input:
Enter the value of num 5
Enter the elements one by one 6 2 4 3
Expected Output:
Sorted array is...1 2 3 4 6 8
Actual Input:
Actual Output:
Result:
iv) Aim: To write a C program to concatenate two strings without built in functions
PROGRAM:
#include<stdio.h>
void main()
{
char str1[50],str2[50];
static int i=0;
int j=0;
printf("\nEnter First String\n");
gets(str1);
printf("\nEnter Second String\n");
gets(str2);
while(str1[i]!='\0')
{
i++;
}
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
Expected Input:
Enter First String
SIETK
Enter Second String
Puttur
Expected Output:
Concatenated String is SIETKPuttur
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Expected Input:
Enter string: javatpoint
String is: javatpoint
Expected Output:
Reverse String is: tnioptavaj
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int limit;
int i;
int sum;
printf("Enter limit of the array: ");
scanf("%d", &limit);
ptr = (int*)malloc(limit * sizeof(int));
for (i = 0; i < limit; i++)
{
printf("Enter element %02d: ", i + 1);
scanf("%d", (ptr + i));
Expected Input:
Expected Output:
Actual Input:
Actual Output:
Result:
ii) Aim: To write a C program to find the total, average of n students using structures
PROGRAM:
#include <stdio.h>
#include <conio.h>
struct student
{
int rollno,tot;
char name[25];
int mark[5];
};
void main()
{
struct student s[5];
int i,n,j;
clrscr();
printf(“Enter the number of students:”);
scanf(“%d”,&n);
printf(“\t*Students Records*\n”);
//take input from user
for(i=0;i<n;i++)
{
printf("\nEnter Student Roll Number: ");
scanf("%d",&s[i].rollno);
printf("\nEnter Student name: ");
scanf("%s",s[i].name);
printf("\nEnter Student 3 subject's marks: ");
for(j=0;j<3;j++)
scanf("%d",&s[i].mark[j]);
}
for(i=0;i<n;i++)
{
s[i].tot=0;
for(j=0;j<3;j++)
s[i].tot = s[i].tot+ s[i].mark[j];
}
for(i=0;i<n;i++)
{
printf("\t*Students Records*\n");
printf("\n==================================\n");
printf("\nStudent's Roll no. – %d", s[i].rollno);
printf("\nStudent's Name – %s", s[i].name);
printf("\nStudent's Total Marks – %d", s[i].tot);
}
getch();
}
Expected Input:
Enter the number of students 1
Rollno :5
Name:Ravi
Total Marks:270
Expected Output:
Rollno :5
Name:Ravi
Total Marks:270
Actual Input:
Actual Output:
Result:
iii) Aim: To write a C program to enter n students data using calloc() and display failed
students list
PROGRAM:
# include <string.h>
# include <stdio.h>
struct student
{
char name[10];
int m[3];
int total;
char result[5];
} *p,*s;
void main()
{
int i,j,l,n;
clrscr();
printf("Enter the no. of students : ");
scanf("%d",&n);
p=(struct student*)malloc(n*sizeof(struct student));
s=p;
for(i=0;i<n;i++)
{
printf("Enter a name : ");
scanf("%s",&p->name);
p-> total=0;l=0;
for(j=0;j<3;j++)
{
printf("Enter Marks of %d Subject : ",j+1);
scanf("%d",&p->m[j]);
if((p->m[j])>100)
{
printf("Wrong Value Entered");
goto one;
}
p->total+=p->m[j];
if(p->m[j]<40)
l=1;
}
if(l==0)
strcpy(p->result,"PASS");
else
strcpy(p->result,"FAIL");
p++;
}
for(i=0;i<n;i++)
{
printf("\n%s\t%s",s->name,s->result);
s++;
}
getch();
}
Expected Input:
Enter the no.of students:1
Enter a name:Dinesh
Enter marks of 1 subject:75
Enter marks of 2 subject:65
Enter marks of 3 subject:86
Expected Output:
Dinesh Pass
Actual Input:
Actual Output:
Result:
iv) Aim: To write a C program to read student name and marks from the command line
and display the student details along with the total.
PROGRAM:
#include <stdio.h>
int main()
{
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for (i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Expected Input:
Expected Output:
For student1
Enter name: Ram
Enter marks: 60
For student2
Enter name: Kumar
Enter marks: 68
Actual Input:
Actual Output:
Result:
Result
i) Aim: To Create and display a singly linked list using self -referential structure
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1;
second->data = 2;
third->data = 3;
head->next = second;
second->next = third;
third->next = NULL;
struct node *current = head;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
return 0;
}
Expected Output:1 2 3
Actual Output:
Result:
ii) Aim: To Demonstrate the differences between structures and unions using a C
program
PROGRAM:
struct myStructure
{
int myNum;
char myLetter;
};
int main()
{
struct myStructure s1;
s1.myNum = 13;
s1.myLetter = 'B';
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Expected Output:
My number:13
My letter:B
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int number, rotate, Msb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--)
{
Msb = (number >> size) & 1;
number = (number << 1) | Msb;
}
printf("After Left rotation the value is = %d",number);
return 0;
}
Expected Input:
Enter any number:6
Enter number of rotations:3
Expect Output:
After Left rotation the value is = 48
Actual Output
Actual Output:
Result:
iv)Aim: To Write a c program to copy one structure variable to another structure of the
same type.
PROGRAM:
#include <stdio.h>
struct Student
{
char name[50];
int age;
double gpa;
};
int main()
{
struct Student student1;
struct Student student2;
strcpy(student1.name, "murali");
student1.age = 35;
student1.gpa = 8.75;
student2 = student1;
printf("Student 2:\n");
printf("Name: %s\n", student2.name);
printf("Age: %d\n", student2.age);
printf("GPA: %.2lf\n", student2.gpa);
return 0;
}
Expected Input &Output:
Student 2:
Name: murali
Age: 35
GPA: 8.75
Result:
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical
integration
PROGRAM:
#include <stdio.h>
int fact(int z);
void main()
{
int n, r, nCr;
printf("Enter the value of n and r?");
scanf("%d %d",&n,&r);
nCr = fact(n) / (fact(r) * fact(n - r));
printf("\nnCr = %d", nCr);
}
int fact(int z)
{
int f = 1, i;
if (z == 0)
{
return(f);
}
else
{
for (i = 1; i <= z; i++)
{
f = f * i;
}
}
return(f);
}
Expected Input:
Enter the value of n and r : 5 3
Expected Output:
ncr = 10
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i;
Expected Input:
Expected Output: 18
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
int main()
{
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10][10];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Expected Input :
Enter the number of rows : 2
Enter the numbers of columns : 2
Enter the elements of the matrix : 1 2 3 4
Expected Output:
The Transposed matrix is :
1 2
3 4
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
#include<math.h>
double f(double x, double y)
{
return -2*x-y;
}
void main()
{
int i;
double y,xi,yi,xf,h;
printf("Enter the initial condition for y: ");
scanf("%lf",&yi);
printf("Enter the initial condition for x: ");
scanf("%lf",&xi);
printf("Enter the value of x for which y is required: ");
scanf("%lf",&xf);
printf("Enter the step-width h: ");
scanf("%lf",&h);
printf("x\t\ty\t\ty'\t\thy'\t\ty+hy'\n");
printf("_______________________________________________________________\n");
while(xi<xf)
{
y=yi+h*f(xi,yi);
printf("%lf\t%lf\t%lf\t%lf\t%lf\n",xi,yi,f(xi,yi),h*f(xi,yi),y);
yi=y;
xi=xi+h;
}
printf("%lf\t%lf\n",xi,yi);
printf("_______________________________________________________________\n");
printf("The value of y is %lf\n\n",y);
}
Expected Input:
Enter the initial condition for y:5
Enter the initial condition for x:6
Enter the value of x for which y is required: 5
Enter the step-width h: 7
Expected Output:
x y y1 hy1 y+hy1
…………………………………………………………………………….
6.000000 5.000000
………………………………………………………………………………
Actual Input:
Actual Output:
Result:
PROGRAM:
# include<stdio.h>
int main ()
{
int n1=0, n2=1, n3, i, number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
Expected Input:
Enter the number of elements: 5
Expected Output:
0 1 1 2 3
Actual Input:
Actual Output:
Result:
Expected Input:
Enter the two numbers : 2 5
Expected Output:
The LCM of 2 and 5 is 10.
Actual Input :
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
int main ()
{
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
if (n < 0)
{
printf("Error! Factorial of a negative number doesn't exist.");
}
else
{
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
Expected Input:
Enter an Integer: 10
Expected output:
Factorial of 10 = 3628800
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
int fun (int m, int n);
void main ()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\output :: %d\n", fun(m,n));
}
Expected Input:
Expected Output:
Actual Input:
Actual Output:
Result:
PROGRAM:
#include<stdio.h>
int main()
{
int n , i;
int sum=0;
printf("Enter the n i.e. max values of series: ");
scanf("%d",&n);
sum = (n * (n + 1)) / 2;
printf("Sum of the series: ");
for (i =1;i <= n;i++)
{
if (i!=n)
printf("%d + ",i);
else
printf("%d = %d ",i,sum);
}
return 0;
}
Expected Input:
Enter the n i.e max value of series : 5
Expected output:
Actual Input:
Actual Output :
Result:
Objective: Explore the basic difference between normal and pointer variables, Arithmetic
operations using pointers and passing variables to functions using pointers
i) Aim: Write a C program to Swap two numbers using call by Reference.
PROGRAM:
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
Expected Input:
Enter the value of x and y = 5 9
Expected Output:
Before Swapping, x = 5 and y = 9
After Swapping, x = 9 and y = 5
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
*ptr = 10;
free(ptr);
printf("%d", *ptr);
return 0;
}
Result:
iii) Aim: To write a C program to Copy one string into another using pointer.
PROGRAM:
#include<stdio.h>
void copystring(char *a, char *b);
int main()
{
char *str1="CODING";
char str2[10];
copystring(str1,str2);
printf("%s",str2);
return 0;
}
void copystring(char *a, char *b)
{
while(*a!='\0')
{
*b++=*a++;
}
b="\0";
}
Expected Input & Output:
CODING
Result:
iv) Aim: To Write a C program to find no of low case, upper case, digits end other
characters using pointers.
PROGRAM:
#include <stdio.h>
#include <ctype.h>
int main()
{
char inputString[100];
printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);
int lowercaseCount = 0;
int uppercaseCount = 0;
int digitCount = 0;
int otherCount = 0;
// Create a pointer to the inputString
char *ptr = inputString;
// Traverse the string using a pointer
while (*ptr != '\0')
{
if (islower(*ptr))
{
lowercaseCount++;
} else if (isupper(*ptr))
{
uppercaseCount++;
} else if (isdigit(*ptr))
{
digitCount++;
} else if (!isspace(*ptr))
{
otherCount++;
}
ptr++;
}
return 0;
}
Result:
Objective: To understand data files and file handling with various file I/O functions. Explore
the differences between text and binary files.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *file;
char text[100];
file = fopen("example.txt", "w");
if (file == NULL)
{
printf("Error opening the file for writing.\n");
return 1;
}
printf("Enter text to write to the file:\n");
fgets(text, sizeof(text), stdin);
fprintf(file, "%s", text);
fclose(file);
file = fopen("example.txt", "r");
if (file == NULL)
{
printf("Error opening the file for reading.\n");
return 1;
}
printf("\nContents of the file:\n");
while (fgets(text, sizeof(text), file) != NULL)
{
printf("%s", text);
}
fclose(file);
}
Expected Input:
Enter text to write to the file:
welcome to sietk
Expected Output:
Contents of the file:
welcome to sietk
Actual Input:
Actual Output:
Result:
ii) Aim: To Write a C program to write and read text into a binary file using fread()
and fwrite()
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE *file;
char text[100];
file = fopen("binary_example.dat", "wb");
if (file == NULL)
{
printf("Error opening the binary file for writing.\n");
return 1;
}
printf("Enter text to write to the binary file:\n");
fgets(text, sizeof(text), stdin);
size_t textLength = strlen(text);
fwrite(text, sizeof(char), textLength, file);
fclose(file);
file = fopen("binary_example.dat", "rb");
if (file == NULL)
{
printf("Error opening the binary file for reading.\n");
return 1;
}
printf("\nContents of the binary file:\n");
size_t bytesRead;
while ((bytesRead = fread(text, sizeof(char), sizeof(text), file)) > 0)
{
fwrite(text, sizeof(char), bytesRead, stdout);
}
fclose(file);
}
Expected Input:
Enter text to write to the binary file: Welcome
Expected Output:
Welcome
Actual Input:
Actual Output:
Result:
iii) Aim: To write a C program to copy the contents of one file to another file
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;
printf("Enter the source file name: ");
scanf("%s", sourceFileName);
sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL)
{
printf("Error opening the source file.\n");
return 1;
}
printf("Enter the destination file name: ");
scanf("%s", destinationFileName);
destinationFile = fopen(destinationFileName, "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("File copied successfully.\n");
}
Actual Input:
Actual Output:
Result:
iv) Aim: To Write a C program to merge two files into the third file using command-
line arguments.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
if (argc != 4)
{
printf("Usage: %s <input_file1> <input_file2> <output_file>\n", argv[0]);
return 1;
}
FILE *file1, *file2, *outputFile;
char ch;
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);
}
outputFile = fopen(argv[3], "w");
if (outputFile == NULL)
{
printf("Error opening %s for writing.\n", argv[3]);
fclose(file1);
fclose(file2);
return 1;
}
while ((ch = fgetc(file1)) != EOF)
{
fputc(ch, outputFile);
}
while ((ch = fgetc(file2)) != EOF) {
fputc(ch, outputFile);
}
fclose(file1);
fclose(file2);
fclose(outputFile);
printf("Files %s and %s merged into %s successfully.\n", argv[1], argv[2], argv[3]);
}
Actual Input:
Actual Output:
Result:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *file;
char filename[100];
char ch;
int lines = 0, words = 0, characters = 0;
int inWord = 0;
printf("Enter the filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL)
{
printf("Error opening the file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF)
{
characters++;
if (ch == '\n')
{
lines++;
}
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
{
inWord = 0;
}
else if (inWord == 0)
{
inWord = 1;
words++;
}
}
fclose(file);
printf("Lines: %d\n", lines);
printf("Words: %d\n", words);
printf("Characters: %d\n", characters);
}
Expected Input:
Enter the filename: sietk.c
Expected Output:
Lines:39
Words:109
Character :838
Actual Input;
Actual Output:
Result:
#include <stdio.h>
#include <stdlib.h>
void printLastNChars(FILE *file, int n)
{
if (file == NULL || n <= 0)
{
printf("Invalid input.\n");
return;
}
fseek(file, 0, SEEK_END);
long fileLength = ftell(file)
for (long i = fileLength - 1; i >= 0 && n > 0; i--)
{
fseek(file, i, SEEK_SET);
char c = fgetc(file);
if (c != EOF)
{
putchar(c);
n--;
}
}
fclose(file);
}
int main()
{
FILE *file;
char filename[100];
int n;
printf("Enter the filename: ");
scanf("%s", filename);
printf("Enter the number of characters to print from the end: ");
scanf("%d", &n);
file = fopen(filename, "r");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}
printf("Last %d characters from the file '%s':\n", n, filename);
printLastNChars(file, n);
return 0;
}
Actual Input:
Actual Output:
Result: