Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

R23 C Programming Lab Record With Program(1)

The document outlines the C Programming course at the KIT-Kalaignar Karunanidhi Institute of Technology, detailing laboratory instructions, program outcomes, educational objectives, and a list of experiments. It emphasizes the importance of maintaining discipline in the lab, following a structured syllabus, and achieving specific course outcomes related to C programming. Additionally, it includes practical examples and algorithms for various programming tasks.

Uploaded by

shivavarthan6008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

R23 C Programming Lab Record With Program(1)

The document outlines the C Programming course at the KIT-Kalaignar Karunanidhi Institute of Technology, detailing laboratory instructions, program outcomes, educational objectives, and a list of experiments. It emphasizes the importance of maintaining discipline in the lab, following a structured syllabus, and achieving specific course outcomes related to C programming. Additionally, it includes practical examples and algorithms for various programming tasks.

Uploaded by

shivavarthan6008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

KIT- KALAIGNAR KARUNANIDHI INSTITUTE OF TECHNOLOGY

(AN AUTONOMOUS INSTITUTION)


(Accredited by NAAC & NBA with ‘A’ Grade)
Kannampalayam Post, Coimbatore -641 402

Department of Computer Science and Engineering

B23CSI101 - C PROGRAMMING

Name ………………………………………………………………………….
Batch …………………….. Reg. No. ………………….…….…
Branch ………………………. Year ……………………………….
KIT-Kalaignarkarunanidhi Institute of Technology
(An Autonomous Institution, Approved by AICTE & Affiliated to Anna University, Chennai)
Coimbatore – 641 402

Department of

………………………………………………………………………………………………

Record Work of

… ..................................................................................................................................Laboratory

Certified that this record is the bona fide work done by

Name:………………………………………………………………………………………………

Class:…………………………………….. Roll No:………………………………………

Branch………………………………………………………………………………………………..

Place: KIT, CBE Faculty In-Charge HOD

Date:

University Register No……………………………………………

Submitted for the University Practical Examination held on

…………………………………………………

Internal Examiner External Examiner


Instructions for Laboratory Classes

1. Enter the lab with record workbook & necessary things.

2. Enter the lab without bags and footwear.

3. Footwear should be kept in the outside shoe rack neatly.

4. Maintain silence during the Lab Hours.

5. Read and follow the work instructions inside the laboratory.

6. Handle the computer systems with care.

7. Shutdown the Computer properly and arrange chairs in order before leaving thelab.

8. The program should be written on the left side pages of the record work book.

9. The record workbook should be completed in all aspects and submitted in the nextclass

itself.

10. Experiment number with date should be written at the top left-hand corner of the

record work book page.

11. Strictly follow the uniform dress code for Laboratory classes.

12. Maintain punctuality for lab classes.

13. Avoid eatables inside and maintain the cleanliness of the lab.
VISION
To produce intellectual graduates to excel in the field of Computer Science Engineering and Technologies.

MISSION
 Providing excellent and intellectual inputs to the students through qualified faculty members.
 Imparting technical knowledge in latest technologies through the industry institute interaction and thereby
making the graduates ready for the industrial environment.
 Enriching the student’s knowledge for active participation in co-curricular and extracurricular activities.
 Promoting research-based projects in contexts to social, legal and technical aspects.

PROGRAMME OUTCOMES (POs)


After the successful completion of the U.G. programme in Computer Science and Engineering, Graduates
will be able to:
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO1: Graduate will be successful in their profession by taking part actively in the field of software and
technology.
PEO2: Graduate will be proficient in analyzing and facing the challenge in computer science and
engineering.
PEO3: Graduate will engage in lifelong learning activities by adapting to the advanced software
technologies for continuous professional development.
PROGRAM SPECIFIC OUTCOME (PSOs)

After the successful completion of the U.G. programme in Computer Science and Engineering, Graduates
will be able to:
PSO1: Categorize the basic engineering knowledge to solve the problems in Computer Science and
Engineering according to the environmental needs.
PSO2: Apply the modern tools to design and develop the software system ethically to the industrial needs.
COURSE OUTCOMES
At the end ofthis course, the student will be able to:

Course Outcomes Knowledge Level


CO1: Demonstrate knowledge on C programming constructs K2
CO2: Construct C programs using decision making and control statements. K3
CO3: Experiment with programs in C using an array K3
CO4: Build programs in C using strings, pointers, functions K3
CO5: Model the applications in C using Structures, Union and File Operations K3

PO6 PO7 PO8 PO11 PSO1 PSO2


PO1 PO2 PO3 PO4 PO5 PO9 PO10 PO12 (K3 (K3
CO/PO & PSO (K3) (K2) (K3) (K3) A3) A3)
(K3) (K4) (K5) (K5) (K6) (A3) (A3) (A3)
(A3) (A3) (A3) (A3)

CO1 K2 3 2 1 - - - - - 2 1
1 1 1 1
CO2 K3 3 2 1 - 1 - - 1 2 - - 2 2 1
CO3 K3 3 2 1 - 1 - - 1 2 - - 2 2 1
CO4 K3 3 2 1 - 1 - - 1 2 - - 2 2 1
CO5 K3 3 2 1 - 1 - - 1 2 - - 2 2 1
Weighted
3 2 1 - 1 - - 1 2 - - 2 2 1
average
SYLLABUS
LIST OF EXPRIMENTS
1. Experiment with I/O statements, operators, expressions
2. Develop C programs for Decision Making Construct.
a) if-else b) switch-case c) goto, break-continue
3. Develop a Cprograms for Loop Control statements.
a) for b) Nested for c) while and do-while
4. Develop a C programs for Array
a) One Dimensional – Sorting and Searching b)Two Dimensional – Matrix Operations c) Traversal
5. Develop a C program to perform the pointers
Linear Search b) Binary Search c) Pointer Operation
6. Build a C programs for the recursive function
7. Implement a C programs for string operations
String operations using build in methods
8. Develop a C program to experiment with Pass by value and Pass by Reference
9. Develop a c program for structure and union
a) Payroll using structure and union b) Student records using structure and union.
10. Develop a C program to perform file operations

Total Instructional hours: (45+15) = 60


CONTENT

S. No Title of the PageNo


Experiment
1(a) C program for formatted and unformatted input and output statements

1(b) C program to perform operations on operators and expressions.


C program to check whether the given number is positive number or negative
2(a) number using if-else statement.
C program to design a menu-based calculator to perform various basic arithmetic
2(b) operations like addition, subtraction, multiplication, division and modulo.

2(c) C program for decision making using goto, break and continue statement

3(a) C program to input a number and calculate its factorial using while loop

3(b)
3(
C program to input a number and calculate sum of digits using do-while loop.
C program to input a number and check whether the number is prime number or not
3(c)
using for loop.

3(d) C program to find the prime numbers from 2 to 50 using nested for loop.

4 (a)(i) C program to input elements in array and sort array elements in ascending order

4(a)(ii) C program to input elements in array and search whether an element exists in array or not.

4(b)(i) C program to implement matrix addition

4(b)(ii) C program to implement matrix subtraction

4(b)(iii) C program to implement matrix multiplication

4(c) C program to read square matrix of order n, transpose it using user defined function.

5 (a) C program to search(linear) an element from an array using pointers

5 (b) C program to perform binary search using pointers

5 (c) C program to read two numbers from user and add them using pointers.

6 C program to find the factorial of a given number using recursion

7 (a) C program to find the length of the string using strlen() function.

7 (b) C program to perform the string copy using strcpy() function.


7 (c) C Program to compare two strings using strcmp() Function.

7 (d) C Program to concatenate two strings using strcat() function

8 (a) C program to swap two numbers using call by value.

8 (b) C Program to Sort the list of numbers using pass by reference.

9 (a) C Program to maintain students records using structure.

9 (b) C Program to create payroll processing using union.

10 (a) C program to display the contents of a file.

10 (b) C program to copy the contents of one file to another


S. No Experiment Prerequisites Learning Objectives

1. To know the basics of problem-


solving techniques.
2. To provide exposure to problem-
solving through programming.
For All 3. To develop C programming language
1 Basics of computer programming
Experiments with conditional statements and loops
4. To develop modular applications in C
using functions pointers and structures
5. To do input/output and file handling
in C
No.
Sl.
Model Exam Marks (25):

Date
Name of the Experiment

Practical Record Book Index Page


Total (100):

Page
Number
Aim &
Algorithm
(20 Marks)

Program
Signature of the Faculty Member

(25 Marks)

Output &
Inference (10
Marks)

Viva-Voce(20
Marks)
Total
(75Marks)
Signature of
the Faculty
Member
No.
Sl.
Model Exam Marks (25):

Date
Name of the Experiment

Practical Record Book Index Page


Total (100):

Page
Number
Aim
&Algorithm
(20 Marks)

Program
(25 Marks)
Signature of the Faculty Member

Output &
Inference
(10 Marks)

Viva-Voce
(20 Marks)

Total
(75
Marks)
Signature
ofthe
Faculty
Member
No.
Sl.
Model Exam Marks (25):

Date
Name of the Experiment

Practical Record Book Index Page


Total (100):

Page
Number
Aim
&Algorithm
(20 Marks)

Program
Signature of the Faculty Member

(25 Marks)

Output &
Inference
(10 Marks)

Viva-Voce
(20 Marks)
Total
(75Marks)
Signature of
the Faculty
Member
No.
Sl.
Model Exam Marks (25):

Date
Name of the Experiment

Practical Record Book Index Page


Total (100):

Page
Number
Aim
&Algorithm
(20 Marks)

Program
Signature of the Faculty Member

(25 Marks)

Output &
Inference
(10 Marks)

Viva-Voce
(20 Marks)
Total
(75Marks)
Signature of
the Faculty
Member
B23CSI101 C PROGRAMMING

Ex. No. 1(a)

Date EXPERIMENT WITH I/O STATEMENTS

AIM:
To write a C program for formatted and unformatted input and output statements.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare all the required variables.

STEP 3: Get input values from the user output using formatted and unformatted input statement.

STEP 4: Display the output using formatted and unformatted output statement.

STEP 5: Stop the program.

14
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
char name [50];
char ch;
int age;
float height;

// Formatted Input and Output


printf ("Enter your name: ");
scanf("%s", name); // Reads a string until a space is encountered

printf ("Enter your age: ");


scanf ("%d", &age); // Reads an integer

printf ("Enter your height in meters (e.g., 1.75): ");


scanf ("%f", &height); // Reads a floating-point number

printf("\nFormatted Output:\n");
printf ("Name: %s\n", name);
printf ("Age: %d\n", age);
printf ("Height: %.2f meters\n", height);

// Unformatted Input and Output


printf("\nUnformatted I/O Example:\n");

printf("Enter a single character: ");


getchar(); // To consume the newline character left in the buffer
ch = getchar(); // Reads a single character

printf("Enter your full name (with spaces): ");


getchar(); // To consume the newline character again
gets(name); // Reads a full string, including spaces (not safe, but used for demonstration)

printf("\nUnformatted Output:\n");
putchar(ch); // Outputs a single character
printf("\n");
puts(name); // Outputs the string

return 0;
}

15
B23CSI101 C PROGRAMMING

OUTPUT:

Enter your name: John


Enter your age: 25
Enter your height in meters : 1.80

Formatted Output:

Name: John
Age: 25
Height: 1.80 meters

Unformatted I/O Example:

Enter a single character: A


Enter your full name (with spaces): John Doe

Unformatted Output:

A
John Doe

16
B23CSI101 C PROGRAMMING

Ex. No. 1(b)

Date EXPERIMENT WITH OPERATORS AND EXPRESSIONS

AIM:
To write a C program to perform operations on operators and expressions.

ALGORITHM:

STEP 1: Start the program

STEP 2: Declare all required variables and initialize them.

STEP 3: Calculate the expression using operators.

STEP 4: Display the Output.

STEP 5: Stop the program.

17
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int a = 10, b = 20, c;
float x = 5.5, y = 2.5;
int result;

// Arithmetic Operators
printf("Arithmetic Operations:\n");
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("b / a = %d\n", b / a);
printf("b %% a = %d\n", b % a);

// Relational Operators
printf("\n Relational Operations:\n");
printf("a > b = %d\n", a > b);
printf("a < b = %d\n", a < b);
printf("a == b = %d\n", a == b);
printf("a != b = %d\n", a != b);

// Logical Operators
printf("\n Logical Operations:\n");
printf("(a > 5 && b > 15) = %d\n", (a > 5 && b > 15));
printf("(a > 15 || b > 15) = %d\n", (a > 15 || b > 15));
printf("!(a > 15) = %d\n", !(a > 15));

// Bitwise Operators
printf("\nBitwise Operations:\n");
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 2 = %d\n", a << 2); // Left shift
printf("a >> 2 = %d\n", a >> 2); // Right shift

// Assignment Operators
printf("\n Assignment Operations:\n");
c = a + b;
printf("c = a + b = %d\n", c);
c += a;
printf("c += a = %d\n", c);
c -= b;
printf("c -= b = %d\n", c);
c *= a;
printf("c *= a = %d\n", c);
c /= a;
18
B23CSI101 C PROGRAMMING

printf("c /= a = %d\n", c);


c %= a;
printf("c %%= a = %d\n", c);

// Increment and Decrement


printf("\n Increment and Decrement:\n");
printf("++a = %d\n", ++a); // Pre-increment
printf("a++ = %d\n", a++); // Post-increment
printf("--b = %d\n", --b); // Pre-decrement
printf("b-- = %d\n", b--); // Post-decrement
printf("a = %d, b = %d\n", a, b);

// Conditional Operator
printf("\n Conditional (Ternary) Operation:\n");
result = (a > b) ? a : b;
printf("Max of a and b = %d\n", result);

return 0;
}

19
B23CSI101 C PROGRAMMING

OUTPUT:

Arithmetic Operations:
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0

Relational Operations:
a>b=0
a<b=1
a == b = 0
a != b = 1

Logical Operations:
(a > 5 && b > 15) = 1
(a > 15 || b > 15) = 1
!(a > 15) = 1

Bitwise Operations:
a&b=0
a | b = 30
a ^ b = 30
~a = -11
a << 2 = 40
a >> 2 = 2

Assignment Operations:
c = a + b = 30
c += a = 40
c -= b = 20
c *= a = 200
c /= a = 20
c %= a = 0

Increment and Decrement:


++a = 11
a++ = 11
--b = 19
b-- = 19
a = 12, b = 18

Conditional (Ternary) Operation:


Max of a and b = 18

20
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. Explain the difference between = = and = = = in C language.

2. How does the ternary operator differ from an if-else statement?

3. What happens if an integer number is divided by zero?

4. What is the associativity of operators?

5. What is the precedence of operators?

RESULT:

21
B23CSI101 C PROGRAMMING

Ex. No. 2(a) C PROGRAM FOR DECISION MAKING USING IF-ELSE


Date STATEMENT

AIM:
To write a C program to check whether the given number is positive number or negative number using
if-else statement.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare all required variables.

STEP 3: Get an input from the user and store it in a variable.

STEP 4: Check the input value whether it is a positive number or negative number.

STEP 5: If the number is less than ZERO, then print the result as “NEGATIVE”. Otherwise display

the result as “POSITIVE”.

STEP 6: Stop the program.

22
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int number;

// Input a number from the user


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

// Check if the number is positive or negative


if (number > 0) {
printf("The number %d is positive.\n", number);
} else if (number < 0) {
printf("The number %d is negative.\n", number);
} else {
printf("The number is zero.\n");
}

return 0;
}

23
B23CSI101 C PROGRAMMING

OUTPUT:

CASE 1: Enter a number: 5


The number 5 is positive.

CASE 2: Enter a number: -3


The number -3 is negative.

CASE 3: Enter a number: 0


The number is zero.

24
B23CSI101 C PROGRAMMING

Ex. No. 2(b) C PROGRAM FOR DECISION MAKING USING SWITCH - CASE
Date STATEMENT

AIM:
To write a C program to design a menu-based calculator to perform various basic arithmetic
operations like addition, subtraction, multiplication, division and modulo.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare all required variables

STEP 3: Get two inputs from the user using scanf() function and store them in “a” and “b” respectively

STEP 4: Get the user option and based on the user options, perform the corresponding arithmetic

operations on the user data.

STEP 5: Store the result in a variable called “c” and display the value of “c” using printf()

STEP 6: Stop the program

25
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
int main() {
int choice;
float num1, num2, result;

// Display the menu


printf("Select an operation to perform:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);

// Input numbers
if (choice >= 1 && choice <= 4) {
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
}

// Decision making using switch-case


switch (choice) {
case 1: // Addition
result = num1 + num2;
printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);
break;
case 2: // Subtraction
result = num1 - num2;
printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);
break;
case 3: // Multiplication
result = num1 * num2;
printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);
break;
case 4: // Division
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default: // Invalid Choice
printf("Invalid choice. Please select an option between 1 and 4.\n");
}

return 0;
}
26
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Addition
Select an operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division

Enter your choice (1-4): 1


Enter two numbers: 10 20
Result: 10.00 + 20.00 = 30.00

Case 2: Division by Zero


Select an operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division

Enter your choice (1-4): 4


Enter two numbers: 10 0
Error: Division by zero is not allowed.

Case 3: Invalid Choice

Select an operation to perform:


1. Addition
2. Subtraction
3. Multiplication
4. Division

Enter your choice (1-4): 5


Invalid choice. Please select an option between 1 and 4.

27
B23CSI101 C PROGRAMMING

Ex. No. 2(c) C PROGRAM FOR DECISION MAKING USING GOTO, BREAK AND
Date CONTINUE STATEMENT

AIM
To write a C program for decision making using goto, break and continue statement.

ALGORITHM

STEP 1: Start the program

STEP 2: Declare and intialize the necessary variables.

STEP3: Goto: The for loop and a goto statement is used to skip printing the number 2. The label skip is

used as the target of the goto statement.

STEP 4: Break: The for loop and the break statement is used to exit the loop when i becomes 3.

STEP 5: Continue: The for loop and the continue statement is used to skip printing the number 2 and

continue with the next iteration.

STEP 6: Display the output

STEP 7: Stop the program.

28
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
int main() {
int choice, i;
int num;

while (1) {
// Display menu
printf("\nMenu:\n");
printf("1. Print numbers from 1 to 10 (using continue)\n");
printf("2. Check if a number is odd or even (using break)\n");
printf("3. Exit program (using goto)\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);

switch (choice) {
case 1: // Use of 'continue'
printf("Numbers from 1 to 10 (skipping 5 using continue):\n");
for (i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the number 5
}
printf("%d ", i);
}
printf("\n");
break;

case 2: // Use of 'break'


printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("The number %d is even.\n", num);
} else {
printf("The number %d is odd.\n", num);
}
break;

case 3: // Use of 'goto'


printf("Exiting the program...\n");
goto end; // Jump to the label 'end'

default:
printf("Invalid choice. Please select 1, 2, or 3.\n");
}
}

end:
printf("Program terminated.\n");
return 0;
}
29
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Print Numbers (Using Continue)


Menu:
1. Print numbers from 1 to 10 (using continue)
2. Check if a number is odd or even (using break)
3. Exit program (using goto)

Enter your choice (1-3): 1


Numbers from 1 to 10 (skipping 5 using continue):
1 2 3 4 6 7 8 9 10

Case 2: Check Odd or Even (Using Break)


Menu:
1. Print numbers from 1 to 10 (using continue)
2. Check if a number is odd or even (using break)
3. Exit program (using goto)

Enter your choice (1-3): 2


Enter a number: 7
The number 7 is odd.

Case 3: Exit Program (Using Goto)


Menu:
1. Print numbers from 1 to 10 (using continue)
2. Check if a number is odd or even (using break)
3. Exit program (using goto)

Enter your choice (1-3): 3


Exiting the program...
Program terminated.

Case 4: Invalid Choice


Menu:
1. Print numbers from 1 to 10 (using continue)
2. Check if a number is odd or even (using break)
3. Exit program (using goto)

Enter your choice (1-3): 4


Invalid choice. Please select 1, 2, or 3.

30
B23CSI101 C PROGRAMMING

INFERENCE

VIVA QUESTIONS
1. What is the purpose of the goto statement in C?

2. What is the significance of labels when using the goto statement?

3. What are case labels in a switch statement?

4. How does the continue statement influence the flow of a loop?

5. What would happen if the continue statement is not used in a loop?

RESULT

31
B23CSI101 C PROGRAMMING

Ex. No. 3(a)


C PROGRAM BY USING WHILE, DO-WHILE AND FOR LOOPS.
Date

AIM:
To write a C program to input a number and calculate its factorial using while loop.

ALGORITHM:

STEP 1: Start the program

STEP 2: Declare a variable (int fact) and initialize it with 1.

STEP 3: Read a number whose factorial is to be found. Store it in a variable (int num).

STEP 4: Set the while loop to the condition (i <= num) where initial value of i = 1

STEP 5: Inside the while loop, multiply the variable fact and variable i, and store the result in

variable fact. Increment the loop variable i by 1 (i++).

STEP 6: Print the factorial.

STEP 7: Stop the program.

32
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int number, factorial = 1, i;

// Input a number from the user


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

// Check if the number is negative


if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
i = 1;
// While loop to calculate factorial
while (i <= number) {
factorial *= i;
i++;
}
printf("Factorial of %d is %d\n", number, factorial);
}

return 0;
}

33
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Positive Number


Enter a positive integer: 5
Factorial of 5 is 120

Case 2: Zero
Enter a positive integer: 0
Factorial of 0 is 1

Case 3: Negative Number


Enter a positive integer: -3
Factorial is not defined for negative numbers.

34
B23CSI101 C PROGRAMMING

Ex.No. 3(b)
C PROGRAM BY USING WHILE, DO-WHILE AND FOR LOOPS.
Date

AIM:
To write a C program to input a number and calculate sum of digits using do-while loop.

ALGORITHM:

STEP 1: Start the program

STEP 2: Input a number from user. Store it in some variable say n.

STEP 3: Find last digit of the number. To get last digit modulo division the number by 10 i.e.,
lastDigit = num % 10.

STEP 4: Add last digit found above to sum i.e., sum = sum + lastDigit.

STEP 5: Remove last digit from number by dividing the number by 10 i.e., num = num / 10.

STEP 6: Repeat step 3-5 till number becomes 0. Finally, you will be left with the sum of digits in
sum.
STEP 7: Stop the program.

35
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int number, sum = 0, digit;

// Input a number from the user


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

// Do-while loop to calculate the sum of digits


do {
// Extract the last digit of the number
digit = number % 10;
sum += digit; // Add the digit to the sum
number = number / 10; // Remove the last digit
} while (number != 0); // Continue until the number becomes 0

// Output the result


printf("Sum of digits is: %d\n", sum);

return 0;
}

36
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Positive Number


Enter a number: 12345
Sum of digits is: 15

Case 2: Single Digit Number


Enter a number: 7
Sum of digits is: 7

Case 3: Number with Zero(s)


Enter a number: 1023
Sum of digits is: 6

37
B23CSI101 C PROGRAMMING

Ex.No. 3(c)
C PROGRAM BY USING WHILE, DO-WHILE AND FOR LOOPS.
Date

AIM:
To write a C program to input a number and check whether the number is prime number or not
using for loop.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Input a number from user. Store it in some variable say n.

STEP 3: Declare and initialize another variable say isPrime = 1. isPrime variable is used as a
notification or flag variable. Assigning 0 means number is composite and 1 means prime.

STEP 4: Run a loop from 2 to num/2, increment 1 in each iteration.

STEP 5: Check, divisibility of the number i.e., if(num%i == 0) then, the number is not prime. Set
isPrime = 0 indicating number is not prime and terminate from loop.

STEP 6: Outside the loop check the current value of isPrime. According to our assumption if it is
equal to 1 then the number is prime otherwise composite.

STEP 7: Stop the program.

38
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int number, i, isPrime = 1;

// Input a number from the user


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

// Check if the number is less than 2


if (number < 2) {
isPrime = 0; // Numbers less than 2 are not prime
} else {
// Use a for loop to check for factors
for (i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = 0; // If a factor is found, number is not prime
break; // No need to check further
}
}
}

// Output the result


if (isPrime) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}

return 0;
}

39
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Prime Number


Enter a number: 7
7 is a prime number.

Case 2: Not a Prime Number


Enter a number: 10
10 is not a prime number.

Case 3: Edge Case - 1 (Not a Prime Number)


Enter a number: 1
1 is not a prime number.

Case 4: Edge Case - Prime Number 2


Enter a number: 2
2 is a prime number.

40
B23CSI101 C PROGRAMMING

Ex.No. 3(d)
C PROGRAM BY USING WHILE, DO-WHILE AND FOR LOOPS.
Date

AIM:
To write a C program to find the prime numbers from 2 to 50 using nested for loop.

ALGORITHM:

STEP 1: Start the program

STEP 2: Declare the variables I,j

STEP 3: Using nested for loop check for the condition. If the factor is found it is not prime

STEP 4: If it is not found then print the number which is prime.

STEP 5: Stop the program.

41
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int num, i, j, isPrime;

// Loop through numbers from 2 to 50


printf("Prime numbers from 2 to 50 are:\n");
for (num = 2; num <= 50; num++) {
isPrime = 1; // Assume the number is prime

// Nested for loop to check if the number is divisible by any number between 2 and num/2
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // If num is divisible by i, it is not a prime number
break; // No need to check further
}
}

// If isPrime is still 1, the number is prime


if (isPrime == 1) {
printf("%d ", num); // Print the prime number
}
}
printf("\n");

return 0;
}

42
B23CSI101 C PROGRAMMING

OUTPUT:

Prime numbers from 2 to 50 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

43
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. Difference between Entry controlled and Exit controlled loop?

2. What are all loop control statements in C?

3. What will happen if break statement is not used in switch case in C?

4. What is the difference between the local variable and global variable in C?

5. When is a switch statement better than multiple if statements?

RESULT:

44
B23CSI101 C PROGRAMMING

Ex.No. 4(a)(i) C PROGRAM FOR SIMPLE APPLICATIONS MAKING USE OF


Date BASIC CONCEPT OF ARRAYS.

AIM:
To write a C program to input elements in array and sort array elements in ascending order.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Input size and elements in array from user. Store it in some variable say size and arr.

STEP 3: To select each element from array, run an outer loop from 0 to size – 1.

STEP 4: Run another inner loop from i + 1 to size - 1 to place currently selected element at its correct
position.

STEP 5: Inside inner loop to compare currently selected element with subsequent element and swap
two array elements if not placed at its correct position. Which is if(arr[i] > arr[j]) then swap arr[i] with
arr[j].

STEP 6: After this nested loop gets executed, we get all the elements of the array sorted in ascending
order.

STEP 7: Stop the program.

45
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int n, i, j, temp;

// Input the number of elements


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

int arr[n]; // Declare an array of size n

// Input the elements of the array


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

// Sorting the array in ascending order using Bubble Sort


for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// Output the sorted array


printf("Array elements in ascending order are:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

46
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Array with Unsigned Elements

Enter the number of elements: 5


Enter the elements of the array:
34 12 54 23 9
Array elements in ascending order are:
9 12 23 34 54

Case 2: Array with Already Sorted Elements

Enter the number of elements: 4


Enter the elements of the array:
1234
Array elements in ascending order are:
1234

Case 3: Array with Duplicate Elements


Enter the number of elements: 6
Enter the elements of the array:
528247
Array elements in ascending order are:
224578

47
B23CSI101 C PROGRAMMING

Ex.No. 4(a)(ii) IMPLEMENT ONE DIMENSIONAL ARRAY TO PERFORM


Date SEARCHING.

AIM:
To write a C program to input elements in array and search whether an element exists in array or
not.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Input size and elements in array from user. Store it in some variable say size and arr.

STEP 3: Input number to search from user in some variable say toSearch.

STEP 4: Define a flag variable as found = 0. which means initially we have assumed that searched
element does not exists in array.

STEP 5: Run loop from 0 to size.

STEP 6: Inside loop check if current array element is equal to searched number or not. Which is
if(arr[i] == toSearch) then set found = 1 flag and terminate from loop. Since element is found no need
to continue further.

STEP 7: Outside the loop check if(found == 1), if it is true means element is found, else element is
not found in the array

STEP 8: Stop the program.

48
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int n, i, element, found = 0;

// Input the number of elements


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

int arr[n]; // Declare an array of size n

// Input the elements of the array


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

// Input the element to search for


printf("Enter the element to search: ");
scanf("%d", &element);

// Search for the element in the array


for (i = 0; i < n; i++) {
if (arr[i] == element) {
found = 1; // Element found
break; // Exit the loop as we found the element
}
}

// Output whether the element is found or not


if (found) {
printf("%d is found in the array.\n", element);
} else {
printf("%d is not found in the array.\n", element);
}

return 0;
}

49
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Element Found

Enter the number of elements: 5


Enter the elements of the array:
34 12 54 23 9
Enter the element to search: 23
23 is found in the array.

Case 2: Element Not Found

Enter the number of elements: 5


Enter the elements of the array:
34 12 54 23 9
Enter the element to search: 100
100 is not found in the array.

50
B23CSI101 C PROGRAMMING

Ex. No. 4 b (i) MATRIX OPERATION -ADDITION


Date

AIM:

To write a c program to implement matrix addition

ALGORITHM:

STEP 1: Start

STEP 2: Declare matrix A[r][c];

and matrix B[r][c];

and matrix C[r][c]; r= no. of rows, c= no. of columns

STEP 3: Read r, c, A[][] and B[][]

STEP 4: Declare variable i=0, j=0

STEP 5: Repeat until i < r

5.1 : Repeat until j < c

C[i][j]=A[i][j] + B[i][j]

Set j=j+1

5.2 : Set i=i+1

STEP 6: C is the required matrix after addition.

STEP 7: Stop

51
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int m, n, i, j;

// Input the dimensions of the matrices


printf("Enter the number of rows and columns of the matrices: ");
scanf("%d %d", &m, &n);

int matrix1[m][n], matrix2[m][n], sum[m][n];

// Input the elements of the first matrix


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

// Input the elements of the second matrix


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

// Perform matrix addition


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Output the sum matrix


printf("The sum of the two matrices is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}

return 0;
}

52
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Example with 2x2 Matrices:

Enter the number of rows and columns of the matrices: 2 2

Enter the elements of the first matrix:


12
34
Enter the elements of the second matrix:
56
78
The sum of the two matrices is:
68
10 12

Case 2: Example with 3x3 Matrices:

Enter the number of rows and columns of the matrices: 3 3

Enter the elements of the first matrix:


123
456
789
Enter the elements of the second matrix:
987
654
321
The sum of the two matrices is:
10 10 10
10 10 10
10 10 10

53
B23CSI101 C PROGRAMMING

Ex.No. 4 b (ii) MATRIX OPERATION -SUBTRACTION


Date

AIM:

To write a c program to implement matrix subtraction.

ALGORITHM:

STEP 1: Start

STEP 2: Declare matrix A[r][c];

and matrix B[r][c];

and matrix C[r][c]; r= no. of rows, c= no. of columns

STEP 3: Read r, c, A[][] and B[][]

STEP 4: Declare variable i=0, j=0

STEP 5: Repeat until i < r

5.1 : Repeat until j < c

C[i][j]=A[i][j] - B[i][j]

Set j=j+1

5.2 : Set i=i+1

STEP 6: C is the required matrix after subtraction.

STEP 7: Stop

54
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int m, n, i, j;

// Input the dimensions of the matrices


printf("Enter the number of rows and columns of the matrices: ");
scanf("%d %d", &m, &n);

int matrix1[m][n], matrix2[m][n], difference[m][n];

// Input the elements of the first matrix


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

// Input the elements of the second matrix


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

// Perform matrix subtraction


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
difference[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

// Output the difference matrix


printf("The difference of the two matrices is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", difference[i][j]);
}
printf("\n");
}

return 0;
}

55
B23CSI101 C PROGRAMMING

OUTPUT

Case 1: Example with 2x2 Matrices

Enter the number of rows and columns of the matrices: 2 2


Enter the elements of the first matrix:
58
42
Enter the elements of the second matrix:
32
16
The difference of the two matrices is:
26
3 -4

Case 2: Example with 3x3 Matrices


Enter the number of rows and columns of the matrices: 3 3
Enter the elements of the first matrix:
10 20 30
40 50 60
70 80 90
Enter the elements of the second matrix:
5 10 15
20 25 30
35 40 45
The difference of the two matrices is:
5 10 15
20 25 30
35 40 45

56
B23CSI101 C PROGRAMMING

Ex.No. 4 b(iii) MATRIX OPERATION -MULTIPLICATION


Date

AIM

To write a c program to implement matrix multiplication.

ALGORITHM:

STEP 1: Start

STEP 2: Declare matrix first[c][d];

and matrix second[p][q];

and matrix multiply[c][d]; c,p= no. of rows, d,q= no. of columns

STEP 3: Read k,c, p,d,q, first[][] and second[][]

STEP 4: Declare variable c=0, d=0

STEP 5: Repeat until c<m

5.1 : Repeat until d<n

5.2 : Repeat until k<q

sum = sum + first[c][k]*second[k][d];

Set k=k+1

5.3 : Set c=c+1,d=d+1

STEP 6: sum is the required matrix after multiplication.

STEP 7: Stop

57
B23CSI101 C PROGRAMMING

PROGRAM

#include <stdio.h>

int main() {
int m, n, p, q, i, j, k;

// Input the dimensions of the first matrix (m x n)


printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &m, &n);

// Input the dimensions of the second matrix (p x q)


printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &p, &q);

// Check if multiplication is possible (columns of matrix1 must equal rows of matrix2)


if (n != p) {
printf("Matrix multiplication is not possible. The number of columns of the first matrix must equal
the number of rows of the second matrix.\n");
return 1;
}

int matrix1[m][n], matrix2[p][q], result[m][q];

// Input the elements of the first matrix


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

// Input the elements of the second matrix


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

// Initialize the result matrix to 0


for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
result[i][j] = 0;
}
}

// Perform matrix multiplication


for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
for (k = 0; k < n; k++) {
58
B23CSI101 C PROGRAMMING

result[i][j] += matrix1[i][k] * matrix2[k][j];


}
}
}

// Output the result matrix


printf("The product of the two matrices is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

59
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Example with 2x3 and 3x2 Matrices

Enter the number of rows and columns of the first matrix: 2 3


Enter the number of rows and columns of the second matrix: 3 2
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
78
9 10
11 12
The product of the two matrices is:
58 64
139 154

60
B23CSI101 C PROGRAMMING

Ex.No. 4.(c) IMPLEMENT TWO DIMENSIONAL ARRAYS AND PASSING 2D


Date ARRAYS TO FUNCTIONS

AIM:
To Write a C program to read square matrix of order n, transpose it using user defined function and
display transposed matrix from main() function.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Read the entered order of matrix store that value into the variable n.

STEP 3: Read the entered elements using scanf and store the entered elements into the matrix using
nested for loop.

STEP 4: From the main() function calls the transpose() function by passing an 2D array (i/p matrix),
size of the 2D array value as arguments.

STEP 5: In the function transpose(), loop through the matrix elements and convert its rows into
columns using tmp variable.

STEP 6: Finally, display the transposed matrix elements in the main() function.

STEP 7: Stop the program.

61
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

// Function to compute the transpose of a matrix


void transpose(int matrix[][10], int transposed[][10], int n) {
int i, j;
// Transpose the matrix
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
transposed[j][i] = matrix[i][j];
}
}
}

int main() {
int n, i, j;

// Input the order of the square matrix


printf("Enter the order of the square matrix (n x n): ");
scanf("%d", &n);

int matrix[n][n], transposed[n][n];

// Input the elements of the square matrix


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

// Call the transpose function


transpose(matrix, transposed, n);

// Display the transposed matrix


printf("The transposed matrix is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}

return 0;
}

62
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Example with a 3x3 Matrix

Enter the order of the square matrix (n x n): 3


Enter the elements of the matrix:
123
456
789
The transposed matrix is:
147
258
369

Case 2: Example with a 2x2 Matrix

Enter the order of the square matrix (n x n): 2


Enter the elements of the matrix:
12
34
The transposed matrix is:
13
24

63
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. In C, if we pass an array as an argument to a function, what actually get passed?

2. How to initialize a two-dimensional array?

3. What are the uses ofa pointer?

4. Is it possible to have more than one main() function in a C program?

5. Differentiate between arrays and pointers?

RESULT:

64
B23CSI101 C PROGRAMMING

Ex.No. 5(a)
GENERATE A SIMPLE APPLICATION USING POINTER
Date

AIM:
To implement a C program to search (linear) an element from an array using pointers.

ALGORITHM:

STEP 1: Declare and read the number of elements.

STEP 2: Declare and read the array size at runtime.

STEP 3: Input the array elements.

STEP 4: Declare a pointer variable.

STEP 5: Allocate the memory dynamically at runtime.

STEP 6: Enter an element that to be searched.

STEP 7: Check if an element is present in an array by traversing. If an element is found display "Yes",
otherwise "No".

65
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int linearSearch(int *arr, int size, int target) {


for (int i = 0; i < size; i++) {
// Compare the current element using pointer arithmetic
if (*(arr + i) == target) {
return i ; // Return the index of the element if found
}
}
return -1; // Return -1 if the element is not found
}

int main() {
int n, target, result;

// Input the number of elements in the array


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

int arr[n];

// Input the elements of the array


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

// Input the element to search


printf("Enter the element to search: ");
scanf("%d", &target);

// Perform linear search using pointers


result = linearSearch(arr, n, target);

// Output the result


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

66
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Element Found

Enter the number of elements in the array: 5


Enter the elements of the array:
13579
Enter the element to search: 7
Element 7 found at index 3.

Case 2: Element Not Found

Enter the number of elements in the array: 5


Enter the elements of the array:
13579
Enter the element to search: 4
Element 4 not found in the array.

67
B23CSI101 C PROGRAMMING

Ex. No. 5(b)


GENERATE A SIMPLE APPLICATION USING POINTER
Date

AIM:
To write a C program to perform binary search using pointers.

ALGORITHM:

STEP 1: Declare and read the number of elements.

STEP 2: Declare and read the array size at runtime.

STEP 3: Input the array elements.

STEP 4: Declare a pointer variable.

STEP 5: Perform binary search to find the target value

STEP 6: Check if an element is present in an array by traversing. If an element is found display the
elementindex, otherwise print element not found.

STEP 7: Stop the program.

68
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
int binarySearch(int *arr, int size, int target) {
int *left = arr; // Pointer to the first element of the array
int *right = arr + size - 1; // Pointer to the last element of the array
while (left <= right) {
int *mid = left + (right - left) / 2; // Calculate middle element using pointer arithmetic

if (*mid == target) {
return mid - arr; // Return the index of the target element
}
else if (*mid < target) {
left = mid + 1; // Search in the right half
}
else {
right = mid - 1; // Search in the left half
}
}

return -1; // Return -1 if the target is not found


}

int main() {
int n, target, result;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];

// Input the elements of the array


printf("Enter the elements of the array (sorted in ascending order):\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the element to search


printf("Enter the element to search: ");
scanf("%d", &target);

// Perform binary search using pointers


result = binarySearch(arr, n, target);

// Output the result


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

69
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Element Found:

Enter the number of elements in the array: 5


Enter the elements of the array (sorted in ascending order):
13579
Enter the element to search: 7
Element 7 found at index 3.

Case 2: Element Not Found:

Enter the number of elements in the array: 5


Enter the elements of the array (sorted in ascending order):
13579
Enter the element to search: 4
Element 4 not found in the array.

70
B23CSI101 C PROGRAMMING

Ex. No. 5(c)


GENERATE A SIMPLE APPLICATION USING POINTER
Date

AIM:
To write a C program to read two numbers from user and add them using pointers.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare three variables say num1, num2, and sum of int (integer) type

STEP 3: Here first two variable stores the two number entered by user at run-time.

STEP 4: And the third variable, sum will be used to store the summation of given two number using
pointer.

STEP 5: Declare two variables say ptr1 and ptr2 of int pointer (integer pointer) type. To declare any
variable as pointer type variable, just place * (star) before the variable without including any space.

STEP 6: Initialize the address of first variable (that holds first number) num1 to ptr1 using & (address
of) operator.

STEP 7: Initialize the address of second variable (that holds second number) num2 to ptr2 using &
(address of) operator.

STEP 8: Perform the operation (value at ptr1 + value at ptr2). using * (value at address) operator. As
both ptr1 and ptr2 holds the address of entered two number. And finally initialize it to the variable sum
that holds the addition result of given two number by user.

STEP 9: Print the value of sum as output.

STEP 10: Stop the program.

71
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
int num1, num2, sum;
int *ptr1, *ptr2, *ptrSum;

// Pointers to store the addresses of the variables


ptr1 = &num1;
ptr2 = &num2;
ptrSum = &sum;

// Input two numbers from the user


printf("Enter the first number: ");
scanf("%d", ptr1);

printf("Enter the second number: ");


scanf("%d", ptr2);

// Adding the numbers using pointers


*ptrSum = *ptr1 + *ptr2;

// Output the result


printf("The sum of %d and %d is: %d\n", *ptr1, *ptr2, *ptrSum);

return 0;
}

72
B23CSI101 C PROGRAMMING

OUTPUT:

TEST CASES:
Enter the first number: 15
Enter the second number: 25
The sum of 15 and 25 is: 40

73
B23CSI101 C PROGRAMMING

INFERENCE:

VIVAQUESTIONS:

1. What are pointers in C?

2. What are the two types of pointers in C?

3. What are the uses of pointers?

4. What is the syntax of pointer?

5. Are pointers faster?

RESULT:

74
B23CSI101 C PROGRAMMING

Ex.No. 6 CONSTRUCT A C PROGRAM USING RECURSION


Date

AIM:
To write a C program to find the factorial of a given number using recursion.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Read number n from the user.

STEP 4: From the main() function call factorial(n) function with the argument.

STEP 4.1: Start function.

STEP 4.2: if n==1 then return 1.

STEP 4.3: Else


f=n*factorial(n-1)

STEP 4.4: Return f (return the factorial value to main function).

STEP 5: Print the factorial value.

STEP 6: Stop the program.

75
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

// Function to calculate factorial using recursion


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

int main() {
int num;

// Input the number from the user


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

// Check if the number is negative, as factorial is not defined for negative numbers
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
// Call the recursive factorial function and display the result
printf("The factorial of %d is %d.\n", num, factorial(num));
}

return 0;
}

76
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Positive Number:

Enter a number: 5
The factorial of 5 is 120.

Case 2: Negative Number:

Enter a number: -3
Factorial is not defined for negative numbers.

77
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. Can you pass an array to a function?

2. What do you mean by function prototype and why it is used?

3. Can you write a function without any parameters?

4. Can you return multiple values from a function using return statement?

5. What are the various ways of writing return statement in a function?

RESULT:

78
B23CSI101 C PROGRAMMING

Ex.No. 7(a) DEVELOP A C PROGRAM TO PERFORM VARIOUS STRING


Date HANDLING OPERATIONS USING BUILD-IN FUNCTIONS.

AIM:
To Write a C program to find the length of the string using strlen() function.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Read input str.

STEP 4: Find the string length using strlen function.

STEP 5: Print the String length.

STEP 6: Stop the program.

79
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
#include <string.h> // Required for strlen() function

int main() {
char str[100]; // Declare a character array to store the input string

// Input the string from the user


printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Reading the string using fgets to handle spaces

// Remove the newline character that fgets() adds


str[strcspn(str, "\n")] = '\0';

// Calculate the length of the string using strlen() function


int length = strlen(str);

// Output the length of the string


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

return 0;
}

80
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: String with No Spaces:

Enter a string: Hello


The length of the string is: 5

Case 2: String with Spaces:

Enter a string: Hello World


The length of the string is: 11

81
B23CSI101 C PROGRAMMING

Ex.No. 7(b) DEVELOP A C PROGRAM TO PERFORM VARIOUS STRING


Date HANDLING OPERATIONS USING BUILD-IN FUNCTIONS.

AIM:
To write a C program to perform the string copy using strcpy() function.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Read input str.

STEP 4: Copy the string from source string to destination string using strcpy function.

STEP 5: Print the string.

STEP 6: Stop the program.

82
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
#include <string.h> // Required for strcpy() function

int main() {
char source[100], destination[100]; // Declare source and destination character arrays

// Input the source string from the user


printf("Enter a string to copy: ");
fgets(source, sizeof(source), stdin); // Reading the source string using fgets

// Remove the newline character that fgets() adds


source[strcspn(source, "\n")] = '\0';

// Copy the string from source to destination using strcpy()


strcpy(destination, source);

// Output the copied string


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

return 0;
}

83
B23CSI101 C PROGRAMMING

OUTPUT:

Enter a string to copy: Hello, World!


The copied string is: Hello, World!

84
B23CSI101 C PROGRAMMING

Ex.No. 7(c) DEVELOP A C PROGRAM TO PERFORM VARIOUS STRING


Date HANDLING OPERATIONS USING BUILD-IN FUNCTIONS.

AIM:
To write a C Program to compare two strings using strcmp() Function.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Read input str1 and str2.

STEP 4: Compare two strings (str1, str2) using strcmp() function

STEP 5: If the strings are equal then print “Strings are equal”.

STEP 6: If the strings are not equal then print “Strings are not equal”.

STEP 7: Stop the program.

85
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
#include <string.h> // Required for strcmp() function

int main() {
char str1[100], str2[100]; // Declare two character arrays to store the strings

// Input the first string from the user


printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin); // Reading the first string using fgets

// Remove the newline character that fgets() adds


str1[strcspn(str1, "\n")] = '\0';

// Input the second string from the user


printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin); // Reading the second string using fgets

// Remove the newline character that fgets() adds


str2[strcspn(str2, "\n")] = '\0';

// Compare the two strings using strcmp()


int result = strcmp(str1, str2);

// Output the result of the comparison


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

return 0;
}

86
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Strings are Equal:

Enter the first string: Hello


Enter the second string: Hello
The strings are equal.

Case 2: First String is Greater

Enter the first string: Apple


Enter the second string: Banana
The first string is less than the second string.

Case 3: First String is Smaller


Enter the first string: Peach
Enter the second string: Apple
The first string is greater than the second string.

87
B23CSI101 C PROGRAMMING

Ex.No. 7(d) DEVELOP A C PROGRAM TO PERFORM VARIOUS STRING


Date HANDLING OPERATIONS USING BUILD-IN FUNCTIONS.

AIM:
To write a C Program to concatenate two strings using strcat() function.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Read input str1 and str2.

STEP 4: Concatenate two strings (str1, str2) using strcat() function. It takes two strings as a parameter
and then appends the second string at the end of the first string.

STEP 5: After concatenation display the string.

STEP 6: Stop the program.

88
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
#include <string.h> // Required for strcat() function

int main() {
char str1[100], str2[100]; // Declare two character arrays to store the strings

// Input the first string from the user


printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin); // Reading the first string using fgets

// Remove the newline character that fgets() adds


str1[strcspn(str1, "\n")] = '\0';

// Input the second string from the user


printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin); // Reading the second string using fgets

// Remove the newline character that fgets() adds


str2[strcspn(str2, "\n")] = '\0';

// Concatenate the second string to the first string using strcat()


strcat(str1, str2);

// Output the concatenated string


printf("The concatenated string is: %s\n", str1);

return 0;
}

89
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Concatenating Two Strings:

Enter the first string: Hello


Enter the second string: World
The concatenated string is: HelloWorld

Case 2: Concatenating Strings with Spaces:

Enter the first string: Hello


Enter the second string: Beautiful World
The concatenated string is: HelloBeautiful World

90
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. Naming the library functions for handling string.

2. What is the difference between a string copy (strcpy) and a memory copy (memcpy)?

3. How do you determine the length of a string value that was stored in a variable?

4. Which function in C can be used to append a string to another string?

5. What is gets() function?

RESULT:

91
B23CSI101 C PROGRAMMING

Ex.No. 8(a) CONSTRUCT A C PROGRAM USING CALL BY VALUE


Date

AIM:
To write a C program to swap two numbers using call by value.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the variables.

STEP 3: Set a ← 10 and b ← 20.

STEP 4: Call the function swap(a,b).

STEP 4.1: Start function.

STEP 4.2: Assign t ← a.

STEP 4.3: Assign a ← b.

STEP 4.4: Assign b ← t.

STEP 4.5: After swapping Print a and b values.

STEP 4.6: End function.

STEP 5: Stop the program.

92
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

// Function to swap two numbers using call by value


void swap(int a, int b) {
int temp;

// Swapping the values using a temporary variable


temp = a;
a = b;
b = temp;

// Printing swapped values inside the function (call by value does not affect the original values)
printf("Inside swap function:\n");
printf("a = %d, b = %d\n", a, b);
}

int main() {
int num1, num2;

// Input the two numbers from the user


printf("Enter the first number: ");
scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

// Printing original values before swapping


printf("\nBefore swap:\n");
printf("num1 = %d, num2 = %d\n", num1, num2);

// Calling swap function (call by value)


swap(num1, num2);

// Printing values after calling swap function (values in main() will not change)
printf("\nAfter swap (inside main):\n");
printf("num1 = %d, num2 = %d\n", num1, num2);

return 0;
}

93
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1:

Enter the first number: 5


Enter the second number: 10

Before swap:
num1 = 5, num2 = 10
Inside swap function:
a = 10, b = 5

After swap (inside main):


num1 = 5, num2 = 10

94
B23CSI101 C PROGRAMMING

Ex.No. 8(b) GENERATE A SIMPLE APPLICATION USING CALL BY REFERENCE


Date

AIM:
To write a C Program to Sort the list of numbers using pass by reference.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare variables and create an array.

STEP 3: Read the Input for number of elements and each element.

STEP 4: Develop a function to sort the array by passing reference.

STEP 5: Compare the elements in each pass till all the elements are sorted.

STEP 6: Display the output of the sorted elements.

STEP 7: Stop the program.

95
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to sort the array using Bubble Sort (pass by reference)
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]); // Swapping elements if they are in wrong order
}
}
}
}
// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int n;
// Input the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];

// Input the elements of the array


printf("Enter the elements: \n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Print the array before sorting
printf("Array before sorting: ");
printArray(arr, n);

// Sort the array using bubble sort (pass by reference)


bubbleSort(arr, n);
// Print the array after sorting
printf("Array after sorting: ");
printArray(arr, n);
return 0;
}

96
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1:

Enter the number of elements: 5


Enter the elements:
12 11 5 6 7
Array before sorting: 12 11 5 6 7
Array after sorting: 5 6 7 11 12

97
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. What is the difference between printf() and puts()?

2. Define pointer variable?

3. What is use of the strcmp() function?

4. Which data structure is used in recursion?

5. What is the necessity of creating a user defined function in C?

RESULT:

98
B23CSI101 C PROGRAMMING

Ex.No. 9(a) DEVELOP A C SIMPLE APPLICATION USING STRUCTURE AND


Date UNION CONCEPTS.

AIM:
To write a C Program to maintain students records using structure.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the Structure Student with data members such as no, name, m1, m2,
m3, m4, m5, total, avg and grade.

STEP 3: Get the number of students N.

STEP 4: Set a for loop up to N to get the student details as input.

STEP 4.1: Enter the Student details such as Roll no, Name, Mark1, Mark2, Mark3, Mark4, Mark5.

STEP 4.2: Calculate Total and Avg, Grade.

STEP 4.3: Repeat Step 4.1 and 4.2 up to N.

STEP 5: Print Student Roll No, Name, Total, Avg and Grade.

STEP 6: Stop the program.

99
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

// Define the structure for student record


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

// Function to input student details


void inputStudentDetails(struct Student *s) {
printf("Enter the student's name: ");
fgets(s->name, sizeof(s->name), stdin); // Reading name with spaces
s->name[strcspn(s->name, "\n")] = '\0'; // Remove the newline character

printf("Enter the roll number: ");


scanf("%d", &s->rollNumber);

printf("Enter the marks: ");


scanf("%f", &s->marks);

// Clear the buffer for any remaining newline character


getchar();
}

// Function to display student details


void displayStudentDetails(struct Student s) {
printf("\nStudent Details:\n");
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.rollNumber);
printf("Marks: %.2f\n", s.marks);
}

int main() {
struct Student student1; // Declare a variable of type struct Student

// Input student details


printf("Enter student details:\n");
inputStudentDetails(&student1);

// Display student details


printf("\nDisplaying student details:\n");
displayStudentDetails(student1);

return 0;
}

100
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1:
Enter student details:
Enter the student's name: John Doe
Enter the roll number: 101
Enter the marks: 85.5

Displaying student details:


Student Details:
Name: John Doe
Roll Number: 101
Marks: 85.50

101
B23CSI101 C PROGRAMMING

Ex.No. 9(b) DEVELOP A C SIMPLE APPLICATION USING STRUCTURE AND


Date UNION CONCEPTS.

AIM:
To write a C Program to create payroll processing using union.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Declare the Union Employee with data members such as name, eno, basic salary, net salary,
gross salary.

STEP 3: Get the details of an employee.

STEP 4: Enter the employee details such as Name, Emp No and Basic salary.

STEP 5: Calculate HRA=10%*BASIC, DA=3%*BASIC

STEP 6: Calculate GROSS=BASIC+HRA+DA

STEP 7: Print Employee salary details such as Name, Id, Basic, HRA, DA,GROSS.

STEP 8: Stop the program

102
B23CSI101 C PROGRAMMING

PROGRAM:

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

// Define a union for payroll processing


union Payroll {
float salary; // Salary for salaried employees
float hourlyWage; // Hourly wage for hourly employees
};

struct Employee {
char name[50];
int id;
char type; // 'S' for salaried, 'H' for hourly
union Payroll pay; // Union to store either salary or hourly wage
};

// Function to input employee details


void inputEmployeeDetails(struct Employee *e) {
printf("Enter employee name: ");
fgets(e->name, sizeof(e->name), stdin);
e->name[strcspn(e->name, "\n")] = '\0'; // Remove newline character from name

printf("Enter employee ID: ");


scanf("%d", &e->id);

printf("Enter type of employee ('S' for Salaried, 'H' for Hourly): ");
getchar(); // Consume the newline character left by scanf
scanf("%c", &e->type);

if (e->type == 'S' || e->type == 's') {


printf("Enter salary: ");
scanf("%f", &e->pay.salary);
} else if (e->type == 'H' || e->type == 'h') {
printf("Enter hourly wage: ");
scanf("%f", &e->pay.hourlyWage);
} else {
printf("Invalid employee type!\n");
}
}

// Function to display employee details


void displayEmployeeDetails(struct Employee e) {
printf("\nEmployee Details:\n");
printf("Name: %s\n", e.name);
printf("Employee ID: %d\n", e.id);

if (e.type == 'S' || e.type == 's') {


printf("Type: Salaried\n");
printf("Salary: %.2f\n", e.pay.salary);
103
B23CSI101 C PROGRAMMING

} else if (e.type == 'H' || e.type == 'h') {


printf("Type: Hourly\n");
printf("Hourly Wage: %.2f\n", e.pay.hourlyWage);
} else {
printf("Invalid employee type!\n");
}
}

int main() {
struct Employee emp;

// Input employee details


inputEmployeeDetails(&emp);

// Display employee details


displayEmployeeDetails(emp);

return 0;
}

104
B23CSI101 C PROGRAMMING

OUTPUT:

Case 1: Salaried Employee:

Enter employee name: John Doe


Enter employee ID: 101
Enter type of employee ('S' for Salaried, 'H' for Hourly): S
Enter salary: 50000

Employee Details:
Name: John Doe
Employee ID: 101
Type: Salaried
Salary: 50000.00

Case 2: Hourly Employee:

Enter employee name: Alice Smith


Enter employee ID: 102
Enter type of employee ('S' for Salaried, 'H' for Hourly): H
Enter hourly wage: 20.5

Employee Details:
Name: Alice Smith
Employee ID: 102
Type: Hourly
Hourly Wage: 20.50

105
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. What is a structure?

2. Differentiate between array and structure?

3. Define union?

4. Differentiate between address operator and dereferencing operator.

5. What is the difference between structure and union?

RESULT:

106
B23CSI101 C PROGRAMMING

Ex.No. 10 (a) WRITE A C PROGRAM TO PERFORM THE FILE OPERATIONS AND


Date MODES.

AIM:
To write a C program to display the contents of a file.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Read file name.

STEP 3: Open file in read mode

STEP 4: Repeat until end of the file and print the contents if the file.

STEP 5: Close the file.

STEP 6: Stop the program.

107
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
FILE *file;
char ch;

// Open the file in read mode


file = fopen("example.txt", "r");

// Check if the file was opened successfully


if (file == NULL) {
printf("Error opening the file.\n");
return 1; // Exit the program if the file doesn't exist or cannot be opened
}

// Read and display the contents of the file character by character


while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}

// Close the file


fclose(file);

return 0;
}

108
B23CSI101 C PROGRAMMING

OUTPUT:

If the example.txt file contains:


Hello, World!
This is a C program.

If example.txt Does Not Exist:


If the file is not present in the directory, the program will display the following error message:

Error opening the file.

Explanation:
The program uses fopen() to open the file. If the file cannot be opened (e.g., it doesn't exist), fopen()
returns NULL, and an error message is printed.
If the file is opened successfully, the program reads its contents character by character using fgetc() and
prints them to the screen using putchar()

109
B23CSI101 C PROGRAMMING

Ex.No. 10(b) WRITE A C PROGRAM TO PERFORM THE FILE OPERATIONS AND


Date MODES.

AIM:
To write a C program to copy the contents of one file to another.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Read command line arguments.

STEP 3: Check if no of arguments =3 or not. If not print invalid no of arguments.

STEP 4: Open source file in read mode

STEP 5: If source file is NULL pointer, then print source file cannot be open.

STEP 6: Open destination file in write mode.

STEP 7: If destination file is NULL pointer, then print destination file cannot be open.

STEP 8: Read a character from source file and write to destination file until EOF.

STEP 9: Close source file and destination file.

STEP 10: Stop the program.

110
B23CSI101 C PROGRAMMING

PROGRAM:

#include <stdio.h>

int main() {
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;

// Input source and destination file names


printf("Enter the name of the source file: ");
scanf("%s", sourceFileName);
printf("Enter the name of the destination file: ");
scanf("%s", destinationFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file.\n");
return 1;
}

// Open the destination file in write mode


destinationFile = fopen(destinationFileName, "w");
if (destinationFile == NULL) {
printf("Error: Could not open/create destination file.\n");
fclose(sourceFile); // Close the source file before exiting
return 1;
}

// Copy contents from source to destination


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}

printf("File copied successfully.\n");

// Close the files


fclose(sourceFile);
fclose(destinationFile);

return 0;
}

111
B23CSI101 C PROGRAMMING

OUTPUT:

Program Input:
Enter the name of the source file: source.txt
Enter the name of the destination file: destination.txt

Program Output:
File copied successfully.

Explanation of Output:
The message "File copied successfully" confirms that the operation completed without errors.
The content of source.txt was read and written to destination.txt, creating an exact copy.

112
B23CSI101 C PROGRAMMING

INFERENCE:

VIVA QUESTIONS:

1. How to read the content from a file?

2. How to write the content into a file?

3. What is error handling in C?

4. What is the use of rewind function in C?

5. What is FILE pointer?

RESULT:

113

You might also like