Sie sind auf Seite 1von 82

13A12102 - Programming in C & Data Structures Lab

(Lab Manual)
List Of Experiments
1. Practice DOS and LINUX Commands necessary for design of C Programs.
2. Study of the Editors, Integrated development environments, and Compilers in chosen
platform.
3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the
programming environment.
4. Practice programs: Finding the sum of three numbers, exchange of two numbers,
maximum of two numbers, to read and print variable values of all data types of C
language, to find the size of all data types, to understand the priority and associativity of
operators using expressions, to use different library functions of C language.
5. Write a program to find the roots of a quadratic equation.
6. Write a program to compute the factorial of a given number.
7. Write a program to check whether the number is prime or not.
8. Write a program to find the series of prime numbers in the given range.
9. Write a program to generate Fibonacci numbers in the given range.
10. Write a program to find the maximum of a set of numbers.
11. Write a program to reverse the digits of a number.
12. Write a program to find the sum of the digits of a number.
13. Write a program to find the sum of positive and negative numbers in a given set of
numbers.
14. Write a program to check for number palindrome.
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!+-------16. Write a program to generate Pascal Triangle.
17. Write a program to read two matrices and print their sum and product in the matrix form.
18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
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.
20. Write a program to insert a substring in to a given string and delete few characters from
the string. Dont use library functions related to strings.
21. Write a program to perform the operations addition, subtraction, multiplication of
complex numbers.
22. Write a program to split a file in to two files, say file1 and file2. Read lines into the
file from standard input. File1 should consist of odd numbered lines and file2 should
consist of even numbered lines.
23. Write a program to merge two files.
24. Write a program to implement numerical methods Lagranges interpolation, Trapezoidal rule.
25. Write a program to read a set of strings and sort them in alphabetical order.
26. Write a program to sort the elements of an array using sorting by exchange.
27. Write a program to sort the elements of an array using Selection Sort.
28. Write a program to perform Linear Search on the elements of a given array.
29. Write a program to perform Binary Search on the elements of a given array.
30. Write a program to find the number of occurrences of each number in a given array of
numbers.
31. Write a program to read two strings and perform the following operations without using builtin string Library functions and by using your own implementations of functions.
i. String length determination ii .Compare Two Strings
iii. Concatenate them, if they are not equal iv. String reversing
32. Write programs using recursion for Factorial of a number, GCD, LCM, Towers of Hanoi.
33. Write a program to convert infix expression to postfix expression and evaluate postfix
expression.
34. Write a program to exchange two numbers using pointers.
35. Write a program to implement stack, queue, circular queue using array and linked lists.

36. Write a program to perform the operations creation, insertion, deletion, and traversing a
singly linked list
37. 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.
38. 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.
39. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.
40. Write a program to find the square root of a number without using built-in library
function.
41. Write a program to convert from string to number.
42. Write a program to generate pseudo random generator.
43. Write a program to remove duplicates from ordered and unordered arrays.
44. Write a program to sort numbers using insertion sort.
45. Write a program to implement quick sort using non-recursive and recursive approaches. Use
randomized element as partitioning element.
46. Write a program to search a word in a given file and display all its positions.
47. Write a program to generate multiplication tables from 11 to 20.
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.
49. 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.
50. Write a program for tic-tac-toe game.
51. Write a program to find the execution time of a program.
52. 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
1. Practice DOS and LINUX Commands necessary for design of C Programs.
DOS Commands:Internal Commands:
Dos Internal commands are always available to the operator and may be entered from any
Dos Prompt.
These commands are automatically loaded in to the computer.
Some of the internal commands are discussed below.
Date:
This command displays the current system date on the screen and also allows us to change
the date. The user can modify the date. Dates are accepted using the format MM/DD/YY. Where
MM stands for Month, DD stands for Date, and YY stands for Year.
Syntax: C: /> Date {enter key}
Time:
This command is used to display the current system time. The user can also modify the
time.
Syntax: C: /> time
Ver:
This command displays the current Dos version number. It has no additional parameters.
Syntax: C: /> ver
Copy Con:
This command is used to create a new file.
Syntax: C: /> copy con file name
Type:
This type command is used to display the contents (data) of an existing file.
Syntax: C: / > type
Edit:
It is a menu driven text editor. It is used to edit the contents of an existing file. We can also
modify and add new data in an existing file.
Syntax: C: / > edit

Copy:
This command is used to copy the contents of a file to another file. This command requires
a source file name and target file name.
Syntax: C: / > copy source file name target file name.
The above command copies the contents of source file name to target file name. It target
file name doesnt exist it will create the file and copy the contents. If it is already existed file it will
over write it.
Ren: (or) Rename:
This command is used to rename a file. This command requires an old file name (or) New
file name. When invoked the comm. and changes old file to new.
Syntax: C: / > Ren old file name New file name
Del (or) Erase:
This command is used to delete a file from memory.
Syntax: C: / > del file name
Cls:
This command is used to clear the screen. It will erase all the characters in the screen and
displays the prompt in the first line of the screen. It has no parameters.
Syntax: C: / > cls
Md (or) Mkdir:
This command is used to create a directory (or ) sub directory.
Syntax: C: / > MD directory name
CD (or) CHDIR:
This command is used to change (or) activate an existing directory.
Syntax: C: / >CD Directory name
RD (or) RMDIR:
This command is used to remove an existing directory. Before using this command it is
important to note that the directory which should be removed should not contain any files (or)
sub directories.
Syntax: C: /> RD directory name
CD. . :
This command is used to come out from current directory.
Syntax: C: / >CD. .
CD\:
This command is used to come out from all sub directories at once.
Syntax: C : \ > CD\
Dir:
This command is used to display all files and sub directories under the given directory. It
displays one file on a line with details like file name, extension, size in bytes, data and time of file
creator.
Syntax: C :/> DIR
DIR/P :
This command is used to display the list of files and sub directories page by page.
Syntax: C :/> Dir/P Enter.
DIR/W :
This command is used to display the list of files and sub directories in a wide format
containing only file names and extensions placing file name side by side.
Syntax: C :/> Dir/w Enter.
Dir/R :
This command is used to display the file names in lower case.
Syntax: C :/> Dir/r Enter.

LINUX Commands:Command Example


cat

cd

cp

dd

df
less
ln

locate

logout
ls

Description
Sends file contents to standard output. This is a way to list
the contents of short files to the screen. It works well with
piping.
cat .bashrc
Sends the contents of the ".bashrc" file to the screen.
Change directory
cd /home
Change the current working directory to /home. The '/'
indicates relative to root, and no matter what directory you
are in when you execute this command, the directory will
be changed to "/home".
cd httpd
Change the current working directory to httpd, relative to
the current location which is "/home". The full path of the
new working directory is "/home/httpd".
cd ..
Move to the parent directory of the current directory. This
command will make the current working directory "/home.
cd ~
Move to the user's home directory which is
"/home/username". The '~' indicates the users home
directory.
Copy files
cp myfile yourfile
Copy the files "myfile" to the file "yourfile" in the current
working directory. This command will create the file
"yourfile" if it doesn't exist. It will normally overwrite it
without warning if it exists.
cp -i myfile yourfile
With the "-i" option, if the file "yourfile" exists, you will be
prompted before it is overwritten.
cp -i /data/myfile .
Copy the file "/data/myfile" to the current working
directory and name it "myfile". Prompt before overwriting
the file.
cp -dpr srcdir destdir
Copy all files from the directory "srcdir" to the directory
"destdir" preserving links (-p option), file attributes (-p
option), and copy recursively (-r option). With these
options, a directory and all it contents can be copied to
another directory.
dd
if=/dev/hdb1 Disk duplicate. The man page says this command is to
of=/backup/
"Convert and copy a file", but although used by more
advanced users, it can be a very handy command. The "if"
means input file, "of" means output file.
Show the amount of disk space used on each mounted
filesystem.
less textfile
Similar to the more command, but the user can page up
and down through the file. The example displays the
contents of textfile.
Creates a symbolic link to a file.
ln -s test symlink
Creates a symbolic link named symlink that points to the
file test Typing "ls -i test symlink" will show the two files
are different with different inodes. Typing "ls -l test
symlink" will show that symlink points to the file test.
A fast database driven file locator.
slocate -u
This command builds the slocate database. It will take
several minutes to complete this command. This command
must be used before searching for files, however cron runs
this command periodically on most systems.
locate whereis
Lists all files whose names contain the string "whereis".
Logs the current user off the system.
List files
ls
List files in the current working directory except those
starting with . and only show the file name.
ls -al
List all files in the current working directory in long listing
format showing permissions, ownership, size, and time and

more
more /etc/profile
ls -al |more
mv
mv -i myfile yourfile
mv -i /data/myfile .
pwd
more /etc/profile
shutdown
shutdown -h now
shutdown -r now
whereis
whereis ls
man
man pwd
pwd
mkdir
dirName
mkdir temp

Creates the directory temp


Removes a directory dirName

rmdir temp
rm data1
rm -i muon*

Removes the directory temp.


Deletes the file data1 in the current directory.
Removes all of your muon data files (careful!! rm * will
remove ALL your files) .The "-i" makes the computer
prompt before removing each file. If you really want to
work without a net, omit the "-i".
will copy the file data1 to the directory newdata (assuming
it has already been created)
moves the file data1 to the folder newdata and deletes the
old one.
Mounts a drive to the operating system.Linux does not 'see'
the floppy drive until we tell it to.
Shows the disk usage. This will tell you how much disk
space you have left on your hard drive as well as the
floppy.

rmdir
dirName

cp data1 newdata/
mv data1 newdata/
Mount
Df

date stamp
Allows file contents or piped output to be sent to the
screen one page at a time.
Lists the contents of the "/etc/profile" file to the screen
one page at a time.
Performs a directory listing of all files and pipes the output
of the listing through more. If the directory listing is longer
than a page, it will be listed one page at a time.
Move or rename files
Move the file from "myfile" to "yourfile". This effectively
changes the name of "myfile" to "yourfile".
Move the file from "myfile" from the directory "/data" to
the current working directory.
Show the name of the current working directory
Lists the contents of the "/etc/profile" file to the screen
one page at a time.
Shuts the system down.
Shuts the system down to halt immediately.
Shuts the system down immediately and the system
reboots.
Show where the binary, source and manual page files are
for a command
Locates binaries and manual pages for the ls command.
This command brings up the online Unix manual. Use it on
each of the commands below.
You will see the manual for the pwd command
Shows what directory (folder) you are in.
In Linux, your home directory is /home/particle
Creates a directory with name dirName.

2. Study of the Editors, Integrated development environments, and Compilers in chosen


platform.
Editor:An editor is a computer application software that performs processing: the composition,
editing, formatting and sometimes printing of any sort of written material.

Different types of Editors:Notepad:Notepad is a common text-only (plain text) editor. The resulting filestypically saved with the .txt
extensionhave no format tags or styles, making the program suitable for editing system files
that are to be used in a DOS environment and occasionally, source code for later compilation or
execution, usually through a command prompt. Notepad offers only the most basic text
manipulation functions, such as finding text. Only newer versions of Windows include an updated
version of Notepad with a search and replace function. However it is still poor in comparison to
full-scale editors.
WordPad:WordPad is a basic word processor that is included with almost all versions of Microsoft
Windows. WordPad can format and print text, including fonts, bold, italic, colored, and centered
text, etc., but lacks intermediate features such as a spell checker, thesaurus, and the creation of
tables. However WordPad can read, render, and save many RTF features that it cannot create such
as tables, strikeout, superscript, subscript, "extra" colors, text background colors, numbered lists,
right or left indent, quasi-hypertext and URL linking, and various line spacings. WordPad is well
suited for taking notes, writing letters and stories, or for usage in various tablet PCs and smart
phones.
Notepad++ :Notepad++ is a text editor and source code editor for Windows. It aims to be a lightweight and
robust editor for a variety of programming and scripting languages. One advantage of Notepad++
over the built-in Windows text editor Notepad, is that Notepad++ supports tabbed editing, which
allows working with multiple open files. Notepad++ opens large files significantly faster and can
be used as a replacement for Windows Notepad. Notepad++ is distributed as free software.
Microsoft Word :Microsoft Word is a word processor developed by Microsoft. Among its features, Word includes a
built-in spell checker, a thesaurus, a dictionary, and utilities for manipulating and editing text. The
following are some aspects of its feature set :- WordArt , Macros , Layout issues , Bullets and
numbering , AutoSummarize , Password protection
EditPlus :EditPlus is a 32-bit text editor for the Microsoft Windows operating system.The editor contains
tools for programmers, including syntax highlighting (and support for custom syntax files), file
type conversions, line ending conversion (between Linux, Windows and Mac styles), regular
expressions for search-and-replace, keystroke, spell check, full support for Unicode editing,
customizable keyboard shortcuts, auto-completion, code folding, and more. Files can be browsed
and edited in tabs, and an internal file browser is implemented in the software. The "View in
Browser" button is useful for editing HTML code and viewing the results immediately in the
editor.
Integrated Development Environment
Introduction:
An integrated development environment (IDE) is also known as integrated design
environment or
integrated debugging environment or interactive development
environment.
It is a software application that provides comprehensive facilities to computer
programmers for software development.
IDEs are designed to maximize programmer productivity by providing tightly-knit
components with similar user interfaces. i.e., this helps the programmer has to do less
mode switching versus using discrete development programs.
However, because an IDE is a complicated piece of software by its very nature, this higher
productivity only occurs after a lengthy learning process.
Typically an IDE is dedicated to a specific programming language, allowing a feature set
that most closely matches the programming paradigms of the language.
There are some multiple-language IDEs, such as Eclipse, ActiveState Komodo, IntelliJ IDEA,
Oracle JDeveloper, recent versions of NetBeans, Microsoft Visual Studio, Genuitec
MyEclipse, WinDev, and Xcode.
IDEs typically present a single program in which all development is done.
Many modern IDEs also have a class browser, an object inspector, and a class hierarchy
diagram, for use with object-oriented software development.

Components of IDE
An IDE normally consists of:
A source code editor
A compiler and/or an interpreter
Build automation tools
Linker
Loader
A debugger
Source Code Editor
The software used to write programs is known as a source code editor or simply text
editor.
An editor helps to enter, change, and store character data.
The main difference between text processing and program writing is that programs are
written using lines of code, while most text processing is done with characters and lines.
Editor could be a generalized word processor, but it is more often a special editor included
with the compiler.
Some of the features we could expect in editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a
program to another and formatting commands.
Compiler or Interpreter
The code in a source file stored on the disk must be translated into machine language. This
is the job of the translator.
Compiler and interpreters are translators. Compiler compiles the entire program at once
where as the interpreter interprets the program line by line.
The translator reads the program and writes the resulting object module to a file that can
then be combined with other precompiled units to form the final program.
Build Automation Tools
Build automation is the act of scripting or automating a wide variety of tasks that software
developers do in their day-to-day activities including things like:
compiling computer source code into binary code
packaging binary code
running tests
deployment to production systems
creating documentation and/or release notes
Linker
A program is made up of many functions. We write some of these functions, and they are a part
of our source program.
However, there are other functions, such as input/output processes and mathematical library
functions that exist elsewhere and must be attached to our program.
The linker assembles all of these functions into final executable program.
Loader
Once our program has been linked, it is ready for execution.
To execute a program, we use an operating system command, such as run, to load the program
into primary memory and execute it.
Getting the program into memory is the function of an operating system program knows as the
loader.
It locates the executable program and reads it into memory. When everything is loaded, the
program takes control and it begins execution.
In todays integrated development environment, these steps are combined under one mouse
click or pull-down window.
Debugger
A debugger or debugging tool is a computer program that is used to test and debug other
programs.
Debuggers also offer more sophisticated functions such as running a program step by step
(single-stepping or program animation), stopping (breaking) (pausing the program to examine
the current state) at some event or specified instruction by means of a breakpoint, and
tracking the values of variables.
Some debuggers have the ability to modify program state while it is running.
It may also be possible to continue execution at a different location in the program to bypass a
crash or logical error.

List of the C Compilers


Compiler

Author

AMPC

Axiomatic
Sdn Bhd

GCC C
RCC (RCOR
Compiler)

Solutions Windows,Unix
Other

GNU Project
C Rodrigo
(rcor)

Mark Williams C

Mark
Company

Microsoft C

Microsoft

Portable
Compiler

Operating System

Caetano
Williams

&

IDE?

License type

Yes

Proprietary

Windows,Unix,IBM
mainframe, AmigaOS, No
VAX/VMS, RTEMS

GPL

Windows,Unix

No

GPL

Windows,Other

Yes

Proprietary

Windows

Yes

Proprietary

C Anders
Magnusson
Windows,Unix,Other No
and others

Tiny C Compiler Fabrice Bellard

Windows,Unix

No

Turbo C

Embarcadero

Other

No

CCS C Compiler

CCS, Inc.

Windows,Unix,Other Yes

BSD
LGPL
Proprietary freely available
Proprietary

2.01

3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the
programming environment.
Introduction:C language is a high level programming language. Most of the operating systems has been
written in C language.
Three Requirements
Three things are necessary for creating C programs: a text editor, a compiler and a C standard
library. A text editor is all that is needed to create the source code for a program in C or in any
other language.
Source code (also referred to as source or code) is the version of software as it is originally written
(i.e., typed into a computer) by a human in plain text (i.e., human readable characters).
A text editor is a program for writing and editing plain text. It differs from a word processor in
that it does not manage document formatting (e.g., typefaces, fonts, margins and italics) or other
features commonly used in desktop publishing. C programs can be written using any of the many
text editors that are available for Linux, such as vi, gedit, kedit or emacs.
A compiler is a specialized program that converts source code into machine language (also called
object code or machine code) so that it can be understood directly by a CPU (central processing
unit). An excellent C compiler is included in the GNU Compiler Collection (GCC),
In Windows Environment:Compiling and Executing C program
1. Opening Turbo C Compiler
In general Turbo C compiler is used in windows environment. Open Turbo C directory and
move to BIN sub-directory present in that directory. In BIN directory , we can see the an exe file
called TC( We can also create a shortcut icon of this exe file and placed in the desktop instead
moving to the required path all the time). By Clicking on this , we can enter into Turbo C compiler.
2. Writing and saving a new file:Choose New File option in File menu to create a new file or press Ctrl F+N. A new window is
opned. Then write a simple program like this and for saving the program press F2 or choose the
option Save in File menu. While saving the program the program give extension as C to specify
that the file is a c file. Let the below file is saved as hello.c.
#include<stdio.h>
void main()
{
printf("Hello! This is my first C program\n");
/* Do something more if you want */

}
2. Compile the program
After saving the program choose compile option from Compile Menu or press Alt+F9 to
compile the program.
If there is no syntax/semantic error in program then the compiler will successfully generate an
executable file, otherwise it will displays the number of errors in the code. By using the errors
information , the programmer can fix the errors in the program.
3. Execute the program
To execute the program, choose Run option from Run menu or press CTrl+F9.If the program
requires any input , then the programmer has to enter the data from command prompt. Since the
above program doesnt require any input the programmer doesnt need to supply any data.
The output is generally displayed on the user screen. Hence choose User Screen option from
Windows menu or press Alt+F5 to see the result.
Now we can see the output as follows:Hello! This is my first C program
In
LINUX
Environment:Compiling and Executing C program
1. Write and save the program
Open a simple text editor like gedit or Vim.Here we are using gedit as it is very simple to use
and its recommended for beginner programmers. Right Click on Desktop or any directory and
select create new File hello.c (.c extension is used to indicate that its a c program). Then write a
simple program like this and for saving the program press Ctrl+S.
#include<stdio.h>
void main()
{
printf("Hello! This is my first C program with Ubuntu 11.10\n");
/* Do something more if you want */
}
2. Compile the program
GCC (GNU Compiler Collection) is installed by default. To compile the program, open the terminal
and move on to the target directory type the command (where gcc implies compiler name, then
it asks for the file name of the source program while -o option specifies the file name of the output
program)
gcc hello.c -o hello1
If there is no syntax/semantic error in you program then the compiler will successfully generate
an executable file, otherwise fix the problem in the code.
3. Execute the program
To execute the program, you need to run ./hello1
4(a). Write a c program to find the sum of three numbers
Aim:- to write a program find the sum of three numbers
Program Description:In this program , we accept three numbers and find their sum.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,sum;
clrscr();
printf("\nEnter three numbers :");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
printf("\n Sum of %3d,%3d and %3d is=%4d",a,b,c,sum);
getch();
}

Input:Enter three numbers :24 32 65


Output:Sum of 24, 32 and 65 is= 121
4(b). Write a c program to exchange of two numbers
Aim:- to write program to exchange of two numbers
Program Description:In this program we exchange two numbers without using the third variable. The
process can be performed by using the third variable also.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
printf("\n Before swapping, values are a=%3d and b=%3d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\n After swapping, values are a=%3d and b=%3d",a,b);
getch();
}
Input:Enter two numbers :7 9
Output:Before swapping, values are a=7 and b=9
After swapping, values are a=9 and b=7
4(c). Write a c program to find maximum of two numbers
Aim:- To write a program to find maximum of two numbers
Program Description:In this program , by using the conditional operator we find the maximum of two
numbers.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
max=(a>b)?a:b;
printf("\n Maximum of %3d and %3dis=%3d",a,b,max);
getch();
}
Input:Enter two numbers :15 36
Output:Maximum of 15 and 36 is= 36
4(d). Write a c program to read and print variable values of all data types of C language and
also find their sizes
Aim:- To write a program to read and print variable values of all data types of C language and also
find their sizes.

Program Description:In this program , we accept variables of all data types that are supported by c language and
find their sizes by using sizeof() operator.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a;
long int l;
unsigned int ul;
float f;
double d;
char c;
clrscr();
printf("\nEnter a integer value :");
scanf("%d",&a);
printf("\nEnter an unsigned value :");
scanf("%u",&ul);
printf("\nEnter a long integer value :");
scanf("%ld",&l);
printf("\nEnter a float value :");
scanf("%f",&f);
printf("\nEnter a double value :");
scanf("%lf",&d);
flushall();
printf("\nEnter a character :");
c=getchar();//scanf("%c",&c);
printf("\n Given values are:\n");
printf("\n Integer =%4d and its size=%4d",a,sizeof(a));
printf("\n Unsigned Integer =%4u and its size=%4d",ul,sizeof(ul));
printf("\n Long Integer =%ld and its size=%4d",l,sizeof(l));
printf("\n Float =%6.2f and its size=%4d",f,sizeof(f));
printf("\n Double =%lf and its size=%4d",d,sizeof(d));
printf("\n Character =%c and its size=%4d",c,sizeof(c));
getch();
}
Input:Enter a integer value :6325
Enter an unsigned value :-958
Enter a long integer value :263547
Enter a float value :36.2541
Enter a double value :23.65874
Enter a character :k
Output:Given values are:
Integer =6325 and its size= 2
Unsigned Integer =64578 and its size=2
Long Integer =263547 and its size=4
Float = 36.25 and its size= 4
Double =23.658740 and its size=8
Character =k and its size=1
4(e). Write a c program to understand the priority and associativity of operators using
expressions
Aim:- To write a program to understand the priority and associativity of operators using
expressions

Program Description:In this program , we demonstrate the use of precedence and associativity.Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int r;
clrscr();
r=2+3*8;
// Since multipliation is having higher priority than addition ,
// multiplication is performed first and then addition
printf("\n Result of the above expression is=%d",r);
r=4*8/2+8;
//Both multiplication and division has equal priority and
// hence by using associativity rule , multiplication is performed
//first and then division as the rule is from left to right
printf("\n Result of the above expression is=%d",r);
}
Input:Result of the expression is=26
Result of the expression is=24
4(f). Write a c program to use different library functions of C language.
Aim:- To write a program to use different library functions of C language
Program Description:In this program, we specify the use of various string and mathematical library functions.
Source Code:#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
void main()
{
int n;
float f;
char name[20];
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
f=sqrt(n);
printf("\n Square root of number=%6.4f",f);
printf("\n Ceil value of above result= %f",ceil(f));
printf("\n Floor value of above result= %f",floor(f));
flushall();
printf("\n Enter a name :");
scanf("%s",name);
printf("\n Length of the name=%d",strlen(name));
printf("\n Given name in uppercase= %s",strupr(name));
printf("\n Given name in lowercase= %s",strlwr(name));
printf(" \n Reverse of the name= %s",strrev(name));
}
Input:Enter a number:8
Square root of number=2.8284
Ceil value of above result= 3.000000
Floor value of above result= 2.000000
Enter a name : krishna
Length of the name=7
Given name in uppercase= KRISHNA
Given name in lowercase= krishna
Reverse of the name= anhsirk

5.Write a program to find the roots of a quadratic equation


Aim:- To write a C program to find the roots of a quadratic equation.
Program Description:In this program, based on descriminant which is equal tob2-4ac, we find the roots of the
quadratic equation. If d>=0 , the roots are real otherwise imaginary.
Source Code :#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,d;
float r1,r2;
clrscr();
printf(" \n Enter the values of a,b,c in a quadratic equation : ");
scanf("%d%d%d",&a,&b,&c);
if(a==0)
{
printf("\n The equation is linear");
r1=(float)-c/b;
printf("\n Linear root of the equation is=%f",r1);
}
else
{
d=(b*b)-(4*a*c);
if(d==0)
{
printf("\n The roots are real and equal");
r1=(float)(-b/(2*a));
printf(" Common root is =%6.2f",r1);
}
else if (d>0)
{
printf("\n The roots are real and distinct");
r1=(float)(-b+sqrt(d)/(2*a));
r2=(float)(-b-sqrt(d)/(2*a));
printf("\n One root = %6.2f",r1);
printf("\n Another root is=%6.2f",r2);
}
else
{
printf(" The roots are imaginary");
}
}
}
Input:
Enter the values of a,b,c in a quadratic equation : 2 4 2
Output:
The roots are real and equal
Common root is = -1
Input:
Enter the values of a,b,c in a quadratic equation : 0 2 6
Output:
The equation is linear
Linear root of the equation is= -3
Input:
Enter the values of a,b,c in a quadratic equation : 2 4 8
Output:
The roots are imaginary

6.Write a program to compute the factorial of a given number


Aim:- To write a program to find the factorial of a given number
Program Description:In this program , we multiply a variable i whose value is 1 with another variable f which is
initialized with 1. For each iteration we increment the value of a variable i by 1 and then multiply
with same variable f. The process repeats until the i <= n.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,f=1,i=1;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
while(i<=n)
{
f*=i;
i++;
}
printf("Factorial of %3d is = %5d",n,f);
getch();
}
Input
Enter a number:6
Output
Factorial of 6 is = 720
7. Write a program to check whether the number is prime or not.
Aim :- to write a program to check whether the number is prime or not
Program Description:In this program , we divide the given number by a set of values from 1 to given number. If
the number of factors for the given number is two (i.e.,it is divisible by 1 and itself),then the given
number is considered as prime number.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,k=0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
i=1;
while(i<=n)
{
if(n%i==0)
k++;
i++;
}
if(k==2)
printf("\n Given number is a prime number");
else
printf("\n Given number is not a prime number");
}
Input:
Enter a number : 6

Output:
Given number is not a prime number
Input:
Enter a number :11
Output:
Given number is a prime number
8.Write a program to find the series of prime numbers in the given range
Aim:- To write a C program to generate all the prime numbers between 1 and n .
Program Description:In this program , we divide a number with 2 to number less than one , if the remainder is 0
for any one of the above divisions , we conclude that it is not a prime number else it is a prime
number. The process repeats for 2 to given n value.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k=0;
clrscr();
printf("Enter n value upto where prime numbers to be found: ");
scanf("%d",&n);
if(n==0)
{
printf(" \n Invalid number entered");
}
printf( \n Required prime numbers are :);
i=2;
while(i<=n)
{
k=0;
j=2;
while(j<n)
{
if(i%j==0)
k=1;
j++;
}
if(k==1)
printf(%4d , i);
i++;
}
}
Input :Enter n value upto where prime numbers to be found: 10
Output:
Required prime numbers are :
2 3 5 7
9. Write a program to generate Fibonacci numbers in the given range.
Aim:- to write a C program to generate the Fibonacci numbers in the given range.
Program Description:In this program , we initialize variable f1 to zero and f2 to f1. We print the variable f which
is the sum of f1 and f2. Then we interchange the values such that f2 is stored in f1 and f value is
stored in f2 . The process repeats until n elements are generated.
Source Code :#include<stdio.h>
#include<conio.h>
void main()

{
int n,i,f1=0,f2=1,f;
clrscr();
printf(" \n Enter how many fibonacci numbers you want to print : ");
scanf("%d",&n);
printf("\n Fibonacci series is :\n");
scanf("%d\t%d",f1,f2);
for(i=3;i<=n;i++)
{
f=f1+f2;
printf("\t%d",f);
f1=f2;
f2=f;
}
getch();
}
Input:
Enter how many fibonacci numbers you want to print : 8
Output:Fibonacci series is :
0 1 1 2 3 5 8 13
10. Write a program to find maximum and minimum of set of numbers
Aim:- To write a C program to find both the largest and smallest in a list of integers
Program Description:In this program , we assume first number is both minimum as well as maximum. For
minimum , we compare minimum value with all other elements in the list. If minimum value is
greater than any other value , we make that number as minimum.
For maximum , we compare maximum value with all other elements in the list. If maximum
value is less than any other value , we make that number as maximum
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,min,max,n;
clrscr();
printf("\n Enter no. of elements:");
scanf("%d",&n);
printf("\n Enter the elements :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
min=max=a[1];
for(i=2;i<=n;i++)
{
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
printf("\n Given elements are:\n");
for(i=1;i<=n;i++)
printf("%5d",a[i]);
printf("\n Maximum Value is=%d",max);
printf("\n Minimum Value is=%d",min);
getch();
}
Input
Enter no. of elements:6
Enter the elements : 12 10 8 2 24 15

Output
Given elements are:
12 10 8 2 24 15
Maximum Value is=24
Minimum Value is=2
11. Write a program to reverse the digits of a number.
Aim :- to write a program to reverse the digits of a number
Program Description:In this program , for each iteration we divide the number by 10 and the remainder is added to a
variable sum which is multiplied by 10 for every iteration and we reduce the number to quotient.
The process repeats until n>0
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
printf("\n The reverse of given number is:%d",s);
}
Input:
Enter a number :325
Output:
The reverse of given number is:523
12.Write a program to find the sum of digits of a number
Aim:- To write a C program to find the sum of digits of a number
Program Description:In this program , for each iteration we divide the number by 10 and the remainder is
added to a variable sum which is initialized to Zero and we reduce the number to quotient. The
process repeats until n>0
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n ,r ,s=0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf("\n Sum of the digits is = %4d",s);
getch();
}
Input:
Enter the number : 256

Output:
Sum of the digits is = 13
13. Write a program to find the sum of positive and negative numbers in a given set of
numbers.
Aim:- To write a program to find the sum of positive and negative numbers in a given set of
numbers.
Program Description:We identify each element of the array as positive or negative by comparing with zero.
Then we separately store the sum of positive and negative values in two variables which are
initialized to zero.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,sp=0,sn=0,i;
clrscr();
printf("\n Enter size of the array :");
scanf("%d",&n);
printf("\n Enter the values of array :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
if(a[i]<0) // negative
sn=sn+a[i];
else // positive
sp=sp+a[i];
}
printf("\n In given numbers,sum of positive values :%d",sp);
printf("\n In given numbers,sum of negative values :%d",sn);
}
Input:Enter size of the array:9
Enter the values of array :
8 -5 4 2 -7 -23 65 -32 24
Output:In given numbers, sum of positive values : 103
In given numbers, sum of negative values :-67
14. Write a program to check for number palindrome.
Aim :- to write a program to check for number palindrome
Program Description:In this program , for each iteration we divide the number by 10 and the remainder is added
to a variable sum which is multiplied by 10 for every iteration and we reduce the number to
quotient. The process repeats until n>0. Finally we check the sum and given number , if both are
equal we conclude it as palindrome.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0,k;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
k=n;
while(n>0)
{

r=n%10;
s=(s*10)+r;
n=n/10;
}
if(k==s)
printf("\n Given number is Palindrome");
else
printf("\n Given number is not a palindrome");
}
Input:
Enter a number:125
Output:
Given number is not a palindrome
Input:
Enter a number:313
Output:
Given number is Palindrome
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 write a program to evaluate the sum of the given series
Program Description:In this program , we find the sum of n terms where in each term the numerator is multipled by x
to get the powers of x and denominator is multiplied by k which is initialized by 1 and for every
iteration it is incremented by 1.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
float sum=1.0,s;
int n,i,x,p,m=1;
clrscr();
printf("\n Enter x value :");
scanf("%d",&x);
printf("\n Enter n value :");
scanf("%d",&n);
p=x;
for(i=2;i<=n;i++)
{
s=(float)p/m;
sum=sum+s;
m=m*i;
p=x*p;
}
printf("\n Sum of the given series is :%6.4f",sum);
getch();
}
Input:Enter x value :2
Enter n value :3
Output:Sum of the given series is :5.0000
16. Write a program to generate Pascals Triangle
Aim:- To generate Pascals Triangle
Program Description:In this program , we find binomial co-efficients and print these values in pyramid format

using nesting of for loops.


Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,num=1,den=1,m,r,s,t,p,k;
clrscr();
printf("Enter a value:");
scanf("%d",&n);
s=21;
m=1;
r=0;
for(i=1;i<=n+1;i++)
{
if(i!=2)
{
for(k=1;k<=s;k++)
printf(" ");
for(j=1;j<=i;j++)
{
for(p=m;p>(m-r);p--)
num=num*p;
for(p=1;p<=r;p++)
den=den*p;
t=num/den;
printf("%5d",t);
r++;
num=1;
den=1;
}
m++;
r=0;
s--;
printf("\n\n"); }
}
}
getch();
}
Input
Enter a value: 5
Output
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
17.Write a program to read two matrices and print their sum and product in the matrix
form.
Aim:- To write a program to read matrices and print their sum nad product in the matrix form.
Program Description:In this program , To find the Sum of two matrices, we add the corresponding elements.
To find the product , we multiply first row elements of first matrix with first column
elements of second matrix. We obtain the first element in the product matrix by adding all the
above products. Then we multiply first row elements of first matrix with second column elements
of second matrix. We obtain the second element in the product matrix by adding all the above
products. Repeat the above process for remaining elements in matrix.

Source Code :#include<stdio.h>


#include<conio.h>
void input(int a[8][8],int r,int c);
void output(int a[8][8],int r,int c);
void add(int a[8][8],int b[8][8],int s[8][8],int r,int c);
void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p);
void main()
{
int a[8][8],b[8][8],s[8][8],r1,c1,r2,c2,ch;
clrscr();
printf("\n Enter rows and columns of first matrix:");
scanf("%d%d",&r1,&c1);
printf("\n Enter rows and columns of second matrix:");
scanf("%d%d",&r2,&c2);
printf("\n Enter the elements of first matrix:");
input(a,r1,c1);
printf("\n Enter the elements of second matrix:");
input(b,r2,c2);
printf("\n Elements of first matrix are:");
output(a,r1,c1);
printf("\n Elements of second matrix are:");
output(b,r2,c2);
if((r1==r2)&&(c1==c2))
{
add(a,b,s,r1,c1);
printf("\n Sum of the two matrices is:");
output(s,r1,c1);
}
else
{
printf("\n Matrix addition is not possible");
}
if(c1==r2)
{
multiply(a,b,s,r1,c2,c1);
printf("\n Product of the two matrices is:");
output(s,r1,c2);
}
else
{
printf("\n Matrix multiplication is not possible");
}

getch();
}
void input(int a[8][8],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
void output(int a[8][8],int r,int c)
{
int i,j;
printf("\n");
for(i=0;i<r;i++)
{

for(j=0;j<c;j++)
{
printf("%4d",a[i][j]);
}
printf("\n ");
}
}
void add(int a[8][8],int b[8][8],int s[8][8],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
s[i][j]=a[i][j]+b[i][j];
}
void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p)
{
int i,j,k;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
s[i][j]=0;
for(k=0;k<p;k++)
s[i][j]=s[i][j]+(a[i][k]*b[k][j]);
}
}
Input
Enter rows and columns of first matrix:3 3
Enter rows and columns of second matrix:3 3
Enter the elements of first matrix: 5 2 6 9 8 7 1 2 1
Enter the elements of second matrix:6 4 7 8 4 1 3 2 5
Output
Elements of first matrix are:
5 2 6
9 8 7
1 2 1
Elements of second matrix are:
6 4 7
8 4 1
3 2 5
Sum of the two matrices is:
11 6 13
17 12 8
4 4 6
Product of the two matrices is:
64 40 67
139 82 106
25 14 14
18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
Aim:- To write a program to read matrix and perform operations on it.
Program Description:By interchanging rows and columns we can obtain transpose of a matrix. By adding the sum
of elements where row subscript and column subscript values are equal . We can find the sum of
principle diagonal elements .Similarly we can identify secondary diagonal elements and add to the
above sum.
By diving the number by 2 we can identify whether the element is even or odd .By identifying
them we can find the sum of even and odd element values of the matrix.

Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a[8][8],s=0,se=0,so=0,n,i,j;
clrscr();
printf("\n Enter the order of the matrix :");
scanf("%d",&n);
printf("\n Enter the elemens of the matrix :");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i][j]%2==0) // even number
se=se+a[i][j];
else
so=so+a[i][j];
if( (i==j) || (i+j)==(n+1) ) //diagonal elements
s=s+a[i][j];
}
printf("\n Sum of all diagonal elements is :%d",s);
printf("\n Sum of even numbers in matrix is :%d",se);
printf("\n Sum of odd numbers in matrix is :%d",so);
printf("\n Transpose of the given matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",a[j][i]);
printf("\n");
}
getch();
}
Input:Enter the order of the matrix :3
Enter the elemens of the matrix :
5 2 6
8 1 9
4 3 2
Output:Sum of all diagonal elements is :18
Sum of even numbers in matrix is :22
Sum of odd numbers in matrix is :18
Transpose of the given matrix is:
5 8 4
2 1 3
6 9 2
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 write a program to count of the number of Vowels, Consonants, blank spaces, digits and
special characters in a given line of text
Program Description:In this program we consider aline of text and we identify whether each character is a
vowel or consonant or digit or any other special character by comparing the character with the
required character.

Source Code:#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char line[80];
int i,vow=0,con=0,digit=0,spch=0,spaces=0;
clrscr();
printf("\n Enter a line of text :");
scanf("%[^\n]",line);
i=0;
while(line[i]!='\0')
{
line[i]=tolower(line[i]);
if(isalpha(line[i])!=0)
{
if(line[i]=='a'||line[i]=='e'||line[i]=='i'||line[i]=='o'||line[i]=='u')
vow++;
else
con++;
}
else if(isdigit(line[i])!=0)
digit++;
else if(line[i]==' ' || line[i]=='\t')
spaces++;
else
spch++;
i++;
}
printf("\n In the given line of text :\n");
printf("\n No. of vowels is=%d",vow);
printf("\n No. of consonants is=%d",con);
printf("\n No. of digits is=%d",digit);
printf("\n No. of spaces is=%d",spaces);
printf("\n No. of special characters is=%d",spch);
getch();
}
Input:Enter a line of text : This is 21st century #!
Output:In the given line of text :
No. of vowels is=4
No. of consonants is=11
No. of digits is=2
No. of spaces is=4
No. of special characters is=2
20. Write a program to insert a sub string in to a given string from a given position. Dont
use library functions related to strings.
Aim:- To insert a sub string in to a given string from a given position.
Program Description:In this program , first we find the sub string length (n) and we shift the entire characters
from insertion position to the end by n positions forward and then we insert the sub string into
main string.
Source Code :#include<stdio.h>
#include<conio.h>
#include<string.h>
void insert(char mstr[],char sstr[],int);
void main()

{
char mstr[80],sstr[20];
int p;
printf("\n Enter the main string :");
gets(mstr);
printf("\n Enter sub string to be inserted :");
gets(sstr);
printf("\n Enter the position where substring to be inserted :");
scanf("%d",&p);
insert(mstr,sstr,p);
printf("\n After inserting , the resultant string is :");
puts(mstr);
}
void insert(char mstr[80],char sstr[30],int p)
{
int l1,l2,i,j;
l1=strlen(mstr);
l2=strlen(sstr);
for(i=l1;i>=p;i--)
mstr[i+l2]=mstr[i];
for(i=p,j=0;j<l2;j++,i++)
mstr[i]=sstr[j];
}
Input:Enter the main string : This is a text
Enter sub string to be inserted : sample
Enter the position where sub string to be inserted : 9
Ouput:
After inserting , the resultant string is : This is a sample text
21. Write a program to perform the operations addition , subtraction , multiplication of
complex numbers.
Aim
To perform various operations on complex numbers
Program Description
In this program , we declare a complex number by using a structure which consists of two fields
namely real, img which represents real and imaginary parts of complex numbers respectively.
Here we accept two complex numbers and perform operations like addition , multiplication etc by
using the common procedure that we use for complex numbers.
Source Code
#include<conio.h>
#include<stdio.h>
struct complex
{
float real;
float img;
};
void output(struct complex);
struct complex add(struct complex,struct complex);
struct complex sub(struct complex,struct complex);
struct complex mul(struct complex,struct complex);
void main()
{
struct complex c1,c2,result;
int choice;
clrscr();
printf("\n Enter first complex number");
printf("\n\n Enter real part :");
scanf("%f",&c1.real);
printf("\n\n Enter imaginary part :");

scanf("%f",&c1.img);
printf("\n Enter second complex number");
printf("\n\n Enter real part :");
scanf("%f",&c2.real);
printf("\n\n Enter imaginary part :");
scanf("%f",&c2.img);
result=add(c1,c2);
printf("\n Sum of two complex numbers=");
output(result);
result=sub(c1,c2);
printf("\n Difference of two complex numbers=");
output(result);
result=mul(c1,c2);
printf("\n Product of two complex numbers=");
output(result);
getch();
}
void output(struct complex k)
{
if (k.img>=0)
printf("%2.1f+%2.1fi",k.real,k.img );
else
printf("%2.1f-%2.1fi",k.real,(-k.img) );
}
struct complex add(struct complex x,struct complex y)
{
struct complex t;
t.real=x.real+y.real;
t.img=x.img+y.img;
return(t);
}
struct complex sub(struct complex x,struct complex y)
{
struct complex t;
t.real=x.real-y.real;
t.img=x.img-y.img;
return(t);
}
struct complex mul(struct complex x,struct complex y)
{
struct complex t;
t.real=(x.real*y.real)-(x.img*y.img);
t.img=(x.real*y.img)+(x.img*y.real);
return(t);
}
Input
Enter first complex number
Enter real part :5.2
Enter imaginary part :3.6
Enter second complex number
Enter real part :4.8
Enter imaginary part :6.2

Output
Sum of two complex numbers=10.0+9.8i
Difference of two complex numbers=0.4-2.6i
Product of two complex numbers=2.6+49.5i
22. Write a program to split a file in to two files, say file1 and file2. Read lines into the
file from standard input. File1 should consist of odd numbered lines and file2 should
consist of even numbered lines.
Aim:- To split the files into two files
Program Description:In this program we identify whether a line is odd numbered or even numbered by using a
variable k which is initialized to 1. This variable is incremented by 1 when we encounter \n
character. The odd numbered lines of text is copied to one file and even numbered lines of text are
copied to another file.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;
int k=1;
clrscr();
fp1=fopen("c:/myfile.txt","w");
printf("\n Enter the contents of the file (press # at end):\n");
ch=getchar();
while(ch!='#')
{
putc(ch,fp1);
ch=getchar();
}
fclose(fp1);
fp1=fopen("c:/myfile.txt","r");
fp2=fopen("c:/file1.txt","w");
fp3=fopen("c:/file2.txt","w");
ch=' ';
while(!feof(fp1))
{
putc(ch,fp2);
ch=getc(fp1);
while(ch!='\n'&& !feof(fp1)) //odd numbered lines
{
putc(ch,fp2);
ch=getc(fp1);
}
if(ch=='\n')
{
k++;
if(k%2==0)// even numbered lines
{
putc(ch,fp3);
ch=getc(fp1);
while(ch!='\n' && !feof(fp1))
{
putc(ch,fp3);
ch=getc(fp1);
}
k++;
}
}
}

fcloseall();
}
Input:Enter the contents of the file (press # at end) :
This is aditya
I am studying B.Tech first year
I joined in CSE department
My home town is Tirupathi
My father is a farmer
My Mother is a house wife
My brother is a chartered Accountant #
Output:C:\>type myfile.txt
This is aditya
I am studying B.Tech first year
I joined in CSE department
My home town is Tirupathi
My father is a farmer
My Mother is a house wife
My brother is a chartered Accountant
C:\>type file1.txt
This is aditya
I joined in CSE department
My father is a farmer
My brother is a chartered Accountant
C:\>type file2.txt
I am studying B.Tech first year
My home town is Tirupathi
My Mother is a house wife
23. Write a program to merge two files
Aim
To write a c program to merge two files
Program Description
Here we open the first file in read mode and third fiel in write mode. Now we copy the entire
contents of first file into third file. Now we close the first file and open the second file and copy the
entire contents of second file to third file.
Source Code
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;
clrscr();
fp1=fopen("file1.txt","r");
if(fp1==NULL)
{
printf("Given file does n't exists");
exit(0);
}
fp3=fopen("file3.txt","w");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,fp3);
}
fclose(fp1);

fp2=fopen("file2.txt","r");
if(fp2==NULL)
{
printf("Given file does n't exists");
exit(0);
}
while(!feof(fp2))
{
ch=getc(fp2);
putc(ch,fp3);
}
fcloseall();
}
Output
C:\TC3\BIN>type file1.txt
This is a demo file
My college name is Aditya College of Engineering
Valasapalle , Madanapalle
C:\TC3\BIN>type file2.txt
My Name is Raghu Chandra
I am studying I btech in Aditya College of Engineering
My branch is CSE
C:\TC3\BIN>type file3.txt
This is a demo file
My college name is Aditya College of Engineering
Valasapalle , Madanapalle
My Name is Raghu Chandra
I am studying I btech in Aditya College of Engineering
My branch is CSE
24a. Write a program to implement numerical method - Lagranges interpolation
Aim:- to implement numerical method - Lagranges interpolation
Program Description:Lagranges Interpolation Formula:
1. Newton-Gregory forward interpolation is applicable only to equally spaced values of the
argument; it is not applicable for unequal spaced values of argument.
2. Lagranges interpolation formula for unequal intervals

f ( x)

( x x1 )( x x2 )......( x xn )
f ( x0 )
( x0 x1 )( x0 x2 )......( x0 xn )

( x x0 )( x x2 )......( x xn )
f ( x1 ) .........
( x1 x1 )( x1 x2 )......( x1 xn )

( x x0 )( x x1 )......( x xn 1 )
f ( xn )
( xn x1 )( xn x2 )......( xn xn 1 )
Source Code:#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#define n 5

void main()
{
float y[20],x[20],xinp,u,sum=0,prodd,prodn;

int i,j;
clrscr();
printf("Enter the values of Interpolation Points \n");
for(i=0;i<n;i++)
scanf("%f",&x[i]);
printf("Enter the corresponding values of Y \n");
for(i=0;i<n;i++)
scanf("%f",&y[i]);
printf(" Enter the value of x at which Y(x) is needed \n");
scanf("%f",&xinp);
for(i=0;i<n;i++)
{
prodn=1.0;
prodd=1.0;
for(j=0;j<n;j++)
{
if(i==j)
continue;
prodn=prodn*(xinp-x[j]);
prodd=prodd*(x[i]-x[j]);
}
sum=sum +(prodn/prodd)*y[i];
}
printf(" The value of y is %f\n",sum);
getch();
}
Input:Enter the values of Interpolation Points
2
5
8
10
12
Enter the corresponding values of Y
4.4
6.2
6.7
7.5
8.7
Enter the value of x at which Y(x) is needed : 7
Output
The value of y is 6.486012
24b. Write a program to implement numerical method- Trapezoidal rule.
Aim:- to implement numerical method- Trapezoidal rule
Program Description:Numerical Integration:
Numerical Integration is a process of evaluating a definite integral from a set of tabulated
values of the integrand f(x).
The three methods of numerical integration used are:
1. Trapezoidal Rule.
2. Simpsons 1/3 rule.
3. Simpsons 3/8 rule.
Trapezoidal Rule:
According to trapezoidal rule,
x0 nh

x0

h
f ( x)dx [( sum of first and last ordinates) 2( sum of the remaining ordinates)]
2

Code:#include<stdio.h>
#include<conio.h>
#include<math.h>
float fun(float x)
{
return(1/(1+(x*x)));
}

Source

void main()
{
float x0,x1,sum,result,h;
int i,n,ch;
clrscr();
printf("\n Enter the lower and upper limits :");
scanf("%f%f",&x0,&x1);
printf("\nEnter the number of intervals :");
scanf("%d",&n);
h=(x1-x0)/n;
sum=fun(x0)+fun(x1);
for(i=1;i<n;i++)
sum=sum+2*fun(x0+i*h);
result=sum*h/2;
printf("\n The Result is = %6.2f",result);
getch();
}
Input:
Enter the lower and upper limits :10 80
Enter the number of intervals :8
Output
The Result is = 0.10
25. Write a program to read a set of strings and sort them in alphabetical order.
Aim:- To write a program to read a set of strings and sort them in alphabetical order
Program Description:The sorting of strings is performed in similar to number sorting where we compare the first
number with all the remaining elements to identify the minimum element and placed it in first
position. Similarly we identify all the elements and place them in the corresponding positions.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[15][20],temp[20];
int i,j,n;
clrscr();
printf("\n Enter number of strings :");
scanf("%d",&n);
printf("\n Enter the strings:\n");
for(i=1;i<=n;i++)
scanf("%s",str[i]);
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
printf("\n After sorting strings are :\n");
for(i=1;i<=n;i++)
printf("%s\n",str[i]);
getch();
}
Input:Enter number of strings :6

Enter the strings


ramu
krishna
lakshman
balaji
deepak
abhiram
Output:After sorting strings are :
abhiram
balaji
deepak
krishna
lakshman
ramu
26. Write a program to sort the elements of an array using sorting by exchange( Bubble
Sort).
Aim:- To sort a given list of elements by Bubble Sort
Program Description:In this program , we first find the maximum value and place it in the last position . Then
find second maximum value and place it in last before position . Repeat the above process until all
elements are sorted.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int list[30], n, I, j;
clrscr();
printf(\n Enter no. of elements);
scanf(%d, &n);
printf(\n Enter elements of the list);
for(i=1;i<=n;i++)
scanf(%d, &list[i]);
printf(\n List before sorting:);
for(i=1;i<n;i++)
printf(%d\t , list[i]);
for(i=1;i<=n;i++)
{
for(j=1;j<=(n-i);j++)
{
if(list[j]>list[j+1])
{
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
}
}
printf(List after sorting);
for(i=1;i<=n;i++)
printf(%4d, list[i]);
}
Input: Enter no. of elements
5
Enter elements
23 5 4 9 1
Output: List before sorting 23 5 4 9 1

After sorting
1 4 5 7 9 23
27.Write a program to sort the elements of an array using selection sort.
Aim:- To sort the elements of an array using selection sort.
Program Description:In this program , we first find the minimum value and place it in the first position . Then
find second minimum value and place it in second position . Repeat the above process until all
elements are sorted.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int list[30], n, i, min, loc, j;
clrscr();
printf(\n Enter no.of elements);
scanf(%d, &n);
printf(\n Enter elements of the list);
for(i=1;i<=n;i++)
scanf(%d, &list[i]);
printf(\n List before sorting:);
for(i=1;i<n;i++)
printf(%d\t , list[i]);
for(i=1;i<n;i++)
{
min=list[i];
for(j=i+1;j<=n;j++)
if(min>list[j])
{
min=list[j];
loc=j;
}
temp=list[i];
list[i]=list[loc];
list[loc]=temp;
}
printf(List after Sorting);
for(i=1;i<=n;i++)
printf(%4d, list[i]);
}
Input
Enter number of elements
5
Enter elements of the list
23 11 18 42 64
Output
List before Sorting: 23 11 18 42 64
List after Sorting: 11 18 23 42 64
28. Write a program to perform Linear search on elements of the given array.
Aim:- To search an element in the list by using linear search method
Program Description:In this program , we compare each element of the list with the searching element. If the
element is found, we print the corresponding position. Otherwise we conclude that the element is
not found.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int list[20],n,i,element,flag=0;
clrscr();
printf("\n Enter the number of elements:");
scanf("%d",&n);

printf("\n Enter the elements:");


for(i=0;i<n;i++)
scanf("%d", &list[i]);
printf("\n Enter the element to be searched:");
scanf("%d",&element);
for(i=0;i<n;i++)
{
if(list[i]==element)
{
printf("Element found at position= %d",i+1);
flag=1;
break;
}
}
if(flag==0)
printf("Element Not found");
getch();
}
Input
Enter the number of elements:6
Enter the elements:8 5 4 3 2 1
Enter the element to be searched:3
Output
Element found at position= 4
29. Write a program to perform Binary search on elements of a given array.
Aim:- To search an element in the array by using binary search method
Program Description:In this program , we first determine the middle position. Then we compare the searching
element with middle position value , if the element is found , we print the middle position and
display the element is found. If searching value is less than the middle position value ,we swift tha
value of last position to middle-1 position other we swift the beginning value position to middle
+1 Otherwise we conclude that the element is not found.
Source Code :#include<stdio.h>
#include<conio.h>
void main()
{
int list[20],n,i,element,flag=0,l,u,m;
clrscr();
printf("\n Enter the number of elements:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
scanf("%d", &list[i]);
printf("\n Enter the element to be searched:");
scanf("%d",&element);
l=0;
u=n-1;
while(l<=u)
{
m=(l+u)/2;
if(list[m]==element)
{
printf("Element found at position= %d",m+1);
flag=1;
break;
}
else

{
if(list[m]<element)
l=m+1;
else
u=m-1;
}
}
if(flag==0)
printf("Element Not found");
getch();
}
Input
Enter the number of elements:8
Enter the elements:4 8 3 21 65 14 87 20
Enter the element to be searched:8
Output
Element found at position= 2
30. Write a program to find the number of occurrences of each number in a given array of
numbers.
Aim:- To write a program to find the number of occurrences of each number in the given array
Program Description:- In this program we first copy distinct values of given array into a
temporary array and by using this temporary array we find the number of occurrences of element
in the given array.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],b[20],i,j,n,count=0,k=1;
clrscr();
printf("\n Enter the size of the array :");
scanf("%d",&n);
printf("\n Enter the array elements");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
// copy distinct elements of A into B
b[k]=a[1];
for(i=2;i<=n;i++)
{
k++;
b[k]=a[i];
for(j=1;j<k;j++)
if(b[j]==b[k])
{
k--;
break;
}
}
printf("\n Occurrences of each number in the array are:\n");
for(i=1,j=1;i<=n&&j<=k;i++)
{
if(b[j]==a[i])
count++;
if(i==n)
{
printf("\n Element %d occurred for %d times",b[j],count);
i=1;
count=0;
j++;
}

}
getch();
}
Input:Enter the size of the array :8
Enter the array elements : 7 5 6 7 2 5 1 5
Output:Occurrences of each number in the array are:
Element 7 occurred for 2 times
Element 5 occurred for 3 times
Element 6 occurred for 1 times
Element 2 occurred for 1 times
Element 1 occurred for 1 times
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 implementations of functions.
i. String length determination ii .Compare Two Strings
iii. Concatenate them, if they are not equal iv. String reversing
Aim:- To write a program to read two strings and perform operations on them without using
library functions.
Program Description:We find the string length by comparing each character of the string and increment a variable
whose initial value is 0 until we encounter a null character. Then this variable specifies the length
of the string. Once we find the length we can perform reversing by printing the characters from
last to first. Similarly by comparing the corresponding position characters in the given two strings
,we can identify whether the given strings are equal or not.
Source Code:#include<stdio.h>
#include<conio.h>
int stringlength(char *s);
int stringcompare(char *s1,char *s2,int ,int)
void stringconcatenate(char *s1,char *s2,int,int);
void stringreverse(char *s,int);
void main()
{
char str1[20],str2[30];
int n,i,k,l1,l2;
clrscr();
printf("\n Enter the first string:");
scanf("%s",str1);
printf("\n Enter the second string: ");
scanf("%s",str2);
l1=stringlength(str1);
printf("\n Length of first string is=%d",l1);
l2=stringlength(str2);
printf("\n Length of Second string is=%d",l2);
k=stringcompare(str1,str2,l1,l2);
if(k==1)
printf("\n Two strings are equal\n");
else
{
printf("\n Two strings are not equal");
printf("\n After concatenating two strings, resultant string is:");
stringconcatenate(str1,str2,l1,l2);
}
printf("\n Reverse of first string is=");

stringreverse(str1,l1);
printf("\n Reverse of second string is=");
stringreverse(str2,l2);
getch();
}
int stringlength(char *str)
{
int k;
for(k=0;str[k]!='\0';k++);
return(k);
}
int stringcompare(char *s1,char *s2,int l1,int l2)
{
int i,t=0;
if(l1==l2)
{
for(i=0;i<l1;i++)
if(s1[i]!=s2[i])
t=1;
if(t==0)
return(1);
else
return(0);
}
else
return(0);
}
void stringconcatenate(char *s1,char *s2,int l1,int l2)
{
int i;
char str[60];
for(i=0;i<l1;i++)
str[i]=s1[i];
str[l1]=' ';
l1++;
for(i=0;i<l2;i++)
str[l1+i]=s2[i];
printf("%s",str);
}
void stringreverse(char *s,int l)
{
int i;
for(i=l-1;i>=0;i--)
printf("%c",s[i]);
}
Input:Enter the first string : krishna
Enter the second string : kishore
Output:Length of first string is=7
Length of Second string is=7
Two strings are not equal
After concatenating two strings, resultant string is :krishna kishore
Reverse of first string is=anhsirk
Reverse of second string is=erohsik
Input:-

Enter the first string:balu


Enter the second string: balu
Output:Length of first string is=4
Length of Second string is=4
Reverse of first string is=ulab
Reverse of second string is=ulab
32(a). Write program using recursion for finding the factorial of a number.
Aim:- To find the factorial of a number using recursion
Program Description:In this program we compare whether n0.If the condition is true we return 0 otherwise we
recursively call the same function by reducing the value of n by 1.
Source Code:#include<stdio.h>
#include<conio.h>
int rfact(int n)
{
if(n==0 || n==1)
return 1;
else
return(n*rfact(n-1));
}
void main()
{
int n,f;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
f= rfact(n);
printf("Factorial of %3d is=%d ",n,f);
getch();
}
Input:Enter a number:5
Output:Factorial of 5 is=120
32(b). Write program using recursion for finding the GCD of two numbers.
Aim:- To find the GCD of two numbers using recursion
Program Description:Let x, y be two values. If x mod y=0 we return y else we consider y value as x and x mod y
as y. By using these new values of x and y we recursively call the same function.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
clrscr();
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
if(a>b)
r=rgcd(a,b);
else
r=rgcd(b,a);
printf("GCD of %3d and %3d is=%3d",a,b,r);

getch();
}
int rgcd(int x,int y)
{
if (x%y==0)
return y;
else
return rgcd(y,(x%y));
}
Input:Enter two numbers:8 2
Output:GCD of 8 and 2 is= 2
32(c). Write program using recursion for finding the LCM of two numbers.
Aim:- To find the LCM of two numbers using recursion.
Program Description:We initialize a variable by 1. We divide this variable with the given two numbers. If both of
the remainders are zero we return the variable otherwise we increment the variable by one.
Source Code:#include<stdio.h>
#include<conio.h>
int lcm(int, int);
void main()
{
int a, b, result;
clrscr();
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
getch();
}
int lcm(int a, int b)
{
static int common = 1;
if (common % a == 0 && common % b == 0)
return common;
common++;
lcm(a, b);
return common;
}
Input:Enter two numbers: 8 6
Output:The LCM of 8 and 6 is 24
32(d). Write program using recursion to solve the problem of Towers of Hanoi.
Aim:- To solve the problem of Towers of Hanoi by using recursion
Program Description:Towers of Hanoi:
Problem:
The Towers of Hanoi is a well known childrens game , played with three poles and a number of
different sized disks. Each disk has a hole in the center , allowing it to be placed around any of the
poles. Initially , the disks are placed on the leftmost pole in the order of decreasing as shown
below:

Left

center

Right

Object of the Game:


The Object of the game is to transfer the disks from the leftmost pole to the right most pole .
Rules of the Game:
Only one disk is to be transferred at a time.
Each disk must always be placed around one of the poles but not outside.
A larger disk should not be placed on top of a smaller disk .
Solution of the Game:
Assume that there are n disks, numbered from smallest to largest . If disks are initially stacked
on the left pole , the problem of moving all n disks to the right pole can be stated in the following
recursive manner.
1. Move the top n-1 disks from the left pole to the center pole.
2. Move the nth disk from left pole to right pole
3. Move the n-1 disks on the center pole to the right pole.
Source Code:#include<stdio.h>
#include<conio.h>
void transfer(int,char,char,char);
void main()
{
int n,ch;
clrscr();
printf("\n Enter no. of disks:");
scanf("%d",&n);
transfer(n,'l','r','t');
getch();
}
void transfer(int n, char from, char to,char temp)
{
if(n>0)
{
transfer(n-1,from,temp,to);
printf("\n Move disk %3d from %3c to %3c",n-1,from,to);
transfer(n-1,temp,to,from);
}
}
Input:Enter no. of disks:3
Output:Move disk
Move disk
Move disk
Move disk
Move disk
Move disk
Move disk

0 from
1 from
0 from
2 from
0 from
1 from
0 from

l to
l to
r to
l to
t to
t to
l to

r
t
t
r
l
r
r

33(a) Write a program to convert infix expression into postfix expression


Aim
To write a c-program to convert infix expression to postfix expression
Program Description
One of the best applications of stack is to convert infix expression to postfix expression. Here
we push all the characters into the stack after encountering the ( character . If the character ) is
encountered , tehn all the elements of the stack are popped until ( the character is encountered.
When an operator is encountered depending upon the priority the expression is cnverted.

Source Code
#include<stdio.h>
#include<conio.h>
#include<string.h>
char stack[20];
int top=-1;
void push(char item)
{
top++;
stack[top]=item;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
int priority(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
case '/':
case '*':return 4;
case '^':
case '$':return 6;
case '(':
case ')':
case '#':return 1;
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':return 1;
break;
default: return 0;
}
}
void convert(char infix[],char postfix[])
{
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{

symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else
{
if(symbol=='(' )
push(symbol);
else if(symbol==')' )
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();//remove out (
}
else
{
if(priority(symbol) > priority(stack[top]))
push(symbol);
else
{
while(priority(symbol<=priority(stack[top])))
{
postfix[j]=pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
void main()
{
char infix[30],postfix[30];
clrscr();
printf("\n Enter a valid infix expression :\n");
gets(infix);
convert(infix,postfix);
printf("\n Equivalent postfix expression is : \n");
puts(postfix);
getch();
}
Input:
Enter a valid infix expression :
(((a+b)/c)*d)-f)
Output:
Equivalent postfix expression is :
ab+c/d*f-

33(b) Write a program to evaluate the postfix expression


Aim
To write a c-program to evaluate the postfix expression
Program Description
One of the best applications of stack is to evaluate the postfix expression. Here we first accept a
postfix expression. We retrieve character by character from postfix expression. While retrieving if
the character is other than Operator then it is pushed into the stack . If the character is operator
,then we pop the top most two elements and perform the respective operation on the two popped
values. The process continues until the entire expression is evaluated.
Source Code
#include<stdio.h>
#include<conio.h>
typedef struct
{
int a[100];
int top;
}stack;
void push(stack *s,int x)
{
if(s->top==99)
{
printf("stack overflow");
exit(0);
}
else
s->a[++s->top]=x;
}
int pop(stack *s)
{
int x;
if(s->top<0)
{
printf("stack underflow");
exit(0);
}
else
x=s->a[s->top--];
return x;
}
int operation(int p1,int p2,char op)
{
switch(op)
{
case '+': return p1+p2;
case '*': return p1*p2;
case '-': return p1-p2;
case '/': return p1/p2;
}
}
int evaluate(char pos[])
{
stack s1;
int p1,p2,result,i,n;
s1.top=-1;
for(i=0;pos[i]!='\0';i++)
{
if(isalpha(pos[i]))
{
printf("Enter the value of %c in the given expression :",pos[i]);

scanf("%d",&n);
push(&s1,n);
}
else
{
p2=pop(&s1);
p1=pop(&s1);
result=operation(p1,p2,pos[i]);
push(&s1,result);
}
}
return pop(&s1);
}
void main()
{
char postfix[100];
clrscr();
printf("Enter a valid postfix string :");
gets(postfix);
printf("Required result is=%d",evaluate(postfix));
getch();
}
Input
Enter a valid postfix string : ab+cEnter the value of a in the given expression :24
Enter the value of b in the given expression :14
Enter the value of c in the given expression : 7
Output
Required result is=31
34. Write a program to exchange two numbers using pointers.
Aim:- To exchange two numbers using pointers
Program Description:We use call by reference to swap two numbers using pointers
Source Code:#include<stdio.h>
#include<conio.h>
void exchange(int *,int *);
void main()
{
int a,b;
clrscr();
printf("\n Enter two numbers :");
scanf("%d%d",&a,&b);
printf("\n Before exchanging ,a=%d and b=%d",a,b);
exchange(&a,&b);
printf("\n After exchanging ,a=%d and b=%d",a,b);
getch();
}
void exchange(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Input:Enter two numbers :5 9
Output:-

Before exchanging ,a=5 and b=9


After exchanging ,a=9 and b=5
35 (a) Write a program to implement stack using arrays
Aim
To write a c program to implement stack using arrays
Program Description
A stack is a list of elements in which an element may be inserted or deleted at only one end
called top of the stack.
Example: a stack of dishes, a stack of coins
Stacks are also called a last-in-first-out (LIFO) list , that means the elements are removed
from a stack in the reverse order of that which they were inserted into the stack.
They are also called piles or push-down lists.
Special terminology used for two basic operations associated with stack are:
o Push is the term used to insert an element into the stack
o Pop is term used to delete an element from the stack
Source Code
#include<stdio.h>
#define MAX 30
#include<stdlib.h>
void push(int stack[],int *top, int value)
{
if(*top<MAX)
{
*top=*top+1;
stack[*top]=value;
}
else
{
printf("The stack is full cannot push a value\n");
exit(0);
}
}
void pop(int stack[], int *top, int *value)
{
if(*top>=0)
{
*value=stack[*top];
*top=*top-1;
}
}
void display(int stack[], int top)
{
int i;
for(i=0;i<=top;i++)
printf("%5d",stack[i]);
}
void main()
{
int stack[MAX],top=-1,n,value;
clrscr();
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
push(stack,&top,value);
printf("\n Enter the element to be inserted :");
scanf("%d", &value);

push(stack,&top,value);
if(top==-1)
{
printf("\n Stack is Empty");
}
printf("\n Elements of stack are:=");
display(stack,top);
pop(stack,&top,&value);
printf("\n After performing pop operation,the value deleted is %d\n", value);
printf("\n Elements of stack are:=");
display(stack,top);
getch();
}
Input
Enter the element to be inserted : 12
Enter the element to be inserted : 36
Elements of stack are:= 12 36
After performing pop operation,the value deleted is 36
Elements of stack are:= 12
35 (b) Write a c program to implement stack using linked list
Aim
To write a c program to implement stack using linked list
Program Description
A stack is a list of elements in which an element may be inserted or deleted at only one end
called top of the stack.
Example: a stack of dishes, a stack of coins
Special terminology used for two basic operations associated with stack are:
o Push is the term used to insert an element into the stack
o Pop is term used to delete an element from the stack
Although array representation of stack is very easy and convenient but it allows only to
represent a fixed sized stack.
In several situations , the size of the stack may vary during the program execution.
The solution for this problem is to represent a stack using the linked list.
Singly linked list structure is sufficient to represent any stack.
Source Code: #include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
void push(struct node **top, int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available Error \n");
exit(0);
}
temp->data=value;
temp->link=*top;
*top=temp;
}

void pop(struct node **top, int *value)


{
struct node *temp;
*value=(*top)->data;
temp=*top;
*top=(*top)->link;
free(temp);
}
void display(struct node *top)
{
struct node *temp;
temp=top;
while(temp!=NULL)
{
printf("%5d",temp->data);
temp=temp->link;
}
}
void main()
{
struct node *top=NULL;
int n, value,choice=0;
clrscr();
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
push(&top,value);
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
push(&top,value);
if(top==NULL)
{
printf("\n Stack is Empty");
}
printf("\n Elements of stack are:=");
display(top);
pop(&top,&value);
printf("\n After performing pop operation,the value deleted is %d\n", value);
printf("\n Elements of stack are:=");
display(top);
getch();
}
Input:
Enter the element to be inserted :15
Enter the element to be inserted :64
Elements of stack are:= 64 15
After performing pop operation,the value deleted is 64
Elements of stack are:= 15
35( c ) Write a program to implement a Queue using arrays
Aim
To write a c-program to implement a Queue using arrays
Program Description
A Queue is a linear list in which additions and deletions take place at different ends.
The end at which new elements are added is called the rear
The end at which the old elements are deleted is called the front.
The terms front and rear are used in describing a linear list only when it is implemented as
a queue.

Queues are also called first-in-first-out(FIFO) lists .


Ex: People waiting in line at a bank.
Source Code
#include<stdio.h>
#include<stdlib.h>
#define MAX 30
void insert(int queue[],int *front,int *rear, int value)
{
if(*front==-1)
*front=0;
if(*rear<MAX-1)
{
*rear=*rear+1;
queue[*rear]=value;
}
else
{
printf("QUEUE OVERFLOW \n");
}
}
void display(int queue[],int front,int rear)
{
int i;
if((front!=-1)&&(front<=rear))
for(i=front;i<=rear;i++)
printf("%4d",queue[i]);
else
printf("Queue is empty");
return;
}
void Delete(int queue[], int *front,int *rear,int *value)
{
*value=queue[*front];
if(*front==*rear)
*front=*rear=-1;
else
*front=*front+1;
}
void main()
{
int queue[MAX],front,rear,value,choice=0;
clrscr();
front=rear=-1;
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
insert(queue,&front,&rear,value);
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
insert(queue,&front,&rear,value);
if(front==-1)
{
printf("\n Queue is Empty");
}
printf("\n Elements of Queue are:=");
display(queue,front,rear);
Delete(queue,&front,&rear,&value);

printf("\n After performing deletion operation,the value deleted is %d\n", value);


printf("\n Elements of Queue are:=");
display(queue,front,rear);
getch();
}
Input
Enter the element to be inserted :47
Enter the element to be inserted :32
Elements of Queue are:= 47 32
After performing deletion operation,the value deleted is 47
Elements of Queue are:= 32
35(d) Write a program to implement a Queue using linked lists
Aim
To write a c-program to implement a Queue using linked lists
Program Description
A Queue is a linear list in which additions and deletions take place at different ends.
The end at which new elements are added is called the rear
The end at which the old elements are deleted is called the front.
The terms front and rear are used in describing a linear list only when it is implemented as
a queue.
Queues are also called first-in-first-out(FIFO) lists .
Ex: People waiting in line at a bank.
A queue can be represented as chain.
There are two possibilities for binding front and rear . They are
The direction of linkage is determined by the relatively difficult of performing additions
and deletions.
For insertion, both linkage directions are well suited
For deletion, front-to-rear linkage is more effective
Source Code
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
void insert(struct node **front, struct node **rear, int value)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available Error\n");
exit(0);
}
temp->data=value;
temp->link=NULL;
if(*rear==NULL)
{
*rear=temp;
*front=*rear;
}
else
{
(*rear)->link=temp;
*rear=temp;

}
}
void Delete(struct node **front, struct node **rear, int *value)
{
struct node *temp;
*value=(*front)->data;
temp=*front;
if(*rear==temp)
*front=*rear=NULL;
else
*front=(*front)->link;
free(temp);
}
void display(struct node **front, struct node **rear)
{
struct node *temp;
temp=*front;
if(*front==*rear)
printf("%4d",temp->data);
else
do
{
printf("%4d",temp->data);
temp=temp->link;
}while(temp!=NULL);
}
void main()
{
struct node *front=NULL,*rear=NULL;
int n, value,choice=0;
clrscr();
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
insert(&front,&rear,value);
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
insert(&front,&rear,value);
if((front==rear) && (front==NULL))
{
printf("\n Queue is Empty");
}
printf("\n Elements of Queue are:=");
display(&front,&rear);
Delete(&front,&rear,&value);
printf("\n After performing deletion operation,the value deleted is %d\n", value);
printf("\n Elements of Queue are:=");
display(&front,&rear);
getch();
}
Input
Enter the element to be inserted :41
Enter the element to be inserted :36
Elements of Queue are:= 41 36
After performing deletion operation,the value deleted is 41

Elements of Queue are:= 36


35 (e) Write a program to implement circular queue using arrays.
Aim :- to implement circular queue using arrays.
Program Description: A circular queue is a queue in which all locations are treated as circular such that the first
location q[0] follows the last location q[max-1]
Source Code :
#include<stdio.h>
#include<stdlib.h>
#define MAX 30
void insert(int cqueue[],int *front,int *rear, int value)
{
if(*front==-1)
*front=0;
if(*rear<MAX-1)
{
*rear=(*rear+1) % MAX;
cqueue[*rear]=value;
}
else if ((*front !=-1) && (*front==*rear))
{
printf("QUEUE OVERFLOW \n");
}
}
void display(int cqueue[],int front,int rear)
{
int i;
if(front!=-1)
{
if(front<=rear)
for(i=front;i<=rear;i++)
printf("%4d",cqueue[i]);
else
if(front > rear)
for(i=rear;i<=front;i++)
printf("%4d",cqueue[i]);
}
else
printf("Queue is empty");
return;
}
void Delete(int cqueue[], int *front,int *rear,int *value)
{
*value=cqueue[*front];
if(*front==*rear)
*front=*rear=-1;
else
*front=(*front+1) % MAX;
}
void main()
{
int cqueue[MAX],front,rear,value,choice=0;
clrscr();
front=rear=-1;
printf("\n Enter the element to be inserted :");
scanf("%d", &value);
insert(cqueue,&front,&rear,value);

printf("\n Enter the element to be inserted :");


scanf("%d", &value);
insert(cqueue,&front,&rear,value);
if((front==rear) && (front==NULL))
{
printf("\n Queue is Empty");
}
printf("\n Elements of Circular Queue are:=");
display(cqueue,front,rear);
Delete(cqueue,&front,&rear,&value);
printf("\n After performing deletion operation,the value deleted is %d\n", value);
printf("\n Elements of Circular Queue are:=");
display(cqueue,front,rear);
getch();
}
Input:
Enter the element to be inserted :45
Enter the element to be inserted :63
Elements of Circular Queue are:= 45 63
After performing deletion operation,the value deleted is 45
Elements of Circular Queue are:= 63
35 (f) Write a program to implement circular queue using linked list.
Aim :- to implement circular queue using linked list.
Program Description: A circular queue is a queue in which all locations are treated as circular such that the first
location q[0] follows the last location q[max-1]
Source Code :
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct node
{
int data ;
struct node * link ;
};
void addcirq ( struct node **f, struct node **r, int item )
{
struct node *q ;
q=malloc(sizeof(struct node));
q->data=item ;
if(*f==NULL)
*f=q;
else
(*r)->link=q;
*r=q ;
(*r)->link=*f ;
}
int delcirq ( struct node **f, struct node **r )
{
struct node *q ;

int item ;
if(*f==NULL)
printf("queue is empty");
else
{
if(*f==*r)
{
item=(*f)->data;
free(*f) ;
*f=NULL ;
*r=NULL ;
}
else
{
q=*f ;
item=q->data;
*f=(*f)->link;
(*r)->link=*f;
free(q);
}
return(item);
}
return NULL ;
}
void cirq_display(struct node *f)
{
struct node *q=f,*p=NULL;
while(q!=p)
{
printf("%d\t",q->data) ;
q=q->link;
p=f;
}
}
void main( )
{
struct node *front, *rear ;
int value;
clrscr();
front=rear=NULL ;
printf("\n Enter the value to be inserted :");
scanf("%d",&value);
addcirq ( &front, &rear,value) ;
printf("\n Enter the value to be inserted :");
scanf("%d",&value);
addcirq ( &front, &rear,value) ;
printf ( "Before deletion,Elements of circular queue are:" ) ;
cirq_display(front);
value=delcirq(&front,&rear);
printf("\n After performing delete operation , the value deleted is:%d",value);
printf ( "\n\nAfter deletion ,elements of circular queue are:" ) ;
cirq_display(front);
getch();
}
Input:Enter the value to be inserted :84
Enter the value to be inserted :42

Before deletion,Elements of circular queue are:84


42
After performing delete operation , the value deleted is:84
After deletion ,elements of circular queue are:42
36. Write a program to perform the operations creation, insertion , deletion and traversing
a singly linked list
Aim
To write a c program to perform various operations on linked list using functions
Program Description
Singly Linked list:
In a linked list, each element of an instance of a data object is represented in a cell or node.
Each node keeps explicit information about the location of other relevant nodes.
This explicit information about the location of another node is called a link or reference.
Let l=(e0,e1,en-1) be a linear list. It is possible to represent these elements in a linked list
where each element ei is represented in a separate node.
Each node has exactly one link field that is used to locate the next element in the list.
The last node has no node to link to and so its link field is null.
The variable firstNode points to the first node in the representation.
Since each node in the linked representation has exactly one link, the structure is called
singly linked list.
The structure is also called chain.
Source Code
#include<stdio.h>
#include<conio.h>
struct list
{
int info;
struct list *link;
};
typedef struct list node;
void create_list(int);
void insert_first(int);
void insert_last(int);
void insert_pos(int,int);
node *del_first(node *);
node *del_last(node *);
node *del_pos(node *,int pos);
void display(node *);
node *start,*last;
void main()
{
int ch,num,pos,count;
start=last=NULL;
do
{
clrscr();
printf("\n 1. Add Node");
printf("\n 2. Insert First");
printf("\n 3.Insert Last");
printf("\n 4.Insert at Position");
printf("\n 5.Delete First");
printf("\n 6.Delete Last");
printf("\n7.Delete at Position");
printf("\n 8.Print List");
printf("\n 9.Exit");
printf("\n Enter your choice :");
scanf("%d",&ch);
switch(ch)
{

case 1: printf("\n Enter a number:");


scanf("%d",&num);
create_list(num);
printf("Node created");
getch();
break;
case 2: printf("\n Enter the number at first");
scanf("%d",&num);
insert_first(num);
printf(" Node inserted at first position");
getch();
break;
case 3: printf("\n Enter the number at last");
scanf("%d",&num);
insert_last(num);
printf(" Node inserted at last position");
getch();
break;
case 4: printf("\n Enter the number");
scanf("%d",&num);
printf("\n Enter the position");
scanf("%d",&pos);
insert_pos(num,pos);
printf(" Node inserted at your specified position");
getch();
break;
case 5: if(start==NULL)
printf("List is empty");
else
start=del_first(start);
getch();
break;
case 6: if(start==NULL)
printf("List is empty");
else
start=del_last(start);
getch();
break;
case 7: if(start==NULL)
printf("List is empty");
else
{
printf("\n Enter the position");
scanf("%d",&pos);
start=del_pos(start,pos);
}
getch();
break;
case 8: if(start==NULL)
printf("List is empty");
else
display(start);
getch();
break;
default: printf("Invalid choice");
exit(0);
}
}
while(ch!=9);
}

void create_list(int item)


{
struct list *new1;
new1=(node *)malloc(sizeof(node));
new1->info=item;
new1->link=NULL;
if(start==NULL)
start=new1;
else
last->link=new1;
last=new1;
}
void insert_first(int item)
{
struct list *new1;
new1=(node *)malloc(sizeof(node));
new1->info=item;
new1->link=NULL;
if(start==NULL)
start=new1;
else
new1->link=start;
start=new1;
}
void insert_last(int item)
{
struct list *new1,*temp;
new1=(node *)malloc(sizeof(node));
new1->info=item;
new1->link=NULL;
temp=start;
while(temp->link!=NULL)
temp=temp->link;
if(start==NULL)
start=new1;
else
last->link=new1;
last=new1;
}
void insert_pos(int item,int pos)
{
struct list *new1,*temp;
int count;
new1=(node *)malloc(sizeof(node));
new1->info=item;
new1->link=NULL;
if(pos==1)
{
new1->link=start;
start=new1;
}
else
{
temp=start;
count =2;
while(count<pos && temp->link!=NULL)
{
temp=temp->link;
count++;
}
if(start==NULL)

start=new1;
else
if(count!=pos)
temp->link=new1;
else
{
new1->link=temp->link;
temp->link=new1;
}
}
}
node *del_first(node *start)
{
node *temp;
temp=start->link;
printf(" %d is deleted from list \n",start->info);
start=temp;
return(start);
}
node *del_last(node *start)
{
node *temp;
if(start->link==NULL)
{
printf(" %d is deleted from list",start->info);
start=NULL;
}
else
{
temp=start;
while(temp->link->link!=NULL)
temp=temp->link;
printf(" %d is deleted from list",temp->link->info);
temp->link=NULL;
}
return(start);
}
node *del_pos(node *start,int pos)
{
node *temp;
int count=2;
if(pos==1)
{
printf(" %d is deleted from list",start->info);
start=start->link;
}
else
{
temp=start;
while(count<pos&&temp->link->link!=NULL)
{
temp=temp->link;
count++;
}
printf(" %d is deleted from list",temp->link->info);
temp->link=temp->link->link;
}
return(start);

}
void display(node *start)
{
node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d ->",temp->info);
temp=temp->link;
}
printf("NULL");
}
Output
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :1
Enter a number:10
Node created

1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :1
Enter a number:20
Node created
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :2
Enter the number at first:5
Node inserted at first position
1. Add Node
2. Insert First
3.Insert Last

4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :3
Enter the number at last:25
Node inserted at last position
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :4
Enter the number :15
Enter the position :3
Node inserted at your specified position
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :8
5 ->10 ->15 ->20 ->25 ->NULL
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :5
5 is deleted from list
1. Add Node
2. Insert First
3.Insert Last
4.Insert at Position
5.Delete First
6.Delete Last
7.Delete at Position
8.Print List
9.Exit
Enter your choice :9

37. 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.
Aim:- To read student records into a file and Write the first class, second class, third class and
failed students lists separately to another file as per JNTU rules.
Program Description:In this program we input the rollno , name and six subject marks of each student and
calciulate the grade of the student based on JNTU A rules.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char rollno[10];
char name[15];
int sub[6];
char grade[15];
}s[20];
void main()
{
int n,k,i,j,avg,d[20],f[20],se[20],t[20],fail[20],dc,fc,sc,tc,failc;
FILE *fp;
clrscr();
printf("\n Enter no. of students :");
scanf("%d",&n);
printf("\n Enter students details :");
for(i=1;i<=n;i++)
{
printf("\n Enter %d student details :",i);
flushall();
printf("\n Roll No :");
gets(s[i].rollno);
flushall();
printf("Name=");
gets(s[i].name);
printf("\n Enter six subject Marks:");
for(j=1;j<=6;j++)
scanf("%d",&s[i].sub[j]);
}
dc=fc=sc=tc=failc=0;
for(i=1;i<=n;i++)
{
if(s[i].sub[1]<40 || s[i].sub[2]<40 ||s[i].sub[3]<40
||s[i].sub[4]<40 ||s[i].sub[5]<40 ||s[i].sub[6]<40)
{
failc++;
fail[failc]=i;
strcpy(s[i].grade,"Fail");
}
else
{
avg=(s[i].sub[1]+s[i].sub[2]+s[i].sub[3]+s[i].sub[4]
+s[i].sub[5]+s[i].sub[6])/6;
if(avg>=70)
{
dc++;

d[dc]=i;
strcpy(s[i].grade,"Distinction");
}
else if(avg>=60)
{
fc++;
f[fc]=i;
strcpy(s[i].grade,"First Class");
}
else if(avg>=50)
{
sc++;
se[sc]=i;
strcpy(s[i].grade,"Second Class");
}
else
{
tc++;
t[tc]=i;
strcpy(s[i].grade,"Third Class");
}
}
}
fp=fopen("Results.txt","w");
fputs("Details of Distinction students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=dc;i++)
{
k=d[i];
fprintf(fp,"%10s%3s%4s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of First class students \n",fp);
fputs("Roll No \t Name \t Grade \n\n",fp);
for(i=1;i<=fc;i++)
{
k=f[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Second class students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=sc;i++)
{
k=se[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Third class students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=tc;i++)
{
k=t[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
fputs("\nDetails of Failed students \n",fp);
fputs("Roll No \t Name \t Grade \n",fp);
for(i=1;i<=failc;i++)
{
k=fail[i];
fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);
}
}

Input:Enter no. of students :5


Enter students details :
Enter 1 student details :
Roll No :108P1A0312
Name=Rakesh
Enter six subject Marks:65 84 73 81 96 77
Enter 2 student details :
Roll No :108P1A0318
Name=Bala Krishna
Enter six subject Marks:42 36 58 64 55 48
Enter 3 student details :
Roll No :108P1A0325
Name=Raghu
Enter six subject Marks:78 84 77 45 55 42
Enter 4 student details :
Roll No :108P1A0342
Name=Krishna
Enter six subject Marks:42 47 43 40 45 51
Enter 5 student details :
Roll No :108P1A0355
Name=Radhika
Enter six subject Marks:55 64 52 51 58 60
Output:C:\TC3\BIN>type results.txt
Details of Distinction students
Roll No
Name
Grade
108P1A0312 Rakesh
Distinction
Details of First class students
Roll No
Name Grade
108P1A0325 Raghu
First Class
Details of Second class students
Roll No
Name
Grade
108P1A0355 Radhika
Second Class
Details of Third class students
Roll No
Name
Grade
108P1A0342 Krishna
Third Class
Details of Failed students
Roll No
Name
Grade
108P1A0318 Bala Krishna Fail
39. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.
Aim:- To perform Base (decimal, octal, hexadecimal, etc) conversion
Program description:
In this program we input a decimal value and we convert that decimal value into binary,
octal and hexe decimal value.
Source Code:
#include<stdio.h>
#include<conio.h>
void dec_bin(int decimal)

{
int r,q,bin[20],i=1,j;
q=decimal;
while(q!=0)
{
bin[i++]=q%2;
q=q/2;
}
for(j=i-1;j>0;j--)
printf("%d",bin[j]);
}
void dec_oct(int decimal)
{
int r,q,oct[10],i=1,j;
q=decimal;
while(q!=0)
{
oct[i++]= q% 8;
q=q/8;
}
for(j=i-1;j>0;j--)
printf("%d",oct[j]);
}
void dec_hex(int decimal)
{
int r,q,i=1,j,temp;
char hexa[10];
q=decimal;
while(q!=0)
{
temp = q % 16;
//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexa[i++]= temp;
q=q/16;
}
for(j=i-1;j>0;j--)
printf("%c",hexa[j]);
}
void main()
{
int decimal,octal;
char hexa[20];
long int bin;
clrscr();

printf("\n Enter a decimal value:");


scanf("%d",&decimal);
printf("\n Given decimal value is=%d",decimal);
printf("\n Equivalent binary value:");
dec_bin(decimal);
printf("\n Equivalent Octal value:");
dec_oct(decimal);
printf("\n Equivalent Hexa decimal value:");
dec_hex(decimal);
}
Output
Enter a decimal value:188
Given decimal value is=188
Equivalent binary value:10111100
Equivalent Octal value:274
Equivalent Hexa decimal value:BC
40. Write a program to find the square root of a number without using built-in library
function.
Aim:- to find the square root of a number without using built-in library function.
Program Description:The square root of a number can be calculated by using the following procedure
Step1 :- Estimate - First find a number that is as close as square root of a given number by
finding the perfect square roots in which the given number lies between.
Step 2:- Divide divide the number by one of those square roots
Step 3:- Average take the average of the result of step 2 and the root
Step 4:- Use the result of step 3 to repeat step2 and step 3 until we have a number htat is accurate
enough.
Ex:- To Find the square root of 10 we use the above procedure
1. Find the two perfect square numbers it lies between
32=9 , 42=16
So square root(10) lies between 3 and 4
2. Divide 10 by 3 , we get 3.33
3. Find average of 3.33 and 3 , we get 3.1667
4. Repeat step 2 i.e., divide 10 by 3.1667 ,we get 3.1579
5. Repeat step 3 i.e., find average of 3.1579 and 3.1667we get 3.1623
6. Try 3.1623 , we get 3.1623 3.1623=10.0001
If this is accurate enough we can stop the process otherwise repeat step2 and
step3.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
float i,n,temp,avg,square;
clrscr();
printf("\n Enter a number :");
scanf("%ld",&n);
if(n>0)
{
for(i=o;i<=n/2;i++)
{
square=i*i;
if(square==n)
{
printf("\n The Square root of %6.0f is =%6.0f,n,i);
getch();
exit(0);
}

if(square>n)
break;
}
while(1)
{
temp=n/I;
avg=(i+temp)/2;
square=avg*avg;
if(square<=n+0.0001 && square >=n-0.0001)
{
printf("\n The Square root of %6.2f is =%6.4f,n,avg);
break;
}
i=avg;
}
}
getch();
}
Input :Enter a number :42
Output:Square Root of 42 is=6.4807
42. Write a program to generate pseudo random generator.
Aim:Program Description:Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for (i = 0; i < 10; i++)
{
printf("random_number[%d]= %d\n", i + 1, rand());
}
}
Output:random_number[1]= 346
random_number[2]= 130
random_number[3]= 10982
random_number[4]= 1090
random_number[5]= 11656
random_number[6]= 7117
random_number[7]= 17595
random_number[8]= 6415
random_number[9]= 22948
random_number[10]= 31126
43(a). Write a program to remove duplicates from ordered arrays.
Aim:- to remove duplicates from ordered arrays
Program Description:Since the elements are in order, we compare the adjacent values .If they are equal it
specifies there is a duplicate element at that position and we shift all the elements from that
position to the last one step back as such the duplicate element is removed. This process is
repeated until all duplicate values are deleted.
Source Code:-

#include<stdio.h>
#include<conio.h>
void main()
{
int a[30],i,j,n;
clrscr();
printf("\n Enter the size of the array:");
scanf("%d",&n);
printf("\n Enter the array elements :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
if(a[i]==a[i+1])// duplicate element found
{
for(k=i+1;k<n;k++)
a[k]=a[k+1]; //shift elements back to remove duplicate
n--;
i--;
}
printf("\n Elements after removing duplicates from ordered array are:");
for(i=1;i<=n;i++)
printf("%3d",a[i]);
}
nput:Enter the size of the array:8
Enter the array elements :5 6 6 7 8 8 8 9
Output:Elements after removing duplicates from ordered array are: 5 6 7 8 9
43(b). Write a program to remove duplicates from unordered arrays.
Aim:- to remove duplicates from unordered arrays
Program Description:We consider first element and compare this element with all other elements. When
comparing ,if they are equal we remove the duplicate element from that position by shifting one
step back all elements from that position to last. The process is repeated until all the duplicate
elements are removed.
Source Code:#include<stdio.h>
#include<conio.h>
void unorderremove(int a[30],int);
void orderremove(int a[30],int);
void main()
{
int a[30],b[30],i,j,n;
clrscr();
printf("\n Enter the size of the array:");
scanf("%d",&n);
printf("\n Enter the array elements :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n Given unordered array is:");
for(i=1;i<=n;i++)
{
printf("%3d",a[i]);
b[i]=a[i];
}
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{

if(a[i]==a[j]) //duplicate element at j


{
for(k=j;k<n;k++) //shift elements back to remove duplicate
a[k]=a[k+1];
n--;
j--;
}
}
printf("\n Elements after removing duplicates from unordered array are:");
for(i=1;i<=n;i++)
printf("%3d",a[i]);
getch();
}
Input:Enter the size of the array:8
Enter the array elements :5 6 2 5 2 2 4 4
Output:Given unordered array is: 5 6 2 5 2 2 4 4
Elements after removing duplicates from unordered array are: 5 6 2 4
44. Write a program to sort numbers using insertion sort.
Aim: - To sort numbers using insertion sort.
Program Description:We assume first element is already sorted. Now we compare the second element with
first and place the second element in its position such that both first and second element are
sorted. Similarly sort all the remaining elements.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,temp,ptr;
clrscr();
printf("\n Enter the no. of elements :");
scanf("%d",&n);
printf("\n Enter the elements of the list :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
a[0]=-9999;
printf("\n Given elements are :");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
for(i=2;i<=n;i++)
{
temp=a[i];
ptr=i-1;
while(temp<a[ptr])
{
a[ptr+1]=a[ptr];
ptr=ptr-1;
}
a[ptr+1]=temp;
}
printf("\n After sorting , elements are :");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
getch();
}
Input
Enter the no. of elements :6
Enter the elements of the list :65 32 10 12 41 22

Output
Given elements are : 65 32 10 12 41 22
After sorting , elements are : 10 12 22 32 41 65
45. Write a program to implement quick sort using non-recursive and recursive
approaches. Use randomized element as partitioning element.
Aim:- To sort the elements of the list in ascending order by quick sort.
Program Description:In this program , we first find pivot position ( pivot position is a position such that all the
elements before the pivot position are less that its value and all the elements after the pivot
position are greater than its value). Then by taking the pivot position , we divide the given list into
two sub lists and again we find pivot positions in the two sub lists. We repeat the process until all
sub lists contain only one element or until all elements are sorted.
Source Code :#include<stdio.h>
#include<conio.h>
#define max 20
int getposition(int x)
{
int k;
k=rand();
return (k%x);
}
void qsort (int list[ ], int first, int last)
{
int pivot,i,j,k,temp;
if(first<last)
{
pivot=getposition(last);
i=first;
j=last;
while(i<j)
{
while((i<last)&&(list[i]<=list[pivot]))
i++;
while(list[j]>list[pivot])
j--;
if(i<j)
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
temp=list[pivot];
list[pivot]=list[j];
list[j]=temp;
qsort(list,first,j-1);
qsort(list,j+1,last);
}
}
void main()
{
int list[max],n,i;
clrscr();
printf("\n Enter the number of elements in the list :");
scanf("%d",&n);
printf("\n Enter the elements of the list :");

for(i=0;i<n;i++)
scanf("%d",&list[i]);
printf("\n The list before sorting is :\n");
for(i=0;i<n;i++)
printf("%4d",list[i]);
qsort (list,0,n-1);
printf("\n The list after sorting is :\n");
for(i=0;i<n;i++)
printf("%4d",list[i]);
getch();
}
Input
Enter the number of elements in the list :6
Enter the elements of the list :8 6 9 4 1 3
Output
The list before sorting is :
8 6 9 4 1 3
The list after sorting is :
1 3 4 6 8 9
46. Write a program to search a word in a given file and display all its positions.
Aim:- To write a program to search a word in a given file and display all its positions
Program Description:In this program we read each word from a file and compare this word with the word which we
want to search. If the two words are equal we increment the counter variable by 1 which is
initialized to zero.This process continues until we reach to the end of file.
Source Code:#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp1;
char ch,file[20],word[20],str[20];
int a[30],k=1,p,i;
clrscr();
printf("\n Enter the path of source file :");
scanf("%s",file);
printf("\n Enter the word to be searched :");
scanf("%s",word);
fp1=fopen(file,"r");
tolower(word);
while(!feof(fp1))
{
fscanf(fp1,"%s",str);
tolower(str);
if(strcmp(str,word)==0)
{
p=(int)ftell(fp1);
p=p-strlen(str)+1;
a[k]=p;
k++;
}
}
printf("\n Given word is : %s",word);
if(k>=1)
{
printf("\n Its position occurrences are :");
for(i=1;i<k;i++)
printf("%3d",a[i]);

printf("\n Total occurrences is =%d",k-1);


}
else
printf("\n Given word is not present in the file");
fclose(fp1);
}
Input:C:\TC3\BIN>type sample.txt
we should not start sentence with because because because is a conjunction
Enter the path of source file :sample.txt
Enter the word to be searched :because
Output:Given word is : because
Its position occurrences are : 35 43 51
Total occurrences is =3
47. Write a program to generate multiplication tables from 11 to 20.
Aim:- to write a program to generate multiplication tables from 11 to 20
Program description:In this program we uses nested for loop to obtain the required result.
Source Code:#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,p,m,t;
clrscr();
k=1;
t=11;
for(i=1;i<=10;i++)
{
p=t;
for(j=1;j<=5;j++) // tables from 11 to 15
{
m=p*k;
printf("%3d*%2d=%3d",p,k,m);
p++;
}
printf("\n");
k++;
if(i==10 && t==11) //tables from 16 to 20
{
printf("\n\n");
i=0;
t=16;
k=1;
}
}
getch();
}
Output:11* 1= 11
12* 1= 12
13* 1= 13
14* 1= 14
15* 1= 15
11* 2= 22
12* 2= 24
13* 2= 26
14* 2= 28
15* 2= 30
11* 3= 33
12* 3= 36
13* 3= 39
14* 3= 42
15* 3= 45
11* 4= 44
12* 4= 48
13* 4= 52
14* 4= 56
15* 4= 60
11* 5= 55
12* 5= 60
13* 5= 65
14* 5= 70
15* 5= 75
11* 6= 66
12* 6= 72
13* 6= 78
14* 6= 84
15* 6= 90
11* 7= 77
12* 7= 84
13* 7= 91
14* 7= 98
15* 7=105
11* 8= 88
12* 8= 96
13* 8=104 14* 8=112 15* 8=120
11* 9= 99
12* 9=108 13* 9=117 14* 9=126 15* 9=135

11*10=110 12*10=120

13*10=130

14*10=140

15*10=150

16* 1= 16
16* 2= 32
16* 3= 48
16* 4= 64
16* 5= 80
16* 6= 96
16* 7=112
16* 8=128
16* 9=144
16*10=160

18* 1= 18
18* 2= 36
18* 3= 54
18* 4= 72
18* 5= 90
18* 6=108
18* 7=126
18* 8=144
18* 9=162
18*10=180

19* 1= 19
19* 2= 38
19* 3= 57
19* 4= 76
19* 5= 95
19* 6=114
19* 7=133
19* 8=152
19* 9=171
19*10=190

20* 1= 20
20* 2= 40
20* 3= 60
20* 4= 80
20* 5=100
20* 6=120
20* 7=140
20* 8=160
20* 9=180
20*10=200

17* 1= 17
17* 2= 34
17* 3= 51
17* 4= 68
17* 5= 85
17* 6=102
17* 7=119
17* 8=136
17* 9=153
17*10=170

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 four digit number in words
Program Description:In this program , we divide the number by 10 and identify the digits in various places and
write the corresponding digit in words by using the switch statement.
Source Code:#include<stdio.h>
#include<conio.h>
void printword(int);
void printtensword(int);
void printteenword(int);
void main()
{
int n,r,i,th,hun,ten,unit;
clrscr();
printf("\n Enter a four digit number:");
scanf("%d",&n);
th=n/1000;
hun=(n%1000)/100;
ten=(n%100)/10;
unit=n%10;
if(n==0)
printf(" Zero ");
if(th>0)
{
printword(th);
printf("thousand");
}
if(hun>0)
{
printword(hun);
printf(" hundred and ");
}
if(ten>1 || unit==0)
printtensword(ten);
if(ten==1)
printteenword(unit);// it depends on unit place
if(unit>0 && ten>1)
printword(unit);
getch();
}
void printword(int ch)
{
switch(ch)

{
case 1: printf(" One ");
break;
case 2: printf(" Two ");
break;
case 3: printf(" Three ");
break;
case 4: printf(" Four ");
break;
case 5: printf(" Five ");
break;
case 6: printf(" Six ");
break;
case 7: printf(" Seven ");
break;
case 8: printf(" Eight ");
break;
case 9: printf(" Nine ");
break;
}
}
void printtensword(int ch)
{
switch(ch)
{
case 2: printf(" Twenty ");
break;
case 3: printf(" Thrirty ");
break;
case 4: printf(" Forty ");
break;
case 5: printf(" Fifty ");
break;
case 6: printf(" Sixty ");
break;
case 7: printf(" Seventy ");
break;
case 8: printf(" Eighty ");
break;
case 9: printf(" Ninty ");
break;
}
}
void printteenword(int ch)
{
switch(ch)
{
case 1: printf(" Eleven ");
break;
case 2: printf(" Twelve ");
break;
case 3: printf(" Thrirteen ");
break;
case 4: printf(" Forteen ");
break;
case 5: printf(" Fifteen ");
break;
case 6: printf(" Sixteen ");
break;
case 7: printf(" Seventeen ");

break;
case 8: printf(" Eighteen ");
break;
case 9: printf(" Ninteen ");
break;
}
}
Input:Enter a four digit number:3265
Output:Three thousand Two hundred and Sixty Five
49. Write a program to generate telephone bill as per BSNL rules
Subscriber
category

<999

10002999

30000
99999

70
0

120
0

200
0

280
0

1.40

1.40

1.40

1.40

140
0

140
0

180
0

180
0

1.40

1.40

1.40

1.40

300
225

300
225

300
225

300
225

1.20

1.20

1.20

1.20

425
400

425
400

425
400

425
400

1.10

1.10

1.10

1.10

975
1000

975
1000

975
1000

975
1000

1.00

1.00

1.00

1.00

1450
1500

1450
1500

1450
1500

1450
1500

0.90

0.90

0.90

0.90

2450
3000

2450
3000

2450
3000

2450
3000

0.80

0.80

0.80

0.80

90
0

90
0

140
0

140
0

1.20

1.20

1.20

1.20

>100000

Plan details and charges


Rural
Basic
Urban

Economy

Special

Special
Plus

Super

Premium

Sulabh

Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban
Same for
both
Rural &
Urban

Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge
Rent
Free Calls
Call
Charge

Note:- The bill amount should include monthly rent , usage charges , service tax(12%) ,education
CESS (2%), Higher Education CESS (1%)
Aim:To write a program to generate the telephone bill as per BSNL rules.
Program Description:In this program , we used nested switch statement to calculate the rent , free calls and call
charge. Finally we generate the telephone bill as per the BSNL rules

Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int ctgy,ptgy,ncalls,tcalls,free_calls;
float rent,call_charge,camt,amt,stax,ecess,hcess,total;
char area_type,month[20],cname[20],cadd[40];
clrscr();
printf("\n Subscribers Categories:");
printf("\n 1. 0-999");
printf("\n 2. 1000-2999");
printf("\n 3. 30000-99999");
printf("\n 4. above 100000");
printf("\n Select the category(1-4) :");
scanf("%d",&ctgy);
clrscr();
printf("\n Plan Categories:");
printf("\n 1. Basic");
printf("\n 2. Economy");
printf("\n 3. Special");
printf("\n 4. Special Plus");
printf("\n 5. Super");
printf("\n 6. Premium");
printf("\n 7. Sulab");
printf("\n Select the plan category(1-7) :");
scanf("%d",&ptgy);
flushall();
printf("\n Enter the area type(r/u):");
scanf("%c",&area_type);
switch(ctgy)
{
case 1: switch(ptgy)
{
case 1:if(area_type=='r')
rent=70;
else
rent=140;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=90;
free_calls=0;
call_charge=1.20;
break;
}
case 2: switch(ptgy)
{
case 1:if(area_type=='r')
rent=120;
else
rent=140;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=90;
free_calls=0;
call_charge=1.20;
break;
}

case 3: switch(ptgy)
{
case 1:if(area_type=='r')
rent=200;
else
rent=180;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=140;
free_calls=0;
call_charge=1.20;
break;
}
case 4: switch(ptgy)
{
case 1:if(area_type=='r')
rent=280;
else
rent=180;
free_calls=0;
call_charge=1.40;
break;
case 7:rent=140;
free_calls=0;
call_charge=1.20;
break;
}
}
switch(ptgy)
{
case 2: rent=300;
free_calls=225;
call_charge=1.20;
break;
case 3: rent=425;
free_calls=400;
call_charge=1.10;
break;
case 4: rent=975;
free_calls=1000;
call_charge=1.00;
break;
case 5: rent=1450;
free_calls=1500;
call_charge=0.90;
break;
case 6: rent=2450;
free_calls=3000;
call_charge=0.80;
break;
}
flushall();
printf("\n Enter the customer name :");
gets(cname);
printf("\n Enter the customer address :");
gets(cadd);

printf("\n Enter billing month:");


scanf("%s",month);
printf("\n Enter number of calls made during the month:");
scanf("%d",&ncalls);
tcalls=ncalls-free_calls;
if(tcalls<0)
tcalls=0;
camt=tcalls*call_charge;
amt=rent+camt;
stax=(amt*12)/100;
ecess=(amt*2)/100;
hcess=(amt*1)/100;
total=rent+camt+stax+ecess+hcess;
clrscr();
printf("\n BHARAT SANCHAR NIGAM LTD.");
printf("\n TELEPHONE BILL");
printf("\n Customer Name:");
puts(cname);
printf("\n Customer Address:");
puts(cadd);
printf("\n Billing Month :");
puts(month);
printf(" \n Summary of Charges \t Amount");
printf("\n Monthly Rent
\t%6.2f",rent);
printf("\n No. of free calls \t%6d",free_calls);
printf("\n No.of Calls Made \t%6d",ncalls);
printf("\n Usage Charges
\t%6.2f",camt);
printf("\n Service Tax
\t%6.2f",stax);
printf("\n Education CESS \t%6.2f",ecess);
printf("\n Higher Edu. CESS \t%6.2f",hcess);
printf("\n Total Charges
\t%6.2f",total);
getch();
}
Input
Subscribers Categories:
1. 0-999
2. 1000-2999
3. 30000-99999
4. above 100000
Select the category(1-4) :2
Plan Categories:
1. Basic
2. Economy
3. Special
4. Special Plus
5. Super
6. Premium
7. Sulab
Select the plan category(1-7) :4
Enter the area type(r/u):u
Enter the customer name :K.Subba Reddy
Enter the customer address :3-25, Gandhi road , Madanapalle
Enter billing month:January-2014
Enter number of calls made during the month:2258
Output
BHARAT SANCHAR NIGAM LTD.
TELEPHONE BILL
Customer Name:K.Subba Reddy
Customer Address:3-25,Gandhi Road, Madanapalle
Billing Month :January-2014

Summary of Charges Amount


Monthly Rent
975.00
No. of free calls
1000
No.of Calls Made
2258
Usage Charges
1258.00
Service Tax
267.96
Education CESS
44.66
Higher Edu. CESS
22.33
Total Charges
2567.95
50. Write a program for tic-tac-toe game.
Aim:- to write a progem for tic tac-toe game
Program Description:Tic-tac-Toe is a two playesr game. In this game we will be given a 3 3 board. The player
assumed to be the winner if he select the cell such that the selected cells are in same row or in
same column or in same diagonal.
Source Code:#include<stdio.h>
#include<conio.h>
#include<dos.h>
/*array to hold cell status*/
char gameBoard[3][3];
/*function prototypes*/
void drawBoard();
int showResult(char ch);
int validateInput(int cell);
void turnPlayerY(int* pCell);
void turnPlayerX(int* pcell);
void getRowCol(int cell,int* pX,int* pY);
void main()
{
int k,x=0,y=0,row=0,col=0,selectedCell=0,availableCell=9;
char startChar='1';
clrscr();

/*make all the cell numbered from 1 to 9*/


for(row=0;row<3;row++)
for(col=0;col<3;col++)
gameBoard[row][col]=startChar++;
/*now draw board with current data in gameboard[][] array*/
drawBoard();

/*loop untill we've played all the cell*/


while(availableCell>=0)
{
/*assume player one is x */
turnPlayerX(&selectedCell);
/*get row and column from the selected cell*/
getRowCol(selectedCell,&x,&y);
/*update gameboard array*/
gameBoard[x][y]='X';
/*decrease available cell*/

availableCell-=1;
/*redraw game board with current data in gameboard[][] array*/
clrscr();
drawBoard();
/*check whether player is winner or not*/
if(showResult('X')==1)
{
break;
}
else if(availableCell==0)
{
printf("\nGame Drawn");
break;
}
/*assume player two is Y*/
turnPlayerY(&selectedCell);
/*get row and column from the selected cell */
getRowCol(selectedCell,&x,&y);
/*Update gameboard array*/
gameBoard[x][y]='Y';
/*decrease available cell*/
availableCell-=1;
/*redraw gameboard with current data in gameboard[][]
array*/
clrscr();
drawBoard();
/*check whether player two is winner or not*/
if(showResult('Y')==1)
{
break;
}
else if(availableCell==0)
{
printf("\nGame Drawn");
break;
}
}
getch();
}

/*function to draw board with current data in gameboard[][] array*/


void drawBoard()
{
int i,j;
printf("\n******TIC TAC TOE*********\n");
printf("\nDigits (1-9) indicates VALID cell number\n");
printf("\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(" %c ",gameBoard[i][j]);

printf("\n");
}
}

/*function to make player X's move */


void turnPlayerX(int *pCell)
{
int cell;
/*loop until player select a valid cell
Note:cells with digit are valid cells*/
do
{
printf("\n Player X, \n Select VALID cell number:");
scanf("%d",&cell);
}while(validateInput(cell)==0);
*pCell=cell;
}

/*FUNCTION TO MAKE PALYER Y'S MOVE*/


void turnPlayerY(int *pCell)
{
int cell;
/*loop until player select a valid cell
Note:cells with digit are valid cells*/
do
{
printf("\nPlayer Y,\n Select VALID cell number:");
scanf("%d",&cell);
}while(validateInput(cell)==0);
*pCell=cell;
}

/*function to calculate row and column number from selected cell*/


void getRowCol(int cell,int*pX,int*pY)
{
*pX=(cell-1)/3;
*pY=(cell-1)%3;
}
/*function to check whether selected cell is VALID or not.
if selected cell is already X or Y,
or it is not in 1-9,then return 0 to indicate INVALID selection*/
int validateInput(int cell)
{
int row,col;
/* if cell is less than 1 or greater than 9,then return false=0; */
if((cell<1)||(cell>9))
return 0;
/*if selected cell is already occupied then return false =0;*/
getRowCol(cell,&row,&col);
if((gameBoard[row][col]=='X')||(gameBoard[row][col])=='Y')
{

return 0;
}
return 1;
}

/*function to show the winner */


int showResult(char ch)
{
int i,j,status=0,d1=0,d2=0,r1=0,r2=0,r3=0,c1=0,c2=0,c3=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
if(i==j) // check principal diagonal
if(gameBoard[i][j]!=ch)
d1=1;
if((i+j)==2) //check secondary diagonal
if(gameBoard[i][j]!=ch)
d2=1;
if(i==0) //check first row
if(gameBoard[i][j]!=ch)
r1=1;
if(i==1) //check second row
if(gameBoard[i][j]!=ch)
r2=1;
if(i==2) // check third row
if(gameBoard[i][j]!=ch)
r3=1;
if(j==0) //check first column
if(gameBoard[i][j]!=ch)
c1=1;
if(j==1) // check second column
if(gameBoard[i][j]!=ch)
c2=1;
if(j==2) //check third column
if(gameBoard[i][j]!=ch)
c3=1;
}
if(d1==0 || d2==0 || r1==0|| r2==0 || r3==0||c1==0||c2==0||c3==0)
{
status=1;
printf("\n Player %c is winner",ch);
}
return status;
}
Input :******TIC TAC TOE*********
Digits (1-9) indicates VALID cell number
1 2 3
4 5 6
7 8 9
Player X,
Select VALID cell number:1

******TIC TAC TOE*********


Digits (1-9) indicates VALID cell number
X 2 3
4 5 6
7 8 9
Player Y,
Select VALID cell number:2

******TIC TAC TOE*********


Digits (1-9) indicates VALID cell number
X Y 3
4 5 6
7 8 9
Player X,
Select VALID cell number:4

******TIC TAC TOE*********


Digits (1-9) indicates VALID cell number
X Y 3
X 5 6
7 8 9
Player Y,
Select VALID cell number:5

******TIC TAC TOE*********


Digits (1-9) indicates VALID cell number
X Y 3
X Y 6
7 8 9
Player X,
Select VALID cell number:7

******TIC TAC TOE*********


Digits (1-9) indicates VALID cell number
X Y 3
X Y 6
X 8 9
Player X is winner
51. Write a program to find the execution time of a program.
Aim:- To find the execution time of a program

Program Description:In this program we find the execution time by starting the clock at beginning of the task and
ending the clock at end of task.
Source Code:#include<stdio.h>
#include<time.h>
void main()
{
int i;
double total_time;
clock_t start, end;
clrscr();
start = clock();//time count starts
srand(time(NULL));
for (i = 0; i < 25000; i++)
{
printf("random_number[%d]= %d\n", i + 1, rand());
}
end = clock();//time count stops
total_time = ((double) (end - start)) / CLK_TCK;//calulate total time
printf("\nTime taken to print 25000 random numbers is: %6.4f seconds", total_time);
return 0;
}
Output:random_number[1]= 26367
random_number[2]= 22547
random_number[3]= 26102
random_number[4]= 8734
random_number[5]= 18502
:
:
:
random_number[24997]= 23216
random_number[24998]= 29173
random_number[24999]= 13056
random_number[25000]= 7925
Time taken to print 25000 random numbers is: 17.5275 seconds

Das könnte Ihnen auch gefallen