0% found this document useful (0 votes)
4 views104 pages

Computer Programming Lab Record

The document outlines a Computer Programming Lab curriculum focusing on familiarization with the Linux programming environment and various programming tools such as Turbo C and GCC. It includes practical exercises for writing, compiling, and executing C programs, along with algorithms for basic computations like temperature conversion and simple interest calculation. The document serves as a comprehensive guide for students to learn programming fundamentals in a structured manner.

Uploaded by

rc.pro.c333
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)
4 views104 pages

Computer Programming Lab Record

The document outlines a Computer Programming Lab curriculum focusing on familiarization with the Linux programming environment and various programming tools such as Turbo C and GCC. It includes practical exercises for writing, compiling, and executing C programs, along with algorithms for basic computations like temperature conversion and simple interest calculation. The document serves as a comprehensive guide for students to learn programming fundamentals in a structured manner.

Uploaded by

rc.pro.c333
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/ 104

COMPUTER

PROGRAMMING LAB
BTECH-R23-JNTU-GV

BY
CH. RAMACHANDRA REDDY
CSE-DEPARTMENT
CHAITANYA ENGINEERING COLLEGE
Page |1

LAB1: Familiarization With Programming Environment

i) AIM: Basic Linux environment and its editors like Vi, Vim & Emacs etc.
Introduction to Linux: Linux is a widely-used, open-source operating system.
In programming, it is known for its stability, security, and powerful tools for
software development. This lab focuses on the basics of the Linux environment,
which is essential for coding in languages like C.

File and Directory Operations:


 pwd (Print Working Directory):
Displays the full path of the current directory.
 ls (List Files):
Lists the files and directories in the current directory.
o ls -l displays detailed information (permissions, owner, size).
o ls -a displays hidden files (starting with).
 cd (Change Directory):
Used to navigate between directories.
 mkdir (Make Directory):
Creates a new directory.
 rmdir (Remove Directory):
Deletes an empty directory.
 rm (Remove File):
Deletes files or directories.
 cp (Copy File/Directory):
Copies files or directories from one location to another.
 mv (Move/Rename File):
Moves or renames files or directories.
 touch (Create Empty File):
Creates a new empty file.

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |2

Editors in Linux: Text editors are essential tools for writing code. You will
explore editors like:
Vi/Vim: A highly customizable text editor, ideal for coding in a terminal.

Steps to Write, Compile, and Execute a C Program Using vi Editor:


Step 1: Open vi editor and create a new file.
1. Open the terminal and navigate to the directory where you want to create
your C program file.
2. Use the vi command to create a new C program file:
$ vi program.c
This will open the vi editor with the new file named program.c.
Step 2: Enter Insert Mode to Write Code.
1. Press i to enter Insert Mode.
2. Type your C program.
Step 3: Save and Exit vi.
1. Once you've finished typing the program, press Esc to exit Insert Mode.
2. To save the file and exit the editor,
3. type: :wq-This command writes the file (saves) and quits the vi editor.
Step 4: compilation & execution Using cc (C Compiler)
cc is usually an alias for gcc on many Linux systems, but sometimes, it points to
a different C compiler. You can compile your program using cc as follows:
$ cc program.c.
Step 5: Execute the Program Using a.out
To run the program, type the following command:
$ ./a.out

Emacs: Another powerful text editor, with more built-in features and
extensibility options.

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |3

ii) AIM: Exposure to Turbo C, gcc


1. Turbo C
Turbo C is an older C compiler originally developed by Borland. It became
quite popular in the 1990s, especially in educational institutions, due to its
simplicity and an integrated development environment (IDE). Despite its age,
it's still taught in some courses for familiarity, though it's not widely used in
modern development environments.
Key Features of Turbo C:
 Integrated IDE: Combines an editor, compiler, and debugger in one.
 Simple to use, with an old-style graphical interface.
 Mainly designed for DOS-based systems, though versions exist for
Windows.
Working with Turbo C:
1. Installing Turbo C:
o You can download Turbo C or Turbo C++ from sites that provide
legacy software. Some versions run on DOSBox, an x86 emulator
for running old DOS programs on modern operating systems like
Windows.
2. Writing a Program:
o Open Turbo C, create a new file, and write your C program.
3. Compiling and Running the Program:
o Press Alt + C to compile.
o Press Ctrl + F9 to run the program.
o The output will be displayed in the output window.
Limitations of Turbo C:
 Outdated and no longer maintained.
 Limited to 16-bit DOS programs.
 Not suitable for modern operating systems or large-scale projects.

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |4

2. GCC (GNU Compiler Collection)


GCC is a modern and widely used compiler that supports multiple
programming languages, including C. It is part of the GNU Project and is open-
source, making it the de facto compiler for C and C++ development on Unix-
like systems, including Linux and macOS.
Key Features of GCC:
 Cross-platform: Available on Linux, macOS, and Windows (via MinGW
or Cygwin).
 Powerful optimization and debugging features.
 Can compile code for multiple architectures, Constantly updated and
maintained.
Working with GCC:
1. Installing GCC:
o On Linux, GCC is usually pre-installed. If not, you can install it
using the package manager:
 Ubuntu/Debian: sudo apt-get install gcc
 Fedora: sudo dnf install gcc
o On Windows, you can install GCC via MinGW or use
environments like Cygwin.
2. Writing and Compiling a Program:
Write your program in any text editor (like vi, vim, nano, or gedit).
 To compile the program, open the terminal and run:
gcc program.c -o program
 Running the Program: After compiling, you can execute the
program with: ./program
Advantages of GCC:
 Actively maintained and widely used in modern systems.
 Supports advanced features and optimizations.
 Handles larger programs and projects, Cross-platform and open-source.

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |5

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

PROGRAM-1:
AIM: To write a program that prints a greeting message using printf().

ALGORITHM:
1. Start the program.
2. Use printf() to display a greeting message.
3. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Print a greeting message
printf("Hello, welcome to the world of C programming!\n");
return 0;
}

OUTPUT:
Hello, welcome to the world of C programming!

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |6

PROGRAM-2:
AIM: To write a program that reads an integer from the user and prints it.

ALGORITHM:
1. Start the program.
2. Declare an integer variable.
3. Use printf() to print the user for input.
4. Use scanf() to read an integer from the user and store it in the variable.
5. Use printf() to print the entered integer.
6. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
int number;
// Print the user for an integer
printf("Enter an integer: ");
// Read the integer input
scanf("%d", &number);
// Print the entered integer
printf("You entered: %d\n", number);
return 0;
}

OUTPUT:
Enter an integer: 25
You entered: 25

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |7

LAB 2: Converting algorithms/flow charts into C Source code.

i) AIM: Sum and average of 3 numbers

ALGORITHM:
1. Start the program .
2. Declare three float variables for the numbers and two float variables for
the sum and average.
3. Use printf() to print the user for the first number.
4. Use scanf() to read the first number.
5. Repeat steps 3 and 4 for the second and third numbers.
6. Calculate the sum of the three numbers.
7. Calculate the average by dividing the sum by 3.
8. Use printf() to display the sum and average.
9. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables
float num1, num2, num3, sum, average;
// Print user to enter three numbers
printf("Enter the first number: ");
scanf("%f", &num1);
printf("Enter the second number: ");
scanf("%f", &num2);
printf("Enter the third number: ");
scanf("%f", &num3);

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |8

// Calculate the sum of the three numbers


sum = num1 + num2 + num3;
// Calculate the average of the three numbers
average = sum / 3;
// Print the sum and average
printf("Sum of the three numbers: %.2f\n", sum);
printf("Average of the three numbers: %.2f\n", average);
return 0;
}

OUTPUT:
Enter the first number: 5.5
Enter the second number: 10.0
Enter the third number: 15.0
Sum of the three numbers: 30.50
Average of the three numbers: 10.17

COMPUTER PROGRAMMING LAB BY: CH.RCR


Page |9

ii) AIM: Conversion of Fahrenheit to Celsius and vice versa


ALGORITHM:
1. Start the program.
2. Declare variables for temperature in Celsius and Fahrenheit.
3. Use printf() to print the user for the temperature and the type of
conversion (F to C or C to F).
4. Use scanf() to read the input temperature and conversion choice.
5. Perform the conversion based on the user's choice:
o Celsius to Fahrenheit: F = C * 9/5 + 32
o Fahrenheit to Celsius: C = (F - 32) * 5/9
6. Use printf() to display the converted temperature.
7. End the program.

SOURCE CODE: [METHOD-1]


//CONVERSION OF [TEMPERATURE] FARENHEIT TO CELSIUS & VICE
VERSA
#include<stdio.h>
int main()
{
float fahrenheit,celsius;
//insertion of temperature parameters in fahrenheit degree
printf("ENTER TEMPERATURE IN FAHRENHEIT:");
scanf("%f",&fahrenheit);
//conversion of Fahrenheit to celsius formula
celsius = (fahrenheit - 32)*5/9;
printf("\nAFTER CONVERSION OF FAHRENHEIT %f TO CELSIUS
IS: %f",fahrenheit, celsius);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 10

//insertion of temperature parameters in celsius degree


printf("\n\nENTER TEMPERATURE IN CELSIUS:");
scanf("%f",&celsius);
//conversion of celsius to fahrenheit formula
fahrenheit = (1.8 * celsius) + 32;
printf("\nAFTER CONVERSION OF CELSIUS %f TO FAHRENHEIT
IS: %f",celsius,fahrenheit);

return 0;
}

OUTPUT:
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.00

(Choice 2 - Fahrenheit to Celsius):


Enter temperature in Fahrenheit: 98.6
Temperature in Celsius: 37.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 11

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables for temperature
float temperature, convertedTemperature;
int choice;
// Print user to choose conversion type
printf("Choose conversion type:\n");
printf("1. Celsius to Fahrenheit\n");
printf("2. Fahrenheit to Celsius\n");
printf("Enter your choice (1 or 2): ");
scanf("%d", &choice);
if (choice == 1) {
// Celsius to Fahrenheit
printf("Enter temperature in Celsius: ");
scanf("%f", &temperature);
convertedTemperature = (temperature * 9/5) + 32;
printf("Temperature in Fahrenheit: %.2f\n", convertedTemperature);
} else if (choice == 2) {
// Fahrenheit to Celsius
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &temperature);
convertedTemperature = (temperature - 32) * 5/9;
printf("Temperature in Celsius: %.2f\n", convertedTemperature);
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 12

else {
printf("Invalid choice.\n");
} return 0;
}

OUTPUT:
Choose conversion type:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice (1 or 2): 1
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.00

(Choice 2 - Fahrenheit to Celsius):


Enter your choice (1 or 2): 2
Enter temperature in Fahrenheit: 98.6
Temperature in Celsius: 37.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 13

iii) AIM: Simple interest calculation


ALGORITHM:
1. Start the program.
2. Declare variables for principal, rate, time, and interest.
3. Use printf() to print the user for the principal amount, rate of interest, and
time period.
4. Use scanf() to read the input values.
5. Calculate the simple interest using the formula: Interest = (Principal *
Rate * Time) / 100
6. Use printf() to display the calculated interest.
7. End the program.

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables for principal, rate, time, and interest
float principal, rate, time, interest;
// Print user for principal amount
printf("Enter the principal amount: ");
scanf("%f", &principal);
// Print user for rate of interest
printf("Enter the rate of interest (in percent): ");
scanf("%f", &rate);
// Print user for time period
printf("Enter the time period (in years): ");
scanf("%f", &time);
// Calculate simple interest
interest = (principal * rate * time) / 100;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 14

// Print the calculated interest


printf("Simple Interest: %.2f\n", interest);
return 0;
}

OUTPUT:
Enter the principal amount: 1000
Enter the rate of interest (in percent): 5
Enter the time period (in years): 2
Simple Interest: 100.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 15

Lab 3: Simple computational problems using arithmetic expressions.

i) AIM: Finding the square root of a given number

SOURCE CODE:
#include <stdio.h>
#include <math.h> // For the sqrt() function
int main() {
// Declare variable to store the input number and result
double number, squareRoot;
// Print user to enter a number
printf("Enter a number to find its square root: ");
scanf("%lf", &number);
// Calculate the square root of the number
squareRoot = sqrt(number);
// Print the square root
printf("Square root of %.2lf is: %.2lf\n", number, squareRoot);

return 0;
}

OUTPUT:
Enter a number to find its square root: 16
Square root of 16.00 is: 4.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 16

ii) AIM: Finding compound interest

SOURCE CODE:
#include <stdio.h>
#include <math.h>
int main() {
// Initialize variables for the principal amount, interest rate, time,
// No. of compounding periods, compound interest (CI), and final amount (A)
double principle, rate, time, n, CI, A;
// Print the user to enter the principal amount
printf("Enter the principal amount: ");
// Take the principal amount as input
scanf("%lf", &principle);
// Print the user to enter an annual interest rate in percentage (for example, 5%
for five years).
printf("Enter the annual interest rate (e.g., for 5%%, enter 5): ");
// Take the annual interest rate as input
scanf("%lf", &rate);
// Convert the entered interest rate to a decimal
rate = rate / 100;
// Print the user to enter the time in years
printf("Enter the time (in years): ");
// Take the time as input
scanf("%lf", &time);
// Print the user to enter the number of times that interest is compounded per
year

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 17

printf("Enter the number of times that interest is compounded annually: ");


// Take the number of compounding periods as input
scanf("%lf", &n);
// Calculate the final amount after time 't' with compound interest
A = principle * pow((1 + rate / n), n * time);
// Calculate the compound interest by subtracting the principal from the final
amount
CI = A - principle;
// Print the compound interest
printf("The compound interest is: %.2lf\n", CI);

return 0;
}

OUTPUT:
Enter the principal amount: 1000
Enter the annual interest rate (e.g., for 5%, enter 5): 8
Enter the time (in years): 6
Enter the number of times that interest is compounded annually: 4
The compound interest is: 608.44

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 18

iii) AIM: Area of a triangle using Heron’s Formulae

SOURCE CODE:
#include <stdio.h>
#include <math.h> // For the sqrt() function
int main() { // Declare variables for the sides of the triangle and the area
double a, b, c, s, area;
// Print user for the lengths of the sides of the triangle
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); // Calculate the semi-perimeter
s = (a + b + c) / 2;
// Calculate the area using Heron's Formula
area = sqrt(s * (s - a) * (s - b) * (s - c)); // Print the area of the triangle
printf("Area of the triangle: %.2lf\n", area);
return 0;
}

OUTPUT:
Enter the length of side a: 5
Enter the length of side b: 6
Enter the length of side c: 7
Area of the triangle: 14.70

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 19

iv) AIM: Distance travelled by an object

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables for speed, time, and distance
double speed, time, distance;
// Prompt user for speed of the object
printf("Enter the speed of the object (in km/h): ");
scanf("%lf", &speed);
// Prompt user for time of travel
printf("Enter the time of travel (in hours): ");
scanf("%lf", &time);
// Calculate the distance travelled using the formula
distance = speed * time;
// Print the distance travelled
printf("Distance travelled: %.2lf km\n", distance);
return 0;
}

OUTPUT:
Enter the speed of the object (in km/h): 60
Enter the time of travel (in hours): 3
Distance travelled: 180.00 km

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 20

LAB 4: Simple computational problems using “OPERATOR’S” the 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)

ALGORITHM:
Step 1: Declare A,B,C,D,E,F,G,i,j.
Step 2: Read A,B,C,D,E,F,G,i,j Values.
Step 3: Evaluate the below expressions
result_a = A + B * C + (D * E) + F * G.
result_b = A / B * C - B + A * D / 3.
result_c = A++ + ++B - --A.
J = (i++) + (++i).
Step 4: Print result_a,result_b,result_c,j
Step 5: Exit or terminate the program.

SOURCE CODE:
#include <stdio.h>
int main()
{
int A = 5, B = 10, C = 2, D = 7, E = 3, F = 4, G = 6;
int i = 5, j , result_a, result_b, result_c;
// a. Evaluate A+B*C+(D*E) + F*G
result_a = A + B * C + (D * E) + F * G;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 21

printf("a. Result of expression A+B*C+(D*E) + F*G is: %d\n", result_a);


// b. Evaluate A/B*C-B+A*D/3
result_b = A / B * C - B + A * D / 3;
printf("b. Result of expression A/B*C-B+A*D/3 is: %d\n", result_b);
// c. Evaluate A+++B---A
result_c = A++ + ++B - --A;
printf("c. Result of expression A+++B---A is: %d\n", result_c);
// d. Evaluate J = (i++) + (++i)
j = (i++) + (++i);
printf("d. Value of J after J = (i++) + (++i) is: %d\n",
j); return 0;
}

OUTPUT:
a.Result of expression A+B*C+(D*E) + F*G is: 70
b.Result of expression A/B*C-B+A*D/3 is:1
c.Result of expression A+++B---A is:11
d.Value of J after J = (i++) + (++i) is:12

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 22

ii) AIM: Find the maximum of three numbers using conditional operator

ALGORITHM:
1. Start
2. Input three numbers a, b, and c.
3. Use the conditional operator to compare the numbers:
o Compare a with b. If a is greater, compare a with c. Otherwise,
compare b with c.
4. The result of the conditional expression will give the maximum of the
three numbers.
5. Output the maximum number.
6. End

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables
int a, b, c, max;
// Input three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
// Find the maximum using conditional operator
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
// Output the maximum number
printf("The maximum of the three numbers is: %d\n", max);
return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 23

OUTPUT:
Enter three numbers: 10 25 15
The maximum of the three numbers is: 25

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 24

iii) AIM: Take marks of 5 subjects in integers, and find the total, average in
float

ALGORITHM:
1. Start
2. Declare variables to store marks of 5 subjects, the total, and the average.
3. Input the marks of 5 subjects.
4. Calculate the total by summing up the marks of all subjects.
5. Calculate the average by dividing the total by 5.
6. Display the total as an integer.
7. Display the average as a floating-point number.
8. End

SOURCE CODE:
#include <stdio.h>
int main() {
// Declare variables to store marks, total, and average
int sub1, sub2, sub3, sub4, sub5, total;
float average;
// Input marks of 5 subjects
printf("Enter the marks of 5 subjects: ");
scanf("%d %d %d %d %d", &sub1, &sub2, &sub3, &sub4, &sub5);
// Calculate total marks
total = sub1 + sub2 + sub3 + sub4 + sub5;
// Calculate average
average = total / 5.0;
// Output total and average
printf("Total Marks: %d\n", total);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 25

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


return 0;
}

OUTPUT:
Enter the marks of 5 subjects: 85 90 78 92 88
Total Marks: 433
Average Marks: 86.60

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 26

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

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

SOURCE CODE:
#include<stdio.h>
int main()
{
// Declare variables to store four numbers
int a1,a2,a3,a4,max,min;
// Prompt user to input four numbers
printf("Input four numbers: \n");
scanf("%d %d %d %d",&a1,&a2,&a3,&a4);
// Find the maximum among the four numbers
if (a1 >= a2 && a1 >= a3 && a1 >= a4)
max = a1;
else if (a2 >= a1 && a2 >= a3 && a2 >= a4)
max = a2;
else if (a3 >= a1 && a3 >= a2 && a3 >= a4)
max = a3;
else
max = a4;
// Find the minimum among the four numbers
if (a1 <= a2 && a1 <= a3 && a1 <= a4)
min = a1;
else if (a2 <= a1 && a2 <= a3 && a2 <= a4)
min = a2;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 27

else if (a3 <= a1 && a3 <= a2 && a3 <= a4)


min = a3;
else
min = a4;
// Calculate and display the difference between max and min
printf("MAXIMUM is %d\n",max);
printf("MINIMUM is %d\n",min);
return 0;
}

OUTPUT:
Input four numbers:
1
2
3
4
MAXIMUM is 4
MINIMUM is 1

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 28

ii) AIM: Write a C program to generate electricity bill.

ALGORITHM:
1. Start the program.
2. Declare variables to store the number of units consumed and the bill
amount.
3. Prompt the user to input the number of electricity units consumed.
4. Read the input value using scanf().
5. Apply the slab rates:
o If the units are ≤ 50, calculate the bill at ₹3.50 per unit.
o If the units are between 51 and 150, calculate the bill for the first
50 units at ₹3.50, and the remaining units at ₹4.00 per unit.
o If the units are > 150, calculate the bill for the first 50 units at
₹3.50, the next 100 units at ₹4.00, and the remaining units at ₹5.00
per unit.
6. Display the final bill amount using printf().
7. End the program.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 29

SOURCE CODE:
// Program to generate an electricity bill
#include <stdio.h> // This header file is used for input-output functions such as
printf() and scanf()

int main() {
// Declare variables
int units; // 'units' is an integer variable to store the number of electricity
units consumed
float billAmount; // 'billAmount' is a floating-point variable to store the final
bill amount

// Get the number of units consumed


printf("Enter the number of electricity units consumed: ");
// Prompt the user to input the number of units consumed
scanf("%d", &units); // Read the integer input and store it in the variable
'units'
// Calculate bill based on the slab system
/* The slab system:
- First 50 units @ ₹3.50 per unit
- Next 100 units @ ₹4.00 per unit (units 51 to 150)
- Above 150 units @ ₹5.00 per unit
*/
if (units <= 50) {
// If units are less than or equal to 50, multiply units by ₹3.50 per unit
billAmount = units * 3.50;
} else if (units <= 150) {
// If units are between 51 and 150, calculate for first 50 units at ₹3.50,
// then calculate remaining units (units - 50) at ₹4.00 per unit

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 30

billAmount = (50 * 3.50) + ((units - 50) * 4.00);


} else {
// If units are greater than 150, calculate for first 50 units at ₹3.50,
// next 100 units at ₹4.00, and the remaining units (units - 150) at ₹5.00
billAmount = (50 * 3.50) + (100 * 4.00) + ((units - 150) * 5.00);
}

// Output the calculated bill amount


// Display the bill amount using '%.2f' to show the result up to 2 decimal
places
printf("Electricity bill for %d units is: ₹%.2f\n", units, billAmount);

return 0; // End of the program


}

OUTPUT-1:
Enter the number of electricity units consumed: 45
Electricity bill for 45 units is: ₹157.50

OUTPUT-2:
Enter the number of electricity units consumed: 170
Electricity bill for 170 units is: ₹665.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 31

iii) AIM: Find the roots of the quadratic equation.

ALGORITHM:
1. Start the program.
2. Declare variables to store coefficients a, b, c, discriminant, and the roots.
3. Prompt the user to input the coefficients of the quadratic equation.
4. Read the input values using scanf().
5. Calculate the discriminant D=b2−4acD = b^2 - 4acD=b2−4ac.
6. Use the value of discriminant to determine the nature of roots:
o If D>0D > 0D>0, the roots are real and different.
o If D=0D = 0D=0, the roots are real and equal.
o If D<0D < 0D<0, the roots are imaginary (complex).
7. Compute the roots using the quadratic formula.
8. Display the roots based on the discriminant value.
9. End the program.

SOURCE CODE:
// Program to find the roots of a quadratic equation
#include <stdio.h> // This header file is used for input-output functions like
printf() and scanf()
#include <math.h> // This header file provides the sqrt() function for square
root calculations
int main() {
// Declare variables to store coefficients and roots
float a, b, c; // Coefficients of the quadratic equation
float discriminant, root1, root2, realPart, imaginaryPart;

// Get the coefficients from the user

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 32

printf("Enter coefficients a, b, and c: ");

// Prompt the user to enter values of a, b, and c


scanf("%f %f %f", &a, &b, &c); // Read three floating-point values and store
them in a, b, and c
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Determine the nature of the roots based on the discriminant
if (discriminant > 0) {
// If discriminant is positive, the roots are real and different
root1 = (-b + sqrt(discriminant)) / (2 * a); // First root
root2 = (-b - sqrt(discriminant)) / (2 * a); // Second root
printf("Roots are real and different: root1 = %.2f, root2 = %.2f\n", root1,
root2);
} else if (discriminant == 0) {
// If discriminant is zero, the roots are real and equal
root1 = -b / (2 * a); // Both roots are the same
printf("Roots are real and equal: root1 = root2 = %.2f\n", root1);
} else {
// If discriminant is negative, the roots are imaginary (complex)
realPart = -b / (2 * a); // Real part of the complex root
imaginaryPart = sqrt(-discriminant) / (2 * a); // Imaginary part
printf("Roots are complex: root1 = %.2f + %.2fi, root2 = %.2f - %.2fi\n",
realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0; // End of the program
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 33

OUTPUT-1:
Enter coefficients a, b, and c: 1 -3 2
Roots are real and different: root1 = 2.00, root2 = 1.00

OUTPUT-2:
Enter coefficients a, b, and c: 1 -2 1
Roots are real and equal: root1 = root2 = 1.00

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 34

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

SOURCE CODE:
// C program to simulate a calculator using switch case
#include <stdio.h> // Includes standard input-output functions
int main() { // Declare two float variables to store the numbers, and a variable to
store the result
float num1, num2, result;
char operator; // Declare a character variable to store the operator
// Prompt the user to enter the numbers
printf("Enter two numbers: ");
// Read the input values from the user
scanf("%f %f", &num1, &num2);
// Ask the user to enter the operator for the operation
printf("Enter an operator (+, -, *, /): ");
// Read the operator
scanf(" %c", &operator); // Notice the space before %c to avoid reading
newline
// Use switch to perform the operation based on the input operator
switch (operator) {
case '+':
result = num1 + num2; // Addition of num1 and num2
printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result); // Print
result
break;

case '-':
result = num1 - num2; // Subtraction of num2 from num1

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 35

printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result); // Print


result
break;

case '*':
result = num1 * num2; // Multiplication of num1 and num2
printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result); // Print
result
break;

case '/':
if (num2 != 0) { // Ensure the denominator is not zero
result = num1 / num2; // Division of num1 by num2
printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result); // Print
result
}
else {
printf("Error! Division by zero is not allowed.\n"); // Error message
for division by zero
}
break;

default:
printf("Error! Invalid operator.\n"); // If the user enters an invalid
operator
break;
}
return 0; // End of the program
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 36

OUTPUT-1:
Enter two numbers: 5 3
Enter an operator (+, -, *, /): +
Result: 5.00 + 3.00 = 8.00
OUTPUT-2:
Enter two numbers: 10 4
Enter an operator (+, -, *, /): -
Result: 10.00 - 4.00 = 6.00
OUTPUT-3:
Enter two numbers: 6 7
Enter an operator (+, -, *, /): *
Result: 6.00 * 7.00 = 42.00
OUTPUT-4:
Enter two numbers: 9 3
Enter an operator (+, -, *, /): /
Result: 9.00 / 3.00 = 3.00
OUTPUT-5:
Enter two numbers: 5 0
Enter an operator (+, -, *, /): /
Error! Division by zero is not allowed.
OUTPUT-6:
Enter two numbers: 8 2
Enter an operator (+, -, *, /): &
Error! Invalid operator.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 37

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

SOURCE CODE:
// Program to check whether a given year is a leap year or not
#include <stdio.h> // Standard input-output header file
int main() {
int year; // Declare an integer variable to store the year
// Prompt the user to enter a year
printf("Enter a year: ");
// Read the input year from the user
scanf("%d", &year);
// Check if the year is a leap year
// A leap year is divisible by 4 and not divisible by 100 unless it is divisible
by 400
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
printf("%d is a leap year.\n", year); // Print if it is a leap year
} else {
printf("%d is not a leap year.\n", year); // Print if it is not a leap year
}
return 0; // End of the program
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 38

OUTPUT-1 (Leap Year):


Enter a year: 2020
2020 is a leap year.

OUTPUT-2 (Not a Leap Year):


Enter a year: 2021
2021 is not a leap year.

OUTPUT-3 (Century Year - Leap Year):


Enter a year: 2000
2000 is a leap year.

OUTPUT-4 (Century Year - Not a Leap Year):


Enter a year: 1900
1900 is not a leap year.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 39

Lab 6: Iterative problems e.g., the sum of series - Loops, while and for loops.

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

SOURCE CODE:
// Program to find the factorial of a given number using a loop
#include <stdio.h> // Standard input-output header file
int main() {
int number; // Declare an integer variable to store the input number
int factorial = 1; // Initialize factorial to 1
// Prompt the user to enter a positive integer
printf("Enter a positive integer: ");
// Read the input number from the user
scanf("%d", &number);

// Check if the input number is negative


if (number < 0) {
printf("Error! Factorial of a negative number doesn't exist.\n");
} else {
// Calculate factorial using a for loop
for (int i = 1; i <= number; ++i) {
factorial *= i; // Multiply factorial by i
}
// Print the factorial of the given number
printf("Factorial of %d = %d\n", number, factorial);
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 40

return 0; // End of the program


}

OUTPUT-1:
Enter a positive integer: 5
Factorial of 5 = 120

OUTPUT-2 (Zero):
Enter a positive integer: 0
Factorial of 0 = 1

OUTPUT-3 (Negative Integer):


Enter a positive integer: -3
Error! Factorial of a negative number doesn't exist.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 41

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

SOURCE CODE:
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
} // flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 42

OUTPUT-1:
Enter a positive integer: 29
29 is a prime number.

OUTPUT-2:
Enter a positive integer: 10
10 is not a prime number.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 43

iii) AIM: Compute sine and cos series

ALGORITHM:
1. Start.
2. Input the angle in degrees.
3. Convert the angle to radians.
4. Calculate sine and cosine using their respective series expansions:
o Sine series: sin⁡(x)=x−x33!+x55!−x77!+…\sin(x) = x -
\frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} +
\dotssin(x)=x−3!x3+5!x5−7!x7+…
o Cosine series: cos⁡(x)=1−x22!+x44!−x66!+…\cos(x) = 1 -
\frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} +
\dotscos(x)=1−2!x2+4!x4−6!x6+…
5. Output the results.
6. End.

SOURCE CODE:
#include <stdio.h>
#include <math.h> // For M_PI and pow

int main() {
double angle_degrees, angle_radians;
double sine_value = 0.0, cosine_value = 1.0;
int terms, i;
double term;

// Input the angle in degrees


printf("Enter the angle in degrees: ");
scanf("%lf", &angle_degrees);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 44

// Input the number of terms for the series


printf("Enter the number of terms: ");
scanf("%d", &terms);
// Convert the angle from degrees to radians
angle_radians = angle_degrees * (M_PI / 180.0);

// Sine series expansion


for (i = 1; i <= terms; i++) {
term = pow(angle_radians, 2 * i - 1) / (1.0);
for (int j = 1; j <= 2 * i - 1; j++) {
term /= j; // Calculating factorial in the loop
}
if (i % 2 == 0) {
sine_value -= term;
} else {
sine_value += term;
}
}
// Cosine series expansion
for (i = 1; i <= terms; i++) {
term = pow(angle_radians, 2 * i) / (1.0);
for (int j = 1; j <= 2 * i; j++) {
term /= j; // Calculating factorial in the loop
}
if (i % 2 == 0) {
cosine_value += term;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 45

} else {
cosine_value -= term;
}
}
// Output the results
printf("Sine(%lf) = %lf\n", angle_degrees, sine_value);
printf("Cosine(%lf) = %lf\n", angle_degrees, cosine_value);

return 0;
}

OUTPUT-1:
Enter the angle in degrees: 30
Enter the number of terms: 5
Sine(30.000000) = 0.500000
Cosine(30.000000) = 0.866025

OUTPUT-2:
Enter the angle in degrees: 45
Enter the number of terms: 5
Sine(45.000000) = 0.707107
Cosine(45.000000) = 0.707107

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 46

iv) AIM: Checking a number palindrome

SOURCE CODE:
#include <stdio.h>
int main() {
int number, original_number, remainder, reversed_number = 0;
// Input the number
printf("Enter a number: ");
scanf("%d", &number);
// Store the original number for comparison later
original_number = number;
// Reverse the digits of the number
while (number != 0) {
remainder = number % 10;
reversed_number = reversed_number * 10 + remainder;
number /= 10;
}
// Check if the original number is equal to the reversed number
if (original_number == reversed_number) {
printf("%d is a palindrome.\n", original_number);
} else {
printf("%d is not a palindrome.\n", original_number);
}

return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 47

Output-1:
Enter a number: 121
121 is a palindrome.

Output-2:
Enter a number: 123
123 is not a palindrome.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 48

v) AIM: Construct a pyramid of numbers.

SOURCE CODE:
#include <stdio.h>
int main()
{ int rows, i, j, space, number;
// Input the number of rows for the pyramid
printf("Enter the number of rows: ");
scanf("%d", &rows);
// Outer loop for each row
for (i = 1; i <= rows; i++) {
// Print spaces before the numbers
for (space = 1; space <= rows - i; space++) {
printf(" ");
}
// Print numbers in increasing order
number = 1;
for (j = 1; j <= i; j++) {
printf("%d ", number);
number++;
}
// Move to the next line after each row
printf("\n");
}
return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 49

OUTPUT-1:
[For input of 5 rows:]
1
12
123
1234
12345

OUTPUT-2:
[For input of 3 rows:]
1
12
123

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 50

Lab 7: 1D Array manipulation, linear search

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

SOURCE CODE:
#include <stdio.h>
int main() {
int n, i, min, max;
// Asking for the number of elements in the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Initialize min and max with the first element of the array
min = arr[0];
max = arr[0];
// Loop to find the min and max
for(i = 1; i < n; i++) {
if(arr[i] < min) {
min = arr[i]; // Update min
}
if(arr[i] > max) {
max = arr[i]; // Update max

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 51

}
}
// Displaying the results
printf("Minimum element: %d\n", min);
printf("Maximum element: %d\n", max);
return 0;
}

OUTPUT-1:
Enter the number of elements in the array: 5
Enter the elements of the array:
12 4 56 1 23
Minimum element: 1
Maximum element: 56

OUTPUT-2:
Enter the number of elements in the array: 3
Enter the elements of the array:
9 18 3
Minimum element: 3
Maximum element: 18

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 52

ii) AIM: Perform linear search on1D array.

ALGORITHM:
1. Start.
2. Declare an array and necessary variables.
3. Input the number of elements and the elements of the array.
4. Ask the user to input the element to search for.
5. Traverse the array:
o If the element is found, display its position (starting from 0).
o If the element is not found after checking all elements, display a
message indicating that the element is not present in the array.
6. End.

SOURCE CODE:
#include <stdio.h>
int main() {
int n, i, search, found = 0;

// Asking for the number of elements in the array


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

int arr[n];

// Input the elements of the array


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

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 53

// Asking for the element to search


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

// Linear search algorithm


for(i = 0; i < n; i++) {
if(arr[i] == search) {
printf("Element %d found at array index %d.\n", search, i);
found = 1; // Element found
break;
}
}

// If the element is not found in the array


if(!found) {
printf("Element %d not found in the array.\n", search);
}

return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 54

OUTPUT-1:
Enter the number of elements in the array: 6
Enter the elements of the array:
10 25 30 45 50 75
Enter the element to search: 45
Element 45 found at array index 3.

OUTPUT-2:
Enter the number of elements in the array: 4
Enter the elements of the array:
5 8 12 16
Enter the element to search: 20
Element 20 not found in the array.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 55

Lab 8: Matrix problems, String operations, Bubble sort

i) AIM: A C program to perform addition, multiplication of two matrices.

SOURCE CODE:
#include <stdio.h>
int main() {
int i, j, k, rows, cols;
// Input rows and columns
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int mat1[rows][cols], mat2[rows][cols], sum[rows][cols],
product[rows][cols];
// Input elements of first matrix
printf("Enter elements of the first matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &mat1[i][j]);
}
}
// Input elements of second matrix
printf("Enter elements of the second matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &mat2[i][j]);
}
}
// Matrix addition

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 56

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


for (j = 0; j < cols; j++) {
sum[i][j] = mat1[i][j] + mat2[i][j];
}
}
// Matrix multiplication
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
product[i][j] = 0;
for (k = 0; k < cols; k++) {
product[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
// Display sum of matrices
printf("Sum of the matrices:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", sum[i][j]);
}
printf("\n");
}
// Display product of matrices
printf("Product of the matrices:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", product[i][j]);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 57

}
printf("\n");
}

return 0;
}

OUTPUT:
Enter the number of rows and columns: 2 2
Enter elements of the first matrix:
12
34
Enter elements of the second matrix:
56
78
Sum of the matrices:
6 8
10 12
Product of the matrices:
19 22
43 50

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 58

ii) AIM: Sort array elements using BUBBLE-SORT.

ALGORITHM:
1. Start.
2. Declare an array and necessary variables.
3. Input the number of elements in the array.
4. Input the array elements.
5. Use the Bubble Sort algorithm:
o Compare adjacent elements, swap if they are in the wrong order.
o Repeat this process for all elements until the array is sorted.
6. Display the sorted array.
7. End.

SOURCE CODE:
#include <stdio.h>
int main() {
int n, i, j, temp;
// Input the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort algorithm

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 59

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


for (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;
}
}
}
// Display the sorted array
printf("Sorted array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 60

OUTPUT-1:
Enter the number of elements: 5
Enter the elements of the array:
52916
Sorted array:
12569

OUTPUT-2:
Enter the number of elements: 4
Enter the elements of the array:
10 4 7 3
Sorted array:
3 4 7 10

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 61

iii) AIM: A c program to demonstrate all the Built-in STRING library functions
exist in C-programming.

DESCRIPTION:
 strlen: Calculates and prints the length of a string.
 strcpy: Copies one string to another.
 strcat: Concatenates two strings.
 strcmp: Compares two strings and checks if they are equal or which one
is greater.
 strchr: Finds the first occurrence of a character in a string.
 strstr: Finds the first occurrence of a substring in a string.

SOURCE CODE:
#include <stdio.h> // For input/output functions
#include <string.h> // For string functions

int main() {
int choice; // To store user's choice
char str1[100], str2[100], ch; // Strings and a character variable
char *ptr; // Pointer to store results for strchr and strstr
int len; // To store string length

do {
// Menu Display
printf("\nString Function Menu:\n");
printf("1. strlen (Calculate string length)\n");
printf("2. strcpy (Copy one string to another)\n");
printf("3. strcat (Concatenate two strings)\n");
printf("4. strcmp (Compare two strings)\n");

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 62

printf("5. strchr (Find first occurrence of a character)\n");


printf("6. strstr (Find substring)\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Reading user's choice

switch (choice) {
case 1: // strlen example
printf("Enter a string: ");
scanf("%s", str1); // Input string
len = strlen(str1); // Calculate string length
printf("Length of the string is: %d\n", len); // Output length
break;

case 2: // strcpy example


printf("Enter source string: ");
scanf("%s", str1); // Input source string
strcpy(str2, str1); // Copy str1 to str2
printf("Copied string: %s\n", str2); // Output copied string
break;

case 3: // strcat example


printf("Enter first string: ");
scanf("%s", str1); // Input first string
printf("Enter second string: ");
scanf("%s", str2); // Input second string
strcat(str1, str2); // Concatenate str2 to str1

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 63

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


break;

case 4: // strcmp example


printf("Enter first string: ");
scanf("%s", str1); // Input first string
printf("Enter second string: ");
scanf("%s", str2); // Input second string
int result = strcmp(str1, str2); // Compare strings
if (result == 0) {
printf("Strings are equal.\n"); // If strings are equal
} else if (result < 0) {
printf("First string is less than the second.\n"); // If str1 < str2
} else {
printf("First string is greater than the second.\n"); // If str1 > str2
}
break;

case 5: // strchr example


printf("Enter a string: ");
scanf("%s", str1); // Input string
printf("Enter the character to search for: ");
scanf(" %c", &ch); // Input character
ptr = strchr(str1, ch); // Find first occurrence of the character
if (ptr != NULL) {
printf("Character found at position: %ld\n", ptr - str1 + 1); // Output
character position
} else {

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 64

printf("Character not found.\n"); // If not found


}
break;

case 6: // strstr example


printf("Enter main string: ");
scanf("%s", str1); // Input main string
printf("Enter substring to search: ");
scanf("%s", str2); // Input substring
ptr = strstr(str1, str2); // Find first occurrence of the substring
if (ptr != NULL) {
printf("Substring found at position: %ld\n", ptr - str1 + 1); // Output
substring position
} else {
printf("Substring not found.\n"); // If not found
}
break;

case 7: // Exit the program


printf("Exiting the program.\n");
break;

default:
printf("Invalid choice! Please try again.\n"); // Invalid input case
}
} while (choice != 7); // Loop until the user chooses to exit

return 0;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 65

Output for Choice 1: strlen (Calculate string length)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 1
Enter a string: hello
Length of the string is: 5

Output for Choice 2: strcpy (Copy one string to another)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 2
Enter source string: world
Copied string: world

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 66

Output for Choice 3: strcat (Concatenate two strings)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 3
Enter first string: hello
Enter second string: world
Concatenated string: helloworld

Output for Choice 4: strcmp (Compare two strings)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 4
Enter first string: apple
Enter second string: banana
First string is less than the second.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 67

Output for Choice 5: strchr (Find first occurrence of a character)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 5
Enter a string: hello
Enter the character to search for: l
Character found at position: 3

Output for Choice 6: strstr (Find substring)


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 6
Enter main string: programming
Enter substring to search: gram
Substring found at position: 4

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 68

Output for Choice 7: Exit


String Function Menu:
1. strlen (Calculate string length)
2. strcpy (Copy one string to another)
3. strcat (Concatenate two strings)
4. strcmp (Compare two strings)
5. strchr (Find first occurrence of a character)
6. strstr (Find substring)
7. Exit
Enter your choice: 7
Exiting the program.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 69

NOTE: THE BELOW PROGRAMS NEED NOT TO BE WRITTEN IN


RECORDS [GREEN COLOURED]

AIM: A c program to concatenate two strings without built-in functions.


SOURCE CODE:
#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
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);
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 70

AIM: A c program to reverse a string without Built-in functions


SOURCE CODE:
#include <stdio.h>
#include <string.h>

// function definition of the revstr()


void revstr(char *str1)
{
// declare variable
int i, len, temp;
len = strlen(str1); // use strlen() to get the length of str string

// use for loop to iterate the string


for (i = 0; i < len/2; i++)
{
// temp variable use to temporary hold the string
temp = str1[i];
str1[i] = str1[len - i - 1];
str1[len - i - 1] = temp;
}
}

int main()
{
char str[50]; // size of char string
printf (" Enter the string: ");
gets(str); // use gets() function to take string

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 71

printf (" \n Before reversing the string: %s \n", str);

// call revstr() function


revstr(str);
printf (" After reversing the string: %s", str);
}

Output
Enter the string: Welcome Friends
Before reversing the string: Welcome Friends
After reversing the string: sdneirF emocleW

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 72

Lab 9: Pointers, structures, Memory allocations

i) AIM: Program to implement structures in C.

SOURCE CODE:
#include <stdio.h>

// Define a structure 'Person'


struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare a variable of type 'Person'
struct Person person1;

// Input details for the person


printf("Enter name: ");
scanf("%s", person1.name);

printf("Enter age: ");


scanf("%d", &person1.age);

printf("Enter height (in cm): ");


scanf("%f", &person1.height);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 73

// Output the details


printf("\nPerson Details:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f cm\n", person1.height);

return 0;
}

OUTPUT:
Enter name: Alice
Enter age: 30
Enter height (in cm): 165

Person Details:
Name: Alice
Age: 30
Height: 165.00 cm

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 74

ii) AIM: Program to implement pointers in C.

SOURCE CODE:
#include <stdio.h>
int main() {
int num = 25; // Declare an integer variable
int *ptr = &num; // Pointer 'ptr' stores the address of 'num'

// Print the value and address using pointer


printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);

// Accessing the value using pointer dereferencing


printf("Value of num using pointer: %d\n", *ptr);
printf("Address stored in pointer: %p\n", ptr);

return 0;
}

OUTPUT:
Value of num: 25
Address of num: 0x7ffeefbff5ac
Value of num using pointer: 25
Address stored in pointer: 0x7ffeefbff5ac

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 75

iii) AIM: Program to Demonstrating Memory Allocation (malloc, calloc, realloc,


and free) in C.

DESCRIPTION:
 malloc: Allocates memory for an array of integers. We store values in the
array.
 calloc: Allocates memory for an array of integers, initializing all elements
to 0.
 realloc: Reallocates the previously allocated memory to hold a larger array.
 free: Frees the allocated memory after use to avoid memory leaks.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h> // For malloc, calloc, realloc, and free

int main() {
int *arr, *newArr, n = 5, i;

// Memory allocation using malloc


arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed with malloc\n");
return 1;
}

// Assign values
for (i = 0; i < n; i++) {
arr[i] = i + 1;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 76

printf("Array using malloc:\n");


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

// Memory allocation using calloc


int *arr2 = (int *)calloc(n, sizeof(int));
if (arr2 == NULL) {
printf("Memory allocation failed with calloc\n");
return 1;
}

printf("Array using calloc (initialized to 0):\n");


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

// Memory reallocation using realloc


newArr = (int *)realloc(arr, 10 * sizeof(int));
if (newArr == NULL) {
printf("Memory reallocation failed with realloc\n");
return 1;
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 77

printf("Array after realloc (resized to 10):\n");


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

// Free allocated memory


free(arr);
free(arr2);
free(newArr);

return 0;
}

OUTPUT:
Array using malloc:
12345
Array using calloc (initialized to 0):
00000
Array after realloc (resized to 10):
1234500000

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 78

LAB 10:
Demonstrate the differences between structures and unions using a C program.

DESCRIPTION:
MAJOR DIFFERENCES:
 Structure: Each member occupies its own space, and all members can store
values at the same time.
 Union: Members share memory, so only one member can store a value at
any given time. Assigning a value to one member overwrites the others.

SOURCE CODE:
#include <stdio.h>
#include <string.h>

// Define a structure 'Student'


struct Student {
int id;
char name[20];
float grade;
};

// Define a union 'Data'


union Data {
int id;
char name[20];
float grade;
};

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 79

int main() {
// Using structure
struct Student student1;
student1.id = 1;
strcpy(student1.name, "Alice");
student1.grade = 9.5;

printf("Structure - Student Details:\n");


printf("ID: %d\n", student1.id);
printf("Name: %s\n", student1.name);
printf("Grade: %.2f\n\n", student1.grade);

// Using union
union Data data1;
data1.id = 1; // Store 'id' first
printf("Union - ID: %d\n", data1.id);

strcpy(data1.name, "Alice"); // Store 'name', overwrites 'id'


printf("Union - Name: %s\n", data1.name);

data1.grade = 9.5; // Store 'grade', overwrites 'name'


printf("Union - Grade: %.2f\n\n", data1.grade);

// After storing grade, id and name values are overwritten


printf("Union after storing grade - ID: %d (corrupted)\n", data1.id);
printf("Union after storing grade - Name: %s (corrupted)\n", data1.name);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 80

return 0;
}

OUTPUT:
Structure - Student Details:
ID: 1
Name: Alice
Grade: 9.50

Union - ID: 1
Union - Name: Alice
Union - Grade: 9.50

Union after storing grade - ID: 1094713344 (corrupted)


Union after storing grade - Name: ⌂⌂⌂⌂⌂⌂ (corrupted)

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 81

Lab 11: Simple functions using call by value

i) AIM: A C function to calculate NCR value.

SOURCE CODE:
#include <stdio.h>

// Function to calculate factorial of a number


long long factorial(int n) {
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i; // Multiply fact by the current number 'i'
}
return fact;
}
// Function to calculate NCR value (nCr = n! / (r! * (n - r)!))
long long nCr(int n, int r) {
long long n_fact = factorial(n); // Calculate n!
long long r_fact = factorial(r); // Calculate r!
long long n_r_fact = factorial(n - r); // Calculate (n - r)!

// Return the NCR value using the formula nCr = n! / (r! * (n - r)!)
return n_fact / (r_fact * n_r_fact);
}

int main() {
int n, r;

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 82

// Input values of n and r


printf("Enter value of n: ");
scanf("%d", &n);

printf("Enter value of r: ");


scanf("%d", &r);

// Calculate and print the NCR value


printf("NCR value (C(%d, %d)) = %lld\n", n, r, nCr(n, r));

return 0;
}

OUTPUT 1:
Enter value of n: 5
Enter value of r: 2
NCR value (C(5, 2)) = 10

OUTPUT 2:
Enter value of n: 6
Enter value of r: 3
NCR value (C(6, 3)) = 20

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 83

ii) AIM: A C function to find the length of a string.

SOURCE CODE:
#include <stdio.h>
// Function to calculate the length of a string
int stringLength(char str[]) {
int length = 0; // Initialize the length to 0

// Loop through the string until we reach the null terminator '\0'
while (str[length] != '\0') {
length++; // Increment length for each character
}

return length; // Return the calculated length


}

int main() {
char str[100]; // Declare a character array to store the input string

// Input the string from the user


printf("Enter a string: ");
scanf("%s", str);

// Calculate and print the length of the string


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

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 84

return 0;
}

OUTPUT 1:
Enter a string: Hello
The length of the string is: 5

OUTPUT 2:
Enter a string: RRRRRRR
The length of the string is: 7

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 85

iii) AIM: A C function to transpose of a matrix.

SOURCE CODE:
#include <stdio.h>

// Function to find the transpose of a matrix


void transposeMatrix(int rows, int cols, int matrix[rows][cols], int
transpose[cols][rows]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Assign the transpose element
transpose[j][i] = matrix[i][j];
}
}
}

int main() {
int rows, cols;

// Input number of rows and columns for the matrix


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

int matrix[rows][cols], transpose[cols][rows];

// Input elements of the matrix

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 86

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}

// Call the function to compute the transpose


transposeMatrix(rows, cols, matrix, transpose);

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Print the transposed matrix
printf("\nTransposed Matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 87

return 0;
}

OUTPUT:
Enter the number of rows: 2
Enter the number of columns: 3
Enter the elements of the matrix:
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6

Original Matrix:
123
456

Transposed Matrix:
14
25
36

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 88

Lab 12: Recursive functions

i) AIM: C Program to Generate Fibonacci Series using Recursion.

SOURCE CODE:
#include <stdio.h>
// Recursive function to find the nth Fibonacci number
int fibonacci(int n) {
if (n == 0) {
return 0; // Base case: Fibonacci(0) = 0
}
else if (n == 1) {
return 1; // Base case: Fibonacci(1) = 1
}
else {
// Recursive call: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

int main() {
int terms;
// Input the number of terms to generate in the Fibonacci series
printf("Enter the number of terms: ");
scanf("%d", &terms);
printf("Fibonacci Series: ");

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 89

// Generate the Fibonacci series up to the specified number of terms

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


printf("%d ", fibonacci(i)); // Call the recursive function
}

printf("\n");

return 0;
}

OUTPUT 1:
Enter the number of terms: 6
Fibonacci Series: 0 1 1 2 3 5

OUTPUT 2:
Enter the number of terms: 8
Fibonacci Series: 0 1 1 2 3 5 8 13

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 90

ii) AIM: C Program to Find the Factorial of a Number using Recursion

SOURCE CODE:
#include <stdio.h>
// Recursive function to calculate factorial of a number
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial(0) = 1 and factorial(1) = 1
} else {
// Recursive case: factorial(n) = n * factorial(n - 1)
return n * factorial(n - 1);
}
}
int main() {
int number;
// Input the number from the user
printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is negative


if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
}
else {
// Call the recursive function and print the result
printf("Factorial of %d is %d\n", number, factorial(number));
}

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 91

return 0;
}

OUTPUT:
Enter a number: 5
Factorial of 5 is 120
Enter a number: 0
Factorial of 0 is 1

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 92

iii) AIM: C Program to Find the Sum of a Series using Recursion

SOURCE CODE:
#include <stdio.h>
// Recursive function to calculate the sum of the series 1 + 2 + 3 + ... + n
int sumOfSeries(int n) {
if (n == 0) {
return 0; // Base case: sum of 0 is 0
} else { // Recursive case: sum(n) = n + sum(n - 1)
return n + sumOfSeries(n - 1);
}
}
int main() {
int number;
// Input the number of terms (n) from the user
printf("Enter the number of terms: ");
scanf("%d", &number);
// Call the recursive function and print the result
printf("Sum of the series 1 + 2 + ... + %d is: %d\n", number,
sumOfSeries(number));

return 0;
}

OUTPUT:
Enter the number of terms: 5
Sum of the series 1 + 2 + ... + 5 is: 15

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 93

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

i) AIM: C Program to Swap Two Numbers Using Call by Reference

SOURCE CODE:
#include <stdio.h>
// Function to swap two numbers using call by reference
void swap(int *x, int *y) {
int temp; // Temporary variable to store the value of one number
temp = *x; // Dereference x to get the value at the address and store in temp
*x = *y; // Dereference y to get the value at the address and store it in x
*y = temp; // Assign the value in temp to y
}
int main() {
int a, b;
// Input two numbers from the user
printf("Enter two numbers:\n");
printf("a: ");
scanf("%d", &a);
printf("b: ");
scanf("%d", &b);
// Print the numbers before swapping
printf("\nBefore swapping: a = %d, b = %d\n", a, b);
// Call the swap function, passing the addresses of a and b
swap(&a, &b);
// Print the numbers after swapping
printf("After swapping: a = %d, b = %d\n", a, b);

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 94

return 0;
}

OUTPUT:
Enter two numbers:
a: 10
b: 20

Before swapping: a = 10, b = 20


After swapping: a = 20, b = 10

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 95

ii) AIM: C Program to Demonstrate Dangling Pointer Problem

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr; // Declare a pointer
// Dynamically allocate memory for an integer
ptr = (int *)malloc(sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Assign a value to the allocated memory
*ptr = 42;
printf("Value before freeing memory: %d\n", *ptr);
// Free the allocated memory
free(ptr);
// Now ptr becomes a dangling pointer
// Attempting to access it will lead to undefined behavior
printf("Attempting to access dangling pointer: %d\n", *ptr); // Undefined
behavior
// Optional: Set the pointer to NULL to avoid dangling pointer issue
ptr = NULL;
// Attempting to access NULL pointer (this will also lead to undefined
behavior)
// Uncommenting the following line will lead to segmentation fault

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 96

// printf("Attempting to access NULL pointer: %d\n", *ptr);

return 0;
}

OUTPUT:
Value before freeing memory: 42
Attempting to access dangling pointer: 42

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 97

Lab 14: File handling operations

i) AIM: C Program to Write and Read Text into a File

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file; // File pointer
char filename[100]; // Array to hold the filename
char content[256]; // Buffer to store data for writing
char readContent[256]; // Buffer to store data read from the file
// Writing to a file
printf("Enter the filename to write: ");
scanf("%s", filename); // Input filename
// Open file in write mode
file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
exit(1); // Exit if file cannot be opened
}
// Prompt for text input
printf("Enter the text to write to the file (max 255 characters): ");
getchar(); // Clear the newline character from the input buffer
fgets(content, sizeof(content), stdin); // Read input from user
fprintf(file, "%s", content); // Write to the file
fclose(file); // Close the file

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 98

printf("Text written to file '%s' successfully.\n", filename);


// Reading from the file
printf("\nReading from the file '%s':\n", filename);
// Open file in read mode
file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
exit(1); // Exit if file cannot be opened
}
// Read and print the contents of the file
while (fgets(readContent, sizeof(readContent), file) != NULL) {
printf("%s", readContent); // Print each line
}
fclose(file); // Close the file
return 0; // Return success
}

OUTPUT:
Enter the filename to write: example.txt
Enter the text to write to the file (max 255 characters): Hello, this is a test file!
Text written to file 'example.txt' successfully.
Reading from the file 'example.txt':
Hello, this is a test file!

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 99

ii) AIM: C Program to Write and Read Text into a Binary File

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 256 // Maximum size for the text input
int main() {
FILE *binaryFile; // Pointer for the binary file
char filename[100]; // Array to hold the filename
char content[MAX_SIZE]; // Buffer to store data for writing
// Writing to a binary file
printf("Enter the filename to write (binary): ");
scanf("%s", filename); // Input filename
// Open file in binary write mode
binaryFile = fopen(filename, "wb");
if (binaryFile == NULL) {
printf("Error opening file for writing.\n");
exit(1); // Exit if file cannot be opened
}
// Prompt for text input
printf("Enter the text to write to the binary file (max 255 characters): ");
getchar(); // Clear the newline character from the input buffer
fgets(content, sizeof(content), stdin); // Read input from user

// Write to the binary file


fwrite(content, sizeof(char), MAX_SIZE, binaryFile);
fclose(binaryFile); // Close the file

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 100

printf("Text written to binary file '%s' successfully.\n", filename);


// Reading from the binary file
printf("\nReading from the binary file '%s':\n", filename);
// Open file in binary read mode
binaryFile = fopen(filename, "rb");
if (binaryFile == NULL) {
printf("Error opening file for reading.\n");
exit(1); // Exit if file cannot be opened
}
// Read and print the contents of the binary file
fread(content, sizeof(char), MAX_SIZE, binaryFile);
printf("%s", content); // Print the content read from the binary file
fclose(binaryFile); // Close the file

return 0; // Return success


}

OUTPUT:
Enter the filename to write (binary): example.bin
Enter the text to write to the binary file (max 255 characters): Hello, this is a
binary file!
Text written to binary file 'example.bin' successfully.
Reading from the binary file 'example.bin':
Hello, this is a binary file!

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 101

iii) AIM: Copy the contents of one file to another file.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *sourceFile; // Pointer for the source file
FILE *destinationFile; // Pointer for the destination file
char sourceFilename[100]; // Array to hold the source filename
char destinationFilename[100]; // Array to hold the destination filename
char buffer[256]; // Buffer to hold data while copying
// Get the source file name from the user
printf("Enter the source filename: ");
scanf("%s", sourceFilename); // Input source filename
// Open the source file in read mode
sourceFile = fopen(sourceFilename, "r");
if (sourceFile == NULL) {
printf("Error opening source file '%s'.\n", sourceFilename);
exit(1); // Exit if the source file cannot be opened
}
// Get the destination file name from the user
printf("Enter the destination filename: ");
scanf("%s", destinationFilename); // Input destination filename

// Open the destination file in write mode


destinationFile = fopen(destinationFilename, "w");
if (destinationFile == NULL) {

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 102

printf("Error opening destination file '%s'.\n", destinationFilename);


fclose(sourceFile); // Close the source file
exit(1); // Exit if the destination file cannot be opened
}
// Copy the contents from source file to destination file
while (fgets(buffer, sizeof(buffer), sourceFile) != NULL) {
fprintf(destinationFile, "%s", buffer); // Write the buffer to the destination
file
}
// Close both files
fclose(sourceFile);
fclose(destinationFile);
printf("Contents copied from '%s' to '%s' successfully.\n", sourceFilename,
destinationFilename);

return 0; // Return success


}

OUTPUT:
Enter the source filename: source.txt
Enter the destination filename: destination.txt
Contents copied from 'source.txt' to 'destination.txt' successfully.

COMPUTER PROGRAMMING LAB BY: CH.RCR


P a g e | 103

COMPUTER PROGRAMMING LAB BY: CH.RCR

You might also like