CPTC Aman Sinha

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

Practical : 1

Practical: Familiarization with the


Programming Environment
Objective
To understand the components and functionalities of a programming environment, including
text editors, compilers, and version control systems, as well as basic command-line
operations.

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. Select a Programming Language


o Choose a language you want to work with, such as Python, C, or Java.
2. Install Necessary Tools
o Text Editor: Download and install a text editor. Familiarize yourself with its
interface and features, such as syntax highlighting, code formatting, and
extensions.
o Compiler/Interpreter: Install the appropriate compiler or interpreter for your
chosen programming language. Ensure it is accessible from the command line.
o Git: Install Git for version control. Understand its role in tracking changes and
collaborating on projects.

Part 2: Using the Text Editor

1. Explore the Interface


o Open the text editor and familiarize yourself with its layout. Identify key
components such as the file explorer, editor pane, and output console.
2. Create and Save Files
o Practice creating a new file, naming it according to your conventions (e.g.,
filename.py or filename.c), and saving it in a designated directory.
3. Utilize Features
o Explore features like:
 Syntax Highlighting: Note how different parts of the code are colored
for clarity.
 Code Completion: Observe how the editor suggests completions for
code elements.
 Error Detection: Look for real-time error highlighting as you type.

Part 3: Compiling and Running Your Code

1. Understand the Compilation Process


o Learn the difference between interpreted languages (like Python) and
compiled languages (like C). Understand how the code is converted into
executable form.
2. Run Programs from the Command Line
o Familiarize yourself with navigating directories in the command line. Practice
commands for changing directories, listing files, and executing your programs.

Part 4: Introduction to Version Control with Git

1. Set Up a Git Repository


o Understand the purpose of a Git repository. Learn how to initialize one and the
significance of the .git folder.
2. Basic Git Commands
o Familiarize yourself with essential Git commands:
 git init: Initializes a new repository.
 git add: Stages changes for commit.
 git commit: Records changes in the repository.
 git status: Displays the state of the working directory and staging
area.
3. Explore Branching and Merging
o Understand the concepts of branching (creating separate lines of development)
and merging (integrating changes from different branches).

Part 5: Basic Command-Line Operations

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

Practical: Programs Using Input/Output Statements and Various Operators


in C Language

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:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

Program 1: Basic Input/Output (I/O) using scanf() and printf()

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() {

int num1, num2;

// Taking input

printf("Enter two integers: ");

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

// Displaying results

printf("Sum: %d\n", num1 + num2);

printf("Difference: %d\n", num1 - num2);


printf("Product: %d\n", num1 * num2);

if (num2 != 0) {

printf("Quotient: %d\n", num1 / num2);

} else {

printf("Division by zero is not allowed.\n");

return 0;

Program 2: Using Arithmetic Operators

Problem Statement:
Write a C program to calculate the area and perimeter of a rectangle using arithmetic
operators.

Code:

#include <stdio.h>

int main() {

float length, breadth, area, perimeter;

// Taking input

printf("Enter the length and breadth of the rectangle: ");

scanf("%f %f", &length, &breadth);

// Calculating area and perimeter

area = length * breadth;

perimeter = 2 * (length + breadth);


// Displaying results

printf("Area of the rectangle: %.2f\n", area);

printf("Perimeter of the rectangle: %.2f\n", perimeter);

return 0;

Program 3: Relational and Logical Operators

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;
}

Program 4: Bitwise Operators

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);

// Applying bitwise operators


printf("Bitwise AND: %d\n", num1 & num2);
printf("Bitwise OR: %d\n", num1 | num2);
printf("Bitwise XOR: %d\n", num1 ^ num2);

return 0;
}

Program 5: Conditional Operator (Ternary Operator)

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);

// Using conditional operator


largest = (num1 > num2) ? num1 : num2;

// Displaying result
printf("The largest number is: %d\n", largest);

return 0;
}

Program 6: Assignment Operators

Problem Statement:
Write a C program to demonstrate the use of compound assignment operators (+=, -=, *=,
/=).

Code:

#include <stdio.h>

int main() {
int num = 10;

printf("Initial value: %d\n", num);

// Using compound assignment operators


num += 5; // num = num + 5
printf("After += 5: %d\n", num);

num -= 3; // num = num - 3


printf("After -= 3: %d\n", num);

num *= 2; // num = num * 2


printf("After *= 2: %d\n", num);

num /= 4; // num = num / 4


printf("After /= 4: %d\n", num);

return 0;
}

Program 7: Logical Operators

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);

// Checking condition using logical AND operator


if (num >= 10 && num <= 50) {
printf("The number is between 10 and 50.\n");
} else {
printf("The number is not between 10 and 50.\n");
}

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

Practical: Programs Using Expression Evaluation and Operator Precedence


in C Language

Objective:

To understand and implement C programs that demonstrate expression evaluation and the
precedence of operators in C.

Tools Required:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

Key Concepts:

 Expression: A combination of variables, constants, and operators that the program


evaluates to produce a value.
 Operator Precedence: Defines the order in which operators are evaluated in an
expression. Higher precedence operators are evaluated before lower precedence
operators.
 Associativity: When operators have the same precedence, associativity determines
whether the expression is evaluated from left to right or right to left.

Operator Precedence Table (Example):

1. Parentheses () - Highest precedence


2. Multiplication *, Division /, Modulus % - Higher precedence
3. Addition +, Subtraction - - Lower precedence
4. Relational Operators <, >, <=, >=
5. Logical AND &&, OR || - Lowest precedence

Program 1: Expression Evaluation Without Parentheses

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);

// Evaluating the expression a + b * c


result = a + b * c;

// Displaying the result


printf("The result of the expression a + b * c is: %d\n", result);

return 0;
}

Explanation:
Since multiplication (*) has higher precedence than addition (+), b * c is evaluated first,
then added to a.

Program 2: Expression Evaluation with Parentheses

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);

// Evaluating the expression (a + b) * c


result = (a + b) * c;

// Displaying the result


printf("The result of the expression (a + b) * c is: %d\n", result);

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.

Program 3: Precedence of Relational and Logical Operators


Problem Statement:
Write a C program to evaluate the expression a > b && b > c and verify how relational and
logical operators are evaluated.

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);

// Evaluating the expression a > b && b > c


result = a > b && b > c;

// Displaying the result


printf("The result of the expression a > b && b > c is: %d\n", result);

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 &&.

Program 4: Operator Precedence in Mixed Expressions

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);

// Evaluating the expression a + b * c / d - e


result = a + b * c / d - e;

// Displaying the result


printf("The result of the expression a + b * c / d - e is: %d\n",
result);
return 0;
}

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)

Program 5: Associativity of Operators

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);

// Evaluating the expression a - b - c


result = a - b - c;

// Displaying the result


printf("The result of the expression a - b - c is: %d\n", result);

return 0;
}

Explanation:
Since subtraction (-) is left-associative, the expression is evaluated as (a - b) - c.

Program 6: Evaluation of Conditional Expressions

Problem Statement:
Write a C program to evaluate a conditional expression using the ternary operator.

Expression: result = (a > b) ? a : b

Code:
#include <stdio.h>

int main() {
int a, b, result;

// Taking input
printf("Enter values for a and b: ");
scanf("%d %d", &a, &b);

// Evaluating the expression using the ternary operator


result = (a > b) ? a : b;

// Displaying the result


printf("The larger value is: %d\n", result);

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

Practical: Programs Using Decision-Making and Branching Statements in C


Language

Objective:

To understand and implement decision-making (control) statements and branching


mechanisms in C using constructs like if, if-else, else-if, switch-case, and goto
statements.

Tools Required:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

Key Concepts:

 Decision-Making Statements: These statements allow the program to execute certain


blocks of code based on specified conditions.
o if, if-else, else-if, switch-case
 Branching Statements: These are used to alter the normal flow of program
execution.
o goto, break, continue

Program 1: Simple if Statement

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);

// Checking if the number is positive


if (number > 0) {
printf("The number is positive.\n");
}
return 0;
}

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.

Program 2: if-else Statement

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);

// Checking if the number is even or odd


if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}

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."

Program 3: else-if Ladder

Problem Statement:
Write a C program to check the grade of a student based on marks using the else-if ladder.

Conditions:

 Marks >= 90: Grade A


 Marks >= 80: Grade B
 Marks >= 70: Grade C
 Marks >= 60: Grade D
 Marks < 60: Grade F
Code:

#include <stdio.h>

int main() {
int marks;

// Taking input
printf("Enter your marks (out of 100): ");
scanf("%d", &marks);

// Checking the grade using else-if ladder


if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else if (marks >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}

return 0;
}

Explanation:
The program evaluates the marks using an else-if ladder and assigns a grade based on the
conditions provided.

Program 4: switch-case Statement

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);

// Taking operator input


printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);

// Performing the operation based on the operator


switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %d\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %d\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator!\n");
}

return 0;
}

Explanation:
The switch-case statement is used to select the arithmetic operation based on the operator
entered by the user.

Program 5: goto Statement

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);

// Using goto statement to check conditions


if (number > 0)
goto positive;
else if (number < 0)
goto negative;
else
goto zero;
positive:
printf("The number is positive.\n");
return 0;

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.

Program 6: Nested if-else Statement

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);

// Checking if the year is a leap year


if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
} else {
printf("%d is a leap year.\n", year);
}
} else {
printf("%d is not a leap year.\n", 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:

This practical demonstrated the use of decision-making and branching statements in C


programming. These control statements are crucial for executing code based on specific
conditions or altering the flow of execution within the program.
Practical : 5

Practical: Programs Using Loop Statements in C Language

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:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

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.

Program 1: Using the for Loop

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;

// Loop to calculate the sum of even numbers


while (num <= 20) {
sum += num; // Add the current even number to the sum
num += 2; // Increment by 2 to get the next even number
}

printf("The sum of even numbers between 1 and 20 is: %d\n", sum);

return 0;
}

Explanation:
The while loop continues to add even numbers from 2 to 20. The loop terminates when num
becomes greater than 20.

Program 3: Using the do-while Loop

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;

// Taking input using do-while loop


do {
printf("Enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);

printf("You entered a positive number: %d\n", 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.

Program 4: Nested for Loop

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);

// Inner loop for calculating and printing the table


for (int j = 1; j <= 10; j++) {
printf("%d x %d = %d\n", i, j, i * j);
}

printf("\n"); // Blank line for separation


}

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.

Program 5: Using the break Statement in a Loop

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.

Program 6: Using the continue Statement in a Loop

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.

Program 7: Infinite while Loop (Demonstration Only)

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:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

Key Concepts:

 1-Dimensional Array: A list of elements stored in contiguous memory locations.


 2-Dimensional Array: A matrix or table-like structure where elements are arranged
in rows and columns.
 Multi-Dimensional Arrays: Arrays with more than two dimensions, which are useful
for representing data in higher dimensions.

Program 1: One-Dimensional Array

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;

// Asking for number of elements in array


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

int arr[n];

// Taking input into the array


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Calculating sum of elements


for (i = 0; i < n; i++) {
sum += arr[i];
}

// Calculating average
average = (float)sum / n;

// Printing the result


printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);

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.

Program 2: Two-Dimensional Array (Matrix Addition)

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;

// Taking input for the first matrix


printf("Enter elements for 2x2 matrix 1:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Taking input for the second matrix


printf("Enter elements for 2x2 matrix 2:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Performing matrix addition


for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Displaying the result matrix


printf("Resultant Matrix after addition:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

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.

Program 3: Two-Dimensional Array (Matrix Multiplication)

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;

// Taking input for the first matrix


printf("Enter elements for 3x3 matrix 1:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Taking input for the second matrix


printf("Enter elements for 3x3 matrix 2:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Performing matrix multiplication


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
result[i][j] = 0;
for (k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Displaying the result matrix


printf("Resultant Matrix after multiplication:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

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.

Program 4: Three-Dimensional Array (Storing and Printing)

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;

// Taking input for the 3x2x2 array


printf("Enter elements for 3x2x2 array:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
printf("Enter element at [%d][%d][%d]: ", i, j, k);
scanf("%d", &arr[i][j][k]);
}
}
}

// Printing the elements of the 3x2x2 array


printf("The elements in the 3x2x2 array are:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
printf("Element at [%d][%d][%d]: %d\n", i, j, k, arr[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.

Program 5: Multi-Dimensional Array for Storing Student Marks

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;

// Taking input for marks


printf("Enter marks for 3 students in 4 subjects:\n");
for (i = 0; i < 3; i++) {
printf("Enter marks for student %d:\n", i + 1);
for (j = 0; j < 4; j++) {
printf("Subject %d: ", j + 1);
scanf("%d", &marks[i][j]);
}
}

// Displaying the marks


printf("\nMarks of students:\n");
for (i = 0; i < 3; i++) {
printf("Student %d: ", i + 1);
for (j = 0; j < 4; j++) {
printf("%d ", marks[i][j]);
}
printf("\n");
}

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:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

Key Concepts:

 String Manipulation Functions in C: C provides several built-in functions in the


string.h library to work with strings. Commonly used string functions include:
o strlen(): Calculates the length of a string.
o strcpy(): Copies one string to another.
o strcat(): Concatenates two strings.
o strcmp(): Compares two strings.
o strrev(): Reverses a string (Note: Not available in all compilers, might need
manual implementation).

Program 1: Calculating the Length of a String

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];

// Taking input for the string


printf("Enter a string: ");
gets(str);

// Calculating the length of the string


int length = strlen(str);

// Printing the length of the string


printf("The length of the string is: %d\n", length);
return 0;
}

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.

Program 2: Copying a String

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];

// Taking input for the source string


printf("Enter the source string: ");
gets(source);

// Copying the source string to the destination string


strcpy(destination, source);

// Printing the copied string


printf("The copied string is: %s\n", destination);

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.

Program 3: Concatenating Two Strings

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);

// Taking input for the second string


printf("Enter the second string: ");
gets(str2);

// Concatenating the second string to the first string


strcat(str1, str2);

// Printing the concatenated string


printf("The concatenated string is: %s\n", 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.

Program 4: Comparing Two Strings

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];

// Taking input for the first string


printf("Enter the first string: ");
gets(str1);

// Taking input for the second string


printf("Enter the second string: ");
gets(str2);

// Comparing the two strings


int result = strcmp(str1, str2);

// Printing the result of comparison


if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("The first string is lexicographically smaller than the
second string.\n");
} else {
printf("The first string is lexicographically greater than the
second string.\n");
}
return 0;
}

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.

Program 5: Reversing a String

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>

// Function to reverse a string


void reverseString(char str[]) {
int n = strlen(str); // Get the length of the string
int i;
for (i = 0; i < n / 2; i++) {
// Swap characters from start and end
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
}

int main() {
char str[100];

// Taking input for the string


printf("Enter a string: ");
gets(str);

// Reversing the string


reverseString(str);

// Printing the reversed string


printf("The reversed string is: %s\n", str);

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.

Program 6: Checking if a String is a Palindrome


Problem Statement:
Write a C program to check if a given string is a palindrome using string manipulation
functions.

Code:

#include <stdio.h>
#include <string.h>

// Function to check if the string is a palindrome


int isPalindrome(char str[]) {
int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
return 0; // Not a palindrome
}
}
return 1; // It is a palindrome
}

int main() {
char str[100];

// Taking input for the string


printf("Enter a string: ");
gets(str);

// Checking if the string is a palindrome


if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}

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

Practical Title: Demonstrating Parameter Passing Mechanisms in C

Objective:

To understand and demonstrate parameter passing mechanisms in C, including:

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.

Program 1: Pass by Value

In this program, we will demonstrate that modifications made to the function parameters do
not reflect in the calling function.

#include <stdio.h>

// Function to swap two numbers using Pass by Value


void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
printf("Inside swapByValue function: a = %d, b = %d\n", a, b);
}

int main() {
int x = 10, y = 20;
printf("Before swapByValue: x = %d, y = %d\n", x, y);

// Calling the function with Pass by Value


swapByValue(x, y);

// After the function call, values remain unchanged


printf("After 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.

Program 2: Pass by Reference

In this program, we will pass the address of the variables to the function, allowing it to
modify the actual values.

#include <stdio.h>

// Function to swap two numbers using Pass by Reference


void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
printf("Inside swapByReference function: a = %d, b = %d\n", *a, *b);
}

int main() {
int x = 10, y = 20;
printf("Before swapByReference: x = %d, y = %d\n", x, y);

// Calling the function with Pass by Reference


swapByReference(&x, &y);

// After the function call, values are swapped


printf("After 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

Practical: Programs to Demonstrate Recursion in C Language

Objective:

To understand and implement recursion in C programming through various examples such as


calculating the factorial of a number, generating the Fibonacci series, and computing the
greatest common divisor (GCD).

Tools Required:

 Any C language compiler (like GCC, Turbo C, Code::Blocks, etc.)

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.

Program 1: Factorial of a Number using Recursion

Problem Statement:
Write a C program to calculate the factorial of a given number using recursion.

Code:

#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}

int main() {
int num;

// Taking input from user


printf("Enter a number: ");
scanf("%d", &num);

// Calculating factorial
int result = factorial(num);

// Displaying the result


printf("Factorial of %d is %d\n", num, result);

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.

Program 2: Fibonacci Series using Recursion

Problem Statement:
Write a C program to generate the Fibonacci series up to n terms using recursion.

Code:

#include <stdio.h>

// Function to calculate the nth Fibonacci number using recursion


int fibonacci(int n) {
if (n == 0) {
return 0; // Base case
} else if (n == 1) {
return 1; // Base case
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}
}

int main() {
int n, i;

// Taking input from the user


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

// Printing the Fibonacci series


printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");

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>

// Function to calculate GCD using recursion


int gcd(int a, int b) {
if (b == 0) {
return a; // Base case
} else {
return gcd(b, a % b); // Recursive call
}
}

int main() {
int num1, num2;

// Taking input from the user


printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

// Calculating GCD
int result = gcd(num1, num2);

// Displaying the result


printf("GCD of %d and %d is %d\n", num1, num2, result);

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.

Program 4: Tower of Hanoi using Recursion

Problem Statement:
Write a C program to solve the Tower of Hanoi problem using recursion.

Code:

#include <stdio.h>

// Function to solve Tower of Hanoi using recursion


void hanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);
return;
}
hanoi(n - 1, from_rod, aux_rod, to_rod); // Move n-1 disks to
auxiliary rod
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
hanoi(n - 1, aux_rod, to_rod, from_rod); // Move n-1 disks to
destination rod
}

int main() {
int num_disks;

// Taking input from the user


printf("Enter the number of disks: ");
scanf("%d", &num_disks);

// Solving Tower of Hanoi


printf("The sequence of moves is:\n");
hanoi(num_disks, 'A', 'C', 'B'); // A = Source rod, C = Destination
rod, B = Auxiliary rod

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.

Program 5: Sum of Digits of a Number using Recursion

Problem Statement:
Write a C program to calculate the sum of digits of a number using recursion.

Code:

#include <stdio.h>

// Function to calculate sum of digits using recursion


int sum_of_digits(int n) {
if (n == 0) {
return 0; // Base case
} else {
return (n % 10) + sum_of_digits(n / 10); // Recursive call
}
}

int main() {
int num;

// Taking input from the user


printf("Enter a number: ");
scanf("%d", &num);
// Calculating the sum of digits
int result = sum_of_digits(num);

// Displaying the result


printf("Sum of digits of %d is %d\n", num, result);

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:

To understand and demonstrate the use of pointers in C by performing operations like:

1. Accessing values using pointers


2. Modifying values using pointers
3. Pointer arithmetic
4. Pointer to pointer

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;

Here, ptr is a pointer to an integer.

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.

Program 1: Basic Pointer Operations


#include <stdio.h>

int main() {
int a = 10; // A normal integer variable
int *ptr; // Pointer to an integer

ptr = &a; // Assigning address of 'a' to the pointer 'ptr'

printf("Address of a: %p\n", &a);


printf("Address stored in pointer ptr: %p\n", ptr);
printf("Value of a using pointer: %d\n", *ptr);
// Modifying value of 'a' using pointer
*ptr = 20;
printf("Modified value of a using pointer: %d\n", a);

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:

 A pointer ptr is assigned the address of the variable a.


 Using the dereference operator (*ptr), the value stored at the address can be accessed
and modified.

Program 2: Pointer Arithmetic


#include <stdio.h>

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

printf("Pointer arithmetic demonstration:\n");


for (int i = 0; i < 5; i++) {
printf("Value of arr[%d] = %d, Address = %p\n", i, *ptr, ptr);
ptr++; // Incrementing pointer to point to the next element
}

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:

 Pointer ptr is initially pointing to the first element of the array.


 Pointer arithmetic (ptr++) is used to move the pointer to the next memory location,
accessing each element of the array in sequence.
Program 3: Pointer to Pointer (Double Pointer)
#include <stdio.h>

int main() {
int a = 100;
int *ptr; // Pointer to an integer
int **pptr; // Pointer to pointer

ptr = &a; // Pointer 'ptr' points to 'a'


pptr = &ptr; // Pointer 'pptr' points to 'ptr'

printf("Value of a: %d\n", a);


printf("Value of a using ptr: %d\n", *ptr);
printf("Value of a using pptr: %d\n", **pptr);

return 0;
}

Output:
Value of a: 100
Value of a using ptr: 100
Value of a using pptr: 100

Explanation:

 ptr stores the address of a.


 pptr is a pointer to ptr, so *pptr gives the address of a, and **pptr gives the value
of a.
 This demonstrates the concept of pointer to pointer, where multiple levels of
dereferencing are used to access the value.

Conclusion:

 Pointer: A powerful feature in C that allows direct access to memory.


 Pointer Arithmetic: Helps in traversing arrays or memory locations.
 Pointer to Pointer: Allows multiple levels of indirection, making it useful in
complex data structures like linked lists, trees, etc.
Practical : 11
Practical: Programs to Demonstrate Command Line Arguments in C
Language

Objective:

To understand how to use command line arguments in C programs for inputting data during
program execution.

Tools Required:

 A C compiler (like GCC, Turbo C, Code::Blocks, etc.)

Key Concepts:

 Command Line Arguments: Inputs provided to a program at the time of execution


via the command line. They are handled in C through the parameters of the main()
function: int main(int argc, char *argv[]).
o argc: The count of command line arguments (including the program name).
o argv: An array of strings representing the arguments.

Example Program: Simple Calculator Using Command Line Arguments

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>

int main(int argc, char *argv[]) {


if (argc != 4) {
printf("Usage: %s <num1> <operator> <num2>\n", argv[0]);
printf("Operators: +, -, *, /\n");
return 1;
}

// Convert command line arguments to numbers


double num1 = atof(argv[1]);
double num2 = atof(argv[3]);
char operator = argv[2][0]; // Get the operator

// Perform the operation based on the operator


double result;
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error: Division by zero.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
return 1;
}

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.

How to Run the Program:

1. Compile the Program:

gcc calculator.c -o calculator

2. Execute the Program with Arguments:

./calculator 10 + 20

This command would output:

Result: 10.00 + 20.00 = 30.00


Conclusion:

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:

To understand and demonstrate the concept of dynamic memory allocation in C using:

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:

1. malloc(size_t size): Allocates a specified amount of memory and returns a


pointer to it. The memory is uninitialized.
2. calloc(size_t num, size_t size): Allocates memory for an array of num
elements, each of size size, and initializes all bytes to zero.
3. realloc(void *ptr, size_t size): Resizes the memory block pointed to by ptr
to the new size. If the new size is larger, the contents will be retained; if it is smaller,
the excess memory is freed.
4. free(void *ptr): Frees the allocated memory, preventing memory leaks.

Program 1: Using malloc()


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

int main() {
int *arr;
int n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

// Allocating memory dynamically using malloc


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

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");

// Free the allocated memory


free(arr);

return 0;
}

Output:
Enter number of elements: 5
Enter 5 elements:
10 20 30 40 50
You entered:
10 20 30 40 50

Explanation:

 The program prompts the user to enter the number of elements.


 It uses malloc() to allocate memory for an array of integers based on user input.
 After inputting values, it displays them and frees the allocated memory using free().

Program 2: Using calloc()


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

int main() {
int *arr;
int n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

// Allocating memory dynamically using calloc


arr = (int *)calloc(n, sizeof(int));

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");

// Free the allocated memory


free(arr);

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:

 The program uses calloc() to allocate memory for an array of integers.


 The initial values in the array are displayed, which should be zero since calloc()
initializes the memory to zero.
 It then accepts user input and frees the allocated memory.

Program 3: Using realloc()


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

int main() {
int *arr;
int n, newSize, i;

printf("Enter initial number of elements: ");


scanf("%d", &n);
// Allocating memory dynamically
arr = (int *)malloc(n * sizeof(int));

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 initial elements


printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Resizing the array


printf("Enter new size for the array: ");
scanf("%d", &newSize);

arr = (int *)realloc(arr, newSize * sizeof(int));


if (arr == NULL) {
printf("Memory reallocation failed!\n");
return 1; // Exit if memory reallocation fails
}

// If new size is greater, input new elements


if (newSize > n) {
printf("Enter additional %d elements:\n", newSize - n);
for (i = n; i < newSize; i++) {
scanf("%d", &arr[i]);
}
}

// Display all elements after reallocation


printf("Elements in the array after resizing:\n");
for (i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Free the allocated memory


free(arr);

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:

 Dynamic memory allocation allows for flexible memory management in C.


 Using malloc(), calloc(), realloc(), and free(), you can effectively manage
memory as needed during program execution.
Practical : 13

Practical: Programs to Demonstrate File Operations in C Language

Objective:

To understand and implement basic file operations in C, including creating, reading, writing,
and closing files.

Tools Required:

 A C compiler (like GCC, Turbo C, Code::Blocks, etc.)

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().

Example Program: Simple File Operations

Problem Statement:
Create a C program that performs the following file operations:

1. Write a list of names to a file.


2. Read the names back from the file and display them.

Code:

#include <stdio.h>

int main() {
FILE *file;
char name[50];
int numNames, i;

// Step 1: Writing to a file


file = fopen("names.txt", "w"); // Open file for writing
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}

// Taking input for names


printf("Enter the number of names: ");
scanf("%d", &numNames);
getchar(); // To consume the newline character after entering numNames

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


printf("Enter name %d: ", i + 1);
fgets(name, sizeof(name), stdin); // Read name with spaces
fprintf(file, "%s", name); // Write name to file
}

fclose(file); // Close the file


printf("Names written to file successfully.\n");

// Step 2: Reading from the file


file = fopen("names.txt", "r"); // Open file for reading
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}

printf("\nNames read from file:\n");


while (fgets(name, sizeof(name), file) != NULL) {
printf("%s", name); // Print each name
}

fclose(file); // Close the file


return 0;
}

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.

How to Run the Program:

1. Compile the Program:

gcc file_operations.c -o file_operations


2. Execute the Program:

./file_operations

Example Interaction:
Enter the number of names: 3
Enter name 1: Alice
Enter name 2: Bob
Enter name 3: Charlie

Names written to file successfully.

Names read from file:


Alice
Bob
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.

You might also like