0% found this document useful (0 votes)
65 views51 pages

POPC Lab Manual 24-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views51 pages

POPC Lab Manual 24-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

BANGALORE INSTITUTE OF TECHNOLOGY

Autonomous Institute, Affiliated to VTU

K.R.ROAD, V.V.PURA, BENGALURU -560 004

Department of CSE/ISE/CSE-DS/AI/IOT

Laboratory Manual

Principles of Programming Using C

BPOPS103

1st Semester

Academic year: 2024-25


BANGALORE INSTITUTE OF TECHNOLOGY
(Autonomous Institute, Affiliated to VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Vision
Establish and develop the Institute as the Centre of higher learning, ever abreast with expanding
horizon of knowledge in the field of Engineering and Technology with entrepreneurial thinking,
leadership excellence for life-long success and solve societal problems.

Mission

1. Provide high quality education in the Engineering disciplines from the undergraduate
through doctoral levels with creative academic and professional programs.
2. Develop the Institute as a leader in Science, Engineering, Technology, Management and
Research and apply knowledge for the benefit of society.
3. Establish mutual beneficial partnerships with Industry, Alumni, Local, State and Central
Governments by Public Service Assistance and Collaborative Research.
4. Inculcate personality development through sports, cultural and extracurricular activities and
engage in social, economic and professional challenges.
BANGALORE INSTITUTE OF TECHNOLOGY
(Autonomous Institute, Affiliated to VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865

DEPARTMENT OF CSE/ISE/CSE-DS/AI/IOT

VISION:
To be a center of excellence in computer engineering education, empowering graduates as
highly skilled professionals.

MISSION:
1. To provide a platform for effective learning with emphasis on technical excellence.
2. To train the students to meet current industrial standards and adapt to emerging
technologies.
3. To instill the drive for higher learning and research initiatives.
4. To inculcate the qualities of leadership and Entrepreneurship.

PROGRAM EDUCATIONAL OBJECTIVES (PEO)

1. Graduates will apply fundamental and advanced concepts of Computer Science


and Engineering for solving real world problems.
2. Graduates will build successful professional careers in various sectors to facilitate
societal needs.
3. Graduates will have the ability to strengthen the level of expertise through higher
studies and research.
4. Graduates will adhere to professional ethics and exhibit leadership qualities to
become an Entrepreneur.

PROGRAM SPECIFIC OUTCOMES (PSOs)

1. The graduates of the program will have the ability to build software products by
applying theoretical concepts and programming skills.
2. The graduates of the program will have the ability to pursue higher
Program Outcomes

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. 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.
3. 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.
4. 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.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. 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.
7. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. 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.
11. 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.
12. 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.
COURSE LEARNING OBJECTIVES (CLO)

CLO 1. Understand the functionalities of a computer and basic concepts of C programming.


CLO 2. Apply programming constructs of C language to solve real-world problems.
CLO 3. Gain knowledge of functions and strings of C program.
CLO 4. Explore data structures like arrays, structures, and pointers in implementing solutions to
problems.
CLO 5. Design and Develop solutions to problems using C programming constructs.

COURSE OUTCOMES (CO)

At the end of the course the student will be able to:


CO 1: Understand the basic concepts of computer, operator, datatypes, functions, arrays, strings,
pointer and structure.
CO 2: Apply the concepts of functions, strings, and data structures to solve the problem.
CO 3: Analyze the various flow control statements and data structures.
CO 4: Explore the knowledge of C programming for real-world problems..

CO TO PO & PSO MAPPING


PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO 10 PO11

BPOPS103 CO1 2

CO2 3 2 2

CO3 2 3 2

CO4 2 2 2 2
Principles of Programming Using C Laboratory

Subject Code : BPOPS103 CIE Marks : 50


Hours/Week : 0:0:2 Total Hours : 20

LIST OF PROGRAMS

Sl. No. Name of Experiment

1. Simulation of a simple calculator.

2. Compute the roots of a quadratic equation by accepting the coefficients. Print


appropriate messages.

3. Find the Armstrong Number between 1 to 1000.

4. Display the pascal triangle by reading the number of rows as input.

5. Implement Binary Search on Integers.

6. Implement Matrix multiplication and validate the rules of multiplication.

7. Compute sin(x)/cos(x) using Taylor series approximation. Compare your result


with the built-in library function. Print both the results with appropriate inferences.

8. Sort the given set of N numbers using Bubble sort.

9. Write functions to implement string operations such as compare, concatenate, and


find string length. Use the parameter passing techniques.

10. Implement structures to read, write and compute average- marks of the students, list
the students scoring above and below the average marks for a class of N students

11. Compute the sum, mean and standard deviation of all elements stored in an array of
N real numbers using pointers

12. Copy a text file to another file, read both the input file name and target file name.
Principles of Programming Using C BPOPS103

Principles of Programming Using C Laboratory

Subject Code : BPOPS103 CIE Marks: 50


Hours/Week : 0:0:2 Total Hours: 20

SCHEDULE OF EXPERIMENTS

Sl. No Name of Experiment WEEK

1 Sample Programs Week1

2 Simulation of a simple calculator. Week2

Compute the roots of a quadratic equation by accepting the


3 Week3
coefficients. Print appropriate messages.

4 Find the Armstrong Number between 1 to 1000. Week4

5 Display the pascal triangle by reading the number of rows as input. Week5

6 Implement Binary Search on Integers. Week6

Implement Matrix multiplication and validate the rules of


7 Week7
multiplication.
Compute sin(x)/cos(x) using Taylor series approximation. Compare
8 your result with the built-in library function. Print both the results Week8
with appropriate inferences.

9 Sort the given set of N numbers using Bubble sort. Week9

Write functions to implement string operations such as compare,


10 concatenate, and find string length. Use the parameter passing Week10
techniques.
Implement structures to read, write and compute average- marks of
11 the students, list the students scoring above and below the average Week11
marks for a class of N students
Compute the sum, mean and standard deviation of all elements
12 Week12
stored in an array of N real numbers using pointers
Copy a text file to another file, read both the input file name and
13 Week13
target file name.

14 Final Lab Test Week14

BIT, Bengaluru - 04 1
Principles of Programming Using C BPOPS103

General Lab Guidelines:


1. Conduct yourself in a responsible manner at all times in the laboratory. Intentional
misconduct will lead to exclusion from the lab.
2. Do not wander around, or distract other students, or interfere with the laboratory
experiments of other students.
3. Read the handout and procedures before starting the experiments. Follow all written
and verbal instructions carefully.
4. If you do not understand the procedures, ask the instructor or teaching assistant.
Attendance in all the labs is mandatory, absence permitted only with prior permission
from the Class teacher.
5. The workplace has to be tidy before, during and after the experiment.
6. Do not eat food, drink beverages or chew gum in the laboratory.
7. Every student should know the location and operating procedures of all Safety
equipment including First Aid Kit and Fire extinguisher.
DO’S:-
1. An ID card is a must.
2. Keep your belongings in a designated area.
3. Sign the log book when you enter/leave the laboratory.
4. Records have to be submitted every week for evaluation.
5. The program to be executed in the respective lab session has to be written in the lab
observation copy beforehand.
6. After the lab session, shut down the computers.
7. Report any problem in system (if any) to the person in-charge
DON'TS:-
1. Do not insert metal objects such as clips, pins and needles into the computer
casings(They may cause fire) and should not attempt to repair, open, tamper or interfere
with any of the computer, printing, cabling, or other equipment in the laboratory.
2. Do not change the system settings and keyboard keys.
3. Do not upload, delete or alter any software/ system files on laboratory computers.
4. No additional material should be carried by the students during regular labs.
5. Do not open any irrelevant websites in labs.
6. Do not use a flash drive on lab computers without the consent of the lab instructor.
7. Students are not allowed to work in the Laboratory alone or without the presence of the
instructor/teaching assistant.

BIT, Bengaluru - 04 2
Principles of Programming Using C BPOPS103

Introduction to C
A computer, in simple terms, can be defined. As an electronic device. That is designed to accept
data, perform their arithmetical mathematical and logical operations at high speed, and output
the result.

Basic organization of computer:

A computer is an electronic device that basically performs five major operation.


1. Accepting data or instruction
2. Storing data.
3. Processing data
4. Displaying data.
5. Controlling and coordinating all operations inside a computer.

➢ Input.
• This is a process of entering data instruction into the computer.
• The data and instructions can be entered by using different input devices such as
keyboard, most common scanner, The track ball, Etc.
• Note that computers understand binary languages, which consist of only two symbols,
0 and 1. So it is the responsibility of the input device to convert the input data into
binary codes.

BIT, Bengaluru - 04 3
Principles of Programming Using C BPOPS103

➢ Storage.
Storage is the process of saving data and instructions permanently in the computer so
that they can be used for processing new line A computer has two type of storage areas.
1. Primary storage
• Primary storage, also known as main memory, is the storage area that is directly
accessible by the CPU at very high speed.
• Drawback of main memory is that it is volatile in nature, that is, as soon as the
computer is switched off, the information stored gets erased.
• RAM and ROM are the examples of primary storage.
2. Secondary storage.
Also known as axillary memory. This is just the opposite of primary storage. It basically
overcomes all the drawbacks of the primary storage area.
It is cheaper, non volatile and used to permanently store data and programs of those
jobs that are not being currently executed by the CPU.
➢ Processing.
• The process of performing operation on the data as per the instructions specified by the
user is called processing.
• Data and instructions are taken from primary memory and transfer to the arithmetic and
logic unit, which performs all sorts of calculations.
• The intermediate results of processing may be stored in main memory as they may be
required again.
• When processing completes, the final result is then transfered to the main memory.
Hence the data may move from main memory to ALU multiple times before the
processing is over.
➢ Output.
• Output is the processing of the giving the result of data processing to the outside world.
• The results are given through output devices such as monitor, Printer, Etc.
• The output devices Therefore convert the result available in binary code into a human
readable language before displaying it to the user.

1. Control unit.
The control unit is the central nervous system of the entire computer system. It manages
and controls all the components of the computer system.

BIT, Bengaluru - 04 4
Principles of Programming Using C BPOPS103

Program Design Tools: Algorithms, Flowcharts, Pseudocodes:


1. Algorithms:
• The algorithm gives the logic of the program, that is, a step-by-step description of how
to arrive at a solution.
• An algorithm provides a blueprint to writing a program to solve a particular problem.
• It is considered to be an effective procedure for solving a problem in a finite number of
steps. That is, a well-defined algorithm always provides an answer, and is guaranteed
to terminate.
• An algorithm should have the following characteristics:
1. Be precise
2. Be unambiguous
3. Not even a single instruction must be repeated infinitely
4. After the algorithm gets terminated, the desired result must be obtained.
2. Flowchart:
• A flowchart is a graphical or symbolic representation of a process. It is basically used
to design and document virtually complex processes to help the viewers to visualize the
logic of the process.
• When designing a flowchart, each step in the process is depicted by a different symbol
and is associated with a short description.
• The symbols in the flowchart are linked together with arrows to show the flow of logic
in the process.
• The symbols of a flowchart include:
Name Symbol Usage
Start and end Represented as circles, ovals, or rounded
symbol / rectangles. Terminal symbols are always the
Terminal symbol first and the last symbols in a flowchart
Arrows Depict the flow of control of the program.
They illustrate the exact sequence in which
the instructions are executed
Generic Called as an activity, is represented using a
processing step rectangle. Activities include instructions
such as add a to b, save the result. Therefore,
a processing symbol represents arithmetic
and data movement instructions. When more
than one process has to be executed
simultaneously, they can be placed in the
same processing box. However, their
execution will be carried out in the order of
their appearance
Input/Output Represented using a parallelogram and are
Symbol used to get inputs from the users or display
the results to them.
Condition/ Represented using a diamond. It is basically
Decision symbol used to depict a Yes/No question or a
True/False test. The two arrows coming out
of it, one from the bottom vertex and the

BIT, Bengaluru - 04 5
Principles of Programming Using C BPOPS103

other from the right vertex, correspond to


Yes or True, and No or False, respectively.
The arrows should always be labelled. A
decision symbol in a flowchart can have
more than two arrows, which indicate that a
complex decision is being taken.
Labelled Represented by an identifying label inside a
connectors circle and are used in complex or multi sheet
diagrams to substitute for arrows. For each
label, the ‘outflow’ connector must have one
page Off-page or more ‘inflow’ connectors. A pair of
connectorconnector identically labelled connectors issued to
indicate a continued flow when the use of
lines becomes confusing.
Subroutine Indicates pre-defined process such as
subroutines or modules.

Comment Used to add comment or clarification.

3. Pseudocodes:
• Pseudocode is a compact and informal high-level description of an algorithm that uses
the structural conventions of a programming language
• An ideal pseudocode must be complete, describing the entire logic of the algorithm.
• Pseudocodes are an outline of a program that can easily be converted into programming
statements.
• They consist of short English phrases that explain specific tasks within 4 program's
algorithm.
• They should not include keywords in any specific computer language.

Types of Errors:
• Errors if not removed will either give erroneous output or will not let the compiler to
compile the program.
• Errors are broadly classified under four groups namely - a) Runtime error, b) Linker error,
c) Compile-time error, d) Logical error.
a) Runtime error:
Run-time errors occur when the program is being run executed. Such errors occur when
the program performs some illegal operations like:
• Dividing a number by zero
• Opening a file that already exists
• Lack of free memory space
• Finding square or logarithm of negative number
Run-time errors may terminate program execution, so the code must be written in such
a way that it handles all sorts of unexpected errors rather terminating it unexpectedly.
b) Compile-time error:
compile-time errors occur at the time of compilation of the program. Such errors can

BIT, Bengaluru - 04 6
Principles of Programming Using C BPOPS103

be further classified as follows:


i. Syntax Errors: Syntax errors are generated when rules of a programming
language are violated.
ii. Semantic Errors: Semantic errors are those errors which may comply with
rules of the programming language but are not meaningful to the compiler.
c) Logical error:
• Logical errors are errors in the program code that result in unexpected and
undesirable output.
• Such errors are not detected by the compiler, and programmers must check their
code line by line or use a debugger to locate and rectify the errors.
• Logical errors occur due to incorrect statements.
d) Linker Error:
These errors occur when the linker is not able to find the function definition for a given
prototype.

Structure of a C Program:
C program is composed of processor command, global declarative section and one or more
function blocks.
The preprocessor directives are instructions that indicate
how the program has to be compiled. include is one the
preprocessor command through which the compiler include
the needed information from the specified header file to the
particular code.
In Global variables or constants can be declared in the global
declaration part.
C program contains one or more functions. Functions are
defined as a group of statements that are executed together.
Function can be either system defined or user defined
functions. All functions are divided into two parts:
a) Local declaration section: Data will be visible only
within that function. Stated in other terms, the life-time of the
data will be only till the function ends.
b) Statement section: Contains the code that manipulates
the data to perform a specified task.

main() function is a system defined function from which the


C program execution begins. Every C program must include
one main function, where as user defined functions can be of
any number which can be included based on the tasks to be
performed.

Files Used in C Program:


Every C program has four file associated with it: 1) Source File, 2) Header File, 3) Object File,
4) Executable File.
1) Source Code File: Contains the source code of the program. The file extension of any
C source code file is “.c”. This file contains C source code that defines the main function
and maybe other functions.

BIT, Bengaluru - 04 7
Principles of Programming Using C BPOPS103

2) Header File: Header file have the extension “.h”. Subroutines of one program can be
included in the other with the help of the header file i.e., program containing the
subroutine can be compiled and the generated o/p file can be included as the header file.
Note: If the subroutine has been changed then the program has to be recompiled to
include the changed in the current working program.
Standard Header file are:
o string.h – for string handling functions.
o stdlib.h – for some miscellaneous functions.
o stdio.h – for standard input and output function.
o math.h – for mathematical function.
o alloc.h – for dynamic memory allocation.
o conio.h – for clearing the screen.
3) Object File: Object files are generated by the compiler as a result of processing the
source code file. Object files contain compact binary code of the function definitions.
Linker uses these object files to produce an executable file (.exe file) by combining the
object files together. Object files have a *.o” extension, Windows and MS-DOS have a
‘.obj’ extension for the object file.
4) Binary Executable File: The binary executable file is generated by the linker. The
linker links the various object files to produce a binary file that can be directly executed.
On Windows operating system, the executable files have a ‘.exe’ extension.

Compiling and Executing C Programs:

• C is a compiled language, a written C program is compiled through a C compiler that can


create an executable file. C program is human-readable, the executable file is a machine-
readable file.
• In C language programs, there are two kinds of source files, the main (.c) source file, and
header (.h) source files.
• The compilation process shown in Figure 9.6 is done in two steps, In the first step, the
preprocessor program reads the source file as text, and produces another text file as output.
• The output of the preprocessor is a text file which does not contain any preprocessor
statements. This file is ready to be processed by the compiler.

BIT, Bengaluru - 04 8
Principles of Programming Using C BPOPS103

• The compiler translates the source code into an object code. The object code contains the
machine instructions for the CPU, and calls to the operating system API.
• the object file is not an executable file. Therefore, in the next step, the object file is processed
with another special program called a linker.
• The linker combines the object file with library routines (supplied with the compiler) to
produce the final executable file
• In modular programming, the source code is divided into two or more source files. All these
source files are compiled separately thereby producing multiple object files, These object
files are combined by the linker to produce an executable file.

Using of Comments:
It is a good programming practice to place some comments in the code to help the reader
understand the code clearly. C supports two types of comments.
• ‘//’ is used to comment a single statement. This is known as a line comment. End of the
line specifies the end of the comment line.
• ‘/*’ multiline commnent, a ‘/*’ is ended with ‘*/’, all the statement b/w these symbol
are comments. This is also known as block comment.

C Tokens:
Tokens are the basic building blocks in C language. A program is constructed using a
combination of these tokens, There are six main types of tokens in C.

Token in C

Keyword Variable Constants Strings Special Characters Operators


s s
Characters in C:
Computer languages also use a character set that defines the fundamental units used to represent
information. The character set of C are:
• English alphabet: Include both lower case (a - z) as well as upper case (A - 2) letters.
• Digits: Include numerical digits from 0 to 9
• Special characters: Include symbols such as ~, @, #, $, %, ^, &, *, (, ), _, -, +, =, ;, “, ‘, |,
{, }, [, ], \, /, ?, <, >,., !.
• White space characters: These characters are used to print a blank space on the screen.
• Escape sequence:
Escape Purpose Escape Purpose Escape Purpose
sequence sequence sequence
\a Audible \n Newline \r Carriage return
Signal
\b Backspace \v Vertical tab \? Question mark
\t Tab \f New Page\ Clear \\ Back slash
screen
\’ Single quote \O Octal constant \x Hexadecimal
constant
\” Double quote \f Form feed \r Carriage return

BIT, Bengaluru - 04 9
Principles of Programming Using C BPOPS103

Keywords:
• C has a set of reserved words often known as keywords.
• All keywords are basically a sequence of characters that have a fixed meaning.
• All keywords must be written in lowercase (small) letters.
• C language has 32 keywords as listed below.

Basic Datatypes in C:

C language has very few basic datatypes as shown in below table.

The signed and unsigned datatypes in C is shown in below table.

void type holds no value. It is primarily used in three cases:


• To specify the retum type of a function (when the function returns no value).
• To specify the parameters of the function (when the function accepts no arguments from
the caller)
• To create generic pointers, We will read about generic pointers in the chapter on
Pointers.

BIT, Bengaluru - 04 10
Principles of Programming Using C BPOPS103

Variables:
A variable is defined as a meaningful name given to a data storage location in computer
memory. Variable actually refer to address of the memory where the data is stored.
C language supports two basic kinds of variables—numeric and character.
a) Numeric Variables: Numeric variables can be used to store cither integer values or
floating point values. It can also be associated with modifiers like short, long, signed,
unsigned.
b) Character Variables: Character variables are just single characters enclosed within
single quotes, These characters could be any character from the ASCII character set—
letters (‘a’, ‘A’), numerals (‘2’), or special characters (‘&’).
Declaration of variables:
• Each variable to be used in the program must be declared.
• To declare a variable, specify the data type (specifies what kind of value a variable will
store) of the variable followed by its name.
• In C, variable declaration always ends with a semicolon, for example:
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Initialization of variables:
• While declaring variables, we can also initialize them with some value. For example,
int emp_num = 7;
float salary = 2156.35;
char grade = ‘A’;
double balance_amount = 100000000;
• The initializer applies only to the variable defined immediately before it, Therefore, the
statement
“int count, flag = 1;” initializes the variable flag and not count.
• When variables are declared but not initialized they usually contain garbage values.

Input/Output Statement in C:
➢ printf() [Output Statement]:
▪ The printf function (stands for print formatting) is used to display information
required by the user and also prints the values of the variables.
▪ The printf function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text
stream to the standard output.
▪ The syntax of printf() is as given below:
printf ("control string", variable list);
Control String: C string that contains the text that has to be written on to the
standard output device. As part of control string printf() the function can have
as many additional arguments (known as format specifiers) as specified in the
prototype.

BIT, Bengaluru - 04 11
Principles of Programming Using C BPOPS103

➢ scanf() [Input statement]:The scanf() function stands for scan formatting and is used to
read formatted data from the keyboard.
The scanf function takes a text stream from the keyboard, extracts and formats data from
the stream according to a format control string and then stores the data in specified program
variables,
The syntax of the scanf() function can be given as:
scanf("control string", argl, arg2, arg3,……., argn);
Control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arguments arg1, arg2,.., argn, i.e,,
the arguments are actually the variable addresses where each piece of data is to be stored.

BIT, Bengaluru - 04 12
Principles of Programming Using C BPOPS103

Execution Steps of C Program:

Step 1: Open the Terminal


Step 2: Create a directory using mkdir command.
mkdir <folder_name>
Eg: mkdir POPC
Step 3: Change the directory using cd command.
cd <folder_name>
Eg: cd POPC
Step 4: Create a file with “.c” extension → type the program
gedit <file_name>.c
Eg: gedit sample1.c
Step 5: Save the code “ctrl + s”
Quit “ctrl + q”
Step 6: Compile the program using “cc” command.
cc <file_name>.c
Eg: cc sample1.c
Step 7: Get the output
Command: “./a.out”

Sample Programs:

1. Write a C Program to print “Hello World!”


2. Write a C Program to print your details such as name, department, semester, section, register number,
phone number using printf statements.
3. Implement the 2nd program using escape sequence characters (i.e., using single printf statement)
4. Write a C Program to Initialize a variable and print the value.
5. Write a C Program to Read the value of variable by keyboard and print the value.
6. Write a C Program to find the summation of two integer variables.
7. Write a C Program to compute the product of two floating point numbers.
8. Write a C Program to find the area of the square, rectangle and triangle.
9. Write a C Program to compute the square of a integer.
10. Write a C Program to read and display a character.
11. Write a C Program to read values for various data types.
12. Write a C Program to print values for various data types.

Department of CS&E, BIT 13


Principles of Programming Using C BPOPS103

Program 1
Simulation of a Simple Calculator.
Algorithm: To implement Commercial calculator.

Step 1: Start
Step 2: [Enter first number]
read num1
Step 3: [Enter Second number]
read num2
Step 4: [Enter Choice]
read choice
Step 5: [To perform addition]
if choice is equal to plus
add num1 and num2
print result
Step 6: [To perform subtraction]
if choice is equal to minus
subtract num2 from num1
print result
Step 7: [To perform multiplication]
if choice is equal to
multiplication multiply num1 and num2
print result
Step 8: [To perform division]
if choice is equal to division
divide num1 by num2
print result
Step 9: [To perform Modulus]
if choice is equal to modulus
divide num1 by num2
print result (remainder)
Step 10: Stop

Department of CS&E, BIT 14


Principles of Programming Using C BPOPS103

Source Code:

#include<stdio.h>
void main()
{
float sum, sub, mul, div, a, b;
int choice,mod;
printf("Enter the values of a&b\n");
scanf("%f%f", &a,&b);
printf("Enter 1 for Addition,\n2 for Sutraction,\n3 for Multiplication,\n4 for Division,\n5 for
Mod\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("addition\n");
printf(“sum of %d and %d is:”, a,b);
sum=a+b;
printf("%f ",sum);
break;
case 2: printf("subtraction\n");
printf(“Difference of %d and %d is:”, a,b);
sub=a-b;
printf("%f",sub);
break;
case 3: printf("Multiplication\n");
printf(“Product of %d and %d is:”, a,b);
mul=a*b;
printf("%f",mul);
break;
case 4: printf("Division\n");
if(b==0)
printf("Divide by zero error! please enter non-zero number");
else
{
printf(“Division of %d and %d is:”, a,b);
div=a/b;
printf("%f",div);
}
break;
case 5: printf("Modulus\n");
if(a<b)
mod=a;
else
mod=(int)a%(int)b;
printf(“Modulus of %d and %d is:”, a,b);
printf("%d",mod);
break;
Department of CS&E, BIT 15
Principles of Programming Using C BPOPS103

default: printf("Wrong choice, enter correct choice");


}
}

Sample Outputs:
1. Enter the values of a & b
53
Enter 1 for Addition,
2 for Sutraction,
3 for Multiplication,
4 for Division,
5 for Mod
1
addition
sum of 5 and 3 is 8.000000
2. Enter the values of a&b
42
Enter 1 for Addition,
2 for Sutraction,
3 for Multiplication,
4 for Division,
5 for Mod
4
Division
Division of 4 and 2 is 2.000000

Department of CS&E, BIT 16


Principles of Programming Using C BPOPS103

Program 2
Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
Algorithm: To compute all possible roots of the quadratic equation

Step 1: Start
Step 2: [Input the values of a, b, c]
read a, b, c
Step 3: [Calculate the determinant]
determinant = b*b-4*a*c
Step 4: [Check for validity]
If a is equal to 0 and b is equal to 0
print “Invalid Inputs”
Step 5: [Check for different roots]
If a is equal to 0
print “Linear equation”Root1=-c/b
print “Root1”
Step 6: [Check for real and equal roots]
If determinant is equal to 0
print “Roots are real and equal”
Root1= -b/(2*a)
Root2 = -b/(2*a)
Print “Root1 & Root2”
Step 7: [Check for real and distinct roots]
If determinant is greater than 0
Then print “Roots are real and distinct”
Root1= (-b+ (sqrt (fabs (determinant))))/(2*a)
Root2= (-b-(sqrt (fabs (determinant))))/(2*a)
Print “root1 and root2”
End if
Step 8: [Check for imaginary roots]
print “Roots are imaginary”Real=-b/ (2*a)
Imaginary=sqrt (fabs (determinant))/ (2*a)
print “Root1 and Root2”
Step 9: Stop

Department of CS&E, BIT 17


Principles of Programming Using C BPOPS103

Source Code

#include<stdio.h>
#include<math.h>
void main()
{
float a, b, c, disc, re, img, x1, x2;
printf("Enter thevalues for a,b,c\n");
scanf("%f%f%f", &a, &b, &c);
if((a==0)&&(b==0))
{
printf(“Roots cannot be determined\n”);
}
else if(a==0)
{
printf(“Linear Equation\n”);
x1=-c/b;
printf(“Root1=%.3f\n”,x1);
}
else
{
disc=b*b-(4*a*c);
if(disc==0)
{
x1=x2=-b/(2*a);
printf("Roots are equal\n");
printf("x1=%f\n x2=%f",x1,x2);
}
else if(disc>0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("Roots are real and distinct\n");
printf("x1=%f \nx2=%f",x1,x2);
}
else
{
re=-b/(2*a);
img = sqrt(fabs(disc))/(2*a);
printf("Roots are imaginary\n");
printf("x1 =%f+%fi\n",re,img);
printf("x2=%f-%fi\n",re,img);
}
}
}

Department of CS&E, BIT 18


Principles of Programming Using C BPOPS103

Sample Output:

Note: Use “-lm” option for compiling if “math.h” library has been included

1. Enter the values for a,b,c


121
Roots are equal
x1=-1.000000
x2=-1.000000
2. Enter the values for a,b,c
154
Roots are real and distinct
x1=-1.000000
x2=-4.000000

Department of CS&E, BIT 19


Principles of Programming Using C BPOPS103

Program 3
Find the Armstrong Number between 1 to 1000.

Algorithm: To generate the Armstrong number between 1 to 1000.

Step 1: Start
Step 2: [Declare the variables of type int] I, sum, num, count
Step 3: for i  1 to 1000
count ← log10(i) + 1
num ← i
sum ← 0
loop till num != 0
sum ← (num%10) ^ count
num ← num / 10
if sum ← i
print i
end if
count ← 0
Step 4: Stop

Source code

#include<math.h>
#include<stdio.h>
void main()
{
int i, sum, num, count = 0;
printf("Armstrong number between 1 and 1000 are:\n");

// This loop will run for 1 to 1000


for (i = 1; i <= 1000; i++) {
count = log10(i)+1;
num = i;
sum =0;
while(num!=0)
{
sum += pow(num%10, count);
num = num /= 10;
}

// Check for Armstrong Number


if (sum == i) {
printf("%d \n", i);
}
count = 0;
}

Department of CS&E, BIT 20


Principles of Programming Using C BPOPS103

Sample Output:

Armstrong number between 1 and 1000 are:


1
2
3
4
5
6
7
8
9
153
370
371
407

Department of CS&E, BIT 21


Principles of Programming Using C BPOPS103

Program 4:
Display the pascal triangle by reading the numbers of rows as input,
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
-----------------------------------------------------------------------------
nth row

Algorithm: To display the pattern for n number of rows

Step 1: Start
Step 2: [Input the number of rows to display]
Read n
Step 3: for i  0 to n
for j  1 to n-1
print “ “
for j  1 to i
print ”j”
for j  i-1 to 1
print ”j”
Start 4: Stop

Source code

#include <stdio.h>
void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
/* print blank spaces */
for(j=1;j<=n-i;j++)
printf(" ");
/* Display number in ascending order upto middle*/
for(j=1;j<=i;j++)
printf("%d",j);
/* Display number in reverse order after middle */
for(j=i-1;j>=1;j--)
printf("%d",j);
printf("\n");
}
}

Department of CS&E, BIT 22


Principles of Programming Using C BPOPS103

Sample Output:

1. Input number of rows : 4


1
121
12321
1234321
2. Input number of rows : 5
1
121
12321
1234321
123454321

Department of CS&E, BIT 23


Principles of Programming Using C BPOPS103

Program 5:
Implement Binary Search on Integers .
Algorithm: To search a key element using Binary search

Step 1: Start
Step 2: Initialize found  0
Step 3: [Input the number of elements]
read n
Step 4: [ Input the array items]
for i  0 to n-1
read a[i]
end for
Step 5: [Input the key]
read key
Step 6: [Initialize low to zero and high to last element]
Low  0
Highn-1
Step 7: [Calculate mid element and compare with key]
while(low<=high && !found)
mid  (low+high)/2
if a[mid] = key then
found  1
goto step 7
else if a[mid]<key then
lowmid+1
else
highmid-1
end if
end while
Step 8: [Print a message for successful or not successful]
if found ==1 then
print “search successful, print in mid+1 location”
else
print “search unsuccessful key not present in the list”
endif
Step 9: Stop

Department of CS&E, BIT 24


Principles of Programming Using C BPOPS103

Source Code:

#include<stdio.h>
#include<string.h>
void main()
{
int a[10], key, n, i, low, high, mid, found=0;
printf(“Enter the number of elements to read, n=”);
scanf(“%d”,&n);
printf(“Enter the elements in ascending order\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the key to search\n”);
scanf(“%d”,&key);
low=0;
high=n-1;
while(low<=high&&!found)
{
mid=(low+high)/2;
if(a[mid]==key)
found=1;
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
if(found==1)
printf(“Key found in position:%d”,mid+1);
else
printf(“Key not found”);
}

Sample Output:

Enter the number of elements to read, n=5


Enter the elements in ascending order
2
4
5
6
7
Enter the key to search
4
Key found in position:2

Department of CS&E, BIT 25


Principles of Programming Using C BPOPS103

Program 6
Implement Matrix multiplication and validate the rules of multiplication.
Algorithm: To compute product of two matrices

Step 1: Start
Step 2: [input order of matrix A]
read m, n
Step 3: [input order of matrix B]
read p, q
Step 4: [check for compatibility]
if(n!=p)
print “multiplication not possible”
go to step 11
end if
Step 5: [input elements of matrix A]
for i0 to m-1
for j0 to n-1
read a[i][j]
end for
end for
Step 6: [input elements of matrix B]
for i0 to p-1
for j0 to q-1
read b[i][j]
end for
end for
Step 7: [find product of 2 matrices]
for i0 to m-1
for j0 to q-1
c[i][j]0;
for k0 to n-1
c[i][j]c[i][j]+a[i][k]*b[k][j]

end for
end for
end for
Step 8: [print matrix A]
for i0 to m-1
for j0 to n-1
print a[i][j]
end for
end for
Step 9: [print matrix B]
for i0 to p-1
for j0 to q-1
print b[i][j]
Department of CS&E, BIT 26
Principles of Programming Using C BPOPS103

end for
end for
Step 10: [print resultant matrix C]
for i0 to m-1
for j0 to q-1
print c[i][j]
end for
end for
Step 11: Stop

Source code:

#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf("Enter the order of matrix A\n");
scanf("%d %d",&m,&n);
printf("Enter the order of matrix B\n");
scanf("%d %d",&p,&q);
if(n!=p)
{
printf("Matrix multiplication not possible\n");
}
else
{
printf(“enter the values for matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the values for matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
Department of CS&E, BIT 27
Principles of Programming Using C BPOPS103

c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(“the elements of matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("The elements of matrix B\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix C\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
}

Sample Output:

1. Enter the order of matrix A


23
Enter the order of matrix B
23
Matrix multiplication not possible

Department of CS&E, BIT 28


Principles of Programming Using C BPOPS103

2. Enter the order of matrix A


23
Enter the order of matrix B
34
enter the values for matrix A
1
2
3
4
5
6
Enter the values for matrix B
2
3
4
5
1
6
2
7
8
2
3
5
the elements of matrix A
1 2 3
4 5 6
The elements of matrix B
2 3 4 5
1 6 2 7
The resultant matrix C
28 21 17 34
61 54 44 85

Department of CS&E, BIT 29


Principles of Programming Using C BPOPS103

Program 7
Compute sin(x)/cos(x) using Taylor series approximation. Compare your result
with the built-in library function. Print both the results with appropriate
inferences.
Algorithm: To compute sin(x) using Taylor series

Step 1: Start
Step 2: Input value of degree; Read degree
Step 3: [Convert degree to radians]
x=(degree *PI)/180
Step 4: [Initialise]
term =x
sum=term
Step 5: [Calcuate each term and add]
term=-term*x*x/((i-1)*i);
sum=sum+term;
Step 6: [Print the output]
Print the sine value for the given degree
Step 7: Stop

Source code:

#include<stdio.h>
#include<math.h>
void main()
{
int degree,i=2;
double x,nume,denom,sum=0,term;
printf("Enter the value of degree\n");
scanf("%d",&degree);
x=(degree*3.142)/180;
nume=x;
denom=1;
do
{
term=nume/denom;
nume=- nume*x*x;
denom=denom*i*(i+1);
sum=sum+term;
i=i+2;
}
while(fabs(term)>0.00001);
printf("without using library functions in(%d)=%lf",degree,sum);
printf("\nUsing the library functions in(%d)=%lf",degree,sin(x));
}

Department of CS&E, BIT 30


Principles of Programming Using C BPOPS103

Sample Output:

1. Enter the value of degree


90
without using library functions in(90)=1.000000
Using the library functions in(90)=1.000000
2. Enter the value of degree
45
without using library functions in(45)=0.707179
Using the library functions in(45)=0.707179

Department of CS&E, BIT 31


Principles of Programming Using C BPOPS103

Program 8
Sort the given set of N numbers using Bubble sort.
Algorithm: To sort N integer numbers using Bubble sort

Step 1: Start
Step 2: [Input the number of elements]
read n
Step 3: [Input unsorted elements in array]
for i0 to n-1
read a[i]
Step 4: [Output the original elements]
for i0 to n-1
print a[i]
Step 5: [Sort the elements in ascending order]
for i 0 to n-1
for j0 to n-i
if a[j] > a[j+1] then
temp a[j]
a[j]  a[j+1]
a[j+1] temp
end if
end for
end for
Step 6: [Output the sorted elements]
for i0 to n-1
print a[i]
Step 7: Stop

Department of CS&E, BIT 32


Principles of Programming Using C BPOPS103

Source code:

#include<stdio.h>
void main()
{
int a[10],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The original elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nThe sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

Sample Output:

Enter the number of elements


5
Enter the values
3
1
7
2
5
The original elements are
3 1 7 2 5
The sorted elements are
1 2 3 5 7

Department of CS&E, BIT 33


Principles of Programming Using C BPOPS103

Program 9
Write functions to implement string operations such as compare, concatenate and
string length. Use the parameter passing parameters.
Algorithm: To implement the string operations

Step 1: Start
Step 2: [Store two strings in Str1 and Str2]
Str1=String1 and Str2=String2
Step 3: [To find String Length]
initialize i to 0
while(str[i] not equal to 0)
increment i by 1
Step 4: [To Compare two Strings]
initialize i to 0
while (str1[i] is equal to str2[i])
if (str1[i] is equal to null)
break;
increment i by 1
return str1[i]-str2[i];
Step 5: [To Concatenate two Strings]
initialize i to 0 and j to 0
while (str1[i] not equal to null)
increment i by 1
while (str2[j] not equal to null)
str1[i++]=str2[j++];
Step 6: [Output the results]
The length of the String
res1=Comparison of two Strings
res2= Concatenated String
Step 7: stop

Department of CS&E, BIT 34


Principles of Programming Using C BPOPS103

Source Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void stringcompare(char s1[ ],char s2 [])
{
int l1=0,l2=0,i,p=0;
l1=strlen(s1);
l2=strlen(s2);
if(l1!=l2)
{
p=1;
}
else
{
for(i=0;s1[i]!='\0';i++)
{
if(s1[i]!=s2[i])
p=1;
}
}
if(p==1)
printf("strings are different\n");
else
printf("Strings are same\n");
}

void stringlength(char s[])


{
int i;
for(i=0;s[i]!='\0';i++)
{
}
printf("Length of the string is %d\n",i);
}

void stringconcatinate(char s1[ ],char s2[ ])


{
int i,j; for(i=0;s1[i]!='\0';i++)
{
}
for(j=0;s2[j]!='\0';j++)
{
s1[i]=s2[j];
i++;
}
Department of CS&E, BIT 35
Principles of Programming Using C BPOPS103

s1[i]='\0';
printf("Concatenated string is : ");
printf("%s\n",s1);
}

void main()
{
char s1[50],s2[50];
int choice;
printf("Enter a string\n");
scanf("%s",&s1);
printf("Enter another string\n");
scanf("%s",&s2);
printf("Enter\n1 for comparing,\n2 for length,\n3 for concatenation\n");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("Strings compared\n");
stringcompare(s1,s2);
break;
case 2 : printf("Strings length\n");
printf("For first string\n");
stringlength(s1);
printf("For second string\n");
stringlength(s2);
break;
case 3 : printf("String concatenation\n");
stringconcatinate(s1,s2);
break;
default:printf("Invalid input\n");
}
}

Sample Output:

1. Enter a string
hello
Enter another string
world
Enter
1 for comparing,
2 for length,
3 for concatenation
2
Strings length
For first string
Length of the string is 5
Department of CS&E, BIT 36
Principles of Programming Using C BPOPS103

For second string


Length of the string is 5
2. Enter a string
pop
Enter another string
pop
Enter
1 for comparing,
2 for length,
3 for concatenation
1
Strings compared
Strings are same
3. Enter a string
POPC
Enter another string
Laboratory
Enter
1 for comparing,
2 for length,
3 for concatenation
3
String concatenation
Concatenated string is : POPCLaboratory

Department of CS&E, BIT 37


Principles of Programming Using C BPOPS103

Program 10
Implement structures to read, write and compute average- marks and the students
scoring above and below the average marks for a class of N students.
Algorithm: To read, write and compute average- marks and the students scoring above and below the
average marks for a class of N students using structures

Step 1: Start
Step 2: [input number of students]
Read n
Step 3: [input details of students ie.name and marks]
Read name,m1,m2,m3
Step 4: [ Calculate total and average]
fori=0 to n
s[i].total=(s[i].m1+s[i].m2+s[i].m3);
T=T+s[i].total;
AVG=T/N;
Step 5: [Find students above and below average]
for i0 to n
Above avg[j]=i;
j++;
else
below avg[k]=i;
k++;
Step 6: Stop

Department of CS&E, BIT 38


Principles of Programming Using C BPOPS103

Source Code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
char usn[10],name[20];
int marks;
};

void main()
{
struct student s[100];
int n,i;
float sum=0.0,avg;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the student %d details\n",i);
printf("Enter USN:");
scanf("%s",&s[i].usn);
printf("Enter Name:");
scanf("%s",&s[i].name);
printf("Enter marks:");
scanf("%d",&s[i].marks);
sum=sum+s[i].marks;
}
avg=sum/n;
printf("Class Average is %f\n",avg);
printf("Details of students scoring above class average\n");
printf("USN\tName\tMarks\n");
for(i=1;i<=n;i++)
{
if(s[i].marks>avg)
printf("%s\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
printf("Details of students scoring below class average\n");
printf("USN\t Name\t Marks\n");
for(i=1;i<=n;i++)
{
if(s[i].marks<avg)
printf("%s\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
}

Department of CS&E, BIT 39


Principles of Programming Using C BPOPS103

Sample Output:

Enter the number of students


5
Enter the student 1 details
Enter USN: 01
Enter Name: Rakshith
Enter marks: 20
Enter the student 2 details
Enter USN: 02
Enter Name: Monika
Enter marks: 24
Enter the student 3 details
Enter USN: 03
Enter Name: Harika
Enter marks: 18
Enter the student 4 details
Enter USN: 04
Enter Name: Apoorva
Enter marks: 21
Enter the student 5 details
Enter USN: 05
Enter Name: Kiran
Enter marks: 23
Class Average is 21.200001
Details of students scoring above class average
USN Name Marks
02 Monika 24
05 Kiran 23
Details of students scoring below class average
USN Name Marks
01 Rakshith 20
03 Harika 18
04 Apoorva 21

Department of CS&E, BIT 40


Principles of Programming Using C BPOPS103

Program 11
Compute the sum, mean and standard deviation of all elements stored in an array
of N real numbers using pointers.
Algorithm: To find sum, mean and standard deviation for ‘n’ number of elements

Step 1: Start
Step 2: [Input the no. of elements]
Read n
Step 3: [Input the ‘n’ number of elements]
for i0 to n-1
read a[i]
end for
Step 4: [Assign the array elements to pointer ‘ptr’]
Ptra
Step 5: [Calculate sum]
for i0 to n-1
sumsum+ptr[i]
end for
Step 6: [Calculate mean]
Meansum/n
Step 7: [Calculate sumstd]
for i0 to n-1
sumstdsumstd + pow((pow(ptr[i]-mean),2)
end for
Step 8: [Calculate standard deviation std]
Stdsqrt(sumstd/n)
Step 9: [Output sum,mean and standard deviation]
print sum,mean,std
Step 10: Stop

Department of CS&E, BIT 41


Principles of Programming Using C BPOPS103

Source Code

#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr, mean, std,sum=0,sumstd=0;
int i,n;
printf("enter the no of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ptr[i];
}
mean=sum/n;
for(i=0;i<n;i++)
{
sumstd=sumstd+pow((ptr[i]-mean),2);
}
std=sqrt(sumstd/n);
printf("sum=%.3f\n",sum);
printf("mean=%.3f\n",mean);
printf("standard deviation=%.3f\n",std);
}

Sample Output:

enter the no of elements


5
enter the array elements
2
4
7
9
5
sum=27.000
mean=5.400
standard deviation=2.417

Department of CS&E, BIT 42


Principles of Programming Using C BPOPS103

Program 12
Copy a text file to another file, read both the input file name and target file name.
Algorithm: To copy a text from one file to another

Step 1: Start
Step 2: enter the file to open for read
Read file1
Step 3: fopen file1 for reading
Step 4: if fptr1==null
Print “cannot open the file”
Step 5: enter the file to open for writing
Read file2
Step 6: fopen file2 for writing
Step 7: if fptr2==null
Print “cannot open the file”
Step 8: while fptr1 != EOF
fputc(c to ptr2)
c = fgetc(ptr1)
Step 9: print “content copied”
Step 10: fclose fptr1;
fclose fptr2;
Step 11: Stop

Department of CS&E, BIT 43


Principles of Programming Using C BPOPS103

Source Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1);
while (c!= EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename); fclose(fptr1);
fclose(fptr2);
return 0;
}

Sample Output:

File to be read: “read_file.txt”

Department of CS&E, BIT 44


Principles of Programming Using C BPOPS103

Enter the filename to open for reading


read_file.txt
Enter the filename to open for writing
write_file.txt

Contents copied to write_file.txt

File to which contents are written: “write_file.txt”

Department of CS&E, BIT 45

You might also like