PPS Lab Manual 2022-23 Document
PPS Lab Manual 2022-23 Document
Prepared by
MAnanthaLakshmi D Sowmya
Assistant Professor Assistant Professor
--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.
First, we would like to thank Mr. M Narendra Krishna, Vice- Chairman, Sasi
Institute of Technology and Engineering, for his everlasting support.
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:
LIST OF EXPERIMENTS:
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.
*****
Index
*****
Programming for Problem Solving Lab
1a) Familiarization of CODE BLOCKS C++ Editor to edit, compile, execute, test and
debugging C programs
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".
under CodeBlocks, you can only debug your program under a project - single-file program (in
previous section) debugging is not supported.
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
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!".
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
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!
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).
b) Familiarization of RAPTOR Tool to draw flow charts and understand flow of control.
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
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.
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.
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:
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).
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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
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
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
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
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:
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.
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.
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.
Viva Questions:
4. What are the commands used in linux for creating a program, compiling and
executing?
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:
Program:
Output 1:
Output 2:
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
Program:
Output 1:
Output 2:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
Viva Questions:
1. What are input function and output function?
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.
Program:
Output1:
Output2:
Program:
Output1:
Output2:
Program:
Output 1:
Output 2:
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.
Flowchart:
Program:
Output 1:
Output 2:
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
Flowchart:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
Viva Questions:
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
Flowchart:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
Program:
Output 1:
Output 2:
Viva Questions
1. What is the difference between entry-controlled loop and exit controlled loop?
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:
Program:
Output 1:
Output 2:
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:
Program:
Output 1:
Output 2:
Flowchart:
Program:
Output 1:
Output 2:
Viva Questions:
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:
Program:
Output 1:
Output 2:
Flowchart:
Program:
Output 1:
Output 2:
Flowchart:
Program:
Output 1:
Output 2:
Viva Questions
1. Explain nested loops with an example?
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
Program:
Output 1:
Output 2:
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:
Output 1:
Output 2:
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:
Output:
Viva Questions:
1. What is an array?
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:
Output 1:
Output 2:
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:
Output 1:
Output 2:
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:
Output 1:
Output 2:
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.
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Program:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Viva Questions:
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:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
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
Program:
Output1:
Output2:
Viva Questions:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Output1:
Output2:
Program:
Output1:
Output2:
Program:
Output1:
Output2:
Program:
Output1:
Output2:
Program:
Output1:
Output2:
Viva Questions:
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:
Output1:
Output2:
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:
Output1:
Output2:
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:
Output1:
Output2:
Viva Questions
1. Explain the need of dynamic memory management functions ?
5. Define Structure?
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:
Output:
Output:
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:
Output:
Program:
Output:
Viva Questions
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?
*****