0% found this document useful (0 votes)
2 views41 pages

ST C Programming Lab - R2025

The document is a lab manual for the Computer Science and Engineering department at St. Anne’s College, focusing on C programming exercises. It includes problem analysis, flowcharts, pseudocode, and C programs for various tasks such as finding sums, areas, greatest numbers, and performing arithmetic operations. Each exercise is structured with aims, algorithms, programs, and results to guide students in their programming practice.

Uploaded by

Manohar Mani
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)
2 views41 pages

ST C Programming Lab - R2025

The document is a lab manual for the Computer Science and Engineering department at St. Anne’s College, focusing on C programming exercises. It includes problem analysis, flowcharts, pseudocode, and C programs for various tasks such as finding sums, areas, greatest numbers, and performing arithmetic operations. Each exercise is structured with aims, algorithms, programs, and results to guide students in their programming practice.

Uploaded by

Manohar Mani
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

ST.

ANNE’S COLLEGE OF ENGINEERING AND TECHNOLOGY


Approved by AICTE, New Delhi. Affiliated to Anna University, Chennai
Accredited by NAAC
ANGUCHETTYPALAYAM, PANRUTI – 607 106.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (AIML)

LAB MANUAL

CS25C01 – COMPUTER PROGRAMMING: C


LABORATORY
Regulation 2025

Year / Semester : I / I

PREPARED BY

[Link], [Link].,
Assistant Professor / CSE
Create Problem Analysis Charts, Flowcharts and Pseudocode
Ex. No.: 1. a for Sum of Two Numbers

AIM:
To create Problem Analysis Charts, Flowcharts and Pseudocode to find the sum of
two numbers.

Problem Analysis Charts

Given data Required Results


Number 1 Sum of Two numbers
Number 2

Processing List of solution alternatives


Sum = Number 1 + Number 2 i. Define the numbers as constants.
ii. Define the numbers as input values

Flowcharts
Pseudocode

BEGIN
GET Number1, Number2
ADD Sum=Number1 + Number2
PRINT Sum
END

RESULT:
Thus, creation of the Problem Analysis Charts, Flowcharts and Pseudocode for
finding the sum of two numbers had been constructed.
Create Problem Analysis Charts, Flowcharts and Pseudocode
Ex. No.: 1. b for Area of a Triangle

AIM:
To create Problem Analysis Charts, Flowcharts and Pseudocode to find the area of a
triangle.

Problem Analysis Charts

Given data Required Results


breadth, height Area

Processing List of solution alternatives


area = (1/2) * breadth * height [Link] the breadth and height as
constants.
[Link] the breadth and height as
input values

Flowcharts
Pseudocode
BEGIN
GET breadth, height
COMPUTE area = (1/2) * breadth * height
PRINT area
END

RESULT:
Thus, creation of the Problem Analysis Charts, Flowcharts and Pseudocode for
finding the area of a triangle had been constructed.
Create Problem Analysis Charts, Flowcharts and Pseudocode
Ex. No.: 1. c to display the square of a given Number

AIM:
To create Problem Analysis Charts, Flowcharts and Pseudocode to display the square
of a given number.

Problem Analysis Charts

Given data Required Results


num square

Processing List of solution alternatives


Square = num * num i. Define the num as constants.
ii. Define the num as input values

Flowcharts
Pseudocode

BEGIN
INPUT num
COMPUTE square = num * num
PRINT square
END

RESULT:
Thus, creation of the Problem Analysis Charts, Flowcharts and Pseudocode for
displaying the square of a given number had been constructed.
Finding the Greatest of Three Numbers using Conditional Logics
Ex. No.: 2. a

AIM:
To write a C program to find the greatest of three numbers.

ALGORITHM:
STEP 1: Start
STEP 2: Read three integers as num1, num2 and num3.
STEP 3: Compare three numbers by conditional statements (if-else if).
STEP 4: Print the greatest number based on the comparisons.
STEP 5: Stop

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

void main ( ) {

int num1, num2, num3;

clrscr ( );

printf("Enter three numbers: ");


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

if (num1 >= num2 && num1 >= num3) {


printf("The greatest number is: %d\n", num1);
}

else if (num2 >= num1 && num2 >= num3) {


printf("The greatest number is: %d\n", num2);
}

else {
printf("The greatest number is: %d\n", num3);
}

getch ( );
}
To Save: greatest.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to find the greatest of three numbers was executed and output
verified successfully.
Finding the maximum of three numbers using the Ternary Operator
Ex. No.: 2. b

AIM:
To write a C program to find the maximum of three numbers using the ternary
operator.

ALGORITHM:
STEP 1: Start.
STEP 2: Input three numbers: a, b, and c.
STEP 3: Use the ternary operator to compare:
 First, compare a and b:
If a > b, proceed with a. Otherwise, proceed with b.
 Then, compare the result of the first comparison with c:
If the result > c, the result is the maximum. Otherwise, c is the maximum.
STEP 4: Output the maximum value.
STEP 5: End.

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

void main ( ) {
{
int a, b, c, max;
clrscr ( );
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

// Find the maximum using nested ternary operators


max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

printf("The maximum number is: %d\n", max);

getch ( );
}
To Save: max.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to find the maximum of three numbers using the ternary
operator.
Arithmetic Operations using a Switch Statement
Ex. No.: 2. c

AIM:
To write a C program to perform arithmetic operations using a Switch Statement.

ALGORITHM:
STEP 1: Start
STEP 2: Input two numbers, a and b.
STEP 3: Display a menu of operations: 1. Addition 2. Subtraction 3. Multiplication and
4. Division.
STEP 4: Input the user's choice of operation (op).
STEP 5: Use a switch-case structure to perform the operation based on the value of choice:

Case 1: Perform addition (a + b).


Case 2: Perform subtraction (a - b).
Case 3: Perform multiplication (a * b).
Case 4: Perform division (a / b).

STEP 6: Default: Display an error message ("Invalid choice").


STEP 7: End the switch statement.
STEP 8: Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a,b;
int op;
clrscr ( );

printf(" [Link]\n [Link]\n [Link]\n [Link]\n");


printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
default :
printf("Invalid choice.");
break;
}
getch ( );
}

To Save: arithmetic.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to implement arithmetic operations using switch statement was
executed and output verified successfully.
To check the given number is a Prime number using function
Ex. No.: 3. a

AIM:
To write a program to check the given number is a Prime number in C using function.

ALGORITHM:
STEP 1: Start
STEP 2: Read the input number as num
STEP 3: Check if the num is a Negative number if (num <= 0) display an error message if
num is a negative number.
STEP 4: Create a function called isPrime. The isPrime function is used to check the prime
number.
 Returns 1 – if the n is prime number
 Returns 0 – if the n is not a prime number.
STEP 5: Call the isPrime function from the main function and pass the input number num.
STEP 6: The isPrime function will check to see if the given integer n is evenly divisible by 2
to num/2 (n/2).
STEP 7: Display the results on console based on the isPrime function return value.
STEP 8: Stop.

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

int isPrime(int n);

void main ( )
{
// Take the input from the user
int num;
clrscr ( );

printf("Enter a positive numbers: ");


scanf("%d", &num);

// check for negative numbers

if (num <= 1)
{
printf("Error: Invalid Input, Try again \n");
return 0;
}
// call the 'isPrime' with one integer
if(isPrime(num))
{
printf("Number %d is a Prime Number \n", num);
}
else
{
printf("Number %d is not a Prime Number \n", num);
}

return 0;
}

int isPrime(int n)
{
int i;

// Iterate through 2 to n/2

for(i=2; i<=n/2; i++)


{
// Check if 'i' is factor of 'n'
if(n%i == 0)
{
return 0;
}
}

getch ( );
}

To Save: prime.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to check the given number is a Prime number was executed and
output verified successfully.
Swapping of Two Numbers using Call by Value
Ex. No.: 3. b

AIM:
To write a C program to swap two numbers using Call by Value.

ALGORITHM:
STEP 1: Start
STEP 2: Read the input number as a and b.
STEP 3: Print Values before Swapping
STEP 4: Call the function to swap two numbers: swap(a,b)
 Swapping Two Numbers using Third Variable
 Assign t ← x
 Assign x ← y
 Assign y ← t
 Display Values after Swapping
 End function.
STEP 5: Stop the program

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

void swap(int x,int y);

void main ( )
{
int a, b;
clrscr ( );

printf("Enter two numbers: ");


scanf("%d %d", &a, &b);

printf("Before Swapping a= %d and b= %d \n",a,b);


swap(a,b);

getch ( );
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf("After Swapping a= %d and b= %d ",x,y);
}

To Save: swap.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to swap two numbers using Call by Value was executed and
output verified successfully.
Fibonacci Series using Recursion function
Ex. No.: 3. c

AIM:
To write a C Program to find Fibonacci Series using Recursion function.

ALGORITHM:
STEP 1: Start
STEP 2: Read the input number as n
STEP 3: Calling Recursive Function to find Fibonacci series
STEP 4: Declare variable a=-1, b=1 and c as integers.
STEP 5: Check condition and Compute other numbers by adding the two previous numbers
STEP 7: Display the results according to condition.
STEP 8: Stop.

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

void Fib (int n)


{
static int a=-1, b=1, c;
if(n>0)
{
c = a + b;
a = b;
b = c;
printf("%d ",c);
Fib (n-1);
}
}

void main ( )
{
int n; //input number
clrscr ( );

printf("Enter the number: ");


scanf("%d",&n);

printf("Fibonacci Series: ");


Fib (n-0);

getch ( );
}
To Save: Fibonacci.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to find Fibonacci Series using Recursion function was executed
and output verified successfully.
Dynamic Memory Allocation of an array using Pointers
Ex. No.: 4. a

AIM:
To write a C program to perform Dynamic Memory Allocation of an array using
Pointers.

ALGORITHM:
STEP 1: Start
STEP 2: Declare an integer array as a pointer variable.
STEP 3: Input the size of the array.
STEP 4: Dynamically allocate memory for the array using the pointer.
STEP 5: Input the elements of the array using the pointer.
STEP 6: Perform operations such as:
 Display: Traverse and print the array using the pointer.
 Sum: Calculate the sum of elements using the pointer.
 Reverse: Print the array in reverse order using the pointer.
STEP 7: Display the results of the operations.
STEP 8: Free the dynamically allocated memory.
STEP 9: Stop.

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

void main ( ) {
int n, i, sum = 0;
int *arr;
clrscr ( );

printf("Enter the size of the array: ");


scanf("%d", &n);

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


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", (arr + i));
}

printf("Array elements are:\n");


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

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


sum += *(arr + i);
}
printf("Sum of array elements: %d\n", sum);

printf("Array in reverse order:\n");


for (i = n - 1; i >= 0; i--) {
printf("%d ", *(arr + i));
}
printf("\n");

free(arr);

getch ( );
}

To Save: Dma.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to perform Dynamic Memory Allocation of an array was
executed and output verified successfully.
String Manipulations
Ex. No.: 4. b

AIM:
To write a program to performs basic string manipulations such as concatenation,
length calculation and comparison in C

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare necessary variables and arrays for strings.
STEP 3: Input two strings from the user.
STEP 4: Perform the following operations:
STEP 5: Concatenation: Append the second string to the first.
STEP 6: Length Calculation: Calculate the length of both strings.
STEP 7: Comparison: Compare the two strings to check if they are equal.
STEP 8: Display the results of each operation.
STEP 9: End the program.

PROGRAM:
#include <stdio.h>
#include <string.h>
#include<conio.h>

void main ( )
{
char str1[100], str2[100], concatenated [200];
int length1, length2, comparison;
clrscr ( );

// Input strings
printf("Enter the first string: ");
gets(str1); // Use fgets in modern C for safety

printf("Enter the second string: ");


gets(str2);

// String concatenation
strcpy(concatenated, str1); // Copy str1 to concatenated
strcat(concatenated, str2); // Append str2 to concatenated
// String length
length1 = strlen(str1);
length2 = strlen(str2);

// String comparison
comparison = strcmp(str1, str2);

// Output results
printf("\nConcatenated String: %s", concatenated);
printf("\nLength of First String: %d", length1);
printf("\nLength of Second String: %d", length2);

if (comparison == 0) {
printf("\nThe strings are equal.\n");
}
else {
printf("\nThe strings are not equal.\n");
}
getch ( );
}

To Save: Str.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to performs basic String Manipulations such as concatenation,
length calculation and comparison was executed and output verified successfully.
Array Operation
Ex. No.: 4. c

AIM:
To write a C program to perform the insert operation in the array.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Initialize an array arr of size n and input its elements.
STEP 3: Input the element x to be inserted and the position pos where it should be inserted.
STEP 4: Check if the position is valid (i.e., pos should be between 1 and n+1).
 If invalid, print an error message and exit.
STEP 5: Shift all elements from the position pos to the right by one position to make space
for the new element.
STEP 6: Insert the element x at position pos.
STEP 7: Increment the size of the array by 1.
STEP 8: Print the updated array.
STEP 9: End the program.

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

void main ( ) {
int arr[100], n, x, pos, i;
clrscr ( );

// Input the size of the array


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

// Input the elements of the array


printf("Enter %d elements: ", n);
for (i = 0; i < n; i++)

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

// Input the element to be inserted and its position


printf("Enter the element to insert: ");
scanf("%d", &x);
printf("Enter the position (1 to %d): ", n + 1);
scanf("%d", &pos);
// Check if the position is valid
if (pos < 1 || pos > n + 1) {
printf("Invalid position! Please enter a position between 1 and %d.\n", n + 1);
return 1;
}

// Shift elements to the right to make space for the new element
for (i = n; i >= pos; i--) {
arr[i] = arr[i - 1];
}

// Insert the new element


arr[pos - 1] = x;

// Increment the size of the array


n++;

// Print the updated array


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

To Save: Arr.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to perform the insert operation in the array was executed and
output verified successfully.
Storing and Displaying Student Information using Structures
Ex. No.: 5. a

AIM:
To write a C program to perform store and display Student Information using
Structures.

ALGORITHM:
STEP 1: Start
STEP 2: Define the Structure: struct Student groups related variables: rollno, name and
marks.
STEP 3: Read student detail such as rollno, name and marks.
STEP 4: Access Structure Members: Use the dot (.) operator to access and manipulate the
members.
STEP 5: Display the students information.
STEP 6: Stop.

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

struct student {
char name[50];
int roll;
int marks;
} s[5];

void main ( ) {
int i;
clrscr ( );
printf("Enter information of students:\n");

// storing information
for (i = 0; i < 3; i++) {
s[i].roll = i + 1;
printf("\nFor roll number: %d",i+1);
printf("\nEnter the name: ");
scanf("%s", s[i].name);
printf("Enter marks: ");
scanf("%d", &s[i].marks);
}
printf("\n");
printf("Displaying Students Information:");
// displaying information
printf("\n Roll number \t Name \t Marks \n");
for (i = 0; i < 3; i++) {
printf("\t%d\t\t %s\t\t %d\t",i+1,s[i].name,s[i].marks);
printf("\n");
}
getch ( );
}

To Save: Struct.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to perform store and display Student Information using
Structures was executed and output verified successfully.
Employee Payroll System using a Union
Ex. No.: 5. b

AIM:
To write a C program to perform store and display Employee Information using
Structures.

ALGORITHM:
STEP 1: Start
STEP 2: Define a union to hold general employee information (e.g., name, id and salary).
STEP 3: Read employee detail such as name, id and salary.
STEP 4: Union saves memory by sharing space among name, id, and salary.
STEP 5: Display all employee details.
STEP 6: Stop.

PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <string.h>

union Employee {
char name[50];
int id;
float salary;
};

void main ( ) {
union Employee emp;
clrscr ( );

printf("Enter Employee Name: ");


scanf("%s", [Link]);
printf("Employee Name: %s\n", [Link]);
// Input Employee ID
printf("Enter Employee ID: ");
scanf("%d", &[Link]);
printf("Employee ID: %d\n", [Link]);

// Input Employee Salary


printf("Enter Employee Salary: ");
scanf("%f", &[Link]);
printf("Employee Salary: %.2f\n", [Link]);

// Note: Only the last assigned value in the union will be valid
printf("\n Memory Sharing in Union:\n");
printf("Name (corrupted): %s\n", [Link]); // Corrupted due to memory sharing
printf("ID (corrupted): %d\n", [Link]); // Corrupted due to memory sharing
printf("Salary: %.2f\n", [Link]); // Only salary is valid

getch ( );
}

To Save: Uni.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to perform store and display Employee Information using
Structures was executed and output verified successfully.
Reading Data from a Text File
Ex. No.: 6. a

AIM:
To write a C program to read data from a Text File.

ALGORITHM:
STEP 1: Start
STEP 2: Open the file in read mode ("r") using fopen().
STEP 3: Check if the file pointer is NULL (indicating the file could not be opened).
 If NULL, display an error message and exit.
STEP 4: Use a loop to read the file contents:
 Use fscanf() to read formatted data.
STEP 5: Display the read data on the console.
STEP 6: Close the file using fclose().
STEP 7: Stop.

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

void main ( ) {
FILE *file;

int num;
char name[50];
char a[20];

clrscr ( );

printf("enter the file name:");


scanf("%s",&a);

// Open the file in read mode


file = fopen(a, "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error: Could not open file.\n");
return 1;
}

// Read and display formatted data (e.g., integer and string)


while (fscanf(file,"%s", name) != EOF) {
printf("%s\n", name);
}

// Close the file


fclose(file);

getch ( );
}

To Save: Read.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to read data from a Text File was executed and output verified
successfully.
Writing Data in a Text File
Ex. No.: 6. b

AIM:
To write a C program to write data in a Text File.

ALGORITHM:
STEP 1: Start
STEP 2: Declare necessary variables (e.g., file pointer, data to write).
STEP 3: Open the file in write mode using fopen().
 If the file cannot be opened, display an error message and exit.
STEP 4: Write data to the file using fprintf().
STEP 5: Close the file using fclose().
STEP 6: Stop.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void main ( )
{
FILE *filePointer; // File pointer
char data[100]; // Buffer to hold data to write
clrscr ( );
// Open the file in write mode

filePointer = fopen("[Link]", "w");

if (filePointer == NULL) {
printf("Error: Could not open file for writing.\n");
exit(1); // Exit if file cannot be opened
}
// Get data from the user
printf("Enter data to write to the file: ");
fgets(data, sizeof(data), stdin);

// Write data to the file


fprintf(filePointer, "%s", data);

// Close the file


fclose(filePointer);

printf("Data successfully written to '[Link]'.\n");


getch ( );

To Save: Write.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to write data to a File was executed and output verified
successfully.
Writing Data in a Binary File
Ex. No.: 6. c

AIM:
To write a C program to write data in a Binary File.

ALGORITHM:
STEP 1: Start
STEP 2: Create a structure to hold the data you want to store in the binary file.
STEP 3: Use fopen() in binary mode ("wb" for writing).
STEP 4: Use fwrite() to write the structure data to the binary file.
STEP 5: Use fclose() to close the file after operations.
STEP 6: Stop.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

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

void main ( )
{
struct Student s = {101, "John Doe", 85};

FILE *file = fopen("[Link]", "wb");


clrscr ( );

if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
fwrite(&s, sizeof(struct Student), 1, file);
printf("Data written to binary file successfully.\n");
fclose(file);

getch ( );

To Save: BinaryWrite.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to write data in a binary File was executed and output verified
successfully.
Implementation of Standard Libraries (math.h, string.h and stdlib.h)
Ex. No.: 7. a

AIM:
To write a C program to calculate the square root of a number, finds the length of a
string, and generates a random number using standard libraries.

ALGORITHM:
STEP 1: Start
STEP 2: Include the necessary header files (<stdio.h>, <math.h>, <string.h>, <stdlib.h>).
STEP 3: Prompt the user to enter a number to calculate its square root.
STEP 4: Use the sqrt() function from <math.h> to compute the square root.
STEP 5: Prompt the user to enter a string.
STEP 6: Use the strlen() function from <string.h> to calculate the length of the string.
STEP 7: Generate a random number using the rand() function from <stdlib.h>.
STEP 8: Display the results.
STEP 9: Stop.

PROGRAM:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

void main ( ) {
// Step 1: Calculate square root
double number, squareRoot;
int randomNumber, length;
char str[100];

clrscr ( );

printf("Enter a number to find its square root: ");


scanf("%lf", &number);
squareRoot = sqrt(number); // Using math.h
printf("The square root of %.2lf is %.2lf\n", number, squareRoot);

// Step 2: Find string length


printf("Enter a string: ");
scanf("%s", str);
length = strlen(str); // Using string.h
printf("The length of the string \"%s\" is %d\n", str, length);

// Step 3: Generate a random number


srand(time(0)); // Seed the random number generator
randomNumber = rand(); // Using stdlib.h
printf("A random number: %d\n", randomNumber);

getch ( );
}

To Save: stdlibrary.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to calculate the square root of a number, finds the length of a
string, and generates a random number using standard libraries was executed and output
verified successfully.
Implementation of Standard Libraries (time.h)
Ex. No.: 7. b

AIM:
To write a C program to display current date and time using standard libraries.

ALGORITHM:
STEP 1: Start
STEP 2: Include the time.h library in your program.
STEP 3: Initialize variables to store time-related data (e.g., time_t, struct tm).
STEP 4: Use time() to get the current calendar time.
STEP 5: Use localtime() or gmtime() to convert the time to a human-readable format.
STEP 6: Display or manipulate the time as required.
STEP 7: Stop.

PROGRAM:
#include <stdio.h>
#include <time.h>
#include <conio.h>

void main ( )
{
// Step 1: Get the current time
time_t current_time = time(NULL);
struct tm *local_time = localtime(&current_time);

// Step 2: Check if time retrieval was successful


if (current_time == -1) {
printf("Failed to get the current time.\n");
return 1;
}

// Step 3: Convert to local time


if (local_time == NULL) {
printf("Failed to convert to local time.\n");
return 1;
}
// Step 4: Display the current date and time
printf("Current local time: %s", asctime(local_time));

getch ( );
}

To Save: Standardlibrary.c
To Compile: Alt + F9
To Run: Ctrl + F9

RESULT:
Thus, the C program to display current date and time using standard libraries was
executed and output verified successfully.
Implementation of Standard Libraries (time.h)
Ex. No.: 7. c

AIM:
To write a C program to display current date and time using standard libraries.

ALGORITHM:
STEP 1: Start
STEP 2: Create a header file (mylib.h) and declare the function prototype.
STEP 3: Create a library source file (mylib.c) and define the function logic.
STEP 4: In the main program (main.c), include the user-defined header file.
STEP 5: Compile the main program and link it with the object file of the library
STEP 6: Display the result.
STEP 7: Stop

PROGRAM:
1. User-defined header file: mylib.h
#ifndef MYLIB_H
#define MYLIB_H

// Function prototypes
int add(int a, int b);
int sub(int a, int b);
int cub(int a);

#endif

2. Library function definition: mylib.c


#include "mylib.h"

// Function definitions
int add(int a, int b) {
return a + b;
}
int sub(int c, int d) {
return c - d;
}
int cub(int e) {
return e * e * e;
}

3. Main program using library: main.c


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

void main ( )
{
int sum = add(5, 3);
int difference = sub(5, 3);
int c = cub(3);

clrscr ( );

printf("Sum: %d, Difference: %d\n", sum, difference);


printf("Cube: %d\n", c);

getch ( );
}

4. Compilation Command
Note: Save all three files in the same folder.

To Compile and link


gcc main.c my_math.c -o output

To Run:
./ output

RESULT:
Thus, the C program to display current date and time using standard libraries was
executed and output verified successfully.

You might also like