0% found this document useful (0 votes)
41 views162 pages

PPS Lab Manual 2022-23 Document

Uploaded by

lohithvarma12
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)
41 views162 pages

PPS Lab Manual 2022-23 Document

Uploaded by

lohithvarma12
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/ 162

PROGRAMMING FOR

PROBLEM SOLVING LAB


I B.Tech. - Common to all Branches

Prepared by

MAnanthaLakshmi D Sowmya
Assistant Professor Assistant Professor

A N V K Swaroopa P V V Eswara Rao


Assistant Professor Assistant Professor

Academic Year 2022-23

Department of Computer Science & Engineering


SASI INSTITUTE OF TECHNOLOGY & ENGINEERING
Tadepalligudem – 534101 West Godavari Dist, AP, INDIA

SASI PUBLISHING HOUSE


Preface

Programming for Problem Solving Lab deals with developing programs


for Problem solving methods. With this knowledge, the students will acquire the
necessary skills for applying and practicing logical ability to solve the problems
and developing several applications.

From this laboratory manual, the student learns practical aspects of


problem solving. It includes 12 laboratory experiments which can be
implemented in Unix/Linux Operating System, C Programming Language.

--Authors
ACKNOWLEDGEMENT

The Preparation and designing of the Lab Manual has been done by the
contribution of the entire Sasi Institute of Technology and Engineering group. In this
regard the authors express a special thanks to the following people.

We pay obeisance to the dynamic Chairman of Sasi Educational Society, Sri.


Burugupalli Venu Gopala Krishna, for his inspiring presence, which has always been
the principle driving force behind all our endeavors.

First, we would like to thank Mr. M Narendra Krishna, Vice- Chairman, Sasi
Institute of Technology and Engineering, for his everlasting support.

We would like to thank Dr Mohammed Ismail, Principal, Sasi Institute of


Technology and Engineering for his support.

We would also like to thank Dr.M.V.S.S.Nagendranadh, Prof, HOD, Department


of Computer Science & Engineering for providing us with valuable feedback on our
work, which allowed us to constantly improve.

We would also like to thank Dr.K.Subash Bhaghavan, Assoc. Prof, HOD,


Department of Information Technology for providing us with valuable feedback on
our work, which allowed us to constantly improve.

We would also like to thank Dr.P.Kiran Kumar, Prof, HOD, Department of


Computer Science & Technology for providing us with valuable feedback on our
work, which allowed us to constantly improve.

Finally, the authors also thankful to all the Teaching and Non- teaching faculty
of Computer Science and Engineering & Information Technology departments and
Library Staff for providing the resource materials and support to carry out this
manual.

Above all, we would like to thank our parents and other family members for
their constant support and encouragement. Nothing would have been possible without
their blessings and support.
OBJECTIVES:

➢ To apply programming for basic mathematical functions


➢ To design and program mathematical concepts.
➢ To create and use the functions and library functions
➢ Able to apply the theoretical knowledge of formatting of documents
➢ To create and apply user defined types to the real-world problems.
➢ To create files and shapes of the concepts.

RECOMMENDED SYSTEMS/SOFTWARE REQUIREMENTS:

➢ Desktop PC with P-III or above, minimum of 166MHZ or faster


processor with at least
➢ 64MB RAM and 100MB free disk space.
➢ Linux with gcc compiler
INSTRUCTIONS TO THE STUDENTS:

The objective of the laboratory is on-hand experience and learning. The


programs are designed to illustrate phenomena in different concepts of
PROGRAMMING FOR PROBLEM SOLVING LAB. Perform the programs
with interest and an attitude of learning which lay the path to business
applications.
1. Each lab session the student must bring the Observation, Notes,
Record.
2. The students should come to the lab with a prior preparation to complete
the Programs within time.
3. The lab attendance will play a part of the internal assessment of marks.
4. The programs must execute first and write it in the observation book. The
student should get acknowledged the on the same day by the concerned
teacher. Later the programs should be recorded in the record and submit
to the concerned teacher by next lab.
5. Any student failing to complete the programs to be evaluated in the same
laboratory class will lose the Internal Assessment Marks for those
programs.
6. The student shall be responsible for the system issued and take necessary
safety measures in using it.
7. At the time of Mid Exams & End Examinations of the semester, Lab
exams will be conducted.
8. A strict discipline should be maintained inside the laboratory.
9. Do not sit idle, if system is not working. Report immediately to the Lab
Instructor.
10.Shut down the system properly, turn-off the monitor, arrange the chair
properly and then leave.
PROGRAMMING FOR PROBLEM SOLVING LAB

LIST OF EXPERIMENTS:

Exercise 1 (Familiarization with programming environment)


a) Familiarization of CODE BLOCKS C++ Editor to edit, compile, execute, test and
debugging C programs.
b) Familiarization of RAPTOR Tool to draw flow charts and understand flow of control.
c) Acquaintance with basic LINUX commands.

Exercise 2 (Simple computational problems using arithmetic expressions)


a) Write a C Program to display real number with 2 decimal places.
b) Write a C Program to convert Celsius to Fahrenheit and vice versa.
c) Write a C Program to calculate the area of triangle using the formula
area = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐) where 𝑠 = 𝑎+𝑏+𝑐
2
d) Write a C program to find the largest of three numbers using ternary operator.
e) Write a C Program to swap two numbers without using a temporary variable.

Exercise 3 (Problems involving if-then-else structures)


a) Write a C Program to check whether a given number is even or odd using bitwise
operator, shift operator and arithmetic operator.
b) Write a C program to find the roots of a quadratic equation.
c) Write a C Program to display grade based on 6 subject marks using if…else…if
ladder.
d) Write a C program, which takes two integer operands and one operator form the user,
performs the operation, and then prints the result using switch control statement.
(Consider the operators +, -, *, /, %)

Exercise 4 (Iterative problems)


a) Write a C Program to count number of 0’s and 1’s in a binary representation of a
given number.
b) Write a C program to generate all the prime numbers between two numbers supplied
by the user.
c) Write a C Program to print the multiplication table corresponding to number supplied
as input.
Exercise 5 (Iterative problems)
a) Write a C Program to Find Whether the Given Number is
i) Armstrong Number ii) Palindrome Number
b) Write a C Program to print sum of digits of a given number

Exercise 6 (Series examples)


a) Write a C Program to calculate sum of following series
b) 1+2+3+…. n b)1+1/2+1/3+……+1/n c)1+x+x2+x3……+xn

Exercise 7 (1D Array manipulation)


a) Write a C program to interchange the largest and smallest numbers in the array.
b) Write a C program to search an element in an array (linear search).
c) Write a C Program to print the following pattern using a character array
S
SA
SAS
SASI

Exercise 8 (Matrix problems, String operations)


a) Write a C program to add two matrices.
b) Write a C program to multiply two matrices if they are compatible or print an error
message “incompatible matrix sizes” otherwise.
c) Write a C program to check given matrix is symmetric or not.
d) Implement the following string operations with and without library functions.
i) copy ii) concatenate iii) length iv) compare

Exercise 9 (Simple functions)


a) Write a C Program demonstrating the following function types
i. With arguments and with return value.
ii. With arguments and without return value
iii. Without arguments and without return value.
iv. Without arguments and with return value.
b) Write a C Program illustrating call by reference

Exercise 10 (Recursive functions)


Write a C Program illustrating the following with Recursion without Recursion
a) Factorial b) GCD c) Power d) Fibonacci

Exercise 11(Pointers and structures)


a) Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc () function.
b) Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using calloc () function.
Note: Understand the difference between the above two programs.
c) Write a C Program to read and print student details using structures.

Exercise 12 (File operations)


a) Write a C program to open a file and to print it contents on screen.
b) Write a C program to copy files
c) Write a C program merges two files onto a new file.
d) Write a C program to delete a file.

Textbooks:
1. Computer Programing ANSI C, E Balagurusamy, Mc Graw Hill Education
(Private),Limited (TB1)
2. Programming in C, ReemaThareja, Second Edition, Oxford Higher Education (TB2)

Reference Books:
1. Computer Basics and C Programming, V Raja Raman, Second Edition, PHI (RB1)

Course Outcomes:
1) Attain knowledge on using CODE BLOCKS and RAPTOR tools in solving
problems.
2) Examine and analyze alternative solutions to a problem.
3) Design an algorithmic solution to a problem using problem decomposition and step-
wise refinement.
4) Demonstrate conversion of iterative functions to recursive and vice-versa.
5) Implement the concepts of arrays, structures, Unions and files.

COs VS POs MAPPING (DETAILED; HIGH: 3; MEDIUM: 2; LOW:1):


PO PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO
CO 1 2 3 4 5 6 7 8 9 10 11 12 1 2
1 3 3 3 3
2 2 3 3 2
3 2 3 3 2
4 2 3 3 2
5 2 3 3 2
Overall
Course 11 15 15 11

*****
Index

Academic year 2022-23

SI. Date of Signature


Name of the Program Pg. No Marks
No. Completion of faculty
SI. Date of Signature
Name of the Program Pg. No Marks
No. Completion of faculty

*****
Programming for Problem Solving Lab

Exercise 1 (Familiarization with programming environment)


a) Familiarization of CODE BLOCKS C++ Editor to edit, compile, execute, test and
debugging C programs.
b) Familiarization of RAPTOR Tool to draw flow charts and understand flow of control.
c) Introduction to basic LINUX commands.

1a) Familiarization of CODE BLOCKS C++ Editor to edit, compile, execute, test and
debugging C programs

Code Blocks for C Programming

How to Install and Get Started


Code Blocks is an open-source, cross-platform (Windows, Linux, MacOS), and free C/C++ IDE.
It supports many compilers, such as GNU GCC (MinGW and Cygwin) and MS Visual C++. It
supports interactive debugging (via GNU GDB or MS CDB). CodeBlocks.The official website
of CodeBlocks is www.codeblocks.org.

How to Install CodeBlocks

Step 1: Download
Goto http://www.codeblocks.org/downloads. Click "Download the binary release". Select your
operating platform (e.g., Windows XP/Vista/7/8/10). Download the installer with GCC
Compiler, e.g., codeblocks-13.12mingw-setup.exe (which includes MinGW's GNU GCC
compiler and GNU GDB debugger).

Step 2: Install
Run the downloaded installer. Accept the default options.
Verify the Compiler's and Debugger's Path: (For CodeBlocks for Windows) Goto "Settings"
menu ⇒ "Compiler..." ⇒ In "Selected Compiler", choose "GNU GCC Compiler" ⇒ Select tab
"Toolchain Executables" ⇒ Check the "Compiler's Installation Directory". It shall be set to the
"MinGW" sub-directory of the CodeBlocks installation directory, for example, suppose that
CodeBlocks is installed in "C:\Program Files\codeblocks", set it to "C:\Program
Files\codeblocks\MinGW".
Similarly, check the debugger's path. Goto "Settings" menu ⇒ "Debugger..." ⇒ Expand
"GDB/CDB debugger" ⇒ Select "Default" ⇒ In "Executable path", provide the full-path name
of "gdb.exe", for example, "C:\Program Files\codeblocks\MinGW\bin\gdb.exe".

Writing C/C++ Programs in CodeBlocks

Writing Programs (under Project)


Other than the few-line toy programs, you shall create a project for each of your application. A
project contains related files such as source codes, header files, and relevant resources. Also,

Sasi Institute of Technology & Engineering{A} Page 1


Programming for Problem Solving Lab

under CodeBlocks, you can only debug your program under a project - single-file program (in
previous section) debugging is not supported.

1. File ⇒ New ⇒ Project... ⇒ Console Application ⇒ Go.

2. The "Console Application" wizard appears:


a. Next

b. Select "C" ⇒ Next.

Sasi Institute of Technology & Engineering{A} Page 2


Programming for Problem Solving Lab

c. In "Project Title", enter "MyfirstProgram". In "Folder to create project in", set to your working
directory, accept the default for the rest ⇒ Next.

A project directory " MyfirstProgram " will be created under filepath, with a project
configuration filename of " MyfirstProgram.cbp". You could later create more projects under this
working directory

d. In "Compiler" field, accept the defaults of "GNU GCC Compiler" ⇒ Finish.

Sasi Institute of Technology & Engineering{A} Page 3


Programming for Problem Solving Lab

3. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node
" MyfirstProgram " ⇒ Expand "Source" node ⇒ Double-click "main.c", which is a template
program to say "Hello, world!".

4. To build the program, select "Build" menu ⇒ Build.


5. To run the program, select "Build" menu ⇒ Run.
6. To create more source file or header file under the project:
File ⇒ New File... ⇒ Select C/C++ source or C/C++ header.
a. C ⇒ Next.
b. In "Filename with full path" ⇒ click the "Navigate" (...) button to navigate to the project
directory and enter the new file name. Check either the “Debug” and “Release” boxes (or “All")
⇒ Finish.

Sasi Institute of Technology & Engineering{A} Page 4


Programming for Problem Solving Lab

Set Active Project


You can create more projects. However, the "Build" and "Run" commands are always apply to
the active project, which is shown in bold. To activate a project: right-click on the project name
⇒ "Activate Project".
Open an Existing Project
To open an existing project, either:
1. From "File" menu ⇒ "Recent Projects" ⇒ Choose the desired project; or
2. From "File" menu ⇒ "Open..." ⇒ Navigate to your project directory ⇒ Choose
"ProjectName.cbp", where ".cbp" stands for CodeBlocks-Project.
Read "CodeBlocks' Common Errors" if ....

Writing Many C Programs under ONE Project


Although a project may contain many source files, there can only be one main() function among
all the source files. That is, you cannot keep two toy programs (each having a main() function) in
one project (you will get the error "multiple definition of 'main'" when you try to build the
project). You need to create one project for each toy program. This is clumsy!
Codeblock, nonetheless, allow you to add files or remove files from a project. The removed files
are not deleted and remain in the folder. We could use this feature to write many toy programs
under one project. The procedures are as follows:
1. Create a C/C++ project called "ToyProgramProject" (read previous section on how to create a
project). You shall get a "main.c" automatically.
2. Write your C program on "main.c". Build and run the program.
3. To write another program: select "File" ⇒ "Save File as" ⇒ enter a program name such as
"myfirst.c". Remove it from the project (because each project can only have one file with
main()), by right-click on "myfirst.cpp" ⇒ "remove file from project".
4. Continue to write your second C program on "main.c". Build and run.
5. Repeat Step 3 and 4 for another toy program.
6. Suppose that you wish to run "myfirst.cpp" again: First remove "main.cpp" from the project.
Right-click on the project ⇒ Add File ⇒ Choose "myfirst.c" ⇒ Open ⇒ Check both the
"Debug" and "Release" box ⇒ OK. You can now build and run the "myfirst.c".
In brief, use the "Add File" and "Remove File" to place your desired C program file (with the
main() function) under the active project. You can then "Build" the project and "Run" your
program.

CodeBlocks Common Errors


Cannot Compile any C/C++ Program after Installing CodeBlocks
Check:
1. You downloaded the CodeBlocks with "MinGW GNU C/C++ Compiler" (e.g., "codeblocks-
10.05mingw-setup.exe").
2. Goto "Settings" menu ⇒ "Compiler .." ⇒ Select tab "Toolchain Executables" ⇒ Check the
"Compiler's Installation Directory". It shall be set to the "MinGW" sub-directory of the
CodeBlocks installation directory, e.g., "c:\Program Files\codeblocks\MinGW" suppose that
CodeBlocks is installed in "c:\Program Files\codeblocks".
Sasi Institute of Technology & Engineering{A} Page 5
Programming for Problem Solving Lab

3. Cannot Build or Run Program - Build/Run Buttons and Menu-Items are Grey and Not
Selectable -A previous program is still running. You need to terminate the program by closing
the output console window.
4. Error: undefined reference to `WinMain@16'
Check that you have a main() function in your function. Check your spelling of main!
5.(For C Programs) System Error: "xxx.exe has stopped working"
Check your scanf() function. You probably omitted the '&' before the variable name.
Debugging C/C++ Program in CodeBlocks
Able to use a graphics debugger to debug program is crucial in programming. It could save you
countless of hours guessing on what went wrong.
Write a C Program
Follow the steps in "Writing C Program (with Project)" to write the following C program, to be
used for the debugging practice. This program computes and prints the factorial of n
(=1*2*3*...*n). The program, however, has a logical error and produce a wrong answer for
n=20. (It outputs "The Factorial of 20 is -2102132736" - a negative number?!).
/*
* Compute the factorial of n, with n=20.
* n! = 1*2*3*...*n
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 20; // To compute factorial of n
int factorial = 1; // Initialize the product to 1
int i = 1;
while (i <= n) {
factorial = factorial * i;
i++;
}
printf("The Factorial of %d is %d",n,factorial);
return 0;
}
Run the program and observe the output produced:
The Factorial of 20 is -2102132736
Let's use the graphic debugger to debug the program.
Step 1: Set an Initial Breakpoint

Sasi Institute of Technology & Engineering{A} Page 6


Programming for Problem Solving Lab

Set an initial breakpoint at main() function by clicking on the "left-margin" (right-side of the line
number) of the line containing main(). A red circle appears indicating a breakpoint has been set at
that line. A breakpoint suspends program execution for you to examine the internal states.
Step 2: Start Debugging

From "Debug" menu, select "Start (F8)". The program begins execution but suspends its execution
at the breakpoint, i.e., main(). An yellow arrow (as shown in the diagram) appears and points at
the main(), indicating this is the next statement to be executed.
Step 3: Single-Step and Watch the Variables and Outputs

Click the "Debugging Windows" button on the "Debug" toolbar and select "Watches" to enable the
"Watch" pane. (You could also do it from the "Debug" menu.)
Click the "Next line" button on the "Debug" toolbar to single-step thru your program. At each of the
step, you could examine the internal state of your program, such as the value of the variables (in the
"Watches" pane), the outputs produced by your program (in the console), etc.
Single-stepping thru the program and watching the values of the variables and the outputs produced
is the ultimate mean in debugging programs - because it is exactly how the computer runs your
program!

Sasi Institute of Technology & Engineering{A} Page 7


Programming for Problem Solving Lab

Step 4: Breakpoint, Run-To-Cursor, Continue and Stop


As mentioned, a breakpoint suspends program execution and let you examine the internal states of the
program. To set a breakpoint on a particular line, click the left-margin of that line (or select "Toggle
Breakpoint (F5)" from "Debug" menu).
The "Continue" resumes the program execution, up to the next breakpoint, or till the end of the
program.
Single stepping thru a loop with a large count is time-consuming. You could set a breakpoint at the
statement immediately outside the loop (e.g., Line 12 of the above program), and issue "Continue" to
complete the loop.
Alternatively, you can place the cursor on a particular line, right-click and select "Run-To-Cursor" to
resume execution up to this line.
The "Stop" ends the debugging session. Always terminate your current debugging session using
"Stop" or "Continue" till the end of the program.
Problem in the above program is factorial an integer value cannot store a huge value i.e 20!.so by
changing factorial variable to a highest variable will give exact result
Step-Into and Step-Out: To debug a function, you need to use "Step-Into" to step into the
first statement of the function. ("Step-Over" runs the function in a single step without stepping
through the statements inside the function.) You could use "Step-Out" to return to the caller,
anywhere within the function. Alternatively, you can set a breakpoint inside a function.
Watching a Variable: To add a variable into the "Watches" panel, goto "Debug" ⇒ "Edit Watch..."
⇒ "Add" ⇒ Enter the variable name ⇒ You can select the format, or "watch as array".

Executing C Programs
Build (Compile and Link): Select "Build" menu ⇒ Build (Ctrl-F9).
Run: Select "Build" menu ⇒ Run (Ctrl-F10).
Writing Programs (without Creating a Project)
To write programs (such as few-line simple programming exercises):
File ⇒ New ⇒ Empty File.
Enter (copy and paste) the following codes:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello world!\n");
return 0;
}
Save the file as "Hello.c" in your project directory (e.g., "d:\project").either it can be added to
existing project or an individual file.
Build (Compile and Link): Select "Build" menu ⇒ Build (Ctrl-F9).
Run: Select "Build" menu ⇒ Run (Ctrl-F10).

Sasi Institute of Technology & Engineering{A} Page 8


Programming for Problem Solving Lab

b) Familiarization of RAPTOR Tool to draw flow charts and understand flow of control.

RAPTOR Tool – A Flowchart Interpreter

RAPTOR (Rapid Algorithmic Prototyping Tool for Ordered Reasoning) is a free graphical
authoring tool created by Martin C. Carlisle, Terry Wilson, Jeff Humphries and Jason Moore,
designed specifically to help students visualize their algorithms and avoid syntactic baggage.
Students can create flow-chart for a particular program and raptor tool will generate code for it in
various programming languages, such as C, C++, Java and so on.

Symbols in RAPTOR
Raptor has 6 types of symbols, each of which represents a unique kind of instruction. They are –
Assignment, Call, Input, Output, Selection and Loop symbols. The following image shows these
symbols

RAPTOR Program Structure


A RAPTOR program consists of connected symbols that represent actions to be executed.
The arrows that connect the symbols determine the order in which the actions are performed.
The execution of a RAPTOR program begins at the Start symbol and goes along the arrows
to execute the program. The program stops executing when the End symbol is reached.

Sasi Institute of Technology & Engineering{A} Page 9


Programming for Problem Solving Lab

Assignment
The assignment symbol is used to change the value of a variable. The right hand side of the
assignment is evaluated, and the resulting value is placed in the variable on the left hand side. For
example, consider the case where the value of x is currently 5, and the assignment "x <- x + 1" is
executed. First "x+1" is evaluated, yielding the result 6. Then the value of x is changed to be 6.
Note that assignment is very different from mathematical equality. The statement should be read
"Set x to x+1" instead of "x equals x+1". The assignment symbol can also be used to assign a string
expression to a string.

Call
The call symbol is used to invoke procedures such as graphics routines and other instructor-
provided procedures. The call symbol is also used to run subcharts included in a Raptor program..

Input
The input symbol is used to ask the user for a number or string while the flowchart is executing.
When an input symbol is executed, the user will be prompted with a dialog to enter a value that
can be interpreted as either a number or string, depending on what the user types . The user can
also override the source for input by specifying a text file to be used in place of the keyboard (see
Inputting from a File)

Output
The output symbol is used to either write a number or text to the Master Console window. The
user can also override the destination for output by specifying a text file to be used instead of the
Master Console
Selection
The selection structure is used for decision making. The programmer enters in the diamond an
expression that evaluates to Yes (True) or No (False). Such expressions are formally referred to as
Boolean expressions. Based on the result of the expression in the diamond, control of the program
will branch either left (Yes, or True) or right (No, or False). For more information, see Boolean
Expressions.
Sasi Institute of Technology & Engineering{A} Page 10
Programming for Problem Solving Lab

Loop Control
The loop structure is used to repeat a sequence of symbols until a certain condition is met. When
execution reaches the bottom of the loop, it starts over again at the top. The loop is exited when
the diamond symbol is executed and the Boolean expression in the diamond evaluates to yes
(True). Again, more information can be found in Boolean Expressions
Example:

Raptor workspace
The Workspace is where flowcharts are built and executed. Initially, each flowchart contains just
a Start and End block in a "main" tab. The programmer may add subcharts, and these subcharts
will initially contain just a Start and End block. The Start and End blocks may not be deleted from
any chart or subchart.

To construct a flowchart, click on one of the six symbols to the left of the Workspace and then
click (not drag) an insertion point somewhere in the existing flowchart.
An insertion point is indicated when the cursor changes to. The symbol is then added to the
existing flowchart in place. Alternatively, you can right click on an insertion point and insert a
symbol by selecting from the menu.
As the flowchart grows in size, scrollbars will appear that enable you to look at portions of the
flowchart that are off screen. You may also change the scale factor for the flowchart to view more
(or less) of the flowchart at one time.

Sasi Institute of Technology & Engineering{A} Page 11


Programming for Problem Solving Lab

Once symbols have been added, they may be edited in several ways. Right-clicking on a symbol
provides several editing options to the user:

Double-clicking a symbol allows the user to change what will happen when that symbol is
executed (i.e. change the assignment, procedure call, boolean expression, etc.)
Multiple symbols can be selected at one time by left-click dragging a selection box over several
symbols. The selected symbols are displayed in red. The selected symbols may then be edited
using the menu, toolbar, or pop-up menu.
When a program is executing, the Workspace window displays the currently executing instruction
in green.

Using the menu


The top-level menu contains seven choices:
File Edit Scale View Run Window Help
1. The File menu contains the following submenu:
a) New creates a new flowchart.
b) Open opens a previously saved flowchart from disk.
c) Save saves the current flowchart to disk.
d) Save As saves the current flowchart as a different name to disk.
e) Compile If compile is selected, then the user will be prompted for a filename to save the
compiled flowchart. A compiled flowchart cannot be viewed or edited, only run. The
compiled version of a program runs much faster than a graphical version, but it cannot be
executed symbol by symbol, it cannot be paused, and it doesn't display variables in the
watch window. If you ask to compile your flowchart, be sure you do not overwrite the
non-compiled version with the compiled version, because compilation cannot be undone.
f) Page Setup customizes the display for printing.
Sasi Institute of Technology & Engineering{A} Page 12
Programming for Problem Solving Lab

g) Print Preview displays a preview of how the flowchart will appear when printed.
h) Print prints the current flowchart.
i) Print to Clipboard saves a bitmap image of the current flowchart to the clipboard,
allowing easy pasting of the image into other applications.
j) Exit exits the program.
k) A history list of the last several flowchart files accessed is also displayed in the File
menu.
2. The Edit menu contains the following submenu:
a) Undo reverts the flowchart back before the last change was made.
b) Redo cancels the previous undo operation.
c) Comment allows the user to add a comment to a symbol.
d) Cut, Copy, and Delete all function as expected on any selected symbols (those currently
colored red)
e) Paste can be performed only after the user has specified an insertion point with a left
mouse click. Note that when the cursor is at an insertion point, the cursor will change to.
After the insertion point identification and selection of Edit-Paste, the symbol(s) earlier
copied or cut to the clipboard will be inserted.
f) Select All allows the user to select the entire program for copying, cutting, etc.
3. The Scale menu allows the user to change to scaling factor of the Workspace.
4. The View menu contains the following submenu:
a) All Text forces all text in each symbol to be displayed completely.
b) Truncated only displays the amount of text that will fit inside each symbol.
c) No text hides the text in each symbol.
d) Comments toggles the display of comments in the Workspace window.
e) Variables toggles the display of the watch window. For faster execution, turn off
variables and move the slider on the toolbar to the far right. For fastest execution, run a
compiled version of the program.
f) Expand all expands all loop and selection structures which had been collapsed.
g) Collapse all collapses all loop and selection structures to minimize the size of the chart.
5. The Run menu contains the following submenu:
a) Step executes through one shape in a flowchart. Pressing F10 will also execute the
current shape.
b) Execute to Completion runs the entire program until it terminates.
c) Reset halts program execution and clears the value of all variables.
d) Reset/Execute halts program execution, clears the value of all variables, and restarts
execution from the beginning.
e) Pause temporarily halts the execution of a program until execution is resumed by the
user.
f) Clear all Breakpoints removes all currently set breakpoints to allow the current program
to execute until it terminates.
6. The Window menu contains the following submenu:
a) Tile Vertical puts the Raptor Workspace Window and the Raptor Master Console
window side-by-side on the Windows desktop.
b) Tile Horizontal puts the Raptor Workspace Window above the Raptor Master Console
window on the Windows desktop.
7. The Help menu contains the following submenu:

Sasi Institute of Technology & Engineering{A} Page 13


Programming for Problem Solving Lab

a) About gives the version of Raptor currently running.


b) General Help opens the Raptor Help Window.
c) Show Log displays a history of all editing and saving activity on the current Raptor
program.
d) Count Symbols displays in the Master Console the number of symbols in the current
Raptor program.

Using the toolbar

The toolbar implements many of same functions found in the main menu or in pop-up menus.
Hovering the mouse over a single button will display the tooltip for that button.
The New button creates a new flowchart.
The Open button opens a previously saved flowchart from disk.
The Save button saves the current flowchart to disk.
The Cut, Copy, and Paste buttons all function as expected on the currently selected symbols
(those currently colored red).
The Print button prints the current flowchart.
The Undo button reverts the flowchart back before the last change was made.
The Redo button cancels the previous undo operation.
The Execute to Completion button runs the entire program until it terminates.
The Pause button temporarily halts execution of a program until execution is resumed by the user.
The Stop and Reset to Beginning button halts program execution and clears the value of all
variables.
The Step to Next Shape button executes one shape in a flowchart.
The slider bar on the toolbar adjusts the speed of execution of a flowchart. Move the bar to
the left to slow execution. Move the bar to the right to speed up execution. When the slider is
positioned to the far right, Raptor will no longer highlight in green the symbol currently being
executed. This makes the execution run much faster. To run even faster, use the view menu to turn
off the display of variables in the watch window. For fastest execution, use a compiled version of
your program. The drop down box on the right of the toolbar adjusts the scaling factor for the
Workspace window.

Building a flowchart
To build a flowchart, left click on a symbol in the Symbol Window. Move the mouse to the place
in the flowchart where the symbol belongs. You may need to move the cursor slightly to find an
insertion point.
When the cursor is at an insertion point, the cursor will change to. When the left mouse button is
clicked at an insertion point, the selected symbol is added to the existing flowchart at the specified
location. If symbols are incorrectly placed, select Undo, Delete, or Cut from the Edit or Right
Mouse Button menu. Symbols may also be copied and pasted in another area of a flowchart.
Once a symbol has been correctly placed, double click the symbol to edit its contents.

Executing a flowchart
A flowchart may be executed using the Run Menu/Execute option or the toolbar. The symbol being
executed is highlighted in green. Any variables changed by the execution of a symbol are
highlighted in red in the Watch window.
Sasi Institute of Technology & Engineering{A} Page 14
Programming for Problem Solving Lab

Step executes through one shape in a flowchart. Pressing F10 will also execute the current shape.
Execute to Completion runs the entire program until it terminates.
Reset halts program execution and clears the value of all variables in preparation for a subsequent
Execution.
Reset/Execute halts program execution, clears the value of all variables, and restarts execution
from the beginning. Pressing F5 will also perform this function.
Pause temporarily halts the execution of a program until execution is resumed by the user.
Speed Slider sets the speed of program execution. When the slider is entirely to the right
(maximum speed), the Watch Window is not updated, and flowchart symbols are not
highlightedduring execution.

Editing Symbols
Double click a symbol placed in a flowchart to edit its contents.

Assignment
The following dialog appears when editing an assignment symbol:
In the box following "Set", enter a variable. In the box following "to", enter an expression whose
value will be stored in the given variable. If the variable is a string variable, the expression on the
right must be a string expression (see String Variables & Assignment).

Sasi Institute of Technology & Engineering{A} Page 15


Programming for Problem Solving Lab

Input Symbol
The following dialog appears when editing an input symbol:
Enter a prompt to the user in the first textbox. The prompt will appear in the pop-up window in
which the user will enter a value for the variable whose name is specified in the second textbox.
You may select the Expression radio button if you want the prompt to be a string expression that
contains a string variable or concatenation of several string expressions. Depending on what the
user enters during program execution, the variable (in the above example, Age) may be treated as
a number or string (see String vs. Numeric Input).

Output Symbol
The Output Symbol specifies what will be output to the Master Console (or, in some cases, to a
file; see Outputting to a File). First select whether an Expression or Text is to be output. An
expression can be a number, a string literal in double quotes, a variable, a math expression, or a
string expression. Select Text to output a text message containing no variables or math; no quotes
are required. If the "End current line"
checkbox at the bottom of the dialog is checked, the MasterConsole output after this one will start
on the next line.

Sasi Institute of Technology & Engineering{A} Page 16


Programming for Problem Solving Lab

Selection Symbol
The following dialog appears when editing the decision diamond for a selection structure: Enter
in this textbox a Boolean expression that will be evaluated for this symbol. If the Boolean
expression is true, the left branch of the selection will be taken. Otherwise, the right branch
will be taken.

Loop Symbol
The following dialog appears when editing the decision diamond for a loop structure:
Enter in the textbox a Boolean expression that will be evaluated for this symbol. If the Boolean
expression is true, the loop is exited. Otherwise, flow continues the "No" branch below the
diamond and eventually to the top of the loop.

Sasi Institute of Technology & Engineering{A} Page 17


Programming for Problem Solving Lab

Enter in the textbox a Boolean expression that will be evaluated for this symbol. If the Boolean
expression is true, the loop is exited. Otherwise, flow continues the "No" branch below the
diamond and eventually to the top of the loop.

Using the Master Console


The Master Console window displays all user input and output. Input and output are achieved
usingthe input or output symbol.

C) Introduction to basic LINUX commands.

A command is an instruction given by a user telling a computer to do something, such a


run a single program or a group of linked programs. Commands are generally issued by typing
them in at the command line (i.e., the all-text display mode) and then pressing the ENTER key,
which passes them to the shell.
A shell is a program that reads commands that are typed on a keyboard and then executes
(i.e., runs) them. Shells are the most basic method for a user to interact with the system. Every
Unix-like operating system has at least one shell, and most have several. The default shell on most
Linux systems is bash.
A program is a sequence of instructions that is understandable by a CPU (central processing
unit), the main logic unit of a computer. It indicates which operations the CPU should perform on

Sasi Institute of Technology & Engineering{A} Page 18


Programming for Problem Solving Lab

a set of data. Programs are usually files that are stored in one of the bin directories, such as /bin,
/usr/bin and /usr/local/bin.
Commands on Unix-like operating systems are either built-ins or external commands. The
former is part of the shell. The latter consist of both executables, which are programs that have
been written in a programming language (e.g., C, C++, Java, or Python) and then compiled into a
binary, and shell scripts.
A command consists of a command name usually followed by one or more strings (i.e.,
sequences of characters) that comprise options and arguments. Each of these strings is separated
by white space (which consists of one or more spaces or tabs). The general syntax for commands
is
Command [options] [arguments]
The square brackets indicate that the enclosed items are optional. Most commands have at
least a few options and can accept (or require) arguments. However, there are some commands
that do not accept arguments, and a very few with no options.
For Example
The clear command, which is used to remove all previous commands and output from the
display screen, is one of the rare commands that accepts neither options nor arguments. That is, it
can only be used as follows:
Clear pwd,
which stands for print working directory and tells the user the name and location of the current
directory (i.e., the directory in which the user is currently working), likewise does not accept any
arguments. Rather, it receives its input from the shell. Moreover, it only has two very basic options,
--help and --version. Thus, it is almost always used just as pwd
vi editor
The vi is generally considered the de facto standard in Unix editors because −
• It's usually available on all the flavors of Unix system.
• Its implementations are very similar across the board.
• It requires very few resources.
• It is more user friendly than any other editors like ed or ex.
You can use vi editor to edit an existing file or to create a new file from scratch. You can also
use this editor to just read a text file.
Sasi Institute of Technology & Engineering{A} Page 19
Programming for Problem Solving Lab

To Start the vi Editor, there are following way you can start using vi editor −
Command Description
vi filename Creates a new file if it already does not exist, otherwise opens existing file.
vi -R filename Opens an existing file in read only mode.
view filename Opens an existing file in read only mode.
Following is the example to create a new file test file if it already does not exist in the current
working directory −
$vi testfile
As a result, you would see a screen something like as follows −
~
~
~
~
~
~
~
~
~
~
~
~
"testfile" [New File]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused
line. If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline, or
some other non-viewable character present.
So now you have opened one file to start with. Before proceeding further let us
understand few minor but important concepts explained below.

Sasi Institute of Technology & Engineering{A} Page 20


Programming for Problem Solving Lab

Operation Modes
While working with vi editor you would come across following two modes −
Command mode − This mode enables you to perform administrative tasks such as saving files,
executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding
and replacing. In this mode, whatever you type is interpreted as a command.
Insert mode − This mode enables you to insert text into the file. Everything that's typed in this
mode is interpreted as input and finally it is put in the file .The vi always starts in command
mode. To enter text, you must be in insert mode. To come in insert mode you simply type i. To
get out of insert mode, press the Esc key, which will put you back into command mode.
Hint − If you are not sure which mode you are in, press the Esc key twice, and then you'll be in
command mode. You open a file using vi editor and start type some characters and then come in
command mode to understand the difference.
Getting Out of vi
The command to quit out of vi is :q. Once in command mode, type colon, and 'q', followed
by return. If your file has been modified in any way, the editor will warn you of this, and not let
you quit. To ignore this message, the command to quit out of vi without saving is :q!. This lets you
exit vi without saving any of the changes.
The command to save the contents of the editor is :w. You can combine the above
command with the quit command, or :wq and return. The easiest way to save your changes and
exit out of vi is the ZZ command. When you are in command mode, type ZZ and it will do the
equivalent of :wq. You can specify a different file name to save to by specifying the name after
the :w. For example, if you wanted to save the file you were working as another filename called
filename2, you would type: w filename2 and return. Try it once.

Moving within a File


To move around within a file without affecting your text, you must be in command mode
(press Esc twice). Here are some of the commands you can use to move around one character at a
time
Command Description
k Moves the cursor up one line.
j Moves the cursor down one line.
h Moves the cursor to the left one-character position.
l Moves the cursor to the right one-character position.

Sasi Institute of Technology & Engineering{A} Page 21


Programming for Problem Solving Lab

There are following important points to be noted −


1. The vi is case-sensitive, so you need to pay special attention to capitalization when using
commands.
2. Most commands in vi can be prefaced by the number of times you want the action to occur.
For example, 2j moves cursor two lines down the cursor location.
There are many other ways to move within a file in vi. Remember that you must be in command
mode (press Esc twice). Here are some more commands you can use to move around the file −
Command Description
0 or | Positions cursor at beginning of line.
$ Positions cursor at end of line.
W Positions cursor to the next word.
B Positions cursor to previous word.
( Positions cursor to beginning of current sentence.
) Positions cursor to beginning of next sentence.
E Move to the end of Blank delimited word
{ Move a paragraph back
} Move a paragraph forward
[[ Move a section back
]] Move a section forward
n| Moves to the column n in the current line
1G Move to the first line of the file
G Move to the last line of the file
nG Move to nth line of the file
:n Move to nth line of the file
Fc Move forward to c
Fc Move back to c
H Move to top of screen
nH Moves to nth line from the top of the screen
M Move to middle of screen
L Move to botton of screen
nL Moves to nth line from the bottom of the screen
:x Colon followed by a number would position the cursor on line number represented
by x

There are following useful command which you can use along with Control Key –

Command Description
CTRL+d Move forward 1/2 screen
CTRL+f Move forward one full screen
CTRL+u Move backward 1/2 screen
CTRL+b Move backward one full screen
Sasi Institute of Technology & Engineering{A} Page 22
Programming for Problem Solving Lab

CTRL+e Moves screen up one line


CTRL+y Moves screen down one line
CTRL+u Moves screen up 1/2 page
CTRL+d Moves screen down 1/2 page
CTRL+b Moves screen up one page
CTRL+f Moves screen down one page
CTRL+I Redraws screen

Editing Files
To edit the file, you need to be in the insert mode. There are many ways to enter insert mode from
the command mode −
Command Description
i Inserts text before current cursor location.
I Inserts text at beginning of current line.
a Inserts text after current cursor location.
A Inserts text at end of current line.
o Creates a new line for text entry below cursor location.
O Creates a new line for text entry above cursor location.

Deleting Characters
Here is the list of important commands which can be used to delete characters and lines in an
opened file −
Command Description
x Deletes the character under the cursor location.
X Deletes the character before the cursor location.
dw Deletes from the current cursor location to the next word.
d^ Deletes from current cursor position to the beginning of the line.
d$ Deletes from current cursor position to the end of the line.
D Deletes from the cursor position to the end of the current line.
dd Deletes the line the cursor is on.
As mentioned above, most commands in vi can be prefaced by the number of times you
want the action to occur. For example, 2x deletes two characters under the cursor location and
2dddeletes two lines the cursor is on.
Change Commands
You also have the capability to change characters, words, or lines in vi without deleting them. Here
are the relevant commands −
Command Description
cc Removes contents of the line, leaving you in insert mode.
cw Changes the word the cursor is on from the cursor to the lowercase w end of the
word.
r Replaces the character under the cursor. vi returns to command mode after the
replacement is entered.

Sasi Institute of Technology & Engineering{A} Page 23


Programming for Problem Solving Lab

R Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting.
s Replaces the current character with the character you type. Afterward, you are left
in insert mode.
S Deletes the line the cursor is on and replaces with new text. After the new text is
entered, vi remains in insert mode.

Copy and Paste Commands


You can copy lines or words from one place and then you can past them at another place using
following commands −
Command Description
yy Copies the current line.
yw Copies the current word from the character the lowercase w cursor is on until the
end of the word.
p Puts the copied text after the cursor.
P Puts the yanked text before the cursor.

Advanced Commands
There are some advanced commands that simplify day-to-day editing and allow for more efficient
use of vi −
Command Description
J Join the current line with the next one. A count joins that many lines.
<< Shifts the current line to the left by one shift width.
>> Shifts the current line to the right by one shift width.
~ Switch the case of the character under the cursor.
^G Press CNTRL and G keys at the same time to show the current filename and the
status.
U Restore the current line to the state it was in before the cursor entered the line.
u Undo the last change to the file. Typing 'u' again will re-do the change.
J Join the current line with the next one. A count joins that many lines.
:f Displays current position in the file in % and file name, total number of files.
:f filename Renames current file to filename.
:w filename Write to file filename.
:e filename Opens another file with filename.
:cd dirname Changes current working directory to dirname.
:e # Use to toggle between two opened files.
:n In case you open multiple files using vi, use: n to go to next file in the series.
:p In case you open multiple files using vi, use: p to go to previous file in the series.
:N In case you open multiple files using vi, use: N to go to previous file in the series.
:r file Reads file and inserts it after current line
:nr file Reads file and inserts it after line n.

Sasi Institute of Technology & Engineering{A} Page 24


Programming for Problem Solving Lab

Word and Character Searching


The vi editor has two kinds of searches: string and character. For a string search, the / and?
Commands are used. When you start these commands, the command just typed will be shown on
the bottom line, where you type the string to look for.
These two commands differ only in the direction where the search takes place −
The / command searches forwards (downwards) in the file.
The? Command searches backwards (upwards) in the file.
The n and N commands repeat the previous search command in the same or opposite
direction, respectively. Some characters have special meanings while using in search command
and preceded by a backslash (\) to be included as part of the search expression.
Character Description
^ Search at the beginning of the line. (Use at the beginning of a search expression.)
. Matches a single character.
* Matches zero or more of the previous character.
$ End of the line (Use at the end of the search expression.)
[ Starts a set of matching, or non-matching expressions.
< Put in an exp escaped with the ‘\’ to find the ending or beginning of a word.
> See the '<' character description above.

The character search searches within one line to find a character entered after the command.
The f and F commands search for a character on the current line only. f searches forwards and F
searches backwards and the cursor moves to the position of the found character.The t and T
commands search for a character on the current line only, but for t, the cursor moves to the
position before the character, and T searches the line backwards to the position after the
character.
Emacs Editor:
Emacs is one of the oldest and most versatile text editors available for Linux and UNIX-
based systems. It's been around for a long time (more than twenty years for GNU emacs) and is
well known for its powerful and rich editing features. Emacs is also more than just a text editor; it
can be customized and extended with different "modes", enabling it to be used like an Integrated
Development Environment (IDE) for programming languages like Java, C or Python. For those
who have used both the ubiquitous vi and the user-friendly nano, emacs would come as an
interesting cross-between. Its strengths and features would resemble those of vi while its menus,
help files and easy-to-remember command-keys would compare with nano.

Sasi Institute of Technology & Engineering{A} Page 25


Programming for Problem Solving Lab

1 b) Description: Using commands like mkdir, ls, cp, mv, cat, pwd, and man
mkdir
Short for "make directory", mkdir is used to create directories on a file system.
Description
If the specified DIRECTORY does not already exist, mkdir creates it.
More than one DIRECTORY may be specified when calling mkdir.
mkdir syntax
mkdir [OPTION ...] DIRECTORY ...
Options

-m, Set file mode (as with the chmod command).


--mode=MODE
-p, --parents Create parent directories as necessary. When this option is used, no error is
reported if a specified DIRECTORY already exists.
-v, --verbose Verbose output prints a message for each created directory.
-Z, -- Set the SELinux security context of each created directory to the context
context=CTX CTX.
--help Display a help message, and exit.
--version Display version information, and exit.
Examples
mkdir mydir
Creates a new directory called mydir whose parent is the current directory.
ls syntaxlist all the files
$ ls [options] [file|dir]
ls command options

option Description
ls -a list all files including hidden file starting with '.'
ls --color colored list [=always/never/auto]
ls -d list directories - with ' */'
ls -F add one char of */=>@| to enteries
ls -i list file's inode index number
ls -l list with long format - show permissions
ls -la list long format including hidden files
ls -lh list long format with readable file size
ls -ls list with long format with file size
ls -r list in reverse order
ls -R list recursively directory tree
ls -s list file size
Sasi Institute of Technology & Engineering{A} Page 26
Programming for Problem Solving Lab

ls -S sort by file size


ls -t sort by time & date
ls -X sort by extension name
ls command examples
You can press the tab button to auto complete the file or folder names.
List directory Documents/Books with relative path:
$ ls Documents/Books
List directory /home/user/Documents/Books with absolute path.
$ ls /home/user/Documents/Books
List root directory:
$ ls /
List parent directory:
$ ls ..
List user's home directory (e.g: /home/user):
$ ls ~
List with long format: $ ls -l
Show hidden files: $ ls -a
List with long format and show hidden files: $ ls -la
Sort by date/time: $ ls -t
Sort by file size: $ ls -S
List all subdirectories: $ ls *
Recursive directory tree list: $ ls -R
List only text files with wildcard: $ ls *.txt
ls redirection to output file: $ ls > out.txt
List directories only: $ ls -d*/
cp command syntax Copy from source to destination
$ cp [options] source destination
cp command main options:

option Description
cp -a archive files
cp -f force copy by removing the destination file if needed
cp -i interactive - ask before overwrite
cp -l link files instead of copy

Sasi Institute of Technology & Engineering{A} Page 27


Programming for Problem Solving Lab

cp -L follow symbolic links


cp -n no file overwrites
cp -R recursive copy (including hidden files)
cp -u update - copy when source is newer than dest
cp -v verbose - print informative messages
cp command examples
1. Copy single file main.c to destination directory bak: $ cp main.c bak
2. Copy 2 files main.c and def.h to destination absolute path directory /home/usr/rapid/ :
$ cp main.c def.h /home/usr/rapid/
3. Copy all C files in current directory to subdirectory bak :
$ cp *.c bak
4. Copy directory src to absolute path directory /home/usr/rapid/ :
$ cp src /home/usr/rapid/
5. Copy all files and directories in dev recursively to subdirectory bak:
$ cp -R dev bak
6. Force file copy:
$ cp -f test.c bak
7. Interactive prompt before file overwrite:
$ cp -i test.c bak
cp: overwrite 'bak/test.c'? y
8. Update all files in current directory - copy only newer files to destination directory bak:
$ cp -u * bak
mv command in Linux/Unix
Linux mv command. mv command is used to move files and directories.
mv command syntax
$ mv [options] source dest
mv command options
mv command main options:

option Description
mv -f force move by overwriting destination file without prompt
mv -i interactive prompt before overwriting
mv -u update - move when source is newer than destination
mv -v verbose - print source and destination files
man mv help manual

Sasi Institute of Technology & Engineering{A} Page 28


Programming for Problem Solving Lab

mv command examples
1. Move main.c def.h files to /home/usr/rapid/ directory:
$ mv main.c def.h /home/usr/rapid/
2. Move all C files in current directory to subdirectory bak :
$ mv *.c bak
3. Move all files in subdirectory bak to current directory:
$ mv bak/* .
4. Rename file main.c to main.bak:
$ mv main.c main.bak
5. Rename directory bak to bak2:
$ mv bak bak2
6. Update - move when main.c is newer:
$ mv -u main.c bak
$
7. Move main.c and prompt before overwrite bak/main.c:
$ mv -v main.c bak
'bak/main.c' -> 'bak/main.c'
$
The cat Command
cat is one of the most frequently used commands on Unix-like operating systems. It has
three related functions regarding text files: displaying them, combining copies of them and
creating new ones.
cat's general syntax
cat [options] [filenames] [-] [filenames]
The square brackets indicate that the enclosed items are optional.
Reading Files
The most common use of cat is to read the contents of files, and cat is often the most
convenient program for this purpose. All that is necessary to open a text file for viewing on the
display monitor is to type the word cat followed by a space and the name of the file and then press
the ENTER key. For example, the following will display the contents of a file named file1:

Sasi Institute of Technology & Engineering{A} Page 29


Programming for Problem Solving Lab

cat file1
The standard output (i.e., default destination of the output) for cat, as is generally the case
for other command line (i.e., all-text mode) programs, is the monitor screen. However, it can be
redirected from the screen, for example, to another file to be written to that file or to another
command to use as the input for that command.
In the following example, the standard output of cat is redirected using the output
redirection operator (which is represented by a rightward pointing angular bracket) to file2:
cat file1 > file2
That is, the output from cat is written to file2 instead of being displayed on the monitor
screen. The standard output could instead be redirected using a pipe (represented by a vertical bar)
to a filter (i.e., a program that transforms data in some meaningful way) for further processing. For
example, if the file is too large for all of the text to fit on the monitor screen simultaneously, as is
frequently the case, the text will scroll down the screen at high speed and be very difficult to read.
This problem is easily solved by piping the output to the filter less, i.e.,
cat file1 | less
This allows the user to advance the contents of the file one screenful at a time by pressing
the space bar and to move backwards by pressing the b key. The user can exit from less by pressing
the q key.

The standard input (i.e., the default source of input data) for cat, as is generally the case for
other commands on Unix-like systems, is the keyboard. That is, if no file is specified for it to open,
cat will read whatever is typed in on the keyboard.
Typing the command cat followed by the output redirection operator and a file name on
the same line, pressing ENTER to move to the next line, then typing some text and finally pressing
ENTER again causes the text to be written to that file. Thus, in the following example the text that
is typed on the second line will be written to a file named felines:
cat > felines
This is not about a feline.
The program is terminated, and the normal command prompt is restored by pressing
the CONTROL and d keys simultaneously.
pwd command in Linux/Unix
pwd - print working directory, is a Linux command to get the current working directory.

Sasi Institute of Technology & Engineering{A} Page 30


Programming for Problem Solving Lab

pwd syntax
$ pwd [option]
pwd command examples
Change directory to /usr/src directory and print working directory:
$ cd /usr/src
$ pwd
/user/src
Change directory to home directory and print working directory:
$ cd ~
$ pwd
/home/user
Change directory to parent directory of the home directory and print working directory:
$ cd ~/..
$ pwd
/home
Change directory to root directory and print working directory:
$ cd /
$ pwd
The man command is used to format and display the man pages.
The man pages are a user manual that is by default built into most Linux distributions (i.e.,
versions) and most other Unix-like operating systems during installation. They provide extensive
documentation about commands and other aspects of the system, including configuration files,
system calls, library routines and the kernel (i.e., the core of the operating system). A configuration
file is a type of simple database that contains data that tells a program or operating system how to
behave. A system call is a request made via a software interrupt (i.e., a signal to the kernel initiated
by software) by an active process for a service performed by the kernel. A library routine is a
subprogram that is used by programmers to simplify the development of software.
The man pages are tailored to the particular operating system, and version thereof, on
which they are installed. This is beneficial because there can be slight differences in commands
and other items according to the particular system.
The descriptions are rather terse, and they can seem somewhat cryptic to new users.

Sasi Institute of Technology & Engineering{A} Page 31


Programming for Problem Solving Lab

However, users typically find them to be increasingly useful as they become more familiar with
them and gain experience in the use of Unix-like operating systems.
The man command itself is extremely easy to use. Its basic syntax is
man [option(s)] keyword(s)
man is most used without any options and with only one keyword. The keywordis the exact
name of the command or other item for which information is desired. For example, the following
provides information about the ls command (which is used to list the contents of any specified
directory.
man ls
As another example, the following displays the man page about the man pages:
man man
man automatically sends its output through a pager, usually the program less. A pager is a
program that causes the output of any program to be displayed one screenful at a time, rather than
having a large amount of text scroll down the screen at high (and generally unreadable) speed.less
writes a colon at the bottom of the screen to indicate the end of the on-screen page. The user can
move to the next page by pushing the space bar and can return to the previous page by pressing
the b key. Pressing the q exits the man pages and returns the user to the shell program.
Each man page is a self-contained article that is divided into a number of sections, the
headers for which are labeled with upper case letters. The sections for commands are typically
something like NAME, SYNOPSIS, DESCRIPTION, OPTIONS, AUTHOR, BUGS,
COPYRIGHT, HISTORY and SEE ALSO, although there may be some differences according to
the command. Some of these might be broken down into subsections, particularly OPTIONS in
the case of a command that has numerous options.

Sasi Institute of Technology & Engineering{A} Page 32


Programming for Problem Solving Lab

Viva Questions:

1. Explain the purpose of code blocks?

2. Explain advantages of using RAPTOR?

3. Explain the purpose of vi editor?

4. What are the commands used in linux for creating a program, compiling and
executing?

5. What is the difference between compiling and executing?

Sasi Institute of Technology & Engineering{A} Page 33


Programming for Problem Solving Lab

Exercise 2 (Simple computational problems using arithmetic expressions)


a) Write a C Program to display real number with 2 decimal places.
b) Write a C Program to convert Celsius to Fahrenheit and vice versa.
c) Write a C Program to calculate the area of triangle using the formula
area = √(s(s-a)(s-b)(s-c) ) where s= (a+b+c)/2
d) Write a C program to find the largest of three numbers using ternary operator.
e) Write a C Program to swap two numbers without using a temporary variable.

2a) Aim: To write a C Program to display real number with 2 decimal places.
Description:
This program is to print a number only up to 2 decimal places ignoring the remaining places.
Algorithm:
Step 1: Start
Step 2: Declare a float variable n
Step 3: Read n value
Step 4: Print n value using %.2f to display up to 2 decimal places
Step 5: Stop
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 34


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 35


Programming for Problem Solving Lab

2b) Aim: To write a C Program to convert Celsius to Fahrenheit and vice versa.
Description:
This Program is used to convert Celsius to Fahrenheit and vice versa

Algorithm to convert Celsius to Fahrenheit:


Step 1: Start
Step 2: Declare two variables celsius, fahrenheit.
Step 3: Display Enter temp in Celsius.
Step 4: Read value for celsius.
Step 5: Calculate fahrenheit = (1.8 * celsius) + 32.
Step 6: Display the result as Temperature in Fahrenheit.
Step 7: End
Flowchart:

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 36


Programming for Problem Solving Lab

Algorithm to convert Fahrenheit to Celsius:


Step 1: Start
Step 2: Declare two variables fh, cl.
Step 3: Display Enter temperature value in Fahrenheit.
Step 4: Read value for fh.
Step 5: Calculate cl = (fh - 32) / 1.8.
Step 6: Display the result as Converted Celsius value.
Step 7: Stop
Flowchart:

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 37


Programming for Problem Solving Lab

2c) Aim: To write a C Program to calculate the area of triangle using the formula
area = √(s(s-a)(s-b)(s-c) ) where s= (a+b+c)/2
Description: This program is used to find the area of a triangle using the formula
(s(s-a)(s-b)(s-c))1/2.In this first read the values of s,a,b and c then calculate the s value by
using the formula s=(a+b+c)/2.and then place the value of s in the area.
Algorithm:
Step 1: start
Step 2: Read s, a b, A
Step 3: Find the s value by using (a+b+c)/2
Step 4: find the area by using formula area=(s(s-a)(s-b)(s-c))1/2
Step 5: print area
Step 6: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 38


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 39


Programming for Problem Solving Lab

2 d) Aim: To write a C program to find the largest of three numbers using ternary operator.
Description: This program is used to find the largest number among three numbers. To find the
largest number perform the comparison by using ternary operator (?:). For this first read the three
numbers then perform comparison.
Algorithm:
Step 1: start
Step 2: Read a, b, c, big
Step 3: compare the values of all the variables using big=(a>b&&a>c)?a:(b>c)?b:c
Step 4: print big value
Step 5: stop
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 40


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 41


Programming for Problem Solving Lab

2 e) Aim: To write a C Program to swap two numbers without using a temporary variable.
To perform swapping operation using two variables.
Description: This program is used to perform the swapping (exchange) operation for two
variables. That is without using third variable swapping will be perform. For this first read the
two variables then exchange two values by performing arithmetic operations between two
variables.
Algorithm:
Step 1: start
Step 2: Read a,b
Step 3: print a and b values before swapping
Step 4: add the contents of a and b store the result in a
Step 5: subtract the contents of a and b store the result in b
Step 6: subtract the contents of a and b store the result in a
Step 7: print a and b values after swapping
Step 8: stop.
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 42


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 43


Programming for Problem Solving Lab

Viva Questions:
1. What are input function and output function?

2. What are the different types of operators?

3. What is meant by variable?

4. Define datatype? What are different data types?

5. What is meant by constant?

6. What is meant by token?

Sasi Institute of Technology & Engineering{A} Page 44


Programming for Problem Solving Lab

Exercise 3 (Problems involving if-then-else structures)


a) Write a C Program to check whether a given number is even or odd using bitwise
operator, shift operator and arithmetic operator.
b) Write a C program to find the roots of a quadratic equation.
c) Write a C Program to display grade based on 6 subject marks using if…else…if
ladder.
d) Write a C program, which takes two integer operands and one operator form the
user, performs the operation and then prints the result using switch control
statement. (Consider the operators +, -, *, /, %)

3 a) Aim: To write a C Program to check whether a given number is even or odd


using bitwise operator, shift operator and arithmetic operator.
Description:

Using bitwise operator: Least Significant Bit(LSB) of an odd number is always set 1. To check
whether a number is even or odd we need to figure out if LSB is set or not. We use Bitwise AND
& operator to check whether a bit is set or not. Similarly on performing num & 1 it return LSB of
num. If LSB is 1 then the given number is odd otherwise even.

Using shift operator:


If we perform right shift and left shift on a given number once we get the same given number in
the case of even number and a different number in the case of odd number
For example:
( 4 >> 1 ) << 1 = ( 2 ) << 1 = 4.
( 5 >> 1 ) << 1 = ( 2 ) << 1 = 4.

Using Modulo Operator ( % )


This is the most used method to check whether the given number is even or odd in practice.
Modulo operator is used to get the remainder of a division. For example, 5 % 2 returns 1, i.e., the
remainder when divided 5 by 2.
So whenever you divide a given number by 2 and if the remainder is 0 - then it is an even
number, else it is an odd number.

Sasi Institute of Technology & Engineering{A} Page 45


Programming for Problem Solving Lab

Algorithm for even or odd using bitwise operators


Step 1: start
Step 2: Read n value
Step 3: calculate LSB of given number by performing 1 & n
Step 4: if LSB is 1 print given number is odd else print given number is even
Step 5: stop
Flowchart:

Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 46


Programming for Problem Solving Lab

Algorithm for even or odd using shift operator:


Step 1: start
Step 2: Read n value
Step 3: Perform right shift and left shift on number n
Step 4: if the result is same as given number then print n is even else print n is odd
Step 5: stop
Flowchart:

Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 47


Programming for Problem Solving Lab

Algorithm for even or odd using Modulo Operator ( % )


Step 1: start
Step 2: Read n value
Step 3: if n%2 is zero print n is even else print n is odd
Step 4: stop
Flowchart:

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 48


Programming for Problem Solving Lab

3b) Aim: To write a C program to find the roots of a quadratic equation.

Description:
The program takes the coefficients of quadratic equation as inputs in the form of a, b and c. Then
the value of d(b*b)-4*a*c will be evaluated. Depending upon the value of d, roots will be calculated.
If d>0, then r1, r2 will be calculated by using their formulae, if d=0, then a common root called r
will be calculated and printed. Else roots are going to be imaginary.

Algorithm:

Step 1: start
Step 2: initialize a,b,c,d,r1,r2,r
Step 3: read a, b, c
Step 4: perform the operation by using the formula d =(b*b)-4*a*c
Step 5: if d>0 then repeat Steps 6, 7
Step 6:r1=(-b+sqrt(d)/2*a)
r2 =(-b-sqrt (d)/2*a)
Step 7: print r1, r2
Step 8: else if d=0 repeat Steps 9, 10
Step 9: r=b/ (2*a)
Step 10: print r
Step 11: else print roots are imaginary.
Step 12: stop.

Sasi Institute of Technology & Engineering{A} Page 49


Programming for Problem Solving Lab

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 50


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 51


Programming for Problem Solving Lab

3 c) Aim: To write a C Program to display grade based on 6 subject marks using if…else…if
ladder.

Description: This Program displays grade based on input 6 subject marks by using if else if
conditional statement.

Algorithm:
Step 1: start
Step 2: Read subject marks s1, s2, s3, s4, s5 and s6
Step 3: calculate sum=s1+s2+s3+s4+s5+s6
Step 4: calculate percentage p=sum/6
Step 5: if p>=70&&p<=100 else go to step7
Step 6: print A Grade
Step 7: else if p>=60&&p<70 else go to step9
Step 8: print B Grade
Step 9: else if p>=50&&p<60 else go to step11
Step 10: print C Grade
Step 11: else if p>=40&&p<50 else go to step12
Step 12: print D Grade
Step 13: print Failed
Step 14: Stop

Sasi Institute of Technology & Engineering{A} Page 52


Programming for Problem Solving Lab

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 53


Programming for Problem Solving Lab

Program:

Sasi Institute of Technology & Engineering{A} Page 54


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 55


Programming for Problem Solving Lab

3 d) Aim: To write a C program, which takes two integer operands and one operator form the
user, performs the operation and then prints the result using switch control statement.
(Consider the operators +, -, *, /, %)
Description: The theme of the program is to find out the various operation results by considering
the various cases including in the switch statement and the corresponding case will be executed
according to the choice given by the user.

Algorithm:
Step 1: start
Step 2: declare a,b,c,d,op
Step 3: read a,b,op
Step 4: Use Switch case
Step 5: if case ‘+’ perform addition operation
Step 6: if case ‘-‘perform subtraction operation
Step 7: if case ‘*’ perform multiplication operation
Step 8: if case ‘/’ perform division operation
Step 9: if case ‘%’ performs modulo division operation
Step 10: print the result which is in the variable c
Step 11: stop.
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 56


Programming for Problem Solving Lab

Program:

Sasi Institute of Technology & Engineering{A} Page 57


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 58


Programming for Problem Solving Lab

Viva Questions:

1. What is the need of conditional statement?

2. What are different conditional statements?

3. What is the difference between switch and else if ladder?

4. What is the syntax for else if statement?

5. What is the difference between conditional statement and conditional operator?

6. What is the use of default in switch case?

Sasi Institute of Technology & Engineering{A} Page 59


Programming for Problem Solving Lab

Exercise 4 (Iterative problems)


a) Write a C Program to count number of 0’s and 1’s in a binary representation of a
given number.
b) Write a C program to generate all the prime numbers between two numbers supplied
by the user.
c) Write a C Program to print the multiplication table corresponding to number
supplied as input

4 a) Write a C Program to count number of 0’s and 1’s in a binary representation of a given
number
Description: This program takes a number as input and count number of 0’s and 1’s
Algorithm:
Step 1: Start
Step 2: Input a number from user. Store it in some variable say num.
Step 3: Compute total bits required to store integer in memory i.e. INT_SIZE = sizeof(int) * 8.
Step 4: Initialize two variables to store zeros and ones count, say zeros = 0 and ones = 0.
Step 5: Run a loop from 0 to INT_SIZE. The loop structure should look like
for(i=0; i<INT_SIZE; i++).
Step 6: Inside the loop check if Least Significant Bit of a number is set, then increment ones
by 1 otherwise increment zeros by 1.
Step 7: Right shift num 1 time i.e. perform num = num >> 1;
Step 8: Stop

Sasi Institute of Technology & Engineering{A} Page 60


Programming for Problem Solving Lab

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 61


Programming for Problem Solving Lab

Program:

Sasi Institute of Technology & Engineering{A} Page 62


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 63


Programming for Problem Solving Lab

4b) Aim: To write a C program to generate all the prime numbers between two numbers
supplied by the user.
Description: This program takes m and n as input. Then prime numbers ranging from m and n will
be printed. Here i, j are loop counter variables out of which i is used to produce the value to
determination. J produces values ranging from 2 to number/2 .if a number produces a remainder other
than 0 when divided by any number in between 2 and number/2, then we print that number.
Algorithm:
Step 1: start
Step 2: read m and n
Step 3: declare i, m, j, flag, n, number
Step 4: if m<n go to step 3 else print invalid range and go to step
Step 5: for (i=m;i<=n; i++) repeat the Steps 6, 7, 8,9,10
Step 6: flag=1
Step 7: number=i
Step 8: for (j=2; j<=(number/2) && flag==1; j++)
Step 9: if number divides with the contents of j Then flag=0
Step 10: if flag==1 Print number
Step 11: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 64


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 65


Programming for Problem Solving Lab

4 c) Write a C Program to print the multiplication table corresponding to number supplied as


input
Aim: To print the multiplication table
Description: This program is used to display the multiplication table. For this it first read the
table value. According to the given value this program will displays the multiplication table.
Algorithm:
Step 1: start
Step 2: Read n value and range value, Assign i=1
Step 3: repeat steps 4, 5 if i<=range else go to step 7
Step 4: Calculate res=n*i
Step 5: print values in the format n*i=res
Step 6: i=i+1
Step 7: stop
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 66


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 67


Programming for Problem Solving Lab

Viva Questions
1. What is the difference between entry-controlled loop and exit controlled loop?

2. Write the syntax for for loop?

3. What is the syntax for while loop?

4. What the syntax is for do while loop?

5. What is unconditional loop? Give examples?

Sasi Institute of Technology & Engineering{A} Page 68


Programming for Problem Solving Lab

Exercise 5 (Iterative problems)


a) Write a C Program to Find Whether the Given Number is
i) Armstrong Number ii) Palindrome Number
b) Write a C Program to print sum of digits of a given number

5 a) i) Aim: To write a C Program to Find Whether the Given Number is Armstrong Number
Description: This program is used to specify whether the specified number is Armstrong or not. A
number is Armstrong if the sum of cubes of individual digits of a number is equal to the number itself.
First read the number then compute the cubes of individual digits of that number then add the cubes. If
the obtained result is equal to the given number, then print the number is Armstrong. Otherwise
printthe number is not Armstrong.
Algorithm:
Step 1: start
Step 2: Declare num, sum=0, temp, remainder
Step 3: Read num
Step 4: Repeat steps 5,6,7 until n>0 else go to step 8
Step 5: remainder=num%10
Step 6: sum=sum+(remainder* remainder* remainder)
Step 7: num=num/10
Step 8: compare the result sum with the given number num
Step 9: if both are equal then print “no is Armstrong”
Step 10: else print “no is not Armstrong”
Step 11: stop
Flowchart:

Sasi Institute of Technology & Engineering{A} Page 69


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 70


Programming for Problem Solving Lab

5 a) ii) Aim: To write a C Program to Find Whether the Given Number is Palindrome
Number
i) Description: This program is used to specify whether the specified number is Palindrome or
not. A number is Palindrome if the reverse of individual digits of a number is equal to the
number itself. First read the number then calculate the reverse of individual digits of that
number. If the obtained result is equal to the given number, then print the number is
Palindrome.Otherwise print the number is not Palindrome.

Algorithm:
Step 1: start
Step 2: Declare num, rev=0, temp, remainder
Step 3: Read num
Step 4: Repeat steps 5, 6, 7 until n>0 else go to step 8
Step 5: remainder=num%10
Step 6: rev= (rev*10) +remainder
Step 7: num=num/10
Step 8: compare the result rev with the given number num
Step 9: if both are equal then print “no is Palindrome”
Step 10: else print “no is not Palindrome”
Step 11: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 71


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 72


Programming for Problem Solving Lab

5 b) Aim: To write a C Program to print sum of digits of a given number


Description: This program adds the individual digits in the given positive integer by separating
each digit from it by using remn%10. The resultant value of the remainder will be added to
sum.This process continues until the condition n>0 is satisfied. When the control comes out of
loop the value of sum will be printed.
Algorithm:
Step 1: start
Step 2: Declare num, sum=0, temp, remainder
Step 3: Read num
Step 4: Repeat steps 5,6,7 until n>0 else go to step 8
Step 5: remainder=num%10
Step 6: sum=sum+remainder
Step 7: num=num/10
Step 8: print sum
Step 9: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 73


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 74


Programming for Problem Solving Lab

Viva Questions:

1. What are the differences between while and do while?

2. What is a nested loop?

3. Draw flowchart for printing 1 to 100 numbers?

4. Which number is called as Armstrong number?

5. Which number is called as Prime number?

Sasi Institute of Technology & Engineering{A} Page 75


Programming for Problem Solving Lab

Exercise 6 (Series examples)


a) Write a C Program to calculate sum of following series
i) 1+2+3+…. n ii)1+1/2+1/3+……+1/n iii)1+x+x2+x3……+xn

6 a i) Aim: To Write a C Program to calculate sum of following series 1+2+3+…. n

Description: This Program calculates the sum of the following series 1+2+3+…..+n using
looping statements
Algorithm:
Step 1: Start
Step 2: Declare n,sum and i values
Step 3: Read n value
Step 4: Assign sum=0, i=1
Step 5: if i<=n Repeat steps 5 to 7 else go to step 8
Step 6: sum=sum+i
Step 7: i=i+1
Step 8: print sum value
Step 9: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 76


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 77


Programming for Problem Solving Lab

6 a ii) Aim: Write a C Program to calculate sum of following series 1+1/2+1/3+……+1/n


Description: This Program calculates the following series 1+1/2+1/3+……+1/n using looping
statements.
Algorithm:
Step 1: Start
Step 2: Declare n, sum and i values
Step 3: Read n value
Step 4: Assign sum=0, i=1
Step 5: if i<=n Repeat steps 5 to 7 else go to step 8
Step 6: sum=sum+(1/i)
Step 7: i=i+1
Step 8: print sum value
Step 9: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 78


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 79


Programming for Problem Solving Lab

6 a iii) Aim: Write a C Program to calculate sum of following series 1+x+x2+x3……+xn


Description: This Program calculates the following series 1+x+x2+x3……+xn using looping
statements.
Algorithm:
Step 1: Start
Step 2: Declare x, n, sum and i values
Step 3: Read x and n value
Step 4: Assign sum=0, i=1
Step 5: if i<=n Repeat steps 5 to 7 else go to step 9
Step 6: sum=sum+pow(x,i);
Step 7: i=i+1
Step 8: sum=sum+1
Step 9: print sum value
Step 10: stop

Flowchart:

Sasi Institute of Technology & Engineering{A} Page 80


Programming for Problem Solving Lab

Program:

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 81


Programming for Problem Solving Lab

Viva Questions
1. Explain nested loops with an example?

2. Explain any two mathematical functions?

3. What is the output of this C code?


#include <stdio.h>
void main()
{
int k = 0;
for (k)
printf("Hello");
}

4. What is the output of this C code?


#include <stdio.h>
void main()
{
int k = 0;
for (k < 3; k++)
printf("Hello");
}

5. What is loop variable?

Sasi Institute of Technology & Engineering{A} Page 82


Programming for Problem Solving Lab

Exercise – 7 1D Array manipulation


a) Write a C program to interchange the largest and smallest numbers in the array.
b) Write a C program to search an element in an array (linear search).
c) Write a C Program to print the following pattern using a character array
S
SA
SAS
SASI

7 a) Aim: To write and execute a C Program to interchange the largest and smallest
numbers in the array

Description: This program is used to read elements into an array and swap the largest and smallest
numbers in the array.
Algorithm:

Step 1: Start
Step 2: Declare variables a[10], max, min, maxpos, minpos, temp
Step 3: Enter array elements
Step 4: set i=0
Step 5: Repeat step 6 to 7 until i<5
Step 6: read values to a[i]
Step 7: set i=i+1
Step 8: set max=a[0],min=a[0],maxpos=0,minpos=0
Step 9: let i=1
Step 10: if a[i] is greater than max then set max=a[i] and maxpos=i;
Step 11: if a[i] is less than min then set min=a[i] and minpos=i;
Step 12: i=i+1
Step 13: Repeat step10 to 12 until i<5
Step 14: swap the a[maxpos] and a[minpos] using temporary variable
Step 15: print the array elements
Step 16: Stop

Sasi Institute of Technology & Engineering{A} Page 83


Programming for Problem Solving Lab

Program:

Sasi Institute of Technology & Engineering{A} Page 84


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 85


Programming for Problem Solving Lab

7 b) Aim: To write and execute a C Program to search an element in an array (linear search)
Description:
This program is used to search an element in an array using linear search technique.
Algorithm:
Step 1: Start
Step 2: Traverse the array using a for loop
Step 3: In every iteration, compare the key element with the current value of the array
Step 3.1: If the value matches, print the position along the key element
Step 3.2: If the value do not match, print key element not found
Step 4: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 86


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 87


Programming for Problem Solving Lab

7c) To write and execute a C Program to print the following pattern using a character array
S
SA
SAS
SASI
Description:
This program is used to print the following pattern using a character array
S
SA
SAS
SASI

Algorithm:

Step 1: Start
Step 2: Declare the character array s[5], i,j.
Step 3: Read the string
Step 4: Check for(i=0;s[i]!=’\0’;i++)
Step 5: if it is true then check for for(j=0;j<=i;j++) if false then goto step7
Step 6: Display the character
Step 7: Print newline character and goto step4
Step 8: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 88


Programming for Problem Solving Lab

Output:

Sasi Institute of Technology & Engineering{A} Page 89


Programming for Problem Solving Lab

Viva Questions:

1. What is an array?

2. What is the syntax to declare array variable?

3. What is the difference between ordinary variable and array variable?

4. What are the different types of arrays?

5. How can we access an array element?

6. What are the different techniques to search the data?

Sasi Institute of Technology & Engineering{A} Page 90


Programming for Problem Solving Lab

Exercise – 8 Matrix problems, String operations


a) Write a C program to add two matrices.
b) Write a C program to multiply two matrices if they are compatible or print an error
message “incompatible matrix sizes” otherwise.
c) Write a C program to check given matrix is symmetric or not.
d) Implement the following string operations with and without library functions.
i) copy ii) concatenate iii) length iv) compare

8 a) Aim: To write and execute a program C program to add two matrices.


Description: This Program is used to read two matrices and perform addition of two matrices.

Algorithm:
Step 1: Start
Step 2: Read the total number of rows and columns for the matrix
Step 3: Read the elements for Matrix A and store it into two dimensional arrays
Step 4: Read the elements for Matrix B and store it into two dimensional arrays
Step 5: Add the elements of 2 matrices namely A & B through the nested for loops and store the
result into a resultant 2-dimensional array C
Step 6: Display the result
Step 7: Stop

Program:

Sasi Institute of Technology & Engineering{A} Page 91


Programming for Problem Solving Lab

Sasi Institute of Technology & Engineering{A} Page 92


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 93


Programming for Problem Solving Lab

8b) Aim: To write and execute a C program to multiply two matrices if they are compatible or
print an error message “incompatible matrix sizes” otherwise.

Description: This Program is used to perform multiplication of two matrices if they are
compatible in sizes otherwise print an error message “incompatible matrix sizes”.

Algorithm:
Step 1: Start
Step 2: Set MIN to location 0.
Step 3: Search the minimum element in the list.
Step 4: Swap with value at location MIN.
Step 5: Increment MIN to point to next element
Step 6: Repeat until list is sorted
Step 7: Stop

Program:

Sasi Institute of Technology & Engineering{A} Page 94


Programming for Problem Solving Lab

Sasi Institute of Technology & Engineering{A} Page 95


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 96


Programming for Problem Solving Lab

8 c) Aim: To write and execute a C program to check given matrix is symmetric or not.
Description: This Program is used to check whether the given matrix is symmetric or not
Algorithm
Step 1: Start
Step 2: Input the matrix from the user
Step 3: Find the transpose of the matrix
Step 4: If the input matrix and its transpose matrix are same, then the matrix is symmetric
otherwise not
Step 5: Stop

Program:

Sasi Institute of Technology & Engineering{A} Page 97


Programming for Problem Solving Lab

Output 1:

Output 2:

Sasi Institute of Technology & Engineering{A} Page 98


Programming for Problem Solving Lab

8d) Aim: To write and execute a C program to implement the following string operations with and
without library functions.
i) copy ii) concatenate iii) length iv) compare

Description: This Program is used to implement different operations on strings like copy,
concatenate, length and compare with and without library functions.

8 d i) Copy string with library function


Algorithm:
Step 1: Start
Step 2: Declare two-character arrays
Step 3: Read the input string in one character array
Step 4: Copy the input string into another character array using strcpy() function
Step 5: Display string
Step 6: Stop
Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 99


Programming for Problem Solving Lab

Copy string without library function


Algorithm:
Step 1: Start
Step 2: Declare two character arrays a1,a2
Step 3: Read the input string in one character array a1
Step 4: Initialize length=0
Step 5: Repeat upto step6 while a1[length]!=NULL
a2[length]=a1[length]
Step 6: Increment length by 1
Step 7: a2[length]=NULL
Step 8: print the resultant string a2
Step 9: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 100


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 101


Programming for Problem Solving Lab

8d ii) concatenate string with library function


Algorithm:
Step 1: Start
Step 2: Declare two-character arrays
Step 3: Read the first string
Step 4: Read the second string
Step 5: Concatenate two string using strcat() function
Step 6: Display the concatenated string
Step 7: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 102


Programming for Problem Solving Lab

Output1:

Output2:

Concatenate string without library function Algorithm:


Step1: Start
Step2: Declare two character arrays s1,s2
Step3: Initialize i=0,j=0
Step4: Read the two strings s1 and s2
Step5: Repeat upto step6 while s1[i]!=NULL
Step6: Increment i by i+1
Step7: Repeat upto step9 while s2[j]!=NULL
Step8: s1[i]=s2[j]
Step9: Increment j by j+1 and i by i+1
Step10: s1[i]=NULL
Step11: Print the concatenated string s1
Step12: Stop

Sasi Institute of Technology & Engineering{A} Page 103


Programming for Problem Solving Lab

Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 104


Programming for Problem Solving Lab

8 d iii) calculating string length with library function


Algorithm:
Step 1: Start
Step 2: Declare character array a, length variable
Step 3: Read the string
Step 4: Find the length of the string using strlen() function and assign to length
Step 5: Print the length of the string
Step 6: Stop
Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 105


Programming for Problem Solving Lab

Calculating string length without library function


Algorithm:
Step 1: Start
Step 2: Declare character array a,i
Step 3: Read the string
Step 4: initialize i=0
Step 5: Repeat upto step6 while a[i]!=NULL
Step 6: Increment i by i+1
Step 7: Print the length of the string
Step 8: Stop
Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 106


Programming for Problem Solving Lab

8 d iv) String Comparison with library function


Algorithm:
Step 1: Start
Step 2: Declare two character arrays a1,a2
Step 3: Read the two strings
Step 4: if strcmp(a1,a2) is not equal to zero then goto step6
Step 5: print two strings are equal
Step 6: print two strings are not equal
Step 7: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 107


Programming for Problem Solving Lab

Output1:

Output2:

String Comparison without library function


Algorithm:
Step1: Start
Step2: Declare two character arrays a1,a2, temp
Step3: Read two strings
Step4: Initialize i=0
Step5: Repeat upto step9 until a1!=NULL
Step6: if a1[i] is not equal to a2[i] then goto step8
Step7: set temp=1
Step8: set temp=0
Step9: increment i by i+1
Step10: if temp value is not equal to one then goto step12
Step11: print two strings are same
Step12: print two strings are not same
Step13: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 108


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 109


Programming for Problem Solving Lab

Viva Questions:

1. What is a symmetric matrix?

2. What are the rules to be followed for matrix multiplication?

3. What is the difference between strcpy() and strcmp() ?

4. What are the different types of string handling functions?

5. What is the use of strcat() function?

Sasi Institute of Technology & Engineering{A} Page 110


Programming for Problem Solving Lab

Exercise – 9 Simple Functions


a) Write a C Program demonstrating the following function types
i. With arguments and with return value.
ii. With arguments and without return value
iii. Without arguments and without return value.
iv. Without arguments and with return value.
b) Write a C Program illustrating call by reference

9 a. Aim: To write and execute a C Program to demonstrate different types of functions with
reference to arguments and return type.
Description: This program is used to demonstrate different types of functions with reference to
arguments and return type.
9 a. i. With arguments and with return value.
Algorithm for main():
Step 1: Start
Step 2: Declare three variables a, b, c.
Step 3: Read the value of a, b.
Step 4: Call function sum(a,b).
Step 5: receive c value from sum()
Step 6: Print c value
Step 7: Stop
Algorithm for sum():
Step 1: Declare variable c;
Step 2: Perform the operation c=a+b.
Step 3: Return the value of c
Program:

Sasi Institute of Technology & Engineering{A} Page 111


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 112


Programming for Problem Solving Lab

9 a ii. With arguments and without return value


Algorithm for main ():
Step 1: Start
Step 2: Declare two variables x,y
Step 3: Read the values of x,y
Step 4: Call function maximum(x,y)
Step 5: Stop
Algorithm for maximum ():
Step 1: Declare two variables x,y
Step 2: if x is not greater than y then goto step4
Step 3: print x is the maximum
Step 4: print y is the maximum
Step 5: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 113


Programming for Problem Solving Lab

Output1:

Output2:

9 a iii. Without arguments and without return value.


Algorithm for main():
Step 1: Start
Step 2: call function read_value()
Step 3: Stop
Algorithm for read_value():
Step 1: Declare character array
Step 2: Read the string
Step 3: Print the string
Step 4: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 114


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 115


Programming for Problem Solving Lab

9 a iv. Without arguments and with return value.


Algorithm for main():
Step 1: Start
Step 2: Declare the variable sum
Step 3: call function total()
Step 4: receive x+y value from total and store in sum
Step 5: print sum value
Step 6: Stop
Algorithm for total():
Step 1: Declare two variables x,y
Step 2: Initialize x and y
Step 3: Perform the operation x+y
Step 4: Return the value of x+y
Program:

Sasi Institute of Technology & Engineering{A} Page 116


Programming for Problem Solving Lab

Output1:

Output2:

9 b. Aim: To write and execute a C Program to illustrate the concept of call by reference
Description: This program is used to understand the concept of call by reference.
Algorithm for main():
Step 1: Start
Step 2: Declare two variables x,y
Step 3: Read the values of x and y
Step 4: Print the values of x and y before swapping
Step 5: call the function swap(&x,&y)
Step 6: Print the values of x and y after swapping
Step 7: Stop
Algorithm for swap():
Step 1: Declare two pointer variables *a and *b and temp
Step 2: Assign t=*a
Step 3: Assign *a=*b
Step 4: Assign *b=t

Sasi Institute of Technology & Engineering{A} Page 117


Programming for Problem Solving Lab

Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 118


Programming for Problem Solving Lab

Viva Questions:

1. What is a function? Explain types of functions

2. What is the use of return keyword in functions?

3. What is the difference between call by value and call by reference?

4. What are predefined functions? Explain with an example?

5. What is the use of function prototype?

Sasi Institute of Technology & Engineering{A} Page 119


Programming for Problem Solving Lab

Exercise – 10 Recursive Functions


Write a C Program illustrating the following with Recursion and without Recursion
a) Factorial b) GCD c) Power d) Fibonacci
Aim: To Write and execute a C program for the following using recursion and without using
Recursion
Description:
This program is used to implement factorial, GCD, Power and Fibonacci series using recursion
and without recursion
10 a) Factorial using recursion:
Algorithm for main ()
Step 1: Start
Step 2: Declare a variable n.
Step 3: Display Enter a number.
Step 4: Read the value of n.
Step 5: Call function fact(n).
Algorithm for fact()
Step 1: Check if n=0 then return 1.
Step 2: If n not equal to 0 then perform the recursive function (n*fact(n-1)).
Step 3: Display the final result factorial of given number.
Step 4: End
Program:

Sasi Institute of Technology & Engineering{A} Page 120


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 121


Programming for Problem Solving Lab

10 a) Factorial without using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare a variable n.
Step 3: Display Enter a number.
Step 4: Read the value of n.
Step 5: Call function fact(n).
Step 6: Stop
Algorithm for fact()
Step 1: Declare f=1,i
Step 2: Check if n=0 or n=1 then return 1 goto step 6
Step 3: If n not equal to 0
Step 4: for(i=1;i<=n;i++) if condition is false goto step 6
Step 4.1: calculate f=f*i
Step 5: Display the final result factorial of given number.
Program:

Sasi Institute of Technology & Engineering{A} Page 122


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 123


Programming for Problem Solving Lab

10 b) GCD Using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare variables num1,num2,gcd
Step 3: Read the values of num1 and num2
Step 4: call the function gcd(num1,num2)
Step 5: Store the return value in gcd and print the result
Step 6: Stop
Algorithm for gcd()
Step 1: Declare two variables a and b
Step 2: Check if b is equal to 0 then return a
Step 3: if b is not equal to 0 then perform recursive function gcd(b,a%b)
Program:

Sasi Institute of Technology & Engineering{A} Page 124


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 125


Programming for Problem Solving Lab

10 b) GCD without using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare two integer numbers num1, num2
Step 3: Read the values of num1 and num2
Step 4: call the function gcd(num1,num2)
Step 5: receive the denominator and print
Step 6: Stop
Algorithm for gcd()
Step 1:Declare a variable rem, numerator, denominator
Step 2: if num1 is not greater than num2 then goto step4
Step 3: numerator=num1, denominator=num2
Step 4: numerator=num2, denominator=num1
Step 5: compute remainder=numerator%denominator
Step 6: Repeat until the remainder is not equal to zero and perform the following
Step 6.1: numerator=denominator
Step 6.2: denominator=remainder
Step 6.3: remainder=numerator%denominator
Step 7: return the value of denominator
Program:

Sasi Institute of Technology & Engineering{A} Page 126


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 127


Programming for Problem Solving Lab

10 c) Calculating Power using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare two variables base, expo
Step 3: Read the base, exponent
Step 4: Call the function power(base,expo)
Step 5: receive the return value from power()
Step 6: print the value
Step 7: Stop
Algorithm for power()
Step 1: check if exponent is equal to zero then return 1
Step 2: check if exponent is greater than zero then perform recursive function
base*power(base,expo-1) otherwise 1/power(base,-expo)

Program:

Sasi Institute of Technology & Engineering{A} Page 128


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 129


Programming for Problem Solving Lab

10 c) Calculating Power without using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare two variables base, exponent
Step 3: Read the base, exponent
Step 4: Call the function power(base,exponent)
Step 5: receive the return value result from function
Step 6: Print the result
Step 7: Stop

Program:

Sasi Institute of Technology & Engineering{A} Page 130


Programming for Problem Solving Lab

Output1:

Output2:

10 d) Fibonacci using recursion: Algorithm for main():


Step 1: Start
Step 2: Declare two variables n, i.
Step 3: Display Enter a number.
Step 4: Read the value of n.
Step 5: Check for(i=0;i<n;i++).
Step 6: Call the function fib(i).
Step 7: Stop
Algorithm for fib():
Step 1: Declare four variables a, b, c and i=2.
Step 2: Check if n<=1 then return n value.
Step 3: Otherwise return (fib(n-1)+fib(n-2)).
Step 4: Print the Fibonacci series.

Sasi Institute of Technology & Engineering{A} Page 131


Programming for Problem Solving Lab

Program:

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 132


Programming for Problem Solving Lab

10 d) Fibonacci without using recursion:


Algorithm for main()
Step 1: Start
Step 2: Declare two variables n, i.
Step 3: Display Enter a number.
Step 4: Read the value of n.
Step 5: Check for(i=0;i<n;i++).
Step 6: Call the function fib(i).
Step 7: Stop

Algorithm for fib():


Step 1: Declare four variables a, b, c and i=2.
Step 2: Check if n<=1 then return n value.
Step 3: Otherwise initialize a=0, b=1.
Step 4: Check while(i<=n).
Step 5: Perform the operations c=a+b, a=b, b=c, i+1..
Step 6: Return the value of c.
Step 7: Print the Fibonacci series.

Program:

Sasi Institute of Technology & Engineering{A} Page 133


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 134


Programming for Problem Solving Lab

Viva Questions:

1. Explain what is recursion?

2. What is the difference between recursion and iteration?

3. What is the difference between direct and indirect recursion?

4. Write a recursive function to print 1 to 100?

5. What is tail recursion?

Sasi Institute of Technology & Engineering{A} Page 135


Programming for Problem Solving Lab

Exercise 11 Pointers and structures


a) Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc () function.
b) Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using calloc () function.
Note: Understand the difference between the above two programs.
c) Write a C Program to read and print student details using structures.

11 a) Aim: To write and execute a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using malloc () function.
Description:
This program is used find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.
Algorithm:
Step 1: Start
Step 2: Declare pointer variable *s, i, n
Step 3: Initialize sum=0
Step 4: Enter size of the list
Step 5: Read n
Step 6: Assign memory to pointer variable s by using malloc() library method
Step 7: Enter elements into the array
Step 8: read s+i
Step 9: Repeat steps 10 to 11
Step 10: Set sum=sum + pointer of (s+i)
Step 11: Set i = i+1(end of the loop)
Step 12: print the sum value
Step 13: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 136


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 137


Programming for Problem Solving Lab

11 b) Aim: To write and execute a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using calloc () function.
Description:
This program is used find sum of n elements entered by user. To perform this program, allocate
memory dynamically using calloc() function.
Algorithm:
Step 1: Start
Step 2: Declare pointer variable *s, i, n
Step 3: Initialize sum=0
Step 4: Enter size of the list
Step 5: Read n
Step 6: Assign memory to pointer variable s by using calloc() library method
Step 7: Enter elements into the array
Step 8: read s+i
Step 9: Repeat steps 10 to 11
Step 10: Set sum=sum + pointer of (s+i)
Step 11: Set i =i+1(end of the loop)
Step 12: print the sum value
Step 13: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 138


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 139


Programming for Problem Solving Lab

11 c) Aim: To write and execute a C program to read and print student details using structures.
Description: This program is used to read and print student details using structures.
Algorithm:
Step 1: Start
Step 2: Read no. of students: n
Step 3: Read name, branch, register no., and fee amount of n students using structure
Step 4: Print name, branch, register no., and fee amount of n students using structure
Step 5: Exit

Program:

Sasi Institute of Technology & Engineering{A} Page 140


Programming for Problem Solving Lab

Output1:

Output2:

Sasi Institute of Technology & Engineering{A} Page 141


Programming for Problem Solving Lab

Viva Questions
1. Explain the need of dynamic memory management functions ?

2. Explain the difference between malloc() and calloc() ?

3. Explain the advantages of using realloc() ?

4. Explain the difference between malloc() and free() ?

5. Define Structure?

Sasi Institute of Technology & Engineering{A} Page 142


Programming for Problem Solving Lab

Exercise 12 File Operations


a) Write a C program to open a file and to print it contents on screen.
b) Write a C program to copy files
c) Write a C program merges two files onto a new file.
d) Write a C program to delete a file.

12 a) Aim: To write and execute a C program to open a file and to print it contents on screen.
Description: This program is used to open a file and to print it contents on screen.
Algorithm:
Step 1: start
Step 2: declare file pointer
Step 3: declare s [100], fname[20]
Step 4: read source name
Step 5: open a file in read mode
Step 6: if there is no such file then
Step 6.1: print “Error in opening file”
Step 7: while(fgets(s, 99, fp)!=NULL)
Step 8: Print file
Step 9: stop
Program:

Sasi Institute of Technology & Engineering{A} Page 143


Programming for Problem Solving Lab

Output:

Sasi Institute of Technology & Engineering{A} Page 144


Programming for Problem Solving Lab

12 b) Aim: To write and execute a C program to copy files


Description: This program is used to copy the contents of one file into another file
Algorithm:
Step 1: start
Step 2: declare file pointers fs,fd
Step 3: declare source [20], dest [20]
Step 4: read source name
Step 5: read destination name
Step 6: open a file in read mode
Step 7: if there is no such file then
Step 7.1: print “source file not found”
Step 8: open another file in write mode
Step 9: if there is no such file then
Step 9.1: print “destination file cannot be opened”
Step 10: repeat Step10.1 while ((ch=fgetc (fs))! =EOF)
Step 10.1: fputc (ch, fd)
Step 11: close the source file
Step 12: close the destination file
Step 13: Stop
Program:

Sasi Institute of Technology & Engineering{A} Page 145


Programming for Problem Solving Lab

Output:

Sasi Institute of Technology & Engineering{A} Page 146


Programming for Problem Solving Lab

12 c) Aim: To write and execute a C program to merges two files onto a new file.
Description: This program is used to merge the contents of two files and copy the contents into a
new file
Algorithm:
Step 1: Stop
Step 2: Read two files
Step 3: transfer the contents of file1 to file3
Step 4: transfer the contents of file2 to file3
Step 5: print file3
Step 6: stop
Program:

Sasi Institute of Technology & Engineering{A} Page 147


Programming for Problem Solving Lab

Output:

12 d) Aim: To write and execute a C program to delete a file.


Description: This program is used to delete a file.
Algorithm:
Step 1: start
Step 2: declare a file
Step 3: Read file to delete
Step 4: use remove macro to delete file.( status=remove(fname);
Step 5: if
(status==0)
Step 5.1 File
deleted. Step
6: else
Step 6.1: Unable to delete file
Step 7: Stop

Sasi Institute of Technology & Engineering{A} Page 148


Programming for Problem Solving Lab

Program:

Output:

Sasi Institute of Technology & Engineering{A} Page 149


Programming for Problem Solving Lab

Viva Questions

1. Define file? Explain about file basic operations?

2. What are the file handling functions that are used for reading contents from a file?

3. What are the file handling functions that are used for writing contents to a file?

4. What is the use of FEOF?

5. What are the file modes available in C language?

*****

Sasi Institute of Technology & Engineering{A} Page 150

You might also like