Cycle 3 Ge23121 - C Programming Lab Manual Ai & Ds
Cycle 3 Ge23121 - C Programming Lab Manual Ai & Ds
NO:7A RECURSION-POWER
DATE:
AIM:
ALGORITHM:
1.Start
2.Input: Read two integers: x and n
3.Check if n is less than 0: display an error
4.Define a recursive function power(x, n):
5.Display the result: Output the result of x^n
6.End
PROGRAM:
#include <stdio.h>
int power(int x, int n) {
if (n == 0) {
return 1;
}
return x * power(x, n - 1);
}
int main() {
int x, n;
printf("Enter the base (x): ");
scanf("%d", &x);
printf("Enter the exponent (n): ");
scanf("%d", &n);
if (n < 0) {
printf("Exponent must be a non-negative integer.\n");
} else {
printf("%d raised to the power of %d is: %d\n", x, n, power(x, n));
}
return 0;
}
OUTPUT:
Enter the base (x): 3
Enter the exponent (n): 2
3 raised to the power of 2 is: 9
RESULT:
Thus the C program to calculate x raised to the power of n using recursion is written and executed successfully.
EX.NO:7B LENGTH OF A STRING-RECURSION
DATE:
AIM:
To write a C program to find the length of a string using recursion
ALGORITHM:
1. Start
2.Input: Read a string str from the user.
3. Define a recursive function stringLength(str):
4. Output: After calling the stringLength function, display the result (the length of the string).
5. End
PROGRAM:
#include <stdio.h>
int stringLength(char str[]) {
if (str[0] == '\0') {
return 0;
} else {
return 1 + stringLength(str + 1);
}
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("The length of the string is: %d\n", stringLength(str));
return 0;
}
OUTPUT:
Enter a string: Programming
The length of the string is: 12
RESULT:
Thus the C program to find the length of a string using recursion is written and executed successfully.
EX.NO:7C TOWER OF HANOI
DATE:
AIM:
To write a C program to solve the Tower of Hanoi problem using recursion for n disks.
ALGORITHM:
1. Start
2. Input: Read the number of disks n from the user.
3. Define a recursive function towerOfHanoi(n, source, destination, auxiliary):
4. Output: After all the moves are complete, display the steps taken to solve the Tower of Hanoi.
5. End
PROGRAM:
#include <stdio.h>
void towerOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}
towerOfHanoi(n - 1, source, auxiliary, destination);
printf("Move disk %d from %c to %c\n", n, source, destination);
towerOfHanoi(n - 1, auxiliary, destination, source);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
printf("The steps to solve the Tower of Hanoi are:\n");
towerOfHanoi(n, 'A', 'C', 'B'); // A = source, B = auxiliary, C = destination
return 0;
}
OUTPUT:
RESULT:
Thus the Cprogram to solve the Tower of Hanoi problem using recursion for n disks EXECUTED
SUCCESSFULLY
EX.NO:8A ARRAY WITH POINTERS
DATE:
AIM:
To write C program that takes an array of integers as a parameter, uses a pointer to access and modify its values,
and returns the modified array.
ALGORITHM:
1. Start
2. Initialize the Array:Create an array of integers, for example: {1, 2, 3, 4, 5}.
3. Display the Original Array:
4. Define a Function to Modify the Array:
5. Call the Function to Modify the Array:
6. Display the Modified Array:
7. End.
PROGRAM:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
return 0;
}
OUTPUT:
Original array: 1 2 3 4 5
Modified array: 2 4 6 8 10
RESULT:
Thus the C program that takes an array of integers as a parameter, uses a pointer to access and modify its values,
and returns the modified array is written and executed successfully.
EX.NO:8B ARRAY OF POINTERS TO FUNCTIONS
DATE
AIM:
To write a C program that uses an array of pointers to functions, each function performing a different
mathematical operation (addition, subtraction, multiplication, etc.).
ALGORITHM:
1. Start
2. Define arithmetic functions:Addition, subtraction, multiplication, and division.
3. Declare function pointers:Use an array for addition, subtraction, and multiplication.
4. Use a separate pointer for division.
5. Input values:Assign two integers to num1 and num2.
6. Perform calculations:Use the function pointers to call the respective functions.
7. Display the results of addition, subtraction, multiplication, and division.
8. Handle division by zero:If the denominator is zero, print an error message.
9. Output the results and end the program.
PROGRAM:
#include <stdio.h>
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
int main() {
int (*operation[])(int, int) = {add, subtract, multiply};
float (*div_operation)(int, int) = divide;
int num1 = 10, num2 = 5;
printf("Addition: %d + %d = %d\n", num1, num2, operation[0](num1, num2));
printf("Subtraction: %d - %d = %d\n", num1, num2, operation[1](num1, num2));
printf("Multiplication: %d * %d = %d\n", num1, num2, operation[2](num1, num2));
printf("Division: %d / %d = %.2f\n", num1, num2, div_operation(num1, num2));
return 0;
}
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
AIM:
To write aC program to concatenate two strings using pointer arithmetic.
ALGORITHM:
*result = '\0';
}
int main() {
char str1[] = "Hello, ";
char str2[] = "world!";
char result[100];
concatenateStrings(str1, str2, result);
printf("Concatenated string: %s\n", result);
return 0;
}
OUTPUT:
Concatenated string: Hello, world!
RESULT:
Thus the C program to concatenate two strings using pointer arithmetic is written and executed successfully.
EX.NO:8D DYNAMIC MEMEORY ALLOCATION
DATE
AIM:
To write a C program to dynamically allocate memory for an array of integers using malloc(), initialize the array,
and display its values. Use a pointer to access the array.
ALGORITHM:
1. Start the program.
2. Prompt the User for Input
3. Dynamically Allocate Memory for the Array
4. Initialize the Array
5. Display the Array Values
6. Free the Allocated Memory
7. End the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n;
int i;
printf("Enter the number of elements: ");
scanf("%d", &n);
arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
for (i = 0; i< n; i++) {
*(arr + i) = i * 10;
}
printf("Array values: ");
for (i = 0; i< n; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
free(arr);
return 0;
}
OUTPUT:
Enter the number of elements: 5
Array values: 0 10 20 30 40
RESULT:
Thus the C program to dynamically allocate memory for an array of integers using malloc(), initialize the array,
and display its values. Use a pointer to access the array is written and executed successfully.
EX.NO:9A STRUCTURE
DATE
AIM:
To write a C program to define a structure Person that contains a nested structure Address. The Address structure
should contain city, state, and pin_code. Display the Person information along with their address.
ALGORITHM:
1. Start the program.
2. Define a Structure for Address:
3. Define a Structure for Person:
4. Create and Initialize a Person:
5. Display the Person's Information:
6. End the program.
PROGRAM:
#include <stdio.h>
struct Address {
char city[50];
char state[50];
int pin_code;
};
struct Person {
char name[50];
int age;
struct Address address;
};
void displayPersonInfo(struct Person p) {
printf("Person Information:\n");
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
printf("Address:\n");
printf(" City: %s\n", p.address.city);
printf(" State: %s\n", p.address.state);
printf(" Pin Code: %d\n", p.address.pin_code);
}
int main() {
struct Person person1 = {
"John Doe",
30,
{"New York", "NY", 10001}
};
displayPersonInfo(person1);
return 0;
}
OUTPUT:
Person Information:
Name: John Doe
Age: 30
Address:
City: New York
State: NY
Pin Code: 10001
RESULT:
Thus the C program to define a structure Person that contains a nested structure Address. The Address structure
should contain city, state, and pin_code. Display the Person information along with their address is written
and executed successfully.
AIM:
To write a C program to define an array of Book structures where each Book has fields title, author, and
price. Allow the user to input information for multiple books and display the details.
ALGORITHM:
1. Start the program.
2. Define a Structure for a Book:
3. Ask the User for the Number of Books:
4. Create an Array of Books:
5. Input Book Details:
6. Display Book Details:
7. End the program.
PROGRAM:
#include <stdio.h>
struct Book {
char title[100];
char author[100];
float price;
};
void inputBookDetails(struct Book books[], int n) {
for (int i = 0; i< n; i++) {
printf("\nEnter details for Book %d:\n", i + 1);
printf("Title: ");
getchar();
fgets(books[i].title, sizeof(books[i].title), stdin);
books[i].title[strcspn(books[i].title, "\n")] = '\0';
printf("Author: ");
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0';
printf("Price: ");
scanf("%f", &books[i].price);
}
}
void displayBookDetails(struct Book books[], int n) {
printf("\nBook Details:\n");
for (int i = 0; i< n; i++) {
printf("\nBook %d:\n", i + 1);
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Price: %.2f\n", books[i].price);
}
}
int main() {
int n;
printf("Enter the number of books: ");
scanf("%d", &n);
struct Book books[n];
inputBookDetails(books, n);
displayBookDetails(books, n);
return 0;
}
OUTPUT:
RESULT:
Thus the C program to define an array of Book structures where each Book has fields title, author, and price.
Allow the user to input information for multiple books and display the detailsis written and executed
successfully.
AIM:
To write a C program to define a structure Student with fields name, roll_no, and marks. Use a pointer to a
structure to assign values to the fields and display the information
ALGORITHM:
1. Start the program.
2. Define the Structure for a Student:
3. Declare a Pointer to the Student Structure
4. Create an Instance of the Student Structure
5. Make the Pointer Point to the Student Structure:
6. Assign Values Using the Pointer:
7. Display the Student Information:
8. End the program
PROGRAM:
#include <stdio.h>
struct Student {
char name[100];
int roll_no;
float marks;
};
int main() {
struct Student *ptr;
struct Student student1;
ptr = &student1;
printf("Enter student's name: ");
fgets(ptr->name, sizeof(ptr->name), stdin);
ptr->name[strcspn(ptr->name, "\n")] = '\0';
printf("Enter roll number: ");
scanf("%d", &ptr->roll_no);
return 0;
}
OUTPUT:
Enter student's name: Sam
Enter roll number: 249
Enter marks: 99
Student Information:
Name: Sam
Roll Number: 249
Marks: 99.00
RESULT:
Thus the C program to define a structure Student with fields name, roll_no, and marks. Use a pointer to a
structure to assign values to the fields and display the information is written and executed successfully.
AIM:
To write a C program to define a structure Employee that contains an integer id and a union
salary_info. The union contains a basic_salary (float) and bonus (int). Display employee details using both
structure and union.
ALGORITHM:
1. Start the program.
2. Declare the Structure and Union:Define a union named SalaryInfo with two members ,Define a structure
named Employee with two fields:
3. Get Employee ID:
4. Ask for Salary Type:
5. Input Salary Information:
6.Display Employee Information:
7. Handle Invalid Input:
8. End the program.
PROGRAM:
#include <stdio.h>
union SalaryInfo {
float basic_salary;
int bonus;
};
struct Employee {
int id;
union SalaryInfosalary_info;
};
int main() {
struct Employee emp1;
printf("Enter Employee ID: ");
scanf("%d", &emp1.id);
int choice;
printf("Enter your choice : \n1 to input Basic Salary\n 2 to input Bonus:\n ");
scanf("%d", &choice);
if (choice == 1) {
printf("\nEnter Basic Salary: ");
scanf("%f", &emp1.salary_info.basic_salary);
printf("\nEmployee Details:\n");
printf("ID: %d\n", emp1.id);
printf("Basic Salary: %.2f\n", emp1.salary_info.basic_salary);
}
else if (choice == 2) {
printf("\nEnter Bonus: ");
scanf("%d", &emp1.salary_info.bonus);
printf("\nEmployee Details:\n");
printf("ID: %d\n", emp1.id);
printf("Bonus: %d\n", emp1.salary_info.bonus);
}
else {
printf("Invalid choice! Please enter 1 or 2.\n");
}
return 0;
}
OUTPUT 1:
Enter Employee ID: 101
Enter your choice :
1 to input Basic Salary
2 to input Bonus:
1
Enter Basic Salary: 25000
Employee Details:
ID: 101
Basic Salary: 25000.00
Output 2:
Enter Employee ID: 101
Enter your choice :
1 to input Basic Salary
2 to input Bonus:
2
Enter Bonus: 1000
Employee Details:
ID: 101
Bonus: 1000
RESULT:
Thus the C program to define a structure Employee that contains an integer id and a union salary_info. The union
contains a basic_salary (float) and bonus (int). Display employee details using both structure and union is written
and executed successfully.
EX.NO:10A FILE
DATE
AIM:
To write a C program that reads the contents of a text file and writes it to another text file. If the source file
doesn't exist, display an error message.
ALGORITHM:
1. Start the Program.
2. Declare File Pointers:
3. Open the Source File:
Attempt to open the source file (e.g., source.txt) in read mode.
If the source file does not exist or cannot be opened:
o Display the message: "Error: Source file does not exist."
o Exit the program (stop execution).
4. Open the Destination File:
Attempt to open the destination file (e.g., destination.txt) in write mode.
If the destination file cannot be opened (due to permissions or other issues):
o Display the message: "Error: Unable to open destination file."
o Close the source file and exit the program (stop execution).
5. Copy Data from Source to Destination:
Read the contents of the source file one character at a time.
Write each character read from the source file into the destination file.
6. Close the Files:
After all characters have been copied, close both the source and destination files.
7. Display Success Message:
Print the message: "File copied successfully!" to indicate that the process has finished successfully.
8. End the Program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *source, *destination;
char ch;
source = fopen("source.txt", "r");
if (source == NULL) {
printf("Error: Source file does not exist.\n");
return 1;
}
destination = fopen("destination.txt", "w");
if (destination == NULL) {
printf("Error: Unable to open destination file.\n");
fclose(source);
return 1;
}
return 0;
}
OUTPUT:
Error: Source file does not exist.
RESULT:
Thus the C program that reads the contents of a text file and writes it to another text file. If the source file doesn't
exist, display an error message is written and executed successfully.
EX.NO:10B FILE POINTERS
DATE
AIM:
To write a C program to use file pointers. Open a file in write mode, write some text, and then move the file
pointer to a specific location to overwrite a part of the file.
ALGORITHM:
1. Start the Program.
2. Open the File in Write Mode:
Open the file example.txt in write mode (this will create the file if it doesn't exist).
If the file cannot be opened, print an error message and stop the program.
3. Write Initial Text to the File:
Write the first line of text: "Hello, this is a simple C program."
Write the second line of text: "We will overwrite part of this text."
4. Close the File:
Close the file after writing the initial content to ensure the text is saved.
5.Reopen the File in Read-Write Mode:
Reopen example.txt in read-write mode (r+), which allows both reading and writing.
If the file cannot be opened, print an error message and stop the program.
6. Move the File Pointer to a Specific Location:
Use fseek() to move the file pointer to the 30th byte from the beginning of the file.
This is where we will overwrite part of the text.
7. Overwrite Part of the File:
From the 30th byte, overwrite the existing content with the new text: "This text will overwrite part of the
original text."
This new text will replace the old text starting from the specified position.
8.Close the File Again:
Close the file to save all changes and ensure the file is properly closed.
9. Display a Success Message:
Print a message: "File successfully modified." to notify the user that the operation was completed.
10. End the Program.
PROGRAM:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error: Could not open file for writing.\n");
return 1;
}
fprintf(file, "Hello, this is a simple C program.\n");
fprintf(file, "We will overwrite part of this text.\n");
fclose(file);
file = fopen("example.txt", "r+");
if (file == NULL) {
printf("Error: Could not open file for reading and writing.\n");
return 1;
}
fseek(file, 30, SEEK_SET);
fprintf(file, "This text will overwrite part of the original text.");
fclose(file);
printf("File successfully modified.\n");
return 0;
}
OUTPUT:
File successfully modified.
RESULT:
Thus theC program to use file pointers. Open a file in write mode, write some text, and then move the file pointer
to a specific location to overwrite a part of the file is written and executed successfully.
EX.NO:10C RANDOM ACCESS TO A FILE
DATE
AIM:
To write a C program that demonstrates random access to a file. Use fseek() and ftell() to read specific data from
a file at a given location and display it.
ALGORITHM:
1. Start the Program.
2. Open the File in Read-Write Mode:
o Open the file named example.txt in read-write mode.
o If the file cannot be opened, display an error message and stop the program.
3. Move the File Pointer to a Specific Location:
o Use fseek() to move the file pointer 10 bytes from the beginning of the file.
o This will position the file pointer to the 10th byte.
4. Get the Current Position of the File Pointer:
o Use ftell() to get the current position of the file pointer.
o Display this position to show where the file pointer is located.
5. Read Data from the Current File Pointer Location:
o Use fgets() to read data from the file starting from the current position (the 10th byte).
o Store the data in a buffer and display it.
6. Move the File Pointer Further:
o Use fseek() to move the file pointer 20 bytes forward from its current position.
o This will adjust the pointer to a new position.
7. Get the New Position of the File Pointer:
o Again, use ftell() to get the new position of the file pointer after the move.
o Display this new position to show the updated location of the pointer.
8. Read More Data from the New File Pointer Location:
o Use fgets() again to read more data starting from the new position.
o Store the new data in the buffer and display it.
o Close the File:Close the file to save all changes and release resources.
9. End the Program.
PROGRAM:
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
long position;
file = fopen("example.txt", "r+");
if (file == NULL) {
printf("Error: Could not open file for reading and writing.\n");
return 1;
}
fseek(file, 10, SEEK_SET);
position = ftell(file);
printf("Current file pointer position: %ld\n", position);
fgets(buffer, sizeof(buffer), file);
printf("Data read from the file: %s\n", buffer);
fseek(file, 20, SEEK_CUR);
position = ftell(file);
printf("New file pointer position: %ld\n", position);
fgets(buffer, sizeof(buffer), file);
printf("Data read from the new position: %s\n", buffer);
fclose(file);
return 0;
}
OUTPUT:
Current file pointer position: 10
Data read from the file: s is a simple C progThis text will overwrite part of the original text.
New file pointer position: 101
Data read from the new position: s is a simple C progThis text will overwrite part of the original text.
RESULT:
Thus theC program that demonstrates random access to a file. Use fseek() and ftell() to read specific data from a
file at a given location and display it is written and executed successfully.
EX.NO:10D FILE HANDLING FUNCTION
DATE
AIM:
To write aC program that copies the contents of one file to another file using file handling functions. Ensure
proper error handling is done if files cannot be opened.
ALGORITHM:
1. Start the Program.
2. Open the Source File:
o Attempt to open source.txt in read mode.
o If it fails, print an error message and exit.
3. Open the Destination File:
o Attempt to open destination.AAtxt in write mode.
o If it fails, print an error message, close the source file, and exit.
4. Copy Data from Source to Destination:
o Read each character from the source file one by one.
o Write each character to the destination file.
5. Close Both Files:
o After copying, close both the source and destination files.
6. Print Success Message:
o Print "File copied successfully."
7. End the Program.
PROGRAM:
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char ch;
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file.\n");
return 1; // Exit the program with an error code
}
destinationFile = fopen("destination.txt", "w");
if (destinationFile == NULL) {
printf("Error: Could not open destination file.\n");
fclose(sourceFile); // Close the source file before exiting
return 1; // Exit the program with an error code
}
fputc(ch, destinationFile);
}
fclose(sourceFile);
fclose(destinationFile);
printf("File copied successfully.\n");
return 0;
}
OUTPUT:
Error: Could not open source file.
RESULT:
Thus the C program that copies the contents of one file to another file using file handling functions. Ensure
proper error handling is done if files cannot be opened is written and executed successfully.
EX.NO:10 E FILE- READING
DATE
AIM:
To Write a C program that attempts to open a file for reading and checks for errors. If an error occurs (e.g., file
doesn't exist), print an appropriate error message and terminate the program.
ALGORITHM:
1.Start the Program.
2. Try to Open the File for Reading:
Attempt to open example.txt in read mode.
3. Check for Errors:
If the file cannot be opened (e.g., it doesn't exist or there is a permission issue), print an error message:
"Error: Could not open the file for reading."
If the file opens successfully, print: "File opened successfully."
4. Close the File:
If the file was opened, close it after the check.
5. End the Program.
PROGRAM:
#include <stdio.h>
int main() {
FILE *file;
return 0;
}
OUTPUT:
File opened successfully.
RESULT:
Thus the C program that attempts to open a file for reading and checks for errors. If an error occurs (e.g., file
doesn't exist), print an appropriate error message and terminate the program is written and executed successfully.