+ All Categories
Home > Documents > R13 I B.tech Lab Manual CDS

R13 I B.tech Lab Manual CDS

Date post: 09-Nov-2015
Category:
Upload: janardhan-babu
View: 30 times
Download: 0 times
Share this document with a friend
Description:
B..Tech Lab manual for the students of JNTUA
Popular Tags:
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. Don’t 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 Lagrange’s 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 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 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.
Transcript
  • 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 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 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 Description cat 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. cd 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.

    cp 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 dd if=/dev/hdb1 of=/backup/

    Disk duplicate. The man page says this command is to "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.

    df Show the amount of disk space used on each mounted filesystem.

    less 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.

    ln 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.

    locate 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". logout Logs the current user off the system. ls 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

  • date stamp more Allows file contents or piped output to be sent to the

    screen one page at a time. more /etc/profile Lists the contents of the "/etc/profile" file to the screen

    one page at a time. ls -al |more 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.

    mv Move or rename files mv -i myfile yourfile Move the file from "myfile" to "yourfile". This effectively

    changes the name of "myfile" to "yourfile". mv -i /data/myfile . Move the file from "myfile" from the directory "/data" to

    the current working directory. pwd Show the name of the current working directory more /etc/profile Lists the contents of the "/etc/profile" file to the screen

    one page at a time. shutdown Shuts the system down. shutdown -h now Shuts the system down to halt immediately. shutdown -r now Shuts the system down immediately and the system

    reboots. whereis Show where the binary, source and manual page files are

    for a command whereis ls Locates binaries and manual pages for the ls command. man This command brings up the online Unix manual. Use it on

    each of the commands below. man pwd You will see the manual for the pwd command pwd Shows what directory (folder) you are in.

    In Linux, your home directory is /home/particle mkdir dirName

    Creates a directory with name dirName.

    mkdir temp Creates the directory temp rmdir dirName

    Removes a directory dirName

    rmdir temp Removes the directory temp. rm data1 Deletes the file data1 in the current directory. rm -i muon* 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".

    cp data1 newdata/ will copy the file data1 to the directory newdata (assuming it has already been created)

    mv data1 newdata/ moves the file data1 to the folder newdata and deletes the old one.

    Mount Mounts a drive to the operating system.Linux does not 'see' the floppy drive until we tell it to.

    Df Shows the disk usage. This will tell you how much disk space you have left on your hard drive as well as the floppy.

    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 Operating System IDE? License type

    AMPC Axiomatic Solutions Sdn Bhd

    Windows,Unix & Other

    Yes Proprietary

    GCC C GNU Project Windows,Unix,IBM mainframe, AmigaOS, VAX/VMS, RTEMS

    No GPL

    RCC (RCOR C Compiler)

    Rodrigo Caetano (rcor)

    Windows,Unix No GPL

    Mark Williams C Mark Williams Company

    Windows,Other Yes Proprietary

    Microsoft C Microsoft Windows Yes Proprietary

    Portable C Compiler

    Anders Magnusson and others

    Windows,Unix,Other No BSD

    Tiny C Compiler Fabrice Bellard Windows,Unix No LGPL

    Turbo C Embarcadero Other No Proprietary - V 2.01 freely available

    CCS C Compiler CCS, Inc. Windows,Unix,Other Yes Proprietary

    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 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 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 #include 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 #include 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 #include 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 #include 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 #include 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 #include #include #include 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 #include #include 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
  • 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 #include 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
  • { 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

  • 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 #include 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 #include 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 #include 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
  • 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 #include 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
  • using nesting of for loops. Source Code :- #include #include 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

  • Source Code :- #include #include 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
  • for(j=0;j
  • Source Code:- #include #include 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
  • Source Code:- #include #include #include 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 #include #include 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
  • 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 #include 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 #include 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

    1 20

    0 1 0 2 0

    0 21

    1 1 1 2 1

    0 1 1

    1 2 1

    ( )( )......( )( ) ( )

    ( )( )......( )

    ( )( )......( )( ) .........

    ( )( )......( )

    ( )( )......( )( )

    ( )( )......( )

    n

    n

    n

    n

    nn

    n n n n

    x x x x x xf x f x

    x x x x x x

    x x x x x xf x

    x x x x x x

    x x x x x xf x

    x x x x x x

    Source Code:- #include #include #include #include #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
  • 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
  • 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 #include 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
  • 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 #include 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
  • printf("\n Enter the elements:"); for(i=0;i
  • { if(list[m]
  • } 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 #include 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
  • 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 #include 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 #include 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 #include 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 #include 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 0 from l to r Move disk 1 from l to t Move disk 0 from r to t Move disk 2 from l to r Move disk 0 from t to l Move disk 1 from t to r Move disk 0 from l to 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 #include #include 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
  • 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
  • 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 #include 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->topa[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+c- Enter 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 #include 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 #define MAX 30 #include void push(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

  • 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 #include 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 #include #define MAX 30 void insert(int queue[],int *front,int *rear, int value) { if(*front==-1) *front=0; if(*rear

  • 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 #include 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 #include #define MAX 30 void insert(int cqueue[],int *front,int *rear, int value) { if(*front==-1) *front=0; if(*rear

  • 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 #include #include 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 #include 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(countlink!=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(countlink->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 #include #include 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
  • 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
  • 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 #include 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 #include void main() { float i,n,temp,avg,square; clrscr(); printf("\n Enter a number :"); scanf("%ld",&n); if(n>0) { for(i=o;i

  • if(square>n) break; } while(1) { temp=n/I; avg=(i+temp)/2; square=avg*avg; if(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 #include 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 #include 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
  • if(a[i]==a[j]) //duplicate element at j { for(k=j;k
  • 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 #include #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
  • for(i=0;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:- #incl

Recommended