Académique Documents
Professionnel Documents
Culture Documents
LABORATORY MANUAL
For
2015-2016
References:
1. “How to Solve it by Computer”, R.G. Dromey, Pearson.
2. “The C Programming Language”, Brian W. Kernighan, Dennis M. Ritchie, Pearson.
3. “Let us C”, Yeswant Kanetkar, BPB publications
4. “Pointers in C”, Yeswant Kanetkar, BPB publications.
5. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A.Ananda Rao,
Pearson Education.
Outcomes:
Apply problem solving techniques to find solutions to problems
Able to use C language features effectively and implement solutions using C language.
CONTENTS
25 Write a program to read a set of strings and sort them in alphabetical order.
Write a program to read two strings and perform the following operations
without using builtin string Library functions and by using your own
26
implementations of functions. i. String length determination ii .Compare Two
Strings iii. Concatenate them, if they are not equal iv. String reversing.
Write programs using recursion for finding Factorial of a number, GCD, LCM,
27
and solving Towers of Hanoi problem.
Write a program to find the square root of a number without using built-in
32
library function.
Write a program to express a four digit number in words. For example 1546
36
should be written as one thousand five hundred and forty six.
Write a program to generate a telephone bill. The contents of it and the rate
37 calculation etc should be as per BSNL rules. Student is expected to gather the
required information through the BSNL website.
38
Write a program to find the execution time of a program.
Design a file format to store a person's name, address, and other information.
39
Write a program to read this file and produce a set of mailing labels.
AIM:- To Practice a DOS and LINUX Commands necessary for design of C Programs
DOS commands:
Summary:
cd <directory name> -- cd is the basic DOS command, it allows you to change directory
dir [name of directory] -- dir allows you to list all contents of the specified directory
edit <filename> -- Opens the default DOS editor to allow modification of a specified file
This tutorial gives you an opportunity to try basic MS-DOS commands. By following the
procedures in this section, you will learn to:
When you first turn on your computer, you will see some cryptic information flash by. MS-DOS
displays this information to let you know how it is configuring your computer. You can ignore it for now.
When the information stops scrolling past, you'll see the following:
C:\>
This is called the command prompt or DOS prompt. The flashing underscore next to the
command prompt is called the cursor. The cursor shows where the command you type will appear.
Typing a Command
This section explains how to type a command at the command prompt and demonstrates the "Bad
command or file name" message.
1. Type the following at the command prompt (you can type the command in either uppercase or
lowercase letters ):
nul
If you make a typing mistake, press the BACKSPACE key to erase the mistake, and then try again.
2. Press ENTER.
The "Bad command or file name" message appears when you type something that MSDOS does
not recognize. Because nul is not a valid MS-DOS command, MS-DOS displays the "Bad command or
file name" message.
ver
In this section, you will view the contents of a directory by using the dir command. The dir command
stands for "directory."
dir :- A list of the files in the WINDOWS directory appears, but scrolls by too quickly to read. You can
modify the dir command so that it displays only one screen of information at a time.
Directory of C:\
This is called a directory list. A directory list is a list of all the files and subdirectories that a
directory contains. In this case, you see all the files and directories in the main or root directory of your
drive. All the files and directories on your drive are stored in the root directory.
dir
dir /p
One screen of information appears. At the bottom of the screen, you will see the following message:
When you typed the dir command this time, you included the /p switch after the command. A switch
modifies the way MS-DOS carries out a command. Generally, a switch consists of a forward slash (/) that
is followed by one or more letters or numbers.
When you used the /p switch with the dir command, you specified that MS-DOS should pause after it
displays each screen of directory list information. The p actually stands for
"page"
Another helpful switch you can use with the dir command is the /w switch. The /w switch indicates that
MS-DOS should show a wide version of the directory list.
dir /w
The directory list appears, with the filenames listed in wide format. Note that only filenames are listed.
No information about the files' size or date and time of creation appears.
2. If the directory contains more files than will fit on one screen, you can combine the /p and /w switches
as follows:
dir /w /p
Next, you will change from the DOS directory to the root directory. The root directory is the directory
you were in before you changed to the DOS directory. Before you begin this section, make sure your
command prompt looks like the following:
C:\DOS>
cd \
Note : that the slash you type in this command is a backslash (\), not a forward slash (/).
No matter which directory you are in, this command always returns you to the root directory of a
drive. The root directory does not have a name. It is simply referred to by a backslash (\).
C:\>
Changing Directories
Look at the list on your screen. All the names that have <DIR> beside them are directories. You
can see a list of the files in another directory by changing to that directory, and then using the dir
command again. In this case, you will change to the DOS directory. Before you begin this section, make
sure you have a directory named DOS by carrying out the following procedure.
1.If you do not see a line in the directory list indicating that you have a directory named Windows, type
the following at the command prompt:
dir /s Windows
You will see a message that includes a line such as the following:
Directory of C:\DIRNAME
To change directories, you will use the cd command. The cd command stands for "change directory."
cd windows
The command prompt changes. It should now look like the following:
C:\WINDOWS>
Next, you will use the dir command to view a list of the files in the DOS directory.
2Make a Directory
Creates a directory.
MKDIR creates any intermediate directories in the path, if needed. For example, assume \a does not exist
then:
4(a)Creating a Directory
In this section, you will create two directories. Creating a directory is helpful if you want to organize
related files into groups to make them easy to find. Before you begin this section, make sure the
command prompt looks like the following:
C:\>
To create a directory, you will use the md command. The md command stands for "make directory."
md fruit
You have now creat ed a directory named FRUIT. You won't see the new FRUIT directory until you carry
out the dir command in the next step.
2. To confirm that you successfully created the FRUIT directory, type the following at the command
prompt:
dir
or
dir /p
Look through the directory list. A new entry somewhere in the list should look
3. To change to the new FRUIT directory, type the following at the command
prompt:
cd fruit
C:\FRUIT>
You will now create a directory within the FRUIT directory, named GRAPES.
md grapes
You will not see the new GRAPES directory until you carry out the dir command in the
I.KAVITHA JACKLEEN M.Tech
11
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
next step.
2. To confirm that you successfully created the GRAPES directory, type the following at the
command prompt:
dir
Directory of C:\FRUIT
3 file(s) 0 bytes
Note that there are three entries in the FRUIT directory. One is the GRAPES directory that you just
created. There are two other entries---one looks like a single period (.) and the other looks like a double
period (..). These directory entries are important to MSDOS, but you can ignore them. They appear in
every directory and cont ain information
The GRAPES directory is a subdirectory of the FRUIT directory. A subdirectory is a directory within
another directory. Subdirectories are useful if you want to further subdivide information.
3. To change to the GRAPES directory, type the following at the command prompt:
cd grapes
C:\FRUIT\GRAPES>
cd ..
C:\FRUIT>
When the cd command is followed by two periods (..), MS-DOS moves up one level in the directory
structure. In this case, you moved up one level from the GRAPES directory to the FRUIT directory.
If you no longer use a particular directory, you may want to delete it to simplify your directory structure.
Deleting a directory is also useful if you type the wrong name when you are creating a directory and you
want to delete the incorrect
directory before creating a new one. In this section, you will delete the GRAPES directory. Before you
begin this
section, make sure the command prompt looks like the following:
C:\FRUIT>
To delete a directory, use the rd command. The rd command stands for "remove
directory."
rd grapes
2. To confirm that you successfully deleted the GRAPES directory, type the following at the command
prompt:
dir
Note You cannot delete a directory if you are in it. Before you can delete a directory, you must make the
directory that is one level higher the current directory. To do this, type cd.. at the command prompt.
5Changing Drives
This section describes how to change drives. Changing drives is useful if you want to work with files that
are on a different drive. So far, you have been working with drive C. You have other drives you can use to
store information. For example, drive D.
following:
C:\FRUIT>
d:
D:\>
I.KAVITHA JACKLEEN M.Tech
13
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
c:\> cd Fruit
C:\FRUIT>
When you type a drive letter followed by a colon, you change to that drive. The drive letter that appears
in the command prompt shows which drive is the current drive.
dir c:\windows
A list of the files in the DOS directory on drive C should scroll past on your screen.
6Copying Files
This section describes how to copy a single file and a group of files. Copying files creates a duplicate of
the original file and does not remove the original file. This is useful for many reasons. For example, if
you want to work on a document at home, you can copy it from your computer at work to a floppy disk
and then take the floppy disk home. To copy a file, you will use the copy command. When you use the
copy command, you must include two parameters. The first is the location and name of the file you want
to copy, or the source. The second is the location to which you want to copy the file, or the destination.
You separate the source and destination with a space. The copy command follows this pattern:
syntax:
In this section, you will copy the notepad.exe files from the WINDOWS directory to the FRUIT
directory. You will specify the source and destination of these files in two different ways. The difference
between the two methods is explained at the end of this section. Before you begin this section, make sure
the command prompt looks like the following:
C:\FRUIT>
To copy the NOTEPAD.EXE files from the WINDOWS directory to the FRUIT directory
1. Return to the root directory by typing the following at the command prompt:
cd\
C:\>
Change to the DOS directory by typing the following at the command prompt:
cd windows
C:\WINDOWS>
2. Make sure the file you are going to copy, NOTEPAD.EXE, is located in the WINDOWS directory by
using the dir command followed by a filename.
dir notepad.exe
3. To copy the NOTEPAD.EXE file from the WINDOWS directory to the FRUIT directory, type the
following at the command prompt:
ex:
1 file(s) copied
4. To confirm that you copied the files successfully, view the contents of the FRUIT directory by typing
the following at the command prompt:
dir \fruit
7Renaming Files
This section explains how to rename files. You may want to rename a file if the information in it changes
or if you decide you prefer another name.
To rename a file, you will use the ren command. The ren command stands for "rename." When you use
the ren command, you must include two parameters. The first is the file you want to rename, and the
second is the new name for the file. You separate the two names with a space. The ren command follows
this pattern:
• Renaming a File
C:\FRUIT>
1. To rename the NOTEPAD.EXE file to PADNOTE.TXT, type the following at the command prompt:
2. To confirm that you renamed the file successfully, type the following at the command prompt:
dir
8Deleting Files
This section explains how to delete, or remove, a file that you no longer want on your disk. If you don’t
have very much disk space, deleting files you no longer use is essential.
To delete a file, you will use the del command. The del command stands for "delete."
• Deleting a File
In this section, you will delete two files using the del command.
Before you begin, make sure your command prompt looks like the following:
C:\FRUIT>
1. Delete the PADNOTE.TXT file by typing the following at the command prompt:
del PADNOTE.TXT
2. To confirm that you deleted the files successfully, type the following at the command prompt:
dir
Before you begin this section, make sure your command prompt looks like the following:
C:\FRUIT>
To delete files in the current directory that end with the extension OLD by using wildcards
1. View all files that end with the extension OLD by typing the following at the command prompt:
dir *.old
2. Delete all files ending with OLD by typing the following at the command prompt:
del *.old
3. To confirm that all the files with the extension OLD have been deleted, type the following at the
command prompt:
dir
Now that the FRUIT directory is empty, you can delete it by using the rd (remove directory) command
that
9Developing C program
Use Command called tc for Turboc IDE
C:\>cd FRUIT
C:\Fruit\>tc
Linux commands:
Basic File handling commands:
1. mkdir – make directories
I.KAVITHA JACKLEEN M.Tech
17
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
Usage: mkdir [OPTION] DIRECTORY...
eg. mkdir ece
2. ls – list directory contents
Usage: ls [OPTION]... [FILE]...
eg. ls ece, ls l ece, ls
3. pwd print name of current working directory
Usage: pwd
4. cd – changes directories
Usage: cd [DIRECTORY]
eg. cd ece
5. cp – copy files and directories
Usage: cp [OPTION]... SOURCE DEST
eg. cp sample.txt sample_copy.txt
cp sample_copy.txt target_dir
6. mv – move (rename) files
Usage: mv [OPTION]... SOURCE DEST
eg. mv source.txt target_dir
mv old.txt new.txt
7. rm remove files or directories
Usage: rm [OPTION]... FILE...
eg. rm file1.txt , rm rf some_dir
8. find – search for files in a directory hierarchy
Usage: find [OPTION] [path] [pattern]
eg. find file1.txt, find name file1.txt
9. history – prints recently used commands
Usage: history
10. vi – Visual editor, a programmers text editor
Usage: vi [OPTION] [file]...
eg. vi file1.txt
Getting Started with C :
Towards Running a C program
To begin with, a C program has to be prepared in two stages
i. Firstly, the program is written in a file using an editor (vi in our case). This form of the program is
called the source program (or source text), and it is not possible to execute this file as is.
ii. Secondly, the completed source file is passed to a compiler – a program which generates a new file
containing a machine code translation of the source text. This file is called as object file or executable
file. The executable file is said to have been compiled from the source text.
Each instruction in a C program is written as a separate statement, ending with a semicolon. These
statements must appear in the same order in which we wish them to be executed; unless the logic of the
problem demands transfer of control to a statement which is out of sequence. [If you don’t understand
this last statement it is alright!]
Your First C Program
Step #1: Typing the program
1(a) Using the vi editor create a file called prog1.c
:w <filename> To save the contents in the screen (buffer) into the file
If the program has any errors/mistakes, those will get listed. Most of the times, the error messages also
contain the exact line number where we have made the mistake. Errors at this stage would be primarily
because of incorrect usage of the syntax (bad typing of the code), these errors are known as syntax errors.
Look at the given program carefully and correct errors, if any.
If there are no errors, you are ready to see the result of compilation. As already mentioned, the result of
successful compilation should have generated an output file. This output file is called a.out. You can see
this file by typing the “ls” command.
Step #3: Executing the C program
Now we have an output file, a.out ready. To make our machine execute the instructions in the a.out file,
the following command is typed.
[user@localhost: Lab2] $./a.out
Note carefully the usage: we are referring to the current directory ‘.’ and then instructing the computer to
execute the file named ‘a.out’ in the current directory.
a.out is default name of the output file, but you can name the output file by using –o when compiling
your .c file.
Method 2:
[user@localhost: Lab2] $gcc –o exefile prog1.c
use ls command to see the file exefile existed or not.
Now execute your program as below
[user@localhost: Lab2] $./exefile
AIM: To Study of the Editors, Integrated development environments, and Compilers in chosen
Editors:
Definition :A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages, and can be
used to change configuration files and programming language source code.
Plain text files vs. word processor files
There are important differences between plain text files created by a text editor and document files
created by word processors such asMicrosoft Word, WordPerfect, and OpenOffice.org.
A plain text file uses a simple character set such as ASCII to represent numbers, letters, and a
small number of symbols. The onlynon-printing characters in the file that can be used to format the
text, are newline, tab, and formfeed.
Word processor documents generally contain formatted text, such as enabling text to appear in
boldface and italics, to use multiplefonts, and to be structured into columns and tables. These
capabilities were once associated only with desktop publishing, but are now available in the simplest
word processor.
Web pages are plain text, with HTML tags to achieve formatting.
Word processors were developed to allow formatting of text for presentation on a printed page, while text
produced by text editors is generally used for other purposes, such as input data for a computer program.
When both formats are available, the user must select with care. Saving a plain text file in a word-
processor format will add formatting information that could disturb the machine-readability of the text.
Saving a word-processor document as a text file will lose formatting information.
Types of text editors :
1) Small and Simple Text Editors:,
Under Microsoft Windows systems come with the simpleNotepad, though many people—
especially programmers—prefer another Windows text editor with more features.
Under Apple Macintosh's classic Mac OS there was the native SimpleText, which was replaced
under Mac OS X by TextEdit, which merges features of a text editor with those of a word
processor such as rulers, margins and multiple font selection.
2) A Text editor with complex functions :
In Unix-like operating systems have the
a) vi editor (or a variant)
b) Emacs editor.
3) Dual operating modes editors: It can allow either a text editor or a word processor., Such
as WordStar
1. String searching algorithm – search string with a replacement string. Different methods are
employed, Global(ly) Search And Replace, Conditional Search and Replace, Unconditional
Search and Replace.
2. Cut, copy, and paste – most text editors provide methods to duplicate and move text within the
file, or between files.
3. Text formatting – Text editors often provide basic formatting features like line wrap, auto-
indentation, bullet list formatting, comment formatting, and so on.
4. Undo and redo – As with word processors, text editors will provide a way to undo and redo the
last edit. Often—especially with older text editors—there is only one level of edit history
remembered and successively issuing the undo command will only "toggle" the last change.
Modern or more complex editors usually provide a multiple level history such that issuing the
undo command repeatedly will revert the document to successively older edits. A separate redo
command will cycle the edits "forward" toward the most recent changes. The number of changes
remembered depends upon the editor and is often configurable by the user.
5. Data transformation – Reading or merging the contents of another text file into the file currently
being edited. Some text editors provide a way to insert the output of a command issued to the
operating system's shell.
7. Filtering – Some advanced text editors allow the editor to send all or sections of the file being
edited to another utility and read the result back into the file in place of the lines being "filtered".
This, for example, is useful for sorting a series of lines alphabetically or numerically, doing
mathematical computations, and so on.
1. Source code editors : are text editors with additional functionality to facilitate the production of
source code. These often feature user-programmable syntax highlighting, and coding tools or
keyboard macros similar to an HTML editor (see below).
2. Folding editors : This subclass includes so-called "orthodox editors" that are derivatives of Xedit.
The specialized version of folding is usually called outlining (see below).
3. IDEs (integrated development environments) : are designed to manage and streamline larger
programming projects. They are usually only used for programming as they contain many features
unnecessary for simple text editing.
4. World Wide Web authors are offered a variety of text editors dedicated to the task of web
development. These create the plain text files that deliver web pages.
HTML editors include: Dreamweaver, E Text Editor, Microsoft
FrontPage, HotDog, Homesite, Nvu, Tidy, and GoLive. Many offer the option of viewing a work
in progress on a built-in web browser. XML editors share many traits.
5. For Mathematicians, physicists, and computer scientists often produce articles and books
using TeX or LaTeX in plain text files.
6. Outliners( also called tree-based editors) :They combine a hierarchical outline tree with a text
editor. Folding (see above) can generally be considered a generalized form of outlining.
7. Simultaneous editing : It is a technique in End-user development research to edit all items in a
multiple selection. It allows the user to manipulate all the selected items at once through direct
manipulation. The Lapis text editor and the multi edit plugin for geditare examples of this
technique. The Lapis editor can also create an automatic multiple selection based on an example
item.
8. Distraction-free editors : provide a minimalistic interface with the purpose of isolating the writer
from the rest of the applications and operating system, thus being able to focus on the writing
alone.
IDE(Integrated Development Environment)
An integrated development environment (IDE) or interactive development environment is
a software application that provides comprehensive facilities to computer programmers for software
development.An IDE normally consists of a source code editor, build automation tools and adebugger.
Several modern IDEs integrate with Intelli-sense coding features.
Some IDEs contain a compiler, interpreter, or both, such as Net Beans and Eclipse; others do not,
such as SharpDevelop and Lazarus. The boundary between an integrated development environment and
other parts of the broadersoftware development environment is not well-defined. Sometimes a version
control system and various tools are integrated to simplify the construction of a GUI(Graphical User
Interface). Many modern IDEs also have a class browser, an object browser, and a class
hierarchy diagram, for use in object-oriented software development.
Some familiar IDEs for doing C-programming in windows and in linux environments are
given below:
Fig (a): Turbo c IDE in windows environment
Fig(b): Anjuta, a C and C++ IDE for the GNOME environment(LINUX Envrionment)
Compilers in chosen platform
1.1Compilation:
language) into an equivalent program in another language (the object or target language).
Compilation is a fundamental concept in the production of software: it is the link between the
(abstract) world of application development and the low-level world of application execution on
machines.
Compiler :
An important part of any compiler is the detection and reporting of errors.
On the other hand, a compiler need not target a real assembly (or machine) language.
Compilers translate source code into object code, which is unique for each type of computer.
many compilers are available for the same language. For example, there is a FORTRAN compiler for PCs
I.KAVITHA JACKLEEN M.Tech
27
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
and another for Apple Macintosh computers. In addition, the compiler industry is quite competitive, so
there are actually many compilers for each language on each type of computer. More than a dozen
companies develop and sell C compilers for the PC.
1.2Asse
mbler:
An assembler is also a type of translator, which converts Assembly program into Machine Program.
1.3 Interpreter:
An interpreter is closely related to a compiler, but takes both source program and input data.
The translation and execution phases of the source program are one and the same.
E.g. Java compilers generate code for a virtual machine called the “Java Virtual Machine” (JVM).
The JVM interpreter then interprets JVM instructions without any further translation.
The advantages of using an interpreter are that is easy to port a language to a new machine: all
one has to do is to implement the virtual machine on the new hardware. Also, since instructions are
evaluated and examined at run-time, it becomes possible to implement very flexible languages. E.g. for
an interpreter it is not a problem to support variables that have a dynamic type, something which is hard
to do in a traditional compiler. Interpreters can even construct “programs” at run time and interpret those
without difficulties, a capability that is available e.g. for Lisp or Prolog.
compilation techniques to deal with the recognition and translation of many other types of
languages including:
• Natural languages;
The complete process of compilation is illustrated (a) Expanding macros (shorthand notations for
as: longer constructs). For example, in C,
a = (3*a+b*(2+a))
#include "header.h"
2.1 Preprocessors:
is replaced by the contents of the file header.h
Preprocessing performs (usually simple) operations
on the source file(s) prior to compilation.Typical
preprocessing operations include:
A linker combines object code (machine code that has not yet been linked) produced from compiling and
assembling many source programs, as well as standard library functions and resources supplied by the
operating system. This involves resolving references in each object file to external variables and
procedures declared in other files.
2.3 Loaders:
Compilers, assemblers and linkers usually produce code whose memory references are made relative to
an undetermined starting location that can be anywhere in memory (relocatable machine code). A loader
calculates appropriate absolute addresses for these memory locations and amends the code to use these
addresses.
Cross Compiler :
A cross compiler is a compiler capable of creating executable code for a platform other than the
one on which the compiler is running. Cross compiler tools are used to generate executables
for embedded system or multiple platforms. It is used to compile for a platform upon which it is not
feasible to do the compiling, like microcontrollers that don't support an operating system. It has become
more common to use this tool for paravirtualization where a system may have one or more platforms in
use.
Not targeted by this definition are source to source translators, which are often mistakenly called
cross compilers.
The Canadian Cross is a technique for building cross compilers for other machines. Given three
machines A, B, and C, one uses machine A (e.g. running Windows XP on an IA-32 processor) to build a
cross compiler that runs on machine B (e.g. running Mac OS Xon an x86-64 processor) to create
executables for machine C (e.g. running Android on an ARM processor). When using the Canadian
Cross with GCC, there may be four compilers involved:
1) The proprietary native Compiler for machine A (1) (e.g. compiler from Microsoft Visual Studio)
is used to build the gcc native compiler for machine A (2).
2) The gcc native compiler for machine A (2) is used to build the gcc cross compiler from machine A
to machine B (3)
3) The gcc cross compiler from machine A to machine B (3) is used to build the gcc cross compiler
from machine B to machine C (4)
[Type the document title] [Year]
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a compiler
is often called a “cross-compiler”.
On the other hand, a compiler need not target a real assembly (or machine) language.
A plain text file uses a simple character set such as ASCII to represent numbers, letters, and a
small number of symbols. The onlynon-printing characters in the file that can be used to format the
text, are newline, tab, and formfeed.
Word processor documents generally contain formatted text, such as enabling text to appear in
boldface and italics, to use multiplefonts, and to be structured into columns and tables. These
capabilities were once associated only with desktop publishing, but are now available in the simplest
word processor.
Web pages are plain text, with HTML tags to achieve formatting.
Word processors were developed to allow formatting of text for presentation on a printed page, while text
produced by text editors is generally used for other purposes, such as input data for a computer program.
P.SRILATHA M.Tech
Departement of CSE 31
[Type the document title] [Year]
When both formats are available, the user must select with care. Saving a plain text file in a word-
processor format will add formatting information that could disturb the machine-readability of the text.
Saving a word-processor document as a text file will lose formatting information.
Types of text editors :
7) Small and Simple Text Editors:,
Under Microsoft Windows systems come with the simpleNotepad, though many people—
especially programmers—prefer another Windows text editor with more features.
Under Apple Macintosh's classic Mac OS there was the native SimpleText, which was replaced
under Mac OS X by TextEdit, which merges features of a text editor with those of a word
processor such as rulers, margins and multiple font selection.
8) A Text editor with complex functions :
In Unix-like operating systems have the
c) vi editor (or a variant)
d) Emacs editor.
9) Dual operating modes editors: It can allow either a text editor or a word processor., Such
as WordStar
10) Text editors for professional users : It can edit files of arbitrary sizes, such as log files or
unusually large texts, such as an entire dictionary placed in a single file.
11) Programmable editors:
e) It can be customized for specific uses. For example, Emacs can be customized by
programming in Lisp. Its Functionality is to make a text editor use the commands of another
text editor with which the user is more familiar.
f) An important group of programmable editors uses REXX as the scripting language. These
"orthodox editors" let the user open a "command line" into which commands and REXX
statements can be typed.
g) IBM's editor forVM/CMS. Among them are THE, KEDIT, SlickEdit, X2, Uni-edit, UltraEdit,
and SEDIT.
h) In Unix environment has vi derivatives such as Vim also support folding as well as macro
languages, and also have a command line.
12) A Text editors for software developers: It include source code syntax highlighting and
automatic completion to make programs easier to read and write.
Editor Features:
9. String searching algorithm – search string with a replacement string. Different methods are
employed, Global(ly) Search And Replace, Conditional Search and Replace, Unconditional
Search and Replace.
10. Cut, copy, and paste – most text editors provide methods to duplicate and move text within the
file, or between files.
P.SRILATHA M.Tech
Departement of CSE 32
[Type the document title] [Year]
11. Text formatting – Text editors often provide basic formatting features like line wrap, auto-
indentation, bullet list formatting, comment formatting, and so on.
12. Undo and redo – As with word processors, text editors will provide a way to undo and redo the
last edit. Often—especially with older text editors—there is only one level of edit history
remembered and successively issuing the undo command will only "toggle" the last change.
Modern or more complex editors usually provide a multiple level history such that issuing the
undo command repeatedly will revert the document to successively older edits. A separate redo
command will cycle the edits "forward" toward the most recent changes. The number of changes
remembered depends upon the editor and is often configurable by the user.
13. Data transformation – Reading or merging the contents of another text file into the file currently
being edited. Some text editors provide a way to insert the output of a command issued to the
operating system's shell.
15. Filtering – Some advanced text editors allow the editor to send all or sections of the file being
edited to another utility and read the result back into the file in place of the lines being "filtered".
This, for example, is useful for sorting a series of lines alphabetically or numerically, doing
mathematical computations, and so on.
16. Syntax highlighting – contextually highlights software code and other text that appears in an
organized or predictable format.
Specialised editors:
Some editors include special features and extra functions, for instance,
9. Source code editors : are text editors with additional functionality to facilitate the production of
source code. These often feature user-programmable syntax highlighting, and coding tools or
keyboard macros similar to an HTML editor (see below).
10. Folding editors : This subclass includes so-called "orthodox editors" that are derivatives of Xedit.
The specialized version of folding is usually called outlining (see below).
11. IDEs (integrated development environments) : are designed to manage and streamline larger
programming projects. They are usually only used for programming as they contain many features
unnecessary for simple text editing.
12. World Wide Web authors are offered a variety of text editors dedicated to the task of web
development. These create the plain text files that deliver web pages.
HTML editors include: Dreamweaver, E Text Editor, Microsoft
FrontPage, HotDog, Homesite, Nvu, Tidy, and GoLive. Many offer the option of viewing a work
in progress on a built-in web browser. XML editors share many traits.
13. For Mathematicians, physicists, and computer scientists often produce articles and books
using TeX or LaTeX in plain text files.
14. Outliners( also called tree-based editors) :They combine a hierarchical outline tree with a text
editor. Folding (see above) can generally be considered a generalized form of outlining.
P.SRILATHA M.Tech
Departement of CSE 33
[Type the document title] [Year]
15. Simultaneous editing : It is a technique in End-user development research to edit all items in a
multiple selection. It allows the user to manipulate all the selected items at once through direct
manipulation. The Lapis text editor and the multi edit plugin for geditare examples of this
technique. The Lapis editor can also create an automatic multiple selection based on an example
item.
16. Distraction-free editors : provide a minimalistic interface with the purpose of isolating the writer
from the rest of the applications and operating system, thus being able to focus on the writing
alone.
IDE(Integrated Development Environment)
An integrated development environment (IDE) or interactive development environment is
a software application that provides comprehensive facilities to computer programmers for software
development.An IDE normally consists of a source code editor, build automation tools and adebugger.
Several modern IDEs integrate with Intelli-sense coding features.
Some IDEs contain a compiler, interpreter, or both, such as Net Beans and Eclipse; others do not, such
as SharpDevelop and Lazarus. The boundary between an integrated development environment and other
parts of the broadersoftware development environment is not well-defined. Sometimes a version control
system and various tools are integrated to simplify the construction of a GUI(Graphical User Interface).
Many modern IDEs also have a class browser, an object browser, and a class hierarchy diagram, for use
in object-oriented software development.
Some familiar IDEs for doing C-programming in windows and in linux environments are
given below:
Fig (a): Turbo c IDE in windows environment
P.SRILATHA M.Tech
Departement of CSE 34
[Type the document title] [Year]
Fig(b): Anjuta, a C and C++ IDE for the GNOME environment(LINUX Envrionment)
P.SRILATHA M.Tech
Departement of CSE 35
[Type the document title] [Year]
1.1Compilation:
language) into an equivalent program in another language (the object or target language).
Compilation is a fundamental concept in the production of software: it is the link between the
(abstract) world of application development and the low-level world of application execution on
machines.
Compiler :
An important part of any compiler is the detection and reporting of errors.
P.SRILATHA M.Tech
Departement of CSE 36
[Type the document title] [Year]
5) The compiler derives its name from the way it works, looking at the entire piece of source code
and collecting and reorganizing the instructions.
6) Compiler differs from an interpreter, that which analyzes interpreter executes each line of source
code in succession, without looking at the entire program.
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a compiler
is often called a “cross-compiler”.
On the other hand, a compiler need not target a real assembly (or machine) language.
Compilers translate source code into object code, which is unique for each type of computer.
many compilers are available for the same language. For example, there is a FORTRAN compiler for
PCs and another for Apple Macintosh computers. In addition, the compiler industry is quite competitive,
so there are actually many compilers for each language on each type of computer. More than a dozen
companies develop and sell C compilers for the PC.
1.2Asse
mbler:
An assembler is also a type of translator, which converts Assembly program into Machine Program.
P.SRILATHA M.Tech
Departement of CSE 37
[Type the document title] [Year]
1.3 Interpreter:
An interpreter is closely related to a compiler, but takes both source program and input data.
The translation and execution phases of the source program are one and the same.
E.g. Java compilers generate code for a virtual machine called the “Java Virtual Machine” (JVM).
The JVM interpreter then interprets JVM instructions without any further translation.
The advantages of using an interpreter are that is easy to port a language to a new machine: all
one has to do is to implement the virtual machine on the new hardware. Also, since instructions are
evaluated and examined at run-time, it becomes possible to implement very flexible languages. E.g. for
an interpreter it is not a problem to support variables that have a dynamic type, something which is hard
to do in a traditional compiler. Interpreters can even construct “programs” at run time and interpret those
without difficulties, a capability that is available e.g. for Lisp or Prolog.
Although the above types of translator are the most well-known, we also need knowledge of
compilation techniques to deal with the recognition and translation of many other types of
languages including:
• Natural languages;
a = (3*a+b*(2+a))
#include "header.h"
2.1 Preprocessors: is replaced by the contents of the file header.h
P.SRILATHA M.Tech
Departement of CSE 39
2.2 Linkers:
A linker combines object code (machine code that has not yet been linked) produced from
compiling and assembling many source programs, as well as standard library functions and
resources supplied by the operating system. This involves resolving references in each object file to
external variables and procedures declared in other files.
2.3 Loaders:
Compilers, assemblers and linkers usually produce code whose memory references are made
relative to an undetermined starting location that can be anywhere in memory (relocatable machine
code). A loader calculates appropriate absolute addresses for these memory locations and amends
the code to use these addresses.
Cross Compiler :
A cross compiler is a compiler capable of creating executable code for a platform other than
the one on which the compiler is running. Cross compiler tools are used to generate executables
for embedded system or multiple platforms. It is used to compile for a platform upon which it is not
feasible to do the compiling, like microcontrollers that don't support an operating system. It has
become more common to use this tool for paravirtualization where a system may have one or more
platforms in use.
Not targeted by this definition are source to source translators, which are often mistakenly called
cross compilers.
The Canadian Cross is a technique for building cross compilers for other machines. Given
three machines A, B, and C, one uses machine A (e.g. running Windows XP on an IA-32 processor)
to build a cross compiler that runs on machine B (e.g. running Mac OS Xon an x86-64 processor) to
create executables for machine C (e.g. running Android on an ARM processor). When using the
Canadian Cross with GCC, there may be four compilers involved:
4) The proprietary native Compiler for machine A (1) (e.g. compiler from Microsoft Visual
Studio) is used to build the gcc native compiler for machine A (2).
5) The gcc native compiler for machine A (2) is used to build the gcc cross compiler from
machine A to machine B (3)
6) The gcc cross compiler from machine A to machine B (3) is used to build the gcc cross
compiler from machine B to machine C (4)
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a
compiler is often called a “cross-compiler”.
On the other hand, a compiler need not target a real assembly (or machine) language.
AIM : To Write, Edit, Debug, Compile and Execute Sample C programs to understand the
programming environment.
1Writing a Program:
A sample C program have to write in an Turbo C or Turbo C++ Editor for that
Keys are ALT+F+N
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf(“ Welcome to C Programming Lab“);
getch( );
}
After that save the program with keys ALT+F+S or F2
OUTPUT:
Welcome to C programming Lab_
2Editing the Program:
For editing a program first we have to open the program, for that use the following keys
ALT+F+O or F3
1) Here open your respect C- file from your respective directory.
2) Edit the program( adding or making changes where the error happens).
3Debug the Program:
Debugging is a methodical process of finding and reducing the number of bugs(errors).
The purpose of a debugger is to allow you to see what is going on inside your C program
while it runs.
A debugger is a computer program that lets you run your program, line by line and
examine the values of variables or look at values passed into functions and let you figure out
why it isn't running the way you expected it to.
Here we use Turbo c++ IDE or Turbo C IDE
Step 1:
First we have to add the variable to which you have to inspect the value for that we have to
use
Add watch(ALT+D+W+A or CTRL+F7)
Step 2:
For Inspecting the Program line by line use ALT+R+T or F7
4 Compiling the program :
Use the keys ALT+C+C or ALT+F9
5 Executing or Running the program(To see the output):
Use the keys ALT+R+R or CTRL+F9
if(a>b)
{
max=a;
}
else
{
max=b;
}
printf("The Maximum of 2 values is : %d", max);
getch();
}
OUTPUT:
4d)AIM: To read and print variable values of all data types of C language
Data type
Char Note Example
Name(data type)
Float(float) ‘f’ %f
is shown in the
'le' format: [-]d.ddde[+-]dd %le
Double(double)
'lf' is shown in the %lf, %4.7lf
format: [-]dddd.ddd
String(char
's' String Notation %s
name[size])
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i;
char c,str[11];
float f;
double d;
long L;
clrscr();
printf("Enter an Integer value ::");
scanf("%d",&i); //Here you can use %x in place of %d
printf("Enter a Long value ::");
scanf("%ld",&L);
printf("Enter a Float value ::");
scanf("%f",&f);
printf("Enter a Double value ::");
scanf("%lf",&d);
fflush(stdin);
printf("Enter a Character value ::");
scanf("%c",&c);
printf("Enter a String ::");
scanf("%s",str);
printf("\nInteger value is :: %d", i);
printf("\nLong Integer value is:: %ld", L);
printf("\nFloat value is :: %f", f);
printf("\nDouble value is :: %lf", d);
printf("\nCharacter value is :: %c",c);
printf("\nString value is :: %s", str);
getch( );
}
OUTPUT:
Enter an Integer value ::15
Enter a Long value ::236589
Enter a Float value ::3.2
Enter a Double value ::6.358954
Enter a Character value ::a
Enter a String ::california
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("size of char datatype :: %d\n", sizeof(char) );
printf("size of short datatype :: %d\n", sizeof(short) );
printf("size of int datatype :: %d\n", sizeof(int) );
printf("size of long datatype :: %d\n", sizeof(long) );
printf("size of float datatype :: %d\n", sizeof(float) );
printf("size of double datatype :: %d\n", sizeof(double) );
printf("size of long double datatype :: %d\n", sizeof(long double) );
getch();
}
OUTPUT:
size of char datatype :: 1
size of short datatype :: 2
size of int datatype :: 2
size of long datatype :: 4
size of float datatype :: 4
size of double datatype :: 8
size of long double datatype :: 10
4f) AIM: To understand the priority and associativity of Operators using Expressions.
#include <stdio.h>
#include<conio.h>
void main( )
{
int a = 20;
int b = 10;
Step 1: start
Step 3: d=b*b-4*a*c
Step 4: if(d>0)
(i)
(a) root1=(-b+sqrt(d))/(2*a)
(b) root2=(-b-sqrt(d))/(2*a)
(c)print root1,root2
Else
if(d==0)
(i)
(a) root1=-b/(2*a)
(b) root2=-b/(2*a)
(c)print root1,root2
Else
Step 6: stop
Program:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
float a,b,c,d,root1,root2;
N.VENKATASIVA REDDY GCET, KADAPA Page 49 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
clrscr();
scanf("%f %f %f",&a,&b,&c);
d=(b*b)-(4*a*c);
if(d>0)
root1=-b+sqrt(d)/(2*a);
root2=-b-sqrt(d)/(2*a);
else if(d<0)
else
getch();
OUTPUT:
Enter the values of a,b,c :: 1 2
3
ROOTS ARE IMAGINARY
Description: Factorial program using recursion in c with while loop.In this program once the
execution reaches the function return statement it will not go back to the function call. Instead,it
executes the function repeatedly. can anybody please tell me what's wrong in this program.
Algorithm :
step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
clrscr( );
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf("\nFactorial value of %d = %d",n,fact);
getch( );
}
OUTPUT:
Enter any number : 5
Factorial value of 5 = 120
#include<stdio.h>
#include<conio.h>
void main( )
int num,i,count=0;
clrscr( );
scanf("%d",&num);
if(num% i==0)
count++; //count=count+1
break;
else
getch( );
}
N.VENKATASIVA REDDY GCET, KADAPA Page 52 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
OUTPUT:
1. Enter a number: 1
2. Enter a number: 5
5 is a prime number
PROGRAM: 8. Write a program to find the series of prime numbers in the given range.
Prime number is a number which is exactly divisible by one and itself only. In this program
the range up to which prime numbers are printed is read. Before printing prime numbers, each and
every number between the ranges is checked. If the number is prime ,it is printed otherwise next
number is verified.
Ex: 2, 3,5,7,………;
Algorithm:
Step1: start
Step2: read n value
Step3: for i=1 i<=n
Step4:repeat a b c d e
a)factorial equal to 0
b) for i=1,j<=1 repeat c,d
c)if i percentage j equal to zero
d) fact equal to factorial added with one
e) if factorial equal to2print as prime number
step5: display the prime no till nth num
6: stop
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int n,m=1,i,j;
clrscr( );
printf("Enter n value ::");
scanf("%d",&n);
printf("\nThe prime numbers are ::");
for(i=1;i<n;i++)
{
for(j=2;j<i;j++)
{
if(i%j= =0)
m++;
}
The sub sequent terms 1 found by adding the preceding two terms in the sequence
t1=0, t2=1
tn=tn-2+tn-1……where n>2
Algorithm:
Step1: start
Step3: f=0,f1=1,f2=1
Step4: do
I++
F1=f2
F2=f
F=f1+f2
While (i<=n)
Step5: print f
Step6: stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c,n,i;
clrscr( );
a=0;
N.VENKATASIVA REDDY GCET, KADAPA Page 56 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
b=1;
printf("Enter n value ::");
scanf("%d",&n);
printf("%d\t%d\t",a,b);
i=2;
while(i<n)
{
c=a+b;
printf("%d\t",c);
a=b;
b=c;
i=i+1;
}
getch( );
}
OUTPUT:
Enter n value ::6
0 1 1 2 3 5
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max;
clrscr( );
printf("Enter the array size ::");
scanf("%d",&n);
printf("Enter the elements of array ::");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
printf("Maximum value is:%d\n",max);
getch( );
}
OUTPUT:
Enter the array size ::5
Enter the elements of array ::52
84
15
69
24
Maximum value is:84
Algorithm:
step1 : start
step 2: read num,r
step 3: while(num>0)
step 4: r=num%10;
step 5: reverse=reverse*10+r;
step 6: num=num/10;
step 7: stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int r,reverse,n;
clrscr( );
printf("Enter a positive integer:");
scanf("%d",&n);
reverse=0;
while(n>0)
{
r=n%10;
reverse=reverse*10+r;
n=n/10;
}
printf("The reverse of the given number is %d",reverse);
getch();
}
OUTPUT:
Enter a positive integer:563
The reverse of the given number is 365
PROGRAM 12. Write a program to find the sum of the digits of a number.
Aim: To find the sum of individual digits of a given number
Description:
In this ,initially sum is assigned to zero using a while loop this number is divided into individual
digits. for each iteration of while loop atleast significant digit of the positive integer are added to
sum using the following statements,
sum-sum+n%10;
Algorithm:
Step 1: start
Step 2: sum0
Step 5: sumsum+num%10;
Step 6: numnum/10;
Step 8:stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum;
clrscr();
sum=0;
printf("Enter a positive integer:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("Sum of individual digits of a number=%d",sum);
getch();
}
OUTPUT:
Enter a positive integer:563
Sum of individual digits of a number=14
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,nsum,psum;
int a[10]={2, -4, 8, 9, -12, 7, -1, 9};
clrscr( );
nsum=psum=0;
for(i=0;i<10; i++)
{
if(a[i]<0)
{
nsum=nsum+a[i];
}
else
{
psum=psum+a[i];
}
}
printf("\n Sum of Negative numbers in the list : %d",nsum);
printf("\n Sum of Positive numbers in the list : %d",psum);
getch();
}
OUTPUT:
Sum of Negative numbers in the list : -17
Sum of Positive numbers in the list : 35
Step 1 :start
Step 2:Read string s1
Step 3:copy the contents of s1 to s2
Step 4:Reverse the string s2
Step 5:if strcmp (s1,s2)==0
Step 6: print string s1 is a palindrome
Step 7:else
Step 8:print string s1 is not a palindrome
Step 9:end of if in step 5
Step 10:Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int r,rev,n,temp;
clrscr( );
printf("Enter a positive integer:");
scanf("%d",&n);
rev=0;
temp=n;
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
if(rev= =temp)
printf("Given number is palindrome");
else
printf("Given number is not palindrome");
getch( );
}
OUTPUT:
Enter a positive integer: 1221
Given number is palindrome
PROGRAM 15: Write a program to evaluate the sum of the following series up to ‘n’ terms e
x=1+x+x2/2!+x3/3!+x4/4!+--------
AIM: To evaluate the sum of the following series up to n terms e x=1+X+X2/2!+X3/3!+X4/4!
+------------
Description:The series contains the factorial and powers.we use math.h header file to calculate the
powers.Here the powers follow the sequence 2,4,6… Using appropriate loops we will calculate the
given sum of the series.
Algorithm:
Step 1 :start
Step 2:Read exponential (y) and base values(x) , assign s<-1,sum=0.0
Step 3:for i=0 upto exponent value (y) increment i by 2
Step 4:fact=1
Step 5:for j=i upto j!=0 decrement by 1
Step 6:fact*=j
Step 7:end of for loop in step5
Step 8:sum=sum+s*pow(x,i)/fact
Step 9: s=-s
End of for loop in step 3
Step 10:print sum
Step 11:stop
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int i=0,j,n,x,fact;
float term=0.0,sum=1.0;
clrscr( );
printf("Enter x value ::");
scanf("%d",&x);
printf("Enter number of terms ::");
scanf("%d",&n);
for(i=1;i<n;i++)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
term=pow(x,i);
sum=sum+(term/fact);
}
printf("\nsum of series = %f",sum);
getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 63 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}
OUTPUT:
Enter x value ::2
Enter number of terms ::4
sum of series = 6.333333
Alogrithm:
Step 1: Start
Step 3: Read n
i) if(j==0||m==0)
ii) Initialize b=1 if not b=b*(m-j+1)/j
iii) Print white space, b .
iv) Goto Step 9
Step 9: increment j, goto Step 8
121
1331
14641
Aim: To Write a program to read two matrices and print their sum and product in the matrix form
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k,row1,col1,row2,col2;
int mat1[10][10],mat2[10][10],prodmat[10][10],matsum[10][10];
clrscr();
printf("enter the order of matrix1\n");
scanf("%d%d",&row1,&col1);
printf("enter the order of matrix2\n");
scanf("%d%d",&row2,&col2);
if(col1= =row2)
{
printf("enter the elements of matrix1\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("enter the elements of matrix2\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
prodmat[i][j]=0;
for(k=0;k<row2;k++)
{
prodmat[i][j]=prodmat[i][j]+(mat1[i][k]*mat2[k][j]);
}
}
}
7 11 8
7 13 1
Description: By the definition trace of matrix is given by the sum of all the elements on its
principle diagonal obviously the matrix has to be a square matrix
trace=a00+a11+a22+-------+an-1
. n-1
. . trace=∑ a11, statement is used to obtain the sum
i+0
i. Sum of diagonal elements of a matrix in c
Algorithm:
Step 1: start
step 2: input m and n dimensions of matrix
step 3: if(m!=n)
step 4: input all the elements of matrix
step 5: trace=0
step 6: for(i=0;i<n;i++)
step 7: trace=trace+a;
step 8: output trace
step 9: stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j,m,n;
int mat[10][10],sumdiag=0;
clrscr();
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
if(m==n)
{
printf("Enter the elements of matrix ::\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<m;i++)
{
Program:
#include<stdio.h>
#include<conio.h>
void main( )
int i,j,row,col;
int mat[10][10];
clrscr( );
scanf("%d%d",&row,&col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&mat[i][j]);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
printf("%3d",mat[i][j]);
printf("\n");
for(i=0;i<col;i++)
for(j=0;j<row;j++)
printf("%3d",mat[j][i]);
printf("\n");
getch( );
OUTPUT:
#include<conio.h>
void main( )
int i,j,m,n;
int mat[10][10],seven,sodd;
clrscr( );
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&mat[i][j]);
seven=sodd=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(mat[i][j]%2= =0)
else
sodd=sodd+mat[i][j];
getch();
OUTPUT:
PROGRAM 19: Write a program to accept a line of characters and print the count of the
number of Vowels, Consonants, blank spaces, digits and special characters.
Aim: To implement a program to accept a line of characters and print the count of number of
vowels,consonants,blankspaces,digits and special characters
Algorithm:
step1: start
step2: declare str[50],intr=0,c=0,w=0,sc=0,d=0
step3: gets(str)
step4: for(i=0;str[i]==’\0’||str[i]!=’/n’;i++)
step5: if(str[i]=’a’||str[i]=’e’||str[i]=’i’||str[i]=’o’||str[i]=’u’)
step6: v++
step7: else if(str[i]>’a’ && str[i]<=’z’)
step8: c++
step9: else if(str[i]=’0’|| str[i]=’1’|| str[i]=’2’|| str[i]=’3’|| str[i]=’4’|| str[i]=’5’|| str[i]=’6’||
str[i]=’7’|| str[i]=’8’|| str[i]=’9’)
step10: d++
step11: else if(str[i]==’ ‘||str[i]=’/t’)
step12: w++;
step13: else
step14: sc++
step15: print the vowels
step16: print the consonants
step17: print the digits
step18: print the special characters
step19: print the words
step20: print the number of characters
Program:
#include<stdio.h>
void main( )
char line[150];
int i,v,c,d,spc,s;
clrscr( );
v=c=d=spc=s=0;
gets(line);
for(i=0;line[i]!='\0';++i)
{
N.VENKATASIVA REDDY GCET, KADAPA Page 76 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E'
||
++v;
++c;
else if(line[i]>='0'&&line[i]<='9')
++d;
++spc;
else
++s;
printf("\nVowels: %d",v);
printf("\n\nConsonants: %d",c);
printf("\n\nDigits: %d",d);
getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 77 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}
OUTPUT:
Vowels: 5
Consonants: 5
Digits: 1
White spaces: 3
Special Characters : 2
PROGRAM 20: Write a program to insert a substring in to a given string and delete few
characters from the string. Don’t use library functions related to strings
Aim: A C program to insert a sub string into the main string from a given position.
Description: String is group of characters where character may a number, alphabet or special
symbol.
Here two strings are considered first one is main and second one is substring.sub string is
inserted into main string from a particular position and the resultant string is displayed.
ALGORITHM:
Step 1 :start
Step 2:Read main string m
Step 3:Read sub string sb
Step 4:Read the position to be inserted p-
Step 5:for i=0 upto p increment i by 1
Step 6:x[i]=m[i]
Step 7:end of for loop in step 5
Step 8:for i=pand j=0 upto sb[j]!=’\0’ increment i,j by 1
Step 9:x[i]=sb[j]
Step 10:end of for loop in step 8
Step 11:x[i]=’\0’
Step 12:l=strlen(x)
Step 13:for i=l and j=p upto m[j]!=’\0’ increment i ,j by 1
Step 14:x[i]=m[j]
Step 15:end of for loop in step 13
Step 16:x[i]=’\0’
Step 17:Print resultant string x
Step 18:Stop
PROGRAM:
#include <stdio.h>
N.VENKATASIVA REDDY GCET, KADAPA Page 78 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
#include <conio.h>
#include <string.h>
void main()
int p,r,i=0;
int t=0;
int x,g,s,n,z;
clrscr( );
gets(a);
gets(b);
scanf("%d",&p);
r = strlen(a);
n = strlen(b);
i=0;
while(i <= r)
c[i]=a[i];
i++;
s = n+r;
z = p+n;
for(i=p;i<s;i++)
x = c[i];
if(t<n)
a[i] = b[t];
t=t+1;
a[z]=x;
z=z+1;
getch( );
OUTPUT:
hiiam
fine
20(b)Write a program to delete few characters from the string (Don’t use library functions
related to strings)
Aim: To Write a program to delete few characters from the string (Don’t use library functions
related to strings)
Program:
#include<stdio.h>
#include<conio.h>
void main( )
char str[15];
int pos,i,j,n;
clrscr();
printf("Enter string:\n");
gets(str);
scanf("%d", &pos);
scanf("%d",&n);
i=pos;
for(j=pos+n;str[j]!='\0';j++)
str[i]=str[j];
i++;
getch( );
OUTPUT:
Enter string:
hi aec students
#include<conio.h>
struct complex
double real;
double img;
};
void main()
int ch;
clrscr( );
printf("\n Enter two Complex Numbers (x+iy):\n Real Part of First Number:");
scanf("%lf",&cn1.real);
scanf("%lf",&cn1.img);
scanf("%lf",&cn2.real);
scanf("%lf",&cn2.img);
N.VENKATASIVA REDDY GCET, KADAPA Page 83 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf(" Select your option:\n\n1 : ADD\n2 : SUBTRACTION \n3 : MULTIPLY\n4 :
Exit\n\n");
printf("enter ur choice:");
scanf("%d",&ch);
switch(ch)
case 1:
cn.real =(cn1.real+cn2.real);
cn.img =(cn1.img+cn2.img);
if(cn.img>0)
else
break;
case 2:
cn.real =(cn1.real-cn2.real);
cn.img =(cn1.img-cn2.img);
if(cn.img>0)
else
break;
case 3:
cn.real=(cn1.real*cn2.real)-(cn1.img*cn2.img);
cn.img=(cn1.real*cn2.img)+(cn1.img*cn2.real);
if(cn.img>0)
printf("\nmultiplication = %lf+%lfi",cn.real,cn.img);
N.VENKATASIVA REDDY GCET, KADAPA Page 84 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
else
printf("\nmultiplication = %lf%lfi",cn.real,cn.img);
break;
default:
printf("Invalid option");
getch( );
OUTPUT:
1 : ADD
2 : SUBTRACTION
3 : MULTIPLY
4 : Exit
enter ur choice:1
addition = 15.000000+9.000000i
Task 22:
Write a program to split a file into Two files, say File1 And File2.Read Lines into the file from
standard input.File1 should consist of odd numbered lines and file2 should consists of even
numbered lines .
Program:
#include<stdio.h>
#include<conio.h>
FILE *fp1,*fp2,*fp3;
char c;
clrscr( );
fp1=fopen("file.txt","r");
fp2=fopen("file1.txt","w");
fp3=fopen("file2.txt","w");
while((c=fgetc(fp1))!=EOF)
while(c!='\n')
fputc(c,fp2);
c=fgetc(fp1);
c=fgetc(fp1);
while(c!='\n')
fputc(c,fp3);
c=fgetc(fp1);
OUTPUT:
Step 1:
3:what abt. u?
5:good bye
6:ok bye
Step 2:
Compile and run(execute) this C-program then it automatically creates 2 files called file1.txt
and file2.txt
Output:
file1.txt file2.txt
1:hi hello hru? 3:what abt. u? 5:good bye 2:fine 4:me also fine 6:ok bye
Task 23:
Write a program to merge two files
Aim: Write a program to merge two files
#include<stdio.h>
main()
FILE *fp1,*fp2,*fp3;
char c;
clrscr();
fp1=fopen("1.txt","r");
fp2=fopen("2.txt","r");
fp3=fopen("3.txt","a");
if(fp1==NULL||fp2==NULL)
exit( );
c=fgetc(fp1);
while(c!=EOF)
fputc(c,fp3);
c=fgetc(fp1);
c=fgetc(fp2);
while(c!=EOF)
fputc(c,fp3);
c=fgetc(fp2);
fcloseall( );
OUTPUT:
hi
students
Step:3 ->Compile and execute this program then it automatically creates a file called 3.txt that
it has
hi students
Task 24:
Output 1:
Output 2:
Enter an expression: x
Enter x0, xn and number of subintervals
016
Value of the integral is 0.500
24(b) Write a program to implement numerical methods Lagrange’s interpolation.
#include<conio.h>
#define MaxN 90
void main( )
int i, j, n;
clrscr();
scanf("%d", &n);
scanf("%f", &x);
numerator=1;
denominator=1;
if(j!=i)
numerator *= x-arr_x[j];
denominator *= arr_x[i]-arr_x[j];
y+=(numerator/denominator)*arr_y[i];
getch( );
OUTPUT:
PROGRAM 25: Write a program to read a set of strings and sort them in alphabetical order
AIM: Program to read five cities and sort them and print sorted list of citied in alphabetical
order
ALGORITHM:
step1:start
Step2:enter 5 city names
Step3:take I and j loop variables
#include<string.h>
void main()
char s[5][20],t[20];
int i,j,n;
clrscr( );
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s",s[i]);
for(i=1;i<n;i++)
for(j=1;j<n;j++)
if(strcmp(s[j-1],s[j])>0)
strcpy(t,s[j-1]);
N.VENKATASIVA REDDY GCET, KADAPA Page 91 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
strcpy(s[j-1],s[j]);
strcpy(s[j],t);
for(i=0;i<n;i++)
printf("\n%s",s[i]);
getch( );
OUTPUT:
Task 31: Write a program to read two strings and perform the following operations without
using built in string Library functions and by using your own implementation of functions.
1 String Length Determination
2 Compare two Strings
3. Concatenate them, if they are not equal
4. String Reverse
Program
#include<stdio.h>
#include<conio.h>
char s1[10],s2[10];
void main()
int ch,l;
clrscr( );
gets(s1);
gets(s2);
scanf("%d",&ch);
switch(ch)
case 1: l=slength(s1);
l=slength(s2);
break;
case 2:
scompare(s1,s2);
break;
case 3:
sconcate(s1,s2);
break;
case 4:
sreverse(s1);
sreverse(s2);
break;
default:
printf("\nWrong entry");
getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 93 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
exit();
getch( );
int i;
for(i=0;s1[i]!='\0';i++);
return i;
char s2[10];
int i,j,len;
len=slength(s1);
for(i=len-1,j=0;i>=0;i--,j++)
s2[j]=s1[i];
s2[j]='\0';
puts(s2);
int i,j,l,m,s=0;
m=slength(s2);
if(l!=m)
return 1;
else
for(i=0,j=0;i<l&&j<m;i++,j++)
if(s1[i]!=s2[j])
s=1;
if(s= =1)
break;
else
continue;
if(s= =0)
return 0;
int i,j,l,m;
if(scompare(s1,s2)==1)
l=slength(s1);
m=slength(s2);
for(i=l,j=0;j<m;i++,j++)
s1[i]=s2[j];
s1[i]='\0';
Output 1:
Enter a String 1 ::aec
Enter UR choice :: 3
Output 2:
Program:
#include<stdio.h>
#include<conio.h>
void main()
int n;
clrscr( );
scanf("%d",&n);
f1=recfactorial(n);
getch( );
if(n==0)
return 1;
return (n*recfactorial(n-1));
Enter n number :5
ii. To find the GCD (greatest common divisor) of two given integers using recursive function.
Description: Let x and y be two numbers. GCD (Greatest Common Divisor) of x and y is the
largest integer that divides both the numbers. Let r be the remainder when x is divided by y. if r is 0
then y is gcd. Otherwise set x=y, y=r and repeat the same process.
Step 1: start
Step 2: read a,b
Step 3: call the sub program GCD(a,b) for print the value
Step 4: stop
Sub program:
PROGRAM:
#include <stdio.h>
void Lcm_rec(int);
int num1,num2;
main()
int max;
clrscr( );
Lcm_rec(max);
getch();
return;
else
LCM of 5 and 9 is 45
iii. To find the LCM of two given integers using recursive function.
#include<stdio.h>
int main()
{
int n1,n2,temp1,temp2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
temp1=n1;
temp2=n2;
while(temp1!=temp2)
{
if(temp1>temp2)
temp1-=temp2;
else
temp2-=temp1;
}
printf("LCM of two numbers %d and %d is %d", n1, n2, (n1*n2)/temp1);
return 0;
N.VENKATASIVA REDDY GCET, KADAPA Page 100 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}
Output:
#include<stdio.h>
#include<conio.h>
void main()
int m,n,g;
int recgcd(int,int);
clrscr();
printf("Enter 2 values:");
scanf("%d%d",&m,&n);
g=recgcd(m,n);
getch();
if(n= =0)
return m;
else
Here source ,intermediate and destination are the three towers. We have to transfer all
the disks from source to destination towers. Here the restriction is not to place a big disk on
smaller one . for this we use intermediate tower. Finally the arrangements in the destination
tower must be as same as the disks in the source tower at first.
#include<conio.h>
void main()
void towers(int,char,char,char);
int n;
clrscr();
towers(n,'A','C','B');
getch();
if(n= =1)
return;
else
towers(n-1,fromtower,auxtower,totower);
towers(n-1,auxtower,totower,fromtower);
return;
OUTPUT:
void main()
int *a,*b,temp;
clrscr();
scanf("%d%d",a,b);
printf("%d %d",*a,*b);
temp=*a;
*a=*b;
*b=temp;
getch();
OUTPUT:
Enter 2 Numbers ::
37. Aim: To Write a program to read student records into a file. Record consists of rollno, name and
marks of a student in six subjects and class. Class field is empty initially. Compute the class of a
student. The calculation of the class is as per JNTUA rules. Write the first class, second class, third
class and failed students lists separately to another file.
Program:
#include<stdio.h>
#define NULL 0
struct record
char nam;
int rno;
int s1,s2,s3,s4,s5,s6;
};
void main()
FILE *fp,*fp1;
fp=fopen("file1.txt","r");
fp1=fopen("file2.txt","w");
if(fp==NULL)
exit();
else
while(getc(fp)!=EOF)
fscanf(fp,"%c %d %d %d %d %d %d
%d",&it.nam,&it.rno,&it.s1,&it.s2,&it.s3,&it.s4,&it.s5,&it.s6);
n=it.s1+it.s2+it.s3+it.s4+it.s5+it.s6;
n=(n/6);
if(n>70&&n<100)
fprintf(fp1,"distinction");
else if(n>60&&n<70)
fprintf(fp1,"first class");
else if(n>50&&n<60)
fprintf(fp1,"second class");
else if(n>40&&n<50)
fprintf(fp1,"third class");
else
fprintf(fp1,"fail");
fcloseall();
Output :
Content in file1.txt
a 409 60 65 67 79 94 96
distinction
38. Aim:A file consists of information about employee salary with fields employeeid, name, Basic,
HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employeeid, name, and basic
have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is 20% of the
basic, other deductions is user specified. Compute the Gross and Net salary of the employee and
update the file.
Program:
#include<stdio.h>
#include<conio.h>
struct employee
int id;
char name[22];
double bsal;
};
void main()
FILE *fp;
clrscr();
fp=fopen("sal.txt","r");
fscanf(fp,"%d",&emp.id);
fscanf(fp,"%s",&emp.name);
fscanf(fp,"%u",&emp.bsal);
da=((emp.bsal)*10)/100;
hra=((emp.bsal)*80)/100;
it=((emp.bsal)*20)/100;
pf= ((emp.bsal)*8)/100;
gross_sal=emp.bsal+da+hra;
net_sal=gross_sal-it-pf;
fclose(fp);
fp=fopen("sal.txt","a");
fprintf(fp,"\nEmployee Details");
fprintf(fp,"\n****************");
fprintf(fp,"\nID= %d",emp.id);
fprintf(fp,"\nNAME= %s",emp.name);
fprintf(fp,"\nDA= %u",da);
fprintf(fp,"\nHRA= %u",hra);
fprintf(fp,"\nPF= %u",pf);
fclose(fp);
getch();
}
N.VENKATASIVA REDDY GCET, KADAPA Page 109 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
File sal.txt contains:
4567
RAMESH
5600
Output:
Employee Details
****************
ID= 4567
NAME= RAMESH
DA= 17587
HRA= 17587
PF= 40284
void main(void)
char base_digits[16] =
while (number_to_convert != 0)
++index;
printf("%c", base_digits[converted_number[index]]);
printf("\n");
getch();
Output:
Task 40:
write a program to find the square root of a number without using built-in library function.
Aim: write a program to find the square root of a number without using built-in library
function
#include<stdio.h>
int i,product = 0;
for(i=0;i<MAX_NUMBER;i++)
product = i*i;
if(product==number)
return i;
else if(product>number)
break;
return 0;
int main( )
int n=0,result=0;
clrscr( );
scanf("%d",&n);
if(n<0)
return 0;
result = find_sqrt(n);
if(result)
printf("sqrt of %d is %d\n",n,result);
else
getch( );
Output:
sqrt of 25 is 5
Task 41:
Write a program to convert from string to number
#include <stdio.h>
void main()
char a[100];
int n;
scanf("%s", a);
n = toString(a);
getch();
int toString(char a[ ]) {
if (a[0] == '-') {
sign = -1;
if (sign == -1) {
offset = 1;
else {
offset = 0;
n = 0;
n = n * 10 + a[c] - '0';
if (sign == -1)
n = -n;
return n;
Output:
String = -5632
Integer = -5632
Task 42:
Usage of rand( ):
Output:
That is correct!
void main( )
int i,j;
clrscr();
for(i=1;i<=10;i++)
for(j=11;j<=20;j++)
printf("%d*%d=%d",j,i,j*i);
printf("\n");
getch();
Output:
Multiplication table from 11 to 20
11*1=11 12*1=12 13*1=13 14*1=14 15*1=15 16*1=16 17*1=17 18*1=18 19*1=19
20*1=20
Task 48: write a program to express a four digit number in words. For example 1546 should
be written as one thousand five hundred and forty six.
Aim: to express a four digit number in words. For example 1546 should be written as one
thousand five hundred and forty six.
#include<stdio.h>
#include<conio.h>
char a[10][12]={"one","two","three","four","five","six","seven",eight","nine"};
"eighteen","ninteen"};
char tens[10][15]={twenty","thirty","fourtey","fiftey","sixty","seventy","eighty",
"ninty"};
if(num>10000000)return 5;
if(num>100000)return 4;
else if(num>1000)return 1;
else if(num>100)return 2;
else if(num>10)return 3;
else
return 0;
int n;
if(num<10)
printf(" %s %s",a[num-1],s);
printf(" %s %s",b[(num-10)-1],s);
else if(num>20)
printf(" %s ",tens[(num-20)/10]);
n=num%10;
printf(" %s %s",a[n-1],s);
void main()
N.VENKATASIVA REDDY GCET, KADAPA Page 118 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{
int ch=1;
clrscr( );
printf("enter no\n");
scanf("%ld",&num);
while( ch!=0)
ch=check(num);
switch(ch)
case 1: n=num/1000;
prnt(n," thousand");
num=num-n*1000;
break;
case 2:
n=num/100;
num=num-n*100;
break;
case 3:
printf(" %s",tens[(num-20)/10]);
num=num%10;
break;
case 4:
n=num/100000;
prnt(n,"lacks");
num=num-n*100000;
N.VENKATASIVA REDDY GCET, KADAPA Page 119 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
break;
case 5:
n=num/10000000;
prnt(n,"crores");
num=num-n*10000000;
break;
printf(" %s",a[num-1]);
getch( );
Output:
49. Aim: Write a program to generate a telephone bill. The contents of it and the rate calculation etc
should be as per BSNL rules. Student is expected to gather the required information through the
BSNL website.
Program:
Customer name::
Telephone number::
Units to be billed::
Calculate Bill Amount from the given input amount of each customer and prepare the Bill and print
it.*/
Program:
void main()
int n,i;
struct bill
char name[20];
int num;
int units;
}a[50];
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s",&a[i].name);
scanf("%d",&a[i].num);
scanf("%d",&a[i].units);
printf("\n\n");
clrscr();
printf("*************************\n\n");
for(i=0;i<n;i++)
printf("\nNAME :: %s",a[i].name);
getch();
Output:
*************************
NAME :: abc
NAME :: efg
Program:
#include<stdio.h>
#include<time.h>
void main( )
double time_spent;
int sum,a,b;
clrscr();
begin = clock();
a=9;
b=90;
sum=a+b;
printf("sum=%d",sum);
end = clock();
getch();
Output:
sum=99
Time spent for execution of sum of 2 numbers :: 0.000000e+00
52. Aim:Design a file format to store a person's name, address, and other information. Write a
program to read this file and produce a set of mailing labels
Program:
#include<stdio.h>
void main()
struct details
char name[20];
char add[100];
char tel[20];
}d;
FILE *fp;
clrscr();
fp=fopen("label.txt","rw");
printf("\n***********************");
fscanf(fp,"%s",&d.name);
printf("%s",d.name);
printf("\nAddress :: ");
fscanf(fp,"%s",&d.add);
printf("%s",d.add);
fscanf(fp,"%s",&d.tel);
printf("%s",d.tel);
clrscr();
printf("*************************\n\n");
printf("\n%s",d.name);
printf("\n%s",d.add);
printf("\nTel NO:%s",d.tel);
getch();
Output:
***********************
Address :: DOORNO:2-3-567,NELLOREPALEM,ATMAKUR,S.P.S.R.NELLORE(AP)
*************************
PRAKESH
DOORNO:2-3-567,NELLOREPALEM,ATMAKUR,S.P.S.R.NELLORE(AP)
Tel NO:955689