CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] DEVELOP A PROGRAM USING INPUT AND OUTPUT
STATEMENTS
DATE:
AIM:
To write a C program to using Input and Output Statements.
PROCEDURE:
1. Start the program.
2. Use Unformulated input & output statements to get char or string
getchar(), getche() , getch() & gets()
3. Print the char or string using unformulated output statements
putch(), putchar() & puts()
4. Use formatted Input statements to read different types of data
scanf()
5. Print different types of data using formatted output statements
printf()
6. Stop the program.
SYNTAX:
Unformatted I/O
◦ charvariable=getchar();
◦ charvariable=getche();
◦ charvariable=getch();
◦ gets(chararray_variable);
◦ putch(charvariable);
◦ puts(chararray_variable);
Formatted I/O
◦ scanf(“format specifiers”,address of variables);
◦ printf(“Any text”);
◦ printf(“Any text,format spcifiers”,variables);
◦ printf(“format spcifiers”,variables);
1
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
PROGRAM:
#include <stdio.h>
#include <conio.h>
int main() {
// gets: Read a string from standard input
// puts: Write a string to standard output
char str[100];
printf("READING AND PRINTING STRING USING gets and puts");
printf("\nEnter a string: ");
gets(str);
puts(str);
// getchar: Read a character from standard input
// putch: Write a character to standard output
char ch;
printf("\nREADING AND PRINTING A CHARACTER USING getchar and putch");
printf("\nEnter a character: ");
ch = getchar();
putch(ch);
// getche: Read a character from standard input with echo
printf("\n");
printf("\nREADING A CHARACTER USING getche");
printf("\nEnter a character: ");
ch = getche();
printf("\nCharacter entered using getche: %c\n", ch);
// getch: Read a character from standard input without echo
printf("\nREADING A CHARACTER USING getch");
printf("\nEnter a character using getch: ");
ch = getch();
printf("\nCharacter entered using getch: %c\n", ch);
return 0;
}
2
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program for I/O statements has been written & executed successfully.
3
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] DEVELOP A PROGRAM USING ALL TYPE OF OPERATORS
AND EXPRESSIONS
DATE:
AIM:
To Write C programs using type of operators and expressions.
ALGORITHM:
1. Start the program.
2. Use Arithmetic operators (+,-,*,/,%)
3. Use Increment & Decrement Operators (++,--)
4. Use comparison operators (>,<,>=,<=,==,!=)
5. Use Bit wise operators (~,^,|,&)
6. Use logical operators (||,&&,!)
7. Use Ternary Operator (?:)
8. Stop the program.
SYNTAX:
Expression = Operand operator Operand
Operator : Symbol
Operand : variable or Constant
var1=Var2+Var3 (or) Var1=Value1+Value2; (or) Var1=Var2+value
Logical Operators : returns True(1) or false(0) values-Condition1&& Condition2
Ternary Operator: if condition is true, True part will be executed. Otherwise, False part will
be executed Var1= ( condition)? True part: False Part
PROGRAM:
#include <stdio.h>
int main() {
// Arithmetic operators
int a = 10, b = 5;
printf("Arithmetic Operators for a=10, b=5:\n");
printf("a + b = %d\n", a + b); // Addition
printf("a - b = %d\n", a - b); // Subtraction
printf("a * b = %d\n", a * b); // Multiplication
printf("a / b = %d\n", a / b); // Division
printf("a %% b = %d\n", a % b); // Modulus
// Relational operators
printf("\nRelational Operators for a=10, b=5:\n");
4
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("a > b is %d\n", a > b); // Greater than
printf("a < b is %d\n", a < b); // Less than
printf("a >= b is %d\n", a >= b); // Greater than or equal to
printf("a <= b is %d\n", a <= b); // Less than or equal to
printf("a == b is %d\n", a == b); // Equal to
printf("a != b is %d\n", a != b); // Not equal to
// Bitwise operators
int x = 5; // Binary: 0101
int y = 3; // Binary: 0011
printf("\nBitwise Operators for x=(0101) and y=3(0011):\n");
printf("x & y = %d\n", x & y); // Bitwise AND: 0001 (1)
printf("x | y = %d\n", x | y); // Bitwise OR: 0111 (7)
printf("x ^ y = %d\n", x ^ y); // Bitwise XOR: 0110 (6)
printf("~x = %d\n", ~x); // Bitwise NOT: 11111010 (-6)
printf("x << 1 = %d\n", x << 1); // Left shift by 1: 1010 (10)
printf("y >> 1 = %d\n", y >> 1); // Right shift by 1: 0001 (1)
// Logical operators
int c = 1, d = 0;
printf("\nLogical Operators for c=1 and d=0:\n");
printf("c && d is %d\n", c && d); // Logical AND
printf("c || d is %d\n", c || d); // Logical OR
printf("!c is %d, !d is %d\n", !c, !d); // Logical NOT
// Increment and decrement operators
int num = 5;
printf("\nIncrement and Decrement Operators for num=5:\n");
printf("num++ is %d\n", num++); // Post-increment
printf("++num is %d\n", ++num); // Pre-increment
printf("num-- is %d\n", num--); // Post-decrement
printf("--num is %d\n", --num); // Pre-decrement
// Assignment operators
int result;
printf("\nAssignment Operators for a=10 and b=5:\n");
result = a + b;
printf("result = a + b assigns result as %d\n", result);
result += a; // Equivalent to: result = result + a
printf("result += a assigns result as %d\n", result);
5
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
// Ternary operator (Conditional operator)
int max = (a > b) ? a : b; // If a > b, max = a, else max = b
printf("\nTernary Operator for a=10 and b=5 :\n");
printf("Maximum of %d and %d is: %d\n", a, b, max);
return 0;
}
OUTPUT:
6
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
RESULT:
Thus the C program for expressions has been written & executed successfully.
7
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] FINDING ODD OR EVEN USING IF-ELSE STATEMENT
DATE:
AIM:
To Write a C program to find whether a given number is odd or even using if-else statement.
ALGORITHM:
1. Start the program.
2. Read an input Value
3. Check the value is positive or negative.
4. Divide it by 2.
5. Take the remainder, if the remainder is greater than zero , then
6. Print the given Number is EVEN.
7. Otherwise, print the given Number is ODD.
8. Stop the Program.
SYNTAX:
if(condition)
statement;
else
statement;
PROGRAM:
#include <stdio.h>
int main() {
int num;
// Input a number from the user
printf("Enter a number: ");
scanf("%d", &num);
// Check if the number is positive, negative, or zero
if (num > 0) {
printf("The number is positive.\n");
}
else if (num < 0) {
printf("The number is negative.\n");
}
else {
8
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("The number is zero.\n");
}
// Check if the number is odd or even
if (num % 2 == 0) {
printf("The number is even.\n");
}
else {
printf("The number is odd.\n");
}
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
9
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] CREATING A BASIC CALCULATOR USING SWITCH-CASE
STATEMENT
DATE:
AIM:
To Write a C program to design a calculator to perform the operations, namely, addition,
subtraction, multiplication, division and square of a number.
ALGORITHM:
1. Start the program
2. Read an option to select the operation: [Link] [Link] [Link] [Link] [Link]
3. Enter the input values according to the operation.
4. Use switch case to perform the operation.
5. Print the Result.
6. Stop the program.
SYNTAX:
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block if no case matches
}
PROGRAM:
#include <stdio.h>
int main() {
char operator;
int num1, num2, result;
// Input operator and two numbers from the user
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
10
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
// Perform calculation based on the operator
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
} else {
printf("Error: Division by zero\n");
}
break;
default:
printf("Error: Invalid operator\n");
}
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
11
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] PROGRAM USING GOTO STATEMENTS
DATE:
AIM:
To write a C program using goto statement without any looping constructs.
ALGORITHM:
1. Start the program
2. Write the code to be looped inside the ‘repeat’ segment.
3. To execute the repeat code, use goto statement to call.
4. Print the Result.
5. Stop the program.
PROGRAM:
#include <stdio.h>
int main() {
int i = 1;
// Example of using continue statement without looping
printf("Printing 1 to 5 using continue statement without looping:\n");
repeat:
if (i <= 5) {
if (i == 3) {
i++; // Increment i before goto to avoid infinite loop
goto repeat; // Jump to the 'repeat' label when i equals 3
}
printf("%d\n", i);
i++;
goto repeat; // Repeat the process
}
return 0;
}
12
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
13
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] GENERATE FIBONACCI SERIES USING FOR LOOP
DATE:
AIM:
To write a C program to generate fibonacci series using for loop statement.
ALGORITHM:
1. Start the program
2. first and second are initialized to 0 and 1 respectively, as they are the first two terms of the
Fibonacci series.
3. Inside the for loop, we calculate the next term of the series by adding first and second.
4. Then, first is updated to the value of second, and second is updated to the value of next to
prepare for the next iteration.
5. The loop continues until i reaches the specified number of terms n.
6. Print the Result.
7. Stop the program.
SYNTAX:
for (initialization; condition; increment/decrement) {
// code block to be executed
}
PROGRAM:
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
// Input the number of terms from the user
printf("Enter the number of terms: ");
scanf("%d", &n);
// Print the Fibonacci series using a for loop
printf("Fibonacci Series:\n");
for (int i = 0; i < n; i++) {
if (i <= 1)
next = i;
else {
next = first + second;
first = second;
second = next;
}
14
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("%d, ", next);
}
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
15
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] CALCULATE SUM OF DIGITS USING WHILE LOOP
DATE:
AIM:
To write a C program to calculate sum of digits using while loop.
ALGORITHM:
1. Start the program
2. Initialize sum to zero to store the sum of digits.
3. In the while loop, we repeatedly extract the last digit of the number using the modulus
operator %, add it to the sum, and then remove the last digit from the number by integer
division /.
4. The loop continues until the number becomes zero, indicating that all digits have been
processed.
5. Print the Result.
6. Stop the program.
SYNTAX:
while(condition){
// Code to be executed while the condition is true
}
PROGRAM:
#include <stdio.h>
int main() {
int num, digit, sum = 0;
// Input a number from the user
printf("Enter a number: ");
scanf("%d", &num);
// Calculate the sum of digits
int temp = num; // Store the original number
while (temp != 0) {
digit = temp % 10; // Extract the last digit
sum += digit; // Add the last digit to the sum
temp /= 10; // Remove the last digit from the number
}
// Print the sum of digits
16
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("Sum of digits of %d is: %d\n", num, sum);
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
17
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] CALCULATE SUM OF NUMBERS USING DO-WHILE LOOP
DATE:
AIM:
To write a C program to calculate sum of numbers using do-while loop.
ALGORITHM:
1. Start the program
2. The program prompts the user to enter numbers continuously until they enter zero.
3. Inside the do-while loop, the program first prompts the user to enter a number.
4. It then checks if the entered number is non-negative. If it is, it adds the number to the sum.
5. The loop continues until the user enters ‘0’. Once a negative number is entered, the loop
terminates.
6. Print the Result.
1. Stop the program.
SYNTAX:
do{
// Code to be executed while the condition is true
}while(condition)
PROGRAM:
#include <stdio.h>
int main() {
int num;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%d", &num);
// Initialize sum to 0
int sum = 0;
// Perform the loop at least once
do {
// Add num to sum
sum += num;
// Prompt the user to enter another number
18
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("Enter another number (or 0 to exit): ");
scanf("%d", &num);
} while (num != 0); // Continue looping until num is 0
// Print the sum
printf("The sum is: %d\n", sum);
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
19
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] PROGRAM USING ARRAY TRAVERSING
DATE:
AIM:
To write a C program to traverse through 1D, 2D, multidimensional arrays and prints them.
ALGORITHM:
1. Start the program.
2. Initialize and assign values to 1D, 2D (3*3) and multidimensional array of (2*2*2), (3*2*2).
3. To traverse, calculate the size of each array.
4. Traverse through each array element using for loop.
5. Print the Result.
6. Stop the program.
PROGRAM:
#include <stdio.h>
int main() {
int i,j,k;
int size, rows,cols;
// 1D Array
int arr1D[5] = {1, 2, 3, 4, 5};
// 2D Array
int arr2D[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Multi-dimensional Array
int arrMulti[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
int arrMulti1[3][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}},
{{9, 10}, {11, 12}}
};
// Traversing and Print 1D Array
size = sizeof(arr1D) / sizeof(arr1D[0]);
20
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("1D Array of size %d:\n",size);
for (i = 0; i < size; i++) {
printf("%d ", arr1D[i]);
}
printf("\n");
// Traversing and Print 2D Array
rows = sizeof(arr2D) / sizeof(arr2D[0]); // Calculate number of rows
cols = sizeof(arr2D[0]) / sizeof(arr2D[0][0]); // Calculate number of columns
printf("\n2D Array of %d rows and %d column:\n",rows,cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", arr2D[i][j]);
}
printf("\n");
}
printf("\n");
// Traversing and printing elements of the multidimensional array of 2*2*2
printf("elements of the multidimensional array of 2*2*2\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
printf("%d ", arrMulti[i][j][k]);
}
printf("\n");
}
printf("\n");
}
// Traversing and printing elements of the multidimensional array of 3*2*2
printf("elements of the multidimensional array of 3*2*2\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
printf("%d ", arrMulti1[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
21
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
22
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] PROGRAM USING STRING OPERATION
DATE:
AIM:
To write a C program using string operation.
ALGORITHM:
1. 1. Start the program
2. Get two strings from user.
3. Do below operations,
String length: strlen(string);
String copy: strcpy(destination, string);
String concatenation: strcat(string1, string2);
String comparison: strcmp(string1, string2);
String searching: strstr(string , “character to be searched”);
String tokenization: strtok(string, “ “);
4. Print the Result.
5. Stop the program.
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20], dest[40], *ptr, *ptr1;
// String input
printf("Enter string 1: ");
scanf("%s", str1);
printf("Enter string 2: ");
scanf("%s", str2);
// String length
int length1 = strlen(str1);
int length2 = strlen(str2);
printf("Length of string 1: %d\n", length1);
printf("Length of string 2: %d\n", length2);
// String copy
strcpy(dest, str1);
printf("String copied to destination: %s\n", dest);
// String concatenation
23
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
strcat(dest, str2);
printf("Concatenated string: %s\n", dest);
// String comparison
int result = strcmp(str1, str2);
if (result < 0)
printf("%dString 1 is less than string 2\n",result);
else if (result == 0)
printf("String 1 is equal to string 2\n");
else
printf("String 1 is greater than string 2\n");
// String searching
ptr = strstr(dest, "a");
ptr1=strstr(str2, "a");
if (ptr != NULL)
printf("Substring 'a' found at position: %ld\n", ptr - dest);
else
printf("Substring not found\n");
if (ptr1 != NULL)
printf("Substring 'a' found at position: %ld\n", ptr1 - dest);
else
printf("Substring not found\n");
// String tokenization
char str[] = "Hello World";
char *token = strtok(str, " ");
printf("Tokens of 'Hello World':\n");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
24
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
25
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] PROGRAM USING FUNCTIONS CONCEPT
DATE:
AIM:
To write a C program using function calls and returns, as well as passing arguments both by
value and by reference, including arrays.
ALGORITHM:
1. Start the program
2. Write a function to add two values and return the result, by which function call by passing
value and return were executed.
3. Write a function to swap and double the values of two variables using pointers through
passing by reference.
4. Write a function to print an array by passing the array and its size.
5. Write a function to modify an array by adding a constant value to each element
6. From main function, call each function by passing respective arguments.
7. Print the Result.
8. Stop the program.
PROGRAM:
#include <stdio.h>
// Function to add two numbers and return the result
int add(int a, int b) {
return a + b;
}
// Function to swap the values of two variables using pointers (passing by reference)
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to double the value of a variable using pointers (passing by reference)
void doubleValue(int *num) {
*num *= 2;
}
// Function to print an array
void printArray(int arr[], int size) {
int i;
printf("Array: ");
for (i = 0; i < size; i++) {
26
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to modify an array by adding a constant value to each element
void addConstant(int arr[], int size, int constant) {
int i;
for (i = 0; i < size; i++) {
arr[i] += constant;
}
}
int main() {
// Function calls
int result = add(3, 5);
printf("Result of addition: %d\n", result);
int x = 10, y = 20;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
int num = 5;
printf("Before doubling: num = %d\n", num);
doubleValue(&num);
printf("After doubling: num = %d\n", num);
int arr[] = {1, 2, 3, 4, 5};
int arrSize = sizeof(arr) / sizeof(arr[0]);
printArray(arr, arrSize);
int constant = 10;
printf("Adding %d to each element of the array\n", constant);
addConstant(arr, arrSize, constant);
printArray(arr, arrSize);
return 0;
}
27
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
28
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] SOLVING THE TOWER OF HANOI PROBLEM USING
RECURSION
DATE:
AIM:
To write a C program solving the Tower of Hanoi problem using recursion.
ALGORITHM:
1. Start the program.
2. The towerOfHanoi function takes four parameters: n, the number of disks to be moved;
source, the rod from which disks will be moved; temp, the temp rod; and destination,
the rod to which disks will be moved.
3. If n is 1, it directly moves the disk from the source rod to the destination rod.
4. Otherwise, it recursively moves n-1 disks from the source rod to the temp rod, then
moves the n-th disk from the source rod to the destination rod, and finally recursively
moves n-1 disks from the temp rod to the destination rod
5. Print the Result.
1. Stop the program.
PROGRAM:
#include <stdio.h>
// Function to move disks from source peg to destination peg using temp peg
void towersOfHanoi(int numDisks, char source, char destination, char temp) {
if (numDisks == 1) {
printf("Move disk 1 from peg %c to peg %c\n", source, destination);
return;
}
// Move top n-1 disks from source peg to temp peg using destination peg
towersOfHanoi(numDisks - 1, source, temp, destination);
// Move the remaining disk from source peg to destination peg
printf("Move disk %d from peg %c to peg %c\n", numDisks, source, destination);
// Move the n-1 disks from temp peg to destination peg using source peg
towersOfHanoi(numDisks - 1, temp, destination, source);
}
int main() {
int numDisks;
printf("Enter the number of disks: ");
scanf("%d", &numDisks);
29
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
// Assuming the pegs are labeled A, B, and C
towersOfHanoi(numDisks, 'A', 'C', 'B');
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
30
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] EMPLOYEE DETAILS PROGRAM USING STRUCTURES
DATE:
AIM:
To write a C program to read, store and retrieve employee details using structures: nested
structures, pointers to structures, arrays of structures.
ALGORITHM:
1. Start the program.
2. We define structures: Date for representing day, month and year for representing
employee's DOB.
3. We define the Employee nested structures that contains members for employee's name,
ID, DOB of DATE structure.
4. We create an array of Employee structures to hold details of multiple employees.
5. We use loops to input and print employee details, including their name, ID, DOB.
6. Stop the program.
PROGRAM:
#include <stdio.h>
#include <string.h>
// Define a structure for storing date
struct Date {
int day;
int month;
int year;
};
// Define a nested structure for storing employee details
struct Employee {
int empId;
char name[50];
struct Date dob;
};
int main() {
int i;
// Example of nested structure with user input
struct Employee emp1;
printf("Enter Employee ID: ");
scanf("%d", &[Link]);
printf("Enter Employee Name: ");
31
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
scanf("%s", [Link]);
printf("Enter Employee Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &[Link], &[Link], &[Link]);
printf("Employee Details:\n");
printf("ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("Date of Birth: %d-%d-%d\n", [Link], [Link], [Link]);
printf("\n");
// Example of pointers to structures with user input
struct Employee emp2;
struct Employee *ptrEmp = &emp2;
printf("Enter Employee ID: ");
scanf("%d", &ptrEmp->empId);
printf("Enter Employee Name: ");
scanf("%s", ptrEmp->name);
printf("Enter Employee Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &ptrEmp->[Link], &ptrEmp->[Link], &ptrEmp->[Link]);
printf("Employee Details (via Pointer):\n");
printf("ID: %d\n", ptrEmp->empId);
printf("Name: %s\n", ptrEmp->name);
printf("Date of Birth: %d-%d-%d\n", ptrEmp->[Link], ptrEmp->[Link], ptrEmp->[Link]);
printf("\n");
// Example of arrays of structures with user input
struct Employee empArray[3];
printf("Enter Employee Details for 3 Employees:\n");
for (i = 0; i < 3; i++) {
printf("Enter details for Employee %d:\n", i+1);
printf("ID: ");
scanf("%d", &empArray[i].empId);
printf("Name: ");
scanf("%s", empArray[i].name);
printf("Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &empArray[i].[Link], &empArray[i].[Link],
&empArray[i].[Link]);
printf("\n");
}
printf("Employee Details (Array of Structures):\n");
for (i = 0; i < 3; i++) {
printf("Employee %d:\n", i+1);
printf("ID: %d\n", empArray[i].empId);
printf("Name: %s\n", empArray[i].name);
printf("Date of Birth: %d-%d-%d\n", empArray[i].[Link], empArray[i].[Link],
32
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
empArray[i].[Link]);
printf("\n");
}
return 0;
}
OUTPUT:
33
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
RESULT:
Thus the program is written & executed successfully.
34
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] STUDENT DETAILS PROGRAM USING UNION
DATE:
AIM:
To write a C program to read, store and retrieve student details using union for storing
different types of data.
ALGORITHM:
1. Start the program
2. We define union: StudentUnion for representing id, name and cgpa for representing
student details where each are in different data types.
3. Get students details from user and store in defined union structure.
4. Print the details.
5. Stop the program.
PROGRAM:
#include <stdio.h>
#include <string.h>
// Define a union for storing different types of data
union StudentUnion {
int id;
float cgpa;
char name[20];
};
int main() {
union StudentUnion student;
// Example of using the union with different types of data
printf("Enter an ID: ");
scanf("%d", &[Link]);
printf("ID: %d\n", [Link]);
printf("Enter CGPA: ");
scanf("%f", &[Link]);
printf("CGPA: %f\n", [Link]);
printf("Enter NAME: ");
scanf("%s", [Link]);
printf("Name: %s\n", [Link]);
return 0;
}
35
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
36
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] SEQUENTIAL ACCESS FILE
DATE:
AIM:
To write a C program to read and retrieve file content using sequential file access.
ALGORITHM:
1. Start the program
2. Declare a file pointer filePointer to interact with the file.
3. Use fopen to open the file in read mode ("r").
4. Use fgets in a loop to read lines from the file and print them using fprintf until the end of
the file is reached.
5. close the file using fclose
6. Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *filePointer;
char filename[] = "[Link]";
// Writing data to a file
filePointer = fopen(filename, "w");
if (filePointer == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
// Write data to the file
char inputBuffer[100];
printf("Enter lines of text to write to the file (Enter 'EOF' to end):\n");
while (fgets(inputBuffer, sizeof(inputBuffer), stdin)) {
if (strcmp(inputBuffer, "EOF\n") == 0) // Check for end of input
break;
fprintf(filePointer, "%s", inputBuffer);
}
fclose(filePointer);
printf("Data written to file successfully.\n\n");
// Reading data from the file sequentially
filePointer = fopen(filename, "r");
37
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
if (filePointer == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
printf("Reading data from file:\n");
char buffer[100];
while (fgets(buffer, sizeof(buffer), filePointer)) {
printf("%s", buffer);
}
fclose(filePointer);
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
38
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
[Link] RANDOM ACCESS FILE
DATE:
AIM:
To write a C program to read and retrieve file content using random file access.
ALGORITHM:
1. Start the program
2. We define structure: Record for representing id, name.
3. Get details from user and store in file.
4. To get particular record, use fseek() function to randomly access the record by passing id
for that record.
5. Print the details.
6. Close the file.
7. Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct Record {
int id;
char name[50];
};
int main() {
int i;
FILE *filePointer;
char filename[] = "[Link]";
// Writing data to a file
filePointer = fopen(filename, "wb");
if (filePointer == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
struct Record records[3];
printf("Enter details for 3 records:\n");
for (i = 0; i < 3; i++) {
printf("Record %d:\n", i + 1);
printf("ID: ");
scanf("%d", &records[i].id);
printf("Name: ");
39
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
scanf("%s", records[i].name);
fwrite(&records[i], sizeof(struct Record), 1, filePointer);
}
fclose(filePointer);
printf("Data written to file successfully.\n\n");
// Reading data from the file using random access
filePointer = fopen(filename, "rb");
if (filePointer == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
printf("Reading data from file:\n");
int recordNumber;
printf("Enter record number to read (0-2): ");
scanf("%d", &recordNumber);
fseek(filePointer, recordNumber * sizeof(struct Record), SEEK_SET);
struct Record record;
fread(&record, sizeof(struct Record), 1, filePointer);
printf("Record %d:\n", recordNumber + 1);
printf("ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
fclose(filePointer);
return 0;
}
40
CS3271-PROGRAMMING IN C LABORATORY 2023-2024
OUTPUT:
RESULT:
Thus the program is written & executed successfully.
41