Computer Programming Lab Record
Computer Programming Lab Record
PROGRAMMING LAB
BTECH-R23-JNTU-GV
BY
CH. RAMACHANDRA REDDY
CSE-DEPARTMENT
CHAITANYA ENGINEERING COLLEGE
Page |1
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.
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.
Emacs: Another powerful text editor, with more built-in features and
extensibility options.
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!
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
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);
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
return 0;
}
OUTPUT:
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.00
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);
}
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
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;
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
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
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
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
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
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
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;
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
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;
}
OUTPUT:
Enter three numbers: 10 25 15
The maximum of the three numbers is: 25
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);
OUTPUT:
Enter the marks of 5 subjects: 85 90 78 92 88
Total Marks: 433
Average Marks: 86.60
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;
OUTPUT:
Input four numbers:
1
2
3
4
MAXIMUM is 4
MINIMUM is 1
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.
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
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
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;
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
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
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
}
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.
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
}
Lab 6: Iterative problems e.g., the sum of series - Loops, while and for loops.
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);
OUTPUT-1:
Enter a positive integer: 5
Factorial of 5 = 120
OUTPUT-2 (Zero):
Enter a positive integer: 0
Factorial of 0 = 1
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;
}
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.
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;
} 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
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;
}
Output-1:
Enter a number: 121
121 is a palindrome.
Output-2:
Enter a number: 123
123 is not a palindrome.
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;
}
OUTPUT-1:
[For input of 5 rows:]
1
12
123
1234
12345
OUTPUT-2:
[For input of 3 rows:]
1
12
123
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
}
}
// 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
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;
int arr[n];
return 0;
}
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.
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
}
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
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
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
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");
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;
default:
printf("Invalid choice! Please try again.\n"); // Invalid input case
}
} while (choice != 7); // Loop until the user chooses to exit
return 0;
int main()
{
char str[50]; // size of char string
printf (" Enter the string: ");
gets(str); // use gets() function to take string
Output
Enter the string: Welcome Friends
Before reversing the string: Welcome Friends
After reversing the string: sdneirF emocleW
SOURCE CODE:
#include <stdio.h>
int main() {
// Declare a variable of type 'Person'
struct Person person1;
return 0;
}
OUTPUT:
Enter name: Alice
Enter age: 30
Enter height (in cm): 165
Person Details:
Name: Alice
Age: 30
Height: 165.00 cm
SOURCE CODE:
#include <stdio.h>
int main() {
int num = 25; // Declare an integer variable
int *ptr = # // Pointer 'ptr' stores the address of 'num'
return 0;
}
OUTPUT:
Value of num: 25
Address of num: 0x7ffeefbff5ac
Value of num using pointer: 25
Address stored in pointer: 0x7ffeefbff5ac
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;
// Assign values
for (i = 0; i < n; i++) {
arr[i] = i + 1;
return 0;
}
OUTPUT:
Array using malloc:
12345
Array using calloc (initialized to 0):
00000
Array after realloc (resized to 10):
1234500000
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>
int main() {
// Using structure
struct Student student1;
student1.id = 1;
strcpy(student1.name, "Alice");
student1.grade = 9.5;
// Using union
union Data data1;
data1.id = 1; // Store 'id' first
printf("Union - ID: %d\n", data1.id);
return 0;
}
OUTPUT:
Structure - Student Details:
ID: 1
Name: Alice
Grade: 9.50
Union - ID: 1
Union - Name: Alice
Union - Grade: 9.50
SOURCE CODE:
#include <stdio.h>
// 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;
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
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
}
int main() {
char str[100]; // Declare a character array to store the input string
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
SOURCE CODE:
#include <stdio.h>
int main() {
int rows, cols;
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
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: ");
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
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);
return 0;
}
OUTPUT:
Enter a number: 5
Factorial of 5 is 120
Enter a number: 0
Factorial of 0 is 1
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
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);
return 0;
}
OUTPUT:
Enter two numbers:
a: 10
b: 20
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
return 0;
}
OUTPUT:
Value before freeing memory: 42
Attempting to access dangling pointer: 42
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
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!
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
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!
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
OUTPUT:
Enter the source filename: source.txt
Enter the destination filename: destination.txt
Contents copied from 'source.txt' to 'destination.txt' successfully.