CPTC Aman Sinha
CPTC Aman Sinha
CPTC Aman Sinha
Materials Needed
Computer with internet access
Text editor (e.g., Visual Studio Code, Sublime Text, Atom)
Compiler/Interpreter (e.g., Python, GCC for C/C++)
Command-line interface (e.g., Terminal, Command Prompt)
Git (for version control)
Procedure
Part 1: Setting Up Your Environment
1. File Management
o Learn basic command-line operations for managing files and directories,
including:
Listing files (ls or dir)
Creating directories (mkdir)
Changing directories (cd)
Deleting files (rm or del)
2. Understanding Command-Line Syntax
o Familiarize yourself with the syntax and structure of command-line
commands, including options and arguments.
Conclusion
By completing this practical, you have gained familiarity with the programming environment,
including text editors, compilers, and version control systems. This foundational
understanding will support your development as a programmer.
Practical : 2
Objective:
To understand and implement programs in C that utilize Input/Output (I/O) statements and
various operators such as arithmetic, relational, logical, bitwise, assignment, and conditional
operators.
Tools Required:
Problem Statement:
Write a C program to take two integers as input from the user and display their sum,
difference, product, and quotient.
Code:
#include <stdio.h>
int main() {
// Taking input
// Displaying results
if (num2 != 0) {
} else {
return 0;
Problem Statement:
Write a C program to calculate the area and perimeter of a rectangle using arithmetic
operators.
Code:
#include <stdio.h>
int main() {
// Taking input
return 0;
Problem Statement:
Write a C program to check if a given number is even and divisible by 5.
Code:
#include <stdio.h>
int main() {
int num;
// Taking input
printf("Enter an integer: ");
scanf("%d", &num);
// Checking conditions
if ((num % 2 == 0) && (num % 5 == 0)) {
printf("The number is even and divisible by 5.\n");
} else {
printf("The number does not satisfy the condition.\n");
}
return 0;
}
Problem Statement:
Write a C program to demonstrate the use of bitwise AND, OR, and XOR operators on two
integers.
Code:
#include <stdio.h>
int main() {
int num1, num2;
// Taking input
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
return 0;
}
Problem Statement:
Write a C program to find the largest of two numbers using the conditional operator.
Code:
#include <stdio.h>
int main() {
int num1, num2, largest;
// Taking input
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
// Displaying result
printf("The largest number is: %d\n", largest);
return 0;
}
Problem Statement:
Write a C program to demonstrate the use of compound assignment operators (+=, -=, *=,
/=).
Code:
#include <stdio.h>
int main() {
int num = 10;
return 0;
}
Problem Statement:
Write a C program to check if a number is between 10 and 50 using logical operators.
Code:
#include <stdio.h>
int main() {
int num;
// Taking input
printf("Enter an integer: ");
scanf("%d", &num);
return 0;
}
Conclusion:
This practical helped in understanding the use of various operators and I/O statements in C
programming. The knowledge of these concepts is crucial for building more complex
programs that involve calculations, comparisons, and decisions based on user input.
Practical : 3
Objective:
To understand and implement C programs that demonstrate expression evaluation and the
precedence of operators in C.
Tools Required:
Key Concepts:
Problem Statement:
Write a C program to evaluate the expression a + b * c without parentheses and verify the
result based on operator precedence.
Code:
#include <stdio.h>
int main() {
int a, b, c, result;
// Taking input
printf("Enter values for a, b, and c: ");
scanf("%d %d %d", &a, &b, &c);
return 0;
}
Explanation:
Since multiplication (*) has higher precedence than addition (+), b * c is evaluated first,
then added to a.
Problem Statement:
Write a C program to evaluate the expression (a + b) * c with parentheses and compare it
with the previous program.
Code:
#include <stdio.h>
int main() {
int a, b, c, result;
// Taking input
printf("Enter values for a, b, and c: ");
scanf("%d %d %d", &a, &b, &c);
return 0;
}
Explanation:
By using parentheses, the addition a + b is forced to be evaluated first, followed by
multiplication with c. This changes the order of operations compared to the previous
program.
Code:
#include <stdio.h>
int main() {
int a, b, c;
int result;
// Taking input
printf("Enter values for a, b, and c: ");
scanf("%d %d %d", &a, &b, &c);
return 0;
}
Explanation:
Relational operators (>, <) are evaluated before the logical AND (&&) operator. So, a > b and
b > c are evaluated first, and their results are combined using &&.
Problem Statement:
Write a C program to evaluate a complex expression and understand how different operators
are prioritized.
Expression: result = a + b * c / d - e
Code:
#include <stdio.h>
int main() {
int a, b, c, d, e, result;
// Taking input
printf("Enter values for a, b, c, d, and e: ");
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
Explanation:
The operators are evaluated in the following order based on precedence:
1. b * c (Multiplication)
2. (b * c) / d (Division)
3. a + (b * c / d) (Addition)
4. (a + b * c / d) - e (Subtraction)
Problem Statement:
Write a C program to demonstrate the associativity of operators by evaluating the expression
a - b - c.
Code:
#include <stdio.h>
int main() {
int a, b, c, result;
// Taking input
printf("Enter values for a, b, and c: ");
scanf("%d %d %d", &a, &b, &c);
return 0;
}
Explanation:
Since subtraction (-) is left-associative, the expression is evaluated as (a - b) - c.
Problem Statement:
Write a C program to evaluate a conditional expression using the ternary operator.
Code:
#include <stdio.h>
int main() {
int a, b, result;
// Taking input
printf("Enter values for a and b: ");
scanf("%d %d", &a, &b);
return 0;
}
Explanation:
The ternary operator checks the condition a > b. If true, it returns a; otherwise, it returns b.
Conclusion:
This practical demonstrated how operator precedence and associativity influence the
evaluation of expressions in C. Understanding how different operators are prioritized helps in
writing correct and efficient C programs.
Practical : 4
Objective:
Tools Required:
Key Concepts:
Problem Statement:
Write a C program to check if a given number is positive using the if statement.
Code:
#include <stdio.h>
int main() {
int number;
// Taking input
printf("Enter an integer: ");
scanf("%d", &number);
Explanation:
The program uses a simple if statement to check if the number is greater than zero. If the
condition is true, the message "The number is positive" is displayed.
Problem Statement:
Write a C program to check if a number is even or odd using the if-else statement.
Code:
#include <stdio.h>
int main() {
int number;
// Taking input
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Explanation:
The program uses the if-else statement to check if the number is divisible by 2. If true, it
displays "The number is even"; otherwise, it displays "The number is odd."
Problem Statement:
Write a C program to check the grade of a student based on marks using the else-if ladder.
Conditions:
#include <stdio.h>
int main() {
int marks;
// Taking input
printf("Enter your marks (out of 100): ");
scanf("%d", &marks);
return 0;
}
Explanation:
The program evaluates the marks using an else-if ladder and assigns a grade based on the
conditions provided.
Problem Statement:
Write a C program to perform basic arithmetic operations (addition, subtraction,
multiplication, and division) using the switch-case statement.
Code:
#include <stdio.h>
int main() {
int num1, num2, result;
char operator;
// Taking input
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
return 0;
}
Explanation:
The switch-case statement is used to select the arithmetic operation based on the operator
entered by the user.
Problem Statement:
Write a C program that takes a number as input and uses the goto statement to check whether
the number is positive, negative, or zero.
Code:
#include <stdio.h>
int main() {
int number;
// Taking input
printf("Enter an integer: ");
scanf("%d", &number);
negative:
printf("The number is negative.\n");
return 0;
zero:
printf("The number is zero.\n");
return 0;
}
Explanation:
The goto statement is used to jump to specific labels (positive, negative, or zero) based
on the value of the input number.
Problem Statement:
Write a C program to check if a given year is a leap year using nested if-else statements.
Code:
#include <stdio.h>
int main() {
int year;
// Taking input
printf("Enter a year: ");
scanf("%d", &year);
return 0;
}
Explanation:
The program uses nested if-else statements to check whether the given year is a leap year
by checking conditions for divisibility by 4, 100, and 400.
Conclusion:
Objective:
To understand and implement loop control structures in C language, including for, while,
and do-while loops, which are used for repeated execution of a block of code.
Tools Required:
Key Concepts:
Loops: Loops are control structures used to repeat a block of code multiple times.
o for loop: Used when the number of iterations is known beforehand.
o while loop: Used when the number of iterations is not known and depends on
a condition.
o do-while loop: Similar to while, but the condition is checked after the loop
body is executed.
Problem Statement:
Write a C program to print the first 10 natural numbers using a for loop.
Code:
#include <stdio.h>
int main() {
// Loop to print the first 10 natural numbers
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
Explanation:
The loop runs from 1 to 10, printing each number. The initialization (i = 1), condition (i <=
10), and increment (i++) are all specified in the for statement.
Program 2: Using the while Loop
Problem Statement:
Write a C program to print the sum of all even numbers between 1 and 20 using a while
loop.
Code:
#include <stdio.h>
int main() {
int num = 2, sum = 0;
return 0;
}
Explanation:
The while loop continues to add even numbers from 2 to 20. The loop terminates when num
becomes greater than 20.
Problem Statement:
Write a C program to take input from the user until they enter a positive number using a do-
while loop.
Code:
#include <stdio.h>
int main() {
int number;
return 0;
}
Explanation:
The do-while loop ensures that the body of the loop (input prompt) is executed at least once.
It keeps asking for input until the user enters a positive number.
Problem Statement:
Write a C program to print a multiplication table from 1 to 5 using a nested for loop.
Code:
#include <stdio.h>
int main() {
// Outer loop for the multiplication table numbers
for (int i = 1; i <= 5; i++) {
printf("Multiplication Table for %d:\n", i);
return 0;
}
Explanation:
The outer loop controls the multiplication table number (i), and the inner loop runs from 1 to
10 to print the multiplication for each number.
Problem Statement:
Write a C program to find the first number divisible by 7 between 1 and 50 using a for loop
and the break statement.
Code:
#include <stdio.h>
int main() {
// Loop to find the first number divisible by 7
for (int i = 1; i <= 50; i++) {
if (i % 7 == 0) {
printf("The first number divisible by 7 between 1 and 50 is:
%d\n", i);
break; // Exit the loop as soon as the condition is met
}
}
return 0;
}
Explanation:
The loop checks each number from 1 to 50 for divisibility by 7. The break statement exits
the loop once the first such number is found.
Problem Statement:
Write a C program to print all numbers from 1 to 10 except 5 using the continue statement
in a for loop.
Code:
#include <stdio.h>
int main() {
// Loop to print numbers from 1 to 10, except 5
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the current iteration when i equals 5
}
printf("%d\n", i);
}
return 0;
}
Explanation:
The continue statement skips the iteration when i equals 5, so 5 is not printed, but the rest
of the loop executes normally.
Problem Statement:
Write a C program that demonstrates an infinite loop using a while loop.
Code:
#include <stdio.h>
int main() {
int counter = 0;
// Infinite loop
while (1) {
printf("This is an infinite loop. Counter: %d\n", counter);
counter++;
if (counter == 5) {
printf("Breaking the infinite loop after 5 iterations.\n");
break; // Exit the loop after 5 iterations
}
}
return 0;
}
Explanation:
This program demonstrates an infinite loop, which runs indefinitely because the condition 1
always evaluates to true. The loop is broken after 5 iterations using the break statement.
Conclusion:
This practical demonstrated how to use loop statements (for, while, do-while) and control
statements (break, continue) in C programming. Loop control structures are essential for
executing repetitive tasks efficiently.
Practical : 6
Practical: Programs to Demonstrate Applications of N-Dimensional Arrays in
C Language
Objective:
To understand and implement programs that demonstrate the use of one-dimensional, two-
dimensional, and multi-dimensional arrays in C programming for various applications.
Tools Required:
Key Concepts:
Problem Statement:
Write a C program to find the sum and average of elements in a one-dimensional array.
Code:
#include <stdio.h>
int main() {
int n, i, sum = 0;
float average;
int arr[n];
// Calculating average
average = (float)sum / n;
return 0;
}
Explanation:
The program takes n elements from the user, stores them in a 1-dimensional array, and then
calculates the sum and average of those elements.
Problem Statement:
Write a C program to add two 2x2 matrices using two-dimensional arrays.
Code:
#include <stdio.h>
int main() {
int matrix1[2][2], matrix2[2][2], result[2][2];
int i, j;
return 0;
}
Explanation:
The program takes input for two 2x2 matrices, adds the corresponding elements, and prints
the resulting matrix. Two-dimensional arrays are used to represent the matrices.
Problem Statement:
Write a C program to multiply two 3x3 matrices using two-dimensional arrays.
Code:
#include <stdio.h>
int main() {
int matrix1[3][3], matrix2[3][3], result[3][3];
int i, j, k;
return 0;
}
Explanation:
This program multiplies two 3x3 matrices by using a nested loop structure. Each element in
the resulting matrix is computed by multiplying the corresponding row elements of the first
matrix by the column elements of the second matrix.
Problem Statement:
Write a C program to store elements in a 3x2x2 array and print them.
Code:
#include <stdio.h>
int main() {
int arr[3][2][2];
int i, j, k;
return 0;
}
Explanation:
The program demonstrates a three-dimensional array where elements are arranged in layers
(3 layers, each 2x2). It allows the user to input values into the array and then prints all stored
elements.
Problem Statement:
Write a C program to store and display the marks of 3 students in 4 subjects using a two-
dimensional array.
Code:
#include <stdio.h>
int main() {
int marks[3][4]; // 3 students, 4 subjects
int i, j;
return 0;
}
Explanation:
This program stores the marks of 3 students in 4 subjects using a two-dimensional array. The
first index represents the student, and the second index represents the subjects. The program
allows input and then displays the data in a table format.
Conclusion:
This practical demonstrated how to work with one-dimensional, two-dimensional, and multi-
dimensional arrays in C programming. Arrays are useful for storing multiple elements in a
structured manner, which makes it easy to perform various computations and tasks.
Practical : 7
Practical: Programs to Demonstrate Use of String Manipulation Functions in
C Language
Objective:
To understand and implement various string manipulation functions available in C for tasks
like copying, concatenation, length calculation, comparison, and reversing of strings.
Tools Required:
Key Concepts:
Problem Statement:
Write a C program to calculate the length of a string using the strlen() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
Explanation:
This program takes a string as input from the user and calculates its length using the
strlen() function. The result is displayed to the user.
Problem Statement:
Write a C program to copy one string to another using the strcpy() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char source[100], destination[100];
return 0;
}
Explanation:
The program copies the content of the source string into the destination string using the
strcpy() function. Both the source and destination strings are then printed.
Problem Statement:
Write a C program to concatenate two strings using the strcat() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[50];
// Taking input for the first string
printf("Enter the first string: ");
gets(str1);
return 0;
}
Explanation:
The program concatenates the second string to the end of the first string using the strcat()
function and prints the result.
Problem Statement:
Write a C program to compare two strings using the strcmp() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
Explanation:
The program compares two strings using the strcmp() function. It prints whether the strings
are equal or one is lexicographically smaller or larger than the other.
Problem Statement:
Write a C program to reverse a string using a custom implementation (since strrev() is not
part of the standard C library in all compilers).
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
return 0;
}
Explanation:
This program implements a custom function to reverse a string. It swaps characters from the
start and end of the string until the midpoint is reached. The reversed string is then displayed.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
return 0;
}
Explanation:
This program checks if a given string is a palindrome. It compares characters from the
beginning and end of the string until the midpoint is reached. If all characters match, the
string is a palindrome.
Conclusion:
This practical demonstrated the usage of common string manipulation functions in C, such as
strlen(), strcpy(), strcat(), strcmp(), and the custom function for reversing strings.
These functions are essential for performing operations on strings in C.
Practical : 8
Objective:
1. Pass by Value
2. Pass by Reference
Theory:
1. Pass by Value: In this mechanism, a copy of the actual parameter is passed to the
function. Changes made to the formal parameters in the function do not affect the
actual parameters.
2. Pass by Reference: Instead of passing a copy of the parameter, the address
(reference) of the actual parameter is passed to the function. Therefore, changes made
to the formal parameters affect the actual parameters.
In this program, we will demonstrate that modifications made to the function parameters do
not reflect in the calling function.
#include <stdio.h>
int main() {
int x = 10, y = 20;
printf("Before swapByValue: x = %d, y = %d\n", x, y);
return 0;
}
Output:
Before swapByValue: x = 10, y = 20
Inside swapByValue function: a = 20, b = 10
After swapByValue: x = 10, y = 20
Explanation:
In the Pass by Value mechanism, the values of x and y are copied into the function
parameters a and b. Changing a and b inside the function does not affect x and y.
In this program, we will pass the address of the variables to the function, allowing it to
modify the actual values.
#include <stdio.h>
int main() {
int x = 10, y = 20;
printf("Before swapByReference: x = %d, y = %d\n", x, y);
return 0;
}
Output:
Before swapByReference: x = 10, y = 20
Inside swapByReference function: a = 20, b = 10
After swapByReference: x = 20, y = 10
Explanation:
In the Pass by Reference mechanism, the addresses of x and y are passed to the function.
The function uses these addresses to modify the actual values of x and y, leading to the swap
of their values.
Conclusion:
Pass by Value: Changes made inside the function do not affect the actual variables.
Pass by Reference: Changes made inside the function affect the actual variables
because their memory addresses are passed.
Practical : 9
Objective:
Tools Required:
Key Concepts:
Recursion: A technique where a function calls itself to solve a smaller instance of the
same problem. Recursion continues until a base condition is met, which stops further
recursive calls.
Problem Statement:
Write a C program to calculate the factorial of a given number using recursion.
Code:
#include <stdio.h>
int main() {
int num;
// Calculating factorial
int result = factorial(num);
return 0;
}
Explanation:
This program calculates the factorial of a given number using recursion. The base case is
when n is 0 or 1, where the factorial is 1. The recursive step multiplies n by the factorial of n-
1.
Problem Statement:
Write a C program to generate the Fibonacci series up to n terms using recursion.
Code:
#include <stdio.h>
int main() {
int n, i;
return 0;
}
Explanation:
This program generates the Fibonacci series using recursion. The base cases return 0 and 1
for the 0th and 1st terms, respectively. For other terms, the function recursively adds the
previous two terms to get the next Fibonacci number.
Program 3: GCD (Greatest Common Divisor) using Recursion
Problem Statement:
Write a C program to compute the greatest common divisor (GCD) of two numbers using
recursion.
Code:
#include <stdio.h>
int main() {
int num1, num2;
// Calculating GCD
int result = gcd(num1, num2);
return 0;
}
Explanation:
This program calculates the GCD of two numbers using the Euclidean algorithm, which is
implemented recursively. The base case occurs when b becomes 0, and the function returns a
as the GCD.
Problem Statement:
Write a C program to solve the Tower of Hanoi problem using recursion.
Code:
#include <stdio.h>
int main() {
int num_disks;
return 0;
}
Explanation:
This program solves the Tower of Hanoi problem using recursion. It moves n-1 disks from
the source rod to the auxiliary rod, moves the nth disk to the destination rod, and then moves
the n-1 disks from the auxiliary rod to the destination rod.
Problem Statement:
Write a C program to calculate the sum of digits of a number using recursion.
Code:
#include <stdio.h>
int main() {
int num;
return 0;
}
Explanation:
This program calculates the sum of digits of a given number using recursion. The base case
occurs when the number becomes 0, and the function returns 0. Otherwise, it adds the last
digit of the number to the sum of the digits of the remaining number.
Conclusion:
This practical demonstrated the use of recursion in various applications like calculating
factorial, generating the Fibonacci series, finding the GCD, solving the Tower of Hanoi, and
summing the digits of a number. Recursion is a powerful technique that can simplify the
solution to complex problems by breaking them into smaller subproblems.
Practical : 10
Practical Title: Demonstrating the Use of Pointers in C
Objective:
Theory:
1. Pointer: A pointer is a variable that stores the memory address of another variable.
Pointers are powerful because they allow you to manipulate data stored in memory
directly.
o Declaration:
c
Copy code
int *ptr;
o Accessing values using pointers: You can access the value stored at the
memory location pointed to by the pointer using the dereference operator (*).
2. Pointer Arithmetic: You can perform arithmetic operations on pointers such as
incrementing or decrementing them, which moves the pointer to the next or previous
memory location based on the size of the data type.
3. Pointer to Pointer: A pointer that stores the address of another pointer is called a
pointer to a pointer.
int main() {
int a = 10; // A normal integer variable
int *ptr; // Pointer to an integer
return 0;
}
Output:
Address of a: 0x7ffeefbff54c
Address stored in pointer ptr: 0x7ffeefbff54c
Value of a using pointer: 10
Modified value of a using pointer: 20
Explanation:
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // An array of integers
int *ptr = arr; // Pointer to the first element of
the array
return 0;
}
Output:
Pointer arithmetic demonstration:
Value of arr[0] = 10, Address = 0x7ffeefbff54c
Value of arr[1] = 20, Address = 0x7ffeefbff550
Value of arr[2] = 30, Address = 0x7ffeefbff554
Value of arr[3] = 40, Address = 0x7ffeefbff558
Value of arr[4] = 50, Address = 0x7ffeefbff55c
Explanation:
int main() {
int a = 100;
int *ptr; // Pointer to an integer
int **pptr; // Pointer to pointer
return 0;
}
Output:
Value of a: 100
Value of a using ptr: 100
Value of a using pptr: 100
Explanation:
Conclusion:
Objective:
To understand how to use command line arguments in C programs for inputting data during
program execution.
Tools Required:
Key Concepts:
Problem Statement:
Create a C program that performs basic arithmetic operations (addition, subtraction,
multiplication, division) on two numbers provided as command line arguments.
Code:
#include <stdio.h>
#include <stdlib.h>
return 0;
}
Explanation:
1. Input Handling: The program checks if exactly three arguments are provided (the
program name, the first number, the operator, and the second number). If not, it
displays usage information and exits.
2. Argument Conversion: It converts the first and third arguments from strings to
floating-point numbers using atof(), and retrieves the operator.
3. Operation Execution: Based on the operator provided, it performs the corresponding
arithmetic operation and displays the result. If the division operation is attempted with
zero as the second number, an error message is shown.
./calculator 10 + 20
This practical exercise illustrates how to effectively use command line arguments in C to
perform operations based on user input directly from the command line. Understanding
command line arguments is essential for developing flexible C programs that can handle user
input dynamically.
Practical : 12
Practical Title: Demonstrating Dynamic Memory Allocation in C
Objective:
1. malloc()
2. calloc()
3. realloc()
4. free()
Theory:
Dynamic memory allocation allows programs to request memory at runtime, rather than at
compile time. This is useful for creating data structures like linked lists, trees, and dynamic
arrays.
Functions:
int main() {
int *arr;
int n, i;
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit if memory allocation fails
}
// Input elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display elements
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter number of elements: 5
Enter 5 elements:
10 20 30 40 50
You entered:
10 20 30 40 50
Explanation:
int main() {
int *arr;
int n, i;
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit if memory allocation fails
}
// Displaying initial values (should be zero)
printf("Initial values in the array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Input elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display elements
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter number of elements: 3
Initial values in the array:
0 0 0
Enter 3 elements:
5 15 25
You entered:
5 15 25
Explanation:
int main() {
int *arr;
int n, newSize, i;
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit if memory allocation fails
}
// Input elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
Output:
Enter initial number of elements: 3
Enter 3 elements:
10 20 30
You entered:
10 20 30
Enter new size for the array: 5
Enter additional 2 elements:
40 50
Elements in the array after resizing:
10 20 30 40 50
Explanation:
The program first allocates memory for an array of integers and accepts initial values.
It then prompts the user for a new size, using realloc() to resize the array.
If the new size is greater, it prompts for additional input and displays all elements.
Finally, it frees the allocated memory.
Conclusion:
Objective:
To understand and implement basic file operations in C, including creating, reading, writing,
and closing files.
Tools Required:
Key Concepts:
File Operations in C:
o Opening a file: Using fopen().
o Reading from a file: Using fscanf(), fgets(), or fread().
o Writing to a file: Using fprintf(), fputs(), or fwrite().
o Closing a file: Using fclose().
Problem Statement:
Create a C program that performs the following file operations:
Code:
#include <stdio.h>
int main() {
FILE *file;
char name[50];
int numNames, i;
Explanation:
1. Writing to a File:
o The program opens a file named names.txt in write mode ("w"). If the file
does not exist, it will be created. If it exists, it will be overwritten.
o The user is prompted to enter the number of names. The program reads each
name (including spaces) and writes it to the file using fprintf().
2. Reading from a File:
o The program then reopens the same file in read mode ("r").
o It reads each line from the file using fgets() and prints it to the console until
the end of the file is reached.
3. Error Handling:
o The program checks if the file was opened successfully. If not, it prints an
error message and exits.
./file_operations
Example Interaction:
Enter the number of names: 3
Enter name 1: Alice
Enter name 2: Bob
Enter name 3: Charlie
Conclusion:
This practical demonstrated basic file operations in C, including writing to and reading from
files. Understanding these file operations is crucial for handling data storage and retrieval in
C programming, enabling developers to create applications that can manage persistent data
effectively.