ITP Lab Manual

51
Pakistan Navy Engineering College / National University of Sciences & Technology Prepared by Engr. Sajid Saleem Assistant Professor EPE Department UNIFIED CURRICULA 2012 Introduction To Programming CS-105 Lab Manual (August 2012)

description

hjbvjhbfvbdjbcjjhbdjchbd

Transcript of ITP Lab Manual

Page 1: ITP Lab Manual

Pakistan Navy Engineering College / National University of Sciences

& Technology

Prepared by Engr. Sajid Saleem Assistant Professor

EPE Department UNIFIED CURRICULA 2012

Introduction To Programming

CS-105

Lab Manual (August 2012)

Page 2: ITP Lab Manual
Page 3: ITP Lab Manual

Introduction To Programming

CS-105 (August 2012)

List Of Practicals

S No

Practicals Week

1. Introduction and identification of components of a computer system. Assembling and disassembling of computer hardware

1

2. Exploration of MS Office (MS-Word, MS-Excel and MS-PowerPoint).

2

3. Demonstration of Visual Studio 2005 Environment. Use of program editor, compiler, linker and debugger. Sample program run and debug.

3

4. Introduction to C++ programming

4,5

5. Introduction to classes and objects

6-8

6. Control Statements (if-else)

9

7. Control Statements (switch)

10

8. Loops (for)

11

9. Loops (while)

12

10. Loops (do-while)

13

11. Functions

14

12. Introduction to Recursion

15

Page 4: ITP Lab Manual
Page 5: ITP Lab Manual

LAB 1

INTRODUCTION TO COMPUTER SYSTEM COMPONENTS

LAB OBJECTIVE

Introduction and identification of components of a computer system. Assembling and disassembling of computer hardware.

OVERVIEW

• Familiarization with the hardware components and ports commonly found in a real PC system.

• Familiarization with the often required operations like replacement and addition of RAM or expansion cards.

• Familiarization with the extraction of hardware resource information through window system information.

TASK(S)

Number 1

Component Found (Yes/No)

How many Items Manufacturer Information

No. of Pins/Holes

Power button Reset button Floppy drive CD/DVD drive Port for keyboard Port for mouse Serial port Parallel port LAN port Power socket USB port Modem Port Game Port Processor socket Memory slots PCI slots ISA slots Battery for CMOS BIOS chip Motherboard chipset AGP slot Power supply IDE Controller connectors

Page 6: ITP Lab Manual

Number 2

• Restart the PC using Windows Restart option, and when it restarts press F2 key to enter BIOS setup.

• Find out the details of Hard Disk, processor, available RAM from that screen. • Find out the menu on which you can set the Boot priorities so that you can manage

things in case of running a bootable floppy / CD-ROM. • There is a series of quick test performed at the boot startup that is called POST. Find

out the menu through which you can enable or disable that option. • When you are logged in to your PC, go to • Start Programs Accessories System Tools System Information • When you are logged in to your PC, go to • Start control panel administrative tools computer management device

manager. • Compile the details from System Summary group and the Components group about

the hardware that is installed and recognized by your Operating System.

Page 7: ITP Lab Manual

LAB 2

EXPLORING MS-OFFICE

LAB OBJECTIVE To explore Microsoft Word, PowerPoint, Excel.

OVERVIEW

• The basic knowledge of Microsoft Word, PowerPoint, Excel. • The extensions of Microsoft Word, PowerPoint, Excel. • How to save the files made on Microsoft Word, PowerPoint, Excel. • The short-cut keys used in Microsoft Word, PowerPoint, Excel. • How to change the font, color of the font, size of the font, styles of the font etc in

Microsoft Office • About the rows & columns used in Microsoft-Excel. • About the different types of slides pattern used in Microsoft PowerPoint. • To make different kinds of official documents, such as CV, resumes etc.

TASK(S)

To find the functions of the given short-cut keys in Microsoft Word, PowerPoint, Excel.

SHORT-CUT KEYS FUNCTION IN MS-WORD

FUNCTION IN MS-POWERPOINT

FUNCTION IN MS-EXCEL

Ctrl + A

Ctrl + B

Ctrl + C

Ctrl + D

Ctrl + E

Ctrl + F

Ctrl + G

Ctrl + H

Ctrl + I

Ctrl + J

Page 8: ITP Lab Manual

Ctrl + K

Ctrl + L

Ctrl + M

Ctrl + N

Ctrl + O

Ctrl + P

Ctrl + Q

Ctrl + R

Ctrl + S

Ctrl + T

Ctrl + U

Ctrl + V

Ctrl + W

Ctrl + X

Ctrl + Y

Ctrl + Z

How To Add Printer

• Start Run

• Enter the text \\<server name / IP >

• Double click the printer name to install

Page 9: ITP Lab Manual

How To Open Faculty Share Folder

• Start Run

• Enter the text \\<server name / IP >

• Open “faculty share” folder

• Open the folder of the concerned teacher / faculty member.

Page 10: ITP Lab Manual

LAB 3

DEMONSTRATION OF VISUAL STUDIO 2005 ENVIROMENT

LAB OBJECTIVE

Demonstration of Visual Studio 2005 Environment. Use of program editor, compiler, linker and debugger. Sample program run and debug.

OVERVIEW

What Is the Integrated Development Environment?

The Integrated Development Environment (IDE) that comes with Visual C++ 2005 is a completely self-contained environment for creating, compiling, linking, and testing your C++ programs. It also happens to be a great environment in which to learn C++ (particularly when combined with a great book). Visual C++ 2005 incorporates a range of fully integrated tools designed to make the whole process of writing C++ programs easy. You will see something of these in this chapter, but rather than grind through a boring litany of features and options in the abstract, first take a look at the basics to get a view of how the IDE works and then pick up the rest in context as you go along.

Components of the System

The fundamental parts of Visual C++ 2005, provided as part of the IDE, are the editor, the compiler, the linker, and the libraries. These are the basic tools that are essential to writing and executing a C++ program. Their functions are as follows.

The Editor

The editor provides an interactive environment for you to create and edit C++ source code. As well as the usual facilities, such as cut and paste, which you are certainly already familiar with, the editor also provides color cues to differentiate between various language elements. The editor automatically recognizes fundamental words in the C++ language and assigns a color to them according to what they are. This not only helps to make your code more readable but also provides a clear indicator of when you make errors in keying such words.

The Compiler

The compiler converts your source code into object code, and detects and reports errors in the compilation process. The compiler can detect a wide range of errors that are due to invalid or unrecognized program code, as well as structural errors, where, for example, part of a program can never be executed. The object code output from the compiler is stored in files called object files. There are two types of object code that the compiler produces. These object codes usually have names with the extension .obj.

The Linker

The linker combines the various modules generated by the compiler from source code files, adds required code modules from program libraries supplied as part of C++, and welds everything into an executable whole. The linker can also detect and report errors—for example, if part of your program is missing or a non-existent library component is referenced.

Page 11: ITP Lab Manual

The Libraries

A library is simply a collection of pre-written routines that supports and extends the C++ language by providing standard professionally produced code units that you can incorporate into your programs to carry out common operations. The operations that are implemented by routines in the various libraries provided by Visual C++ 2005 greatly enhance productivity by saving you the effort of writing and testing the code for such operations yourself. I have already mentioned the .NET Framework library, and there are a number of others—too many to enumerate here—but I’ll mention the most important ones.

The Standard C++ Library defines a basic set of routines common to all ISO/ANSI C++ compilers. It contains a wide range of routines including numerical functions such as calculating square roots and evaluating trigonometrical functions, character and string processing routines such as classifying characters and comparing character strings, and many others. You’ll get to know quite a number of these as you develop your knowledge of ISO/ANSI C++. There are also libraries that support the C++/CLI extensions to ISO/ANSI C++.

Native window-based applications are supported by a library called the Microsoft Foundation Classes (MFC). The MFC greatly reduces the effort needed to build the graphical user interface for an application. You’ll see a lot more of the MFC when you finish exploring the nuances of the C++ language. Another library contains a set of facilities called Windows Forms that are roughly the equivalent of the MFC for window-based applications that executed with the .NET Framework. You’ll be seeing how you make use of Windows Forms to develop applications, too.

Using the IDE

All program development and execution in this book is performed from within the IDE. When you start Visual C++ 2005, notice an application window similar to that shown in Figure 1.

The window to the left in Figure is the Solution Explorer window, the top-right window presently showing the Start page is the Editor window, and the window at the bottom is the Output window. The Solution Explorer window enables you to navigate through your program files and display their contents in the Editor window and to add new files to your program. The Solution Explorer window has up to three additional tabs (only two are shown in Figure 1) that display Class View, Resource View, and Property Manager for your application, and you can select which tabs are to be displayed from the View menu. The Editor window is where you enter and modify source code and other components of your application. The Output window displays messages that result from compiling and linking your program.

Page 12: ITP Lab Manual

Figure 1 Toolbar Options

You can choose which toolbars are displayed in your Visual C++ window by right-clicking in the toolbar area. A pop-up menu with a list of toolbars appears, and the toolbars that are currently displayed have check marks alongside.

This is where you decide which toolbars are visible at any one time. You can make your set of toolbars the same as those shown in Figure 1 by making sure the Build, Class Designer, Debug, Standard, and View Designer menu items are checked. Clicking in the gray area to the left of a toolbar checks it if it unchecked and results in it being displayed; clicking a check mark hides the corresponding toolbar.

You don’t need to clutter up the application window with all the toolbars you think you might need at some time. Some toolbars appear automatically when required, so you’ll probably find that the default toolbar selections are perfectly adequate most of the time. As you develop your applications, from time to time you might think it would be more convenient to have access to toolbars that aren’t displayed. You can change the set of toolbars that are visible whenever it suits you by right-clicking in the toolbar area and choosing from the context menu.

Similar to many other Windows applications, the toolbars that make up Visual C++ 2005 come complete with tooltips. Just let the mouse pointer linger over a toolbar button for a second or two and a white label displays the function of that button.

Page 13: ITP Lab Manual

Figure 2 Dockable Toolbars

A dockable toolbar is one that you can drag around with the mouse to position at a convenient place in the window. When it is placed in any of the four borders of the application, it is said to be docked and looks similar to the toolbars you see at the top of the application window. The toolbar on the upper line of toolbar buttons that contains the disk icons and the text box to the right of a pair of binoculars is the Standard toolbar. You can drag this away from the toolbar by placing the cursor on it and dragging it with the mouse while you hold down the left mouse button. It then appears as a separate window you can position anywhere.

Page 14: ITP Lab Manual

If you drag any dockable toolbar away from its docked position, it looks like the Standard toolbar you see in Figure 3, enclosed in a little window—with a different caption. In this state, it is called a floating toolbar. All the toolbars that you see in Figure 1 are dockable and can be floating, so you can experiment with dragging any of them around. You can position them in docked positions where they revert to their normal toolbar appearance. You can dock a dockable toolbar at any side of the main window.

Figure 3

You’ll become familiar with many of the toolbar icons that Visual C++ 2005 uses from other Windows applications, but you may not appreciate exactly what these icons do in the context of Visual C++, so I’ll describe them as we use them. Because you’ll use a new project for every program you develop, looking at what exactly a project is and understanding how the mechanism for defining a project works is a good place to start finding out about Visual C++ 2005.

Documentation

There will be plenty of occasions when you’ll want to find out more information about Visual C++ 2005. The Microsoft Development Network (MSDN) Library provides comprehensive reference material on all the capabilities on Visual C++ 2005 and more besides. When you install Visual C++ 2005 onto your machine, there is an option to install part or all of the MSDN documentation. If you have the disk space available I strongly recommend that you install the MSDN Library. Press the F1 function to browse the MSDN Library. The Help menu also provides various routes into the documentation. As well as offering reference documentation, the MSDN Library is a useful tool when dealing with errors in your code.

Projects and Solutions

A project is a container for all the things that make up a program of some kind—it might be a console program, a window-based program, or some other kind of program, and it usually consists of one or more source files containing your code plus possibly other files containing auxiliary data. All the files for a project are stored in the project folder and detailed information about the project is stored in an XML file with the extension .vcproj that is also in the project folder. The project folder also contains other folders that are used to store the output from compiling and linking your project.

The idea of a solution is expressed by its name, in that it is a mechanism for bringing together all the programs and other resources that represent a solution to a particular data processing problem. For example, a distributed order entry system for a business operation might be composed of several different programs that could each be developed as a project within a single solution; therefore, a solution is a folder in which all the information relating to one or more projects is stored, so one or more project folders are subfolders of the solution folder. Information about the projects in a solution is stored in two files with the extensions .sln and .suo. When you create a project, a new solution is created automatically unless you elect to add the project to an existing solution.

When you create a project along with a solution, you can add further projects to the same solution. You can add any kind of project to an existing solution, but you would usually add only a project that was related in some way to the existing project or projects in the solution. Generally, unless you have a good reason to do otherwise, each of your projects should have its own solution.

Page 15: ITP Lab Manual

Defining a Project

The first step in writing a Visual C++ 2005 program is to create a project for it using the File > New > Project menu option from the main menu or you can press Ctrl+Shift+N. As well as containing files that define all the code and any other data that goes to make up your program, the project XML file in the project folder also records the Visual C++ 2005 options you’re using. Although you don’t need to concern yourself with the project file—it is entirely maintained by the IDE—you can browse it if you want to see what the contents are, but take care not to modify it accidentally. That’s enough introductory stuff for the moment. It’s time to get your hands dirty.

Creating a Project for a Win32 Console Application

You’ll now take a look at creating a project for a console application. First select File > New > Project to bring up the New Project dialog box, shown in Figure 4

Figure 4

The left pane in the New Project dialog box displays the types of projects you can create; in this case, click Win32. This also identifies an application wizard that creates the initial contents for the project. The right pane displays a list of templates available for the project type you have selected in the left pane. The template you select is used by the application wizard when creating the files that make up the project. In the next dialog box, you have an opportunity to customize the files that are created when you click the OK button in this dialog box. For most of the type/template options, a basic set of program source modules are created automatically.

You can now enter a suitable name for your project by typing into the Name: edit box—for example, you could call this one Ex1_01, or you can choose your own project name. Visual C++ 2005 supports long file names, so you have a lot of flexibility. The name of the solution folder appears in the bottom edit box and, by default, the solution folder has the same name

Page 16: ITP Lab Manual

as the project. You can change this if you want. The dialog box also allows you to modify the location for the solution that contains your project—this appears in the Location: edit box. If you simply enter a name for your project, the solution folder is automatically set to a folder with that name, with the path shown in the Location: edit box. By default the solution folder is created for you if it doesn’t already exist. If you want to specify a different path for the solution folder, just enter it in the Location: edit box. Alternatively, you can use the Browse button to select another path for your solution. Clicking the OK button displays the Win32 Application Wizard dialog box shown in Figure 5.

Figure 5

This dialog box explains the settings currently in effect. If you click the Finish button, the wizard creates all the project files based on this. In this case you can click Applications Settings on the left to display the Application Settings page of the wizard shown in Figure 6.

The Application Settings page allows you to choose options that you want to apply to the project. For most of the projects you’ll be creating when you are learning the C++ language, you select the Empty project checkbox, but here you can leave things as they are and click the Finish button. The application wizard then creates the project with all the default files. The project folder will have the name that you supplied as the project name and will hold all the files making up the project definition. If you didn’t change it, the solution folder has the same name as the project folder and contains the project folder plus the files defining the contents of the solution.

Page 17: ITP Lab Manual

Figure 6 If you use Windows Explorer to inspect the contents of the solution folder, you’ll see that it contains three files:

• A file with the extension .sln that records information about the projects in the solution.

• A file with the extension .suo in which user options that apply to the solution will be recorded.

• A file with the extension .ncb that records data about Intellisense for the solution. Intellisense is the facility that provides auto-completion and prompting for code in the Editor window as you enter it.

If you use Windows Explorer to look in the project folder, notice there are six files initially, including a file with the name ReadMe.txt that contains a summary of the contents of the files that have been created for the project. The one file that ReadMe.txt may not mention is a file with a compound name of the form Ex1_01.vcproj.ComputerName.UserName.user used to store options you set for the project.

The project you have created will automatically open in Visual C++ 2005 with the left pane as in Figure 7. I have increased the width of this pane so that you can see the complete names on the tabs.

The Solution Explorer tab presents a view of all the projects in the current solution and the files they contains—here there is just one project of course. You can display the contents of any file as an additional tab in the Editor pane just by double-clicking in name in the Solution Explorer tab. In the edit pane you can switch instantly between any of the files that have been displayed just by clicking on the appropriate tab.

Page 18: ITP Lab Manual

Figure 7

The Class View tab displays the classes defined in your project and also shows the contents of each class. You don’t have any classes in this application, so the view is empty. When we discuss classes, you will see that you can use the Class View tab to move around the code relating to the definition and implementation of all your application classes quickly and easily.

The Property Manager tab shows the properties that have been set for the Debug and Release versions of your project. I’ll explain these versions a little later in this chapter. You can change any of the properties shown by right-clicking a property and selecting Properties from the context menu; this displays a dialog box where you can set the project property. You can also press Alt+F7 to display the properties dialog box at any time; I’ll also discuss this in more detail when we go into the Debug and Release versions of a program.

The Resource View shows the dialog boxes, icons, menus toolbars, and other resources that are used by the program. Because this is a console program, no resources are used; however, when you start writing Windows applications, you’ll see a lot of things here. Through this tab you can edit or add to the resources available to the project.

Like most elements of the Visual C++ 2005 IDE, the Solution Explorer and other tabs provide context sensitive pop-up menus when you right-click items displayed in the tab and in some cases in the empty space in the tab, too. If you find that the Solution Explorer pane gets in your way when writing code, you can hide it by clicking the Autohide icon. To redisplay it, click the name tab on the left of the IDE window.

Modifying the Source Code

The Application wizard generates a complete Win32 console program that you can compile and execute. Unfortunately, the program doesn’t do anything as it stands, so to make it a little more interesting you need to change it. If it is not already visible in the Editor pane, double-

Page 19: ITP Lab Manual

click Ex1_01.cpp in the Solution Explorer pane. This file is the main source file for the program that the Application wizard generated and it looks like that shown in Figure 8.

Figure 8

If the line numbers are not displayed on your system, select Tools > Options from the main menu to display the Options dialog box. If you extend the C/C++ option in the right pane and select General from the extended tree, you can select Line Numbers in the right pane of the dialog box. I’ll first give you a rough guide to what this code in Figure 8 does, and you’ll see more on all of these later.

The first two lines are just comments. Anything following “//”in a line is ignored by the compiler. When you want to add descriptive comments in a line, precede your text by “//”.

Line 4 is an #include directive that adds the contents of the file stdafx.h to this file in place of this #include directive. This is the standard way of adding the contents of .h source files to a .cpp source file a in a C++ program.

Line 7 is the first line of the executable code in this file and the beginning of the function _tmain(). A function is simply a named unit of executable code in a C++ program; every C++ program consists of at least one—and usually many more—functions.

Lines 8 and 10 contain left and right braces, respectively, that enclose all the executable code in the function _tmain(). The executable code is, therefore, just the single line 10 and all this does is end the program.

Now you can add the following two lines of code in the Editor window:

Page 20: ITP Lab Manual

// Ex1_01.cpp : Defines the entry point for the console application. // #include “stdafx.h” #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { std::cout << “Hello world!\n”; return 0; }

The unshaded lines are the ones generated for you. The new lines you should add are shown shaded. To introduce each new line, place the cursor at the end on the text on the preceding line and press Enter to create an empty line in which you can type the new code. Make sure it is exactly as shown in the preceding example; otherwise, the program may not compile.

The first new line is an #include directive that adds the contents of one of the standard libraries for ISO/ANSI C++ to the source file. The <iostream> library defines facilities for basic I/O operations, and the one you are using in the second line that you added writes output to the command line. std::cout is the name of the standard output stream and you write the string “Hello world!\n” to std::cout in the second addition statement. Whatever appears between the pair of double quote characters is written to the command line.

Building the Solution

To build the solution, press F7 or select the Build > Build Solution menu item. Alternatively, you can click the toolbar button corresponding to this menu item. The toolbar buttons for the Build menu may not display, but you can easily fix this by right-clicking in the toolbar area and selecting the Build toolbar from those in the list. The program should then compile successfully. If there are errors, ensure you didn’t make an error while entering the new code, so check the two new lines very carefully.

Files Created by Building a Console Application

After the example has been built without error, take a look in the project folder by using Windows Explorer to see a new subfolder called Debug. This folder contains the output of the build you just performed on the project. Notice that this folder contains several files. Other than the .exe file, which is your program in executable form, you don’t need to know much about what’s in these files. In case you’re curious, however, let’s do a quick run-through of what the more interesting ones are for.

Page 21: ITP Lab Manual

Debug and Release Versions of Your Program

You can set a range of options for a project through the Project > Ex1_01 Properties menu item. These options determine how your source code is processed during the compile and link stages. The set of options that produces a particular executable version of your program is called a configuration. When you create a new project workspace, Visual C++ 2005 automatically creates configurations for producing two versions of your application. One version, called the Debug version, includes information that helps you debug the program. With the Debug version of your program you can step through the code when things go wrong, checking on the data values in the program. The other, called the Release version, has no debug information included and has the code optimization options for the compiler turned on to provide you with the most efficient executable module. These two configurations are sufficient for your needs throughout this book, but when you need to add other configurations for an application, you can do so through the Build > Configuration Manager menu. Note that this menu item won’t appear if you haven’t got a project loaded. This is obviously not a problem, but might be confusing if you’re just browsing through the menus to see what’s there.

Programming with Visual C++ 2005

You can choose which configuration of your program to work with by selecting the configuration from the Active solution configuration drop-down list in the Configuration Manager dialog box, as shown in Figure 9.

Page 22: ITP Lab Manual

Figure 9

Select the configuration you want to work with from the list and then click the Close button. While you’re developing an application, you’ll work with the debug configuration. After your application has been tested using the debug configuration and appears to be working correctly, you typically rebuild the program as a release version; this produces optimized code without the debug and trace capability, so the program runs faster and occupies less memory.

Executing the Program

After you have successfully compiled the solution, you can execute your program by pressing Ctrl+F5. You should see the window shown in Figure 10.

Figure 10

As you see, you get the text that was between the double quotes written to the command line. The “\n” that appeared at the end of the text string is a special sequence called an escape sequence that denotes a newline character. Escape sequences are used to represent characters in a text string that you cannot enter directly from the keyboard.

Page 23: ITP Lab Manual

Dealing with Errors

Of course, if you didn’t type the program correctly, you get errors reported. To show how this works, you could deliberately introduce an error into the program. If you already have errors of your own, you can use those to perform this exercise. Go back to the Editor pane and delete the semicolon at the end of the second-to-last line between the braces (line 8); then rebuild the source file. The Output pane at the bottom of the application window includes the error message:

C2143: syntax error : missing ‘;’ before ‘return’ Every error message during compilation has an error number that you can look up in the documentation. Here, the problem is obvious, however, in more obscure cases, the documentation may help you figure out what is causing the error. To get the documentation on an error, click the line in the Output pane that contains the error number and then press F1. A new window displays containing further information about the error. You can try it with this simple error, if you like.

When you have corrected the error, you can then rebuild the project. The build operation works efficiently because the project definition keeps track of the status of the files making up the project. During a normal build, Visual C++ 2005 recompiles only the files that have changed since the program was last compiled or built. This means that if your project has several source files and you’ve edited only one of the files since the project was last built, only that file is recompiled before linking to create a new .exe file. You’ll also use CLR console programs, so the next section shows you what a CLR console project looks.

TASK(S)

Create a new empty console project by your name. That prints your name, class and roll no.

Page 24: ITP Lab Manual

LAB 4

INTRODUCTION TO C++ PROGRAMMING

LAB OBJECTIVE

Hands-on experience with input / output functions, arithmetic and assignment operators in C++.

OVERVIEW

First Program in C++: Printing a Line of Text

Let us know star with a simple program that prints a line of text. This program illustrates several important features of the C++ language. We consider each line in detail.

1 // Example04_a.cpp 2 // Text-printing program. 3 #include <iostream> // allows program to output data to the screen 4 5 // function main begins program execution 6 int main() 7 { 8 std::cout << "Welcome to C++!\n"; // display message 9 10 return 0; // indicate that program ended successfully 11 12 } // end function main Lines 1 and 2

Each line begin with //, indicating that the remainder of each line is a comment. Programmers insert comments to document programs and also help people read and understand them. Comments do not cause the computer to perform any action when the program is runthey are ignored by the C++ compiler and do not cause any machine-language object code to be generated. The comment Text-printing program describes the purpose of the program. A comment beginning with // is called a single-line comment because it terminates at the end of the current line. [Note: C++ programmers also may use C's style in which a commentpossibly containing many linesbegins with the pair of characters /* and ends with */.]

Line 3 #include <iostream> // allows program to output data to the screen

is a preprocessor directive, which is a message to the C++ preprocessor. Lines that begin with # are processed by the preprocessor before the program is compiled. This line notifies the preprocessor to include in the program the contents of the input/output stream header file <iostream>. This file must be included for any program that outputs data to the screen or

Page 25: ITP Lab Manual

inputs data from the keyboard using C++-style stream input/output. The program outputs data to the screen, as we will soon see.

Line 5

// function main begins program execution

is another single-line comment indicating that program execution begins at the next line.

Line 6 int main()

is a part of every C++ program. The parentheses after main indicate that main is a program building block called a function. C++ programs typically consist of one or more functions and classes. Exactly one function in every program must be main. C++ programs begin executing at function main, even if main is not the first function in the program. The keyword int to the left of main indicates that main "returns" an integer (whole number) value. A keyword is a word in code that is reserved by C++ for a specific use. The left brace, {, (line 7) must begin the body of every function. A corresponding right brace, }, (line 12) must end each function's body.

Line 8 std::cout << "Welcome to C++!\n"; // display message

instructs the computer to perform an actionnamely, to print the string of characters contained between the double quotation marks. A string is sometimes called a character string, a message or a string literal. We refer to characters between double quotation marks simply as strings. White-space characters in strings are not ignored by the compiler.

The entire line 8, including std::cout, the << operator, the string "Welcome to C++!\n" and the semicolon (;), is called a statement. Every C++ statement must end with a semicolon (also known as the statement terminator). Preprocessor directives (like #include) do not end with a semicolon. Output and input in C++ are accomplished with streams of characters. Thus, when the preceding statement is executed, it sends the stream of characters Welcome to C++!\n to the standard output stream objectstd::coutwhich is normally "connected" to the screen.

Notice that we placed std:: before cout. This is required when we use names that we've brought into the program by the preprocessor directive #include <iostream>. The notation std::cout specifies that we are using a name, in this case cout, that belongs to "namespace" std.

The << operator is referred to as the stream insertion operator. When this program executes, the value to the right of the operator, the right operand, is inserted in the output stream. Notice that the operator points in the direction of where the data goes. The characters of the right operand normally print exactly as they appear between the double quotes. Notice, however, that the characters \n are not printed on the screen. The backslash (\) is called an escape character. It indicates that a "special" character is to be output. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n means newline. It causes the cursor (i.e., the current screen-position indicator) to move to the beginning of the next line on the screen. Some other common escape sequences are listed in table 1.

Page 26: ITP Lab Manual

Escape sequence

Description

\n Newline. Position the screen cursor to the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop.

\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.

\a Alert. Sound the system bell.

\\ Backslash. Used to print a backslash character.

\' Single quote. Use to print a single quote character.

\" Double quote. Used to print a double quote character.

Table 1

Line 10

return 0; // indicate that program ended successfully

is one of several means we will use to exit a function. When the return statement is used at the end of main, as shown here, the value 0 indicates that the program has terminated successfully. We discuss functions in detail later, and the reasons for including this statement will become clear. For now, simply include this statement in each program, or the compiler may produce a warning on some systems. The right brace, }, (line 12) indicates the end of function main.

Arithmetic

Most programs perform arithmetic calculations. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication and the percent sign (%) is the modulus operator that will be discussed shortly. The arithmetic operators in table 2 are all binary operators, i.e., operators that take two operands. For example, the expression number1 + number2 contains the binary operator + and the two operands number1 and number2.

Arithmetic operators.

C++ operation C++ arithmetic operator Algebraic expression C++ expression

Addition + f + 7 f + 7

Subtraction - p c p c

Multiplication * bm or b · m b * m

Division / x / y

Modulus % r mod s r % s

Table 2

Page 27: ITP Lab Manual

Integer division (i.e., where both the numerator and the denominator are integers) yields an integer quotient; for example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. Note that any fractional part in integer division is discarded (i.e., truncated) no rounding occurs.

C++ provides the modulus operator, %, that yields the remainder after integer division. The modulus operator can be used only with integer operands. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. In later chapters, we discuss many interesting applications of the modulus operator, such as determining whether one number is a multiple of another (a special case of this is determining whether a number is odd or even).

Addition program that displays the sum of two integers entered at the keyboard.

1 // Example04_b.cpp 2 // Addition program that displays the sum of two numbers. 3 #include <iostream> // allows program to perform input and output 4 5 // function main begins program execution 6 int main() 7 { 8 // variable declarations 9 int number1; // first integer to add 10 int number2; // second integer to add 11 int sum; // sum of number1 and number2 12 13 std::cout << "Enter first integer: "; // prompt user for data 14 std::cin >> number1; // read first integer from user into number1 15 16 std::cout << "Enter second integer: "; // prompt user for data 17 std::cin >> number2; // read second integer from user into number2 18 19 sum = number1 + number2; // add the numbers; store result in sum 20 21 std::cout << "Sum is " << sum << std::end1; // display sum; end line 22 23 return 0; // indicate that program ended successfully 24 25 } // end function main

Page 28: ITP Lab Manual

Arithmetic Expressions in Straight-Line Form

Arithmetic expressions in C++ must be entered into the computer in straight-line form. Thus, expressions such as "a divided by b" must be written as a / b, so that all constants, variables and operators appear in a straight line. The algebraic notation is generally not acceptable to compilers, although some special-purpose software packages do exist that support more natural notation for complex mathematical expressions.

Parentheses for Grouping Sub expressions

Parentheses are used in C++ expressions in the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c we write a * (b + c).

Precedence of arithmetic operators.

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses "on the same level" (i.e., not nested), they are evaluated left to right.

* / %

Multiplication Division Modulus

Evaluated second. If there are several, they are evaluated left to right.

+ -

Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

Table 3

TASK(S)

1. Printing a Single Line of Text with Multiple Statements 2. Printing multiple lines of text with a single statement. 3. Take an integer input from the user and print it on the screen. 4. Write a program to calculate the area of a circle, rectangle and square with respective

inputs taken from the user. a) User will be asked to enter the radius of a circle. Program will display the area of

circle using the formula, area = π r 2 b) User will be asked to enter the length and breadth of a rectangle. Program will display

the area of rectangle using the formula area = (length) x (breadth) c) User will be asked to enter the length of one side of a square. Program will display the

area of that square area = (side) 2

Page 29: ITP Lab Manual

LAB 5

INTRODUCTION TO CLASSES & OBJECTS

LAB OBJECTIVE

To learn, how to make classes and objects and how to use them in programming.

OVERVIEW

In this lab, a student will be

1. Learning basic concepts of Classes & Objects. 2. Learning, how to make classes & objects in the coding. 3. Learning, how to use classes & objects in the coding. 4. Doing different tasks using Classes & Objects.

Consider these examples, which will guide you in more better way.

// Example05_a.cpp // Define class GradeBook with a member function displayMessage; // Create a GradeBook object and call its displayMessage function. #include <iostream> using std::cout; using std::endl; // GradeBook class definition class GradeBook { public: // function that display a welcome message to the GradeBook user void displayMessage() { cout<<”Welcome to the Grade Book!”<< endl; }// end function displayMessage };//end class GradeBook // function main begins program execution int main() { GradeBook myGradeBook; // create a GradeBook object named myGradeBook myGradeBook.displayMessage(); // call object’s displayMessage function

Page 30: ITP Lab Manual

In the above program, first we have made a class named “GradeBook”. Two access specifiers are there, i.e. (Public and Private). Public indicates that a function after the Public (access specifier) can be called by any other functions in a program and by member function of other class. Most data member declarations appear after the access-specifier “private”. Variables or function declared after access specifier “private” are accessible only to member functions of the class for which they are declared. Access specifier “private” will be used later. A function has been defined by a user, which prints a message on the screen. In the main function, we have just made the object of a class i.e. “myGradeBook” and then called a function.

return 0; // indicate successful termination } // end main

// Example05_b.cpp // Define class GradeBook that contains a courseName data member // and member functions to set and get its value; // Create and manipulate a GradeBook object with these functions. #include <iostream> using std::cout; using std::cin; using std::endl; #include <string> // program uses C++ standard string class using std::string; using std::getline; // GradeBook class definition class GradeBook { public: // function that sets the course name void setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function that gets the course name string getCourseName() { return courseName; // return the object's courseName

Page 31: ITP Lab Manual

In the above program we have used two new member functions, set course name & get course name. Set course name stores a course name in a gradebook data member. Member function get course name obtains a gradebook’s course name from that data member. Member function is doing the same work as in example 05-a. This program will take the course name as an input from the user, and then print a message on a screen that this gradebook is for that course name.

} // end function getCourseName // function that displays a welcome message void displayMessage() { // this statement calls getCourseName to get the // name of the course this GradeBook represents cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage private: string courseName; // course name for this GradeBook }; // end class GradeBook // function main begins program execution int main() { string nameOfCourse; // string of characters to store the course name GradeBook myGradeBook; // create a GradeBook object named myGradeBook // display initial value of courseName cout << "Initial course name is: " << myGradeBook.getCourseName() << endl; // prompt for, input and set course name cout << "\nPlease enter the course name:" << endl; getline( cin, nameOfCourse ); // read a course name with blanks myGradeBook.setCourseName( nameOfCourse ); // set the course name cout << endl; // outputs a blank line myGradeBook.displayMessage(); // display message with new course name return 0; // indicate successful termination } // end main

Page 32: ITP Lab Manual

//Example05_c.cpp // Instantiating multiple objects of the GradeBook class and using // the GradeBook constructor to specify the course name // when each GradeBook object is created. #include <iostream> using std::cout; using std::endl; #include <string> // program uses C++ standard string class using std::string; // GradeBook class definition class GradeBook { public: // constructor initializes courseName with string supplied as argument GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName } // end GradeBook constructor // function to set the course name void setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function to get the course name string getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage private:

Page 33: ITP Lab Manual

Above program contains two objects of a class i.e. gradeBook1 & gradeBook2. The program prints two lines on a screen using access specifier, member functions & CONSTRUCTORS. Whenever an object of a class is created, its data member is initialized to the empty string by default. Each class you declare can provide a constructor that can be used to initialize an object of a class, when the object is created.

A constructor is a special member function that must be defined with the same name as the class, so that the compiler can distinguish it from the class's other member functions. An important difference between constructors and other functions is that constructors cannot return values, so they cannot specify a return type (not even void). Normally, constructors are declared public.

string courseName; // course name for this GradeBook }; // end class GradeBook // function main begins program execution int main() { // create two GradeBook objects GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); GradeBook gradeBook2( "CS102 Data Structures in C++" ); // display initial value of courseName for each GradeBook cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() << endl; return 0; // indicate successful termination } // end main

Page 34: ITP Lab Manual

// Example05_d1.h // GradeBook class definition. This file presents GradeBook's public // interface without revealing the implementations of GradeBook's member // functions, which are defined in Example05_d2.cpp #include <string> // class GradeBook uses C++ standard string class using std::string; // GradeBook class definition class GradeBook { public: GradeBook( string ); // constructor that initializes courseName void setCourseName( string ); // function that sets the course name string getCourseName(); // function that gets the course name void displayMessage(); // function that displays a welcome message private: string courseName; // course name for this GradeBook }; // end class GradeBook

// Example05_d2.cpp // GradeBook member-function definitions. This file contains // implementations of the member functions prototyped in Example05_d1.h #include <iostream> using std::cout; using std::endl; #include "Example05_d1.h" // include definition of class GradeBook // constructor initializes courseName with string supplied as argument GradeBook::GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName

Page 35: ITP Lab Manual

} // end GradeBook constructor // function to set the course name void GradeBook::setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function to get the course name string GradeBook::getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void GradeBook::displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage

// Example05_d3.cpp // GradeBook class demonstration after separating // its interface from its implementation. #include <iostream> using std::cout; using std::endl; #include " Example05_d1.h " // include definition of class GradeBook // function main begins program execution int main() { // create two GradeBook objects GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); GradeBook gradeBook2( "CS102 Data Structures in C++" ); // display initial value of courseName for each GradeBook cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() << "\ngradeBook2 created for course: " <<

Page 36: ITP Lab Manual

gradeBook2.getCourseName() << endl; return 0; // indicate successful termination } // end main

The above program simply indicates that if we write the separate codings of class definition containing function proto-types, member-function definition representing the implementation of class, class demonstration after separating its interface from its implementation, a program will execute. Due to this, we can attain the facility of re-usability of class and member-functions.

TASKS

1. Take input of 5 subject names and print them using classes & objects as shown in Example05_b.cpp

2. Recode task 1 using constructors. 3. Recode task 2, separating interface from implementation. Also create your own header

files containing a class. 4. Create a class called Date that includes three pieces of information as data members a

month (type int), a day(type int) and a year(type int). Your class should have a constructor with three parameters to initialize the three data members. Provide a set and a get function for each data member. Provide a member function displayDate that displays a month, day and year separated by forward-slash ( / ). Write a test program that demonstrates class Date’s capabilities.

Page 37: ITP Lab Manual

LAB 6 & 7

CONTROL STATEMENTS (IF-ELSE, SWITCH)

OBJECT To learn the use of if-else & switch statement.

OVERVIEW

// Example06_a.cpp #include <iostream> #include<conio.h> #include <string> using std::cout; using std::cin; using std::endl;

class Number { public: Number( string no ) { setIntegers( no ); } void setIntegers( string no ) { number = no; } string getIntegers() { return number; } void displayMessage() { cout << "enter a number\n" << getIntegers()<< "!" << endl; } private: string number; }; int main () { Number even( "number is even" ); Number odd( "number is odd" ); int a,b; cout<< "inter a number:"<<endl; cin>>a; b=a%2; if ( b==0 )

Page 38: ITP Lab Manual

{cout<<a<<even.getIntegers()} if ( b!=0 ) {cout<<a<<odd.getIntegers();} _getch(); return 0; } 

We make a program to check the number is even or odd. To do this we use if control statements, classes and constructors. This program tell us that we can use if control statements without using else statements. The program checks weather the entered value is even or odd and print the output stream which defined by user in a program.

// Example06_b.cpp #include<iostream> #include<conio.h> #include<string> using std::cout; using std::cin; using std::string; using std::endl; class Alphabets { public: Alphabets( string name ) { setAlphabet( name ); } void setAlphabet( string name ) { wordAlphabet = name; } string getAlphabet() { return wordAlphabet; } void displayMessage() { cout << "Welcome to the grade book for\n" << getAlphabet() << "!" << endl; } private: string wordAlphabet; }; int main () {

Page 39: ITP Lab Manual

Alphabets vowel( "alphabet is vowel" ); Alphabets consonent( "alphabet is consonent" ); char p; cout << "enter an alphabet " << endl; cin>>p; if(p == 'a') cout << vowel.getAlphabet(); else if( p == 'e' ) cout << vowel.getAlphabet(); else if( p == 'i' ) cout << vowel.getAlphabet(); else if( p == 'o' ) cout << vowel.getAlphabet(); else if ( p == 'u' ) cout << vowel.getAlphabet(); else cout << consonent.getAlphabet(); _getch(); return 0; }

To check the entered word is vowel or consonant we use if else control statements. We cannot use else alone. Whenever a program contains else in it, it must contains if. Classes, Objects and Constructors have also been used in the above program.

// Example06_c.cpp #include<iostream> #include<conio.h> #include<string> using std::cout; using std::cin; using std::string; using std::endl; class Number { public: Number( string no ) { setIntegers( no ); } void setIntegers( string no ) { number = no; } string getIntegers()

Page 40: ITP Lab Manual

{ return number; } void displayMessage() { cout << "enter a number\n" << getIntegers()<< "!" << endl; } private: string number; }; int main() { Number even( "number is even" ); Number odd( "number is odd" ); int a,b; cout<<"enter a number"<<endl; cin>>a; b=a%2; switch ( b ) { case 0: cout<<a<<even.getIntegers(); break; default: cout<<a<<odd.getIntegers(); } _getch(); return 0; } In the above program, a number will be taken input by a user and a program will tell whether a number is even or odd number. Switch statement, constructors, classes and objects has been used in this program.

// Example06_d.cpp #include<iostream> #include<conio.h> #include<string> using std::cout; using std::cin; using std::string; using std::endl; class Alphabets { public: Alphabets( string name ) { setAlphabet( name ); }

Page 41: ITP Lab Manual

void setAlphabet( string name ) { wordAlphabet = name; } string getAlphabet() { return wordAlphabet; } void displayMessage() { cout << "Enter a number\n" << getAlphabet() << "!" << endl; } private: string wordAlphabet; }; int main () { Alphabets vowel( "alphabet is vowel" ); Alphabets consonent( "alphabet is consonent" ); char a; cout<<"enter an alphabet"<<endl; cin>>a; switch ( a ) { case 'a': cout <<endl<< vowel.getAlphabet(); break; case 'e': cout <<endl<< vowel.getAlphabet(); break; case 'i': cout <<endl<< vowel.getAlphabet(); break; case 'o': cout <<endl<< vowel.getAlphabet(); break; case 'u': cout <<endl<< vowel.getAlphabet(); break; default: cout <<endl<< consonent.getAlphabet(); } _getch(); return 0; }

Page 42: ITP Lab Manual

In the above program, an alphabet will be taken input by a user and a program will tell whether an alphabet is vowel or consonant. Switch statement, constructors, classes and objects has been used in this program.

TASKS

1. To make a calculator (5 functions) using if-else 2. Take marks of 3 subjects input from user and display their grades using if-else 3. Recode task 1 using switch statement. 4. Recode task 2 using switch statement. 5. A palindrome is a number or a text phrase that reads the same backwards as forwards.

For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a program using if else statements that reads in a five-digit integer and determines whether it is a palindrome.

Page 43: ITP Lab Manual

LAB 8, 9 & 10

LOOPS/CONTROL STATEMENT (FOR, WHILE, DO-WHILE)

LAB OBJECTIVE

To learn, how to repeat the task in programming.

OVERVIEW

In this lab, a student will be learning:

1. The basic concepts of loops. 2. The use of control statements in programming. 3. The way to repeat the task.

Consider these examples which will guide you in more better way:

// Example07_a.cpp // Counter-controlled repetition. #include <iostream> using std::cout; using std::endl; int main() { int counter = 1; // declare and initialize control variable while ( counter <= 10 ) // loop-continuation condition { cout << counter << " "; counter++; // increment control variable by 1 } // end while cout << endl; // output a newline return 0; // successful termination } // end main

 

The above coding is representing an example of “WHILE LOOP”. In the above coding, we have declared a variable named “counter” and initializes it to “1”. The parenthesis after the keyword “while” is representing a condition, means the body of while will repeat itself until the condition becomes false. As an output of this coding a number series from 1 to 10 in the same line will be print. The statement “counter++” is increasing the value of counter by adding 1 into it.

Page 44: ITP Lab Manual

// Example07_b.cpp // Summing integers with the for statement. #include <iostream> using std::cout; using std::endl; int main() {      int total = 0; // initialize total // total even integers from 2 through 20 for ( int number = 2; number <= 20; number += 2 ) total += number;                                cout << "Sum is " << total << endl; // display results return 0; // successful termination } // end main

The above coding is representing an example of “FOR LOOP”. We have declared two variables in the above coding i.e. “total” and “number”. We have initialized “total” with ‘0’ and “number” with 2. The statement “number+=2” will increase the value of “number” by adding 2 in it. And the statement “total+=number” will add the value of “number” in “total”. As an output of this coding, a sum of all even numbers from 2 to 20 will be printed.

// Example07_c.cpp // do...while repetition statement. #include <iostream> using std::cout; using std::endl; int main() {      int counter = 1; // initialize counter do { cout << counter << " "; // display counter counter++; // increment counter } while ( counter <= 10 ); // end do...while cout << endl; // output a newline return 0; // indicate successful termination } // end main

The above coding is representing an example of “DO-WHILE LOOP”. We have declared one variable i.e. “counter” and initialized it to 1. Means the body of loop will repeat itself until the condition becomes false. As an output of this coding, a number series from 1 to 10 will be print in a same line. The statement “counter ++” will increase the value of counter by adding ‘1’ into it.

Page 45: ITP Lab Manual

The main difference between while & do-while loop is that a while loop will only execute if the condition is true, otherwise it will not execute even once. On the other hand, a do-while loop executes once. After that it will check the condition, if the condition is true than it will repeat itself otherwise it will not repeat.

TASKS

1. Write a code that makes a calculator, and it will run as many times as user wants by using FOR loop.

2. Write a code that takes the marks (out of 100) of subjects as an input from user and calculate the sum of that marks using FOR loop. And the loop should repeat until the user press ‘q’ from a keyboard.

3. Write a code which draws a diamond shape with the help of ‘*’ symbol using FOR loop.

4. Recode task # 01 using WHILE loop. 5. Recode task # 02 using WHILE loop. 6. Write a code that generates a random number and print any string that many times.

Page 46: ITP Lab Manual

LAB 11 & 12

FUNCTION AN INTRODUCTION TO RECURSION

LAB OBJECTIVE

To become familiar with functions and recursion.

OVERVIEW

C++ programs are typically written by combining new functions and classes the programmer writes with "prepackaged" functions and classes available in the C++ Standard Library. In this chapter, we concentrate on functions.

The C++ Standard Library provides a rich collection of functions for performing common mathematical calculations, string manipulations, character manipulations, input/output, error checking and many other useful operations. This makes the programmer's job easier, because these functions provide many of the capabilities programmers need. The C++ Standard Library functions are provided as part of the C++ programming environment.

The <cmath> header file provides a collection of functions that enable you to perform common mathematical calculations. For example, you can calculate the square root of 900.0 with the function call. In the figure, the variables x and y are of type double.

Math library functions.

Function Description Example

ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0

ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0

exp( x ) exponential function ex exp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906

fabs( x ) absolute value of x fabs( 5.1 ) is 5.1

fabs( 0.0 ) is 0.0

fabs( -8.76 ) is 8.76

floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0

floor( -9.8 ) is -10.0

fmod( x, y ) remainder of x/y as a floating-point number fmod( 2.6, 1.2 ) is 0.2

log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0

log( 7.389056 ) is 2.0

log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0

Page 47: ITP Lab Manual

Math library functions.

Function Description Example

log10( 100.0 ) is 2.0

pow( x, y ) x raised to power y ( xy ) pow( 2, 7 ) is 128

pow( 9, .5 ) is 3

sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0

sqrt( x ) square root of x (where x is a nonnegative value) sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0

The C++ Standard Library is divided into many portions, each with its own header file. The header files contain the function prototypes for the related functions that form each portion of the library. The header files also contain definitions of various class types and functions, as well as constants needed by those functions. A header file "instructs" the compiler on how to interface with library and user-written components.

C++ Standard Library header files.

C++ Standard Library header file Explanation

<iostream> Contains function prototypes for the C++ standard input and standard output functions, introduced in Chapter 2, and is covered in more detail in Chapter 15, Stream Input/Output. This header file replaces header file <iostream.h>.

<iomanip> Contains function prototypes for stream manipulators that format streams of data. This header file is first used in Section 4.9 and is discussed in more detail in Chapter 15, Stream Input/Output. This header file replaces header file <iomanip.h>.

<cmath> Contains function prototypes for math library functions (discussed in Section 6.3). This header file replaces header file <math.h>.

<cstdlib> Contains function prototypes for conversions of numbers to text, text to numbers, memory allocation, random numbers and various other utility functions. Portions of the header file are covered in Section 6.7; Chapter 11, Operator Overloading; String and Array Objects; Chapter 16, Exception Handling; Chapter 19, Web Programming; Chapter 22, Bits, Characters, C-Strings and structs; and Appendix E, C Legacy Code Topics. This header file replaces header file <stdlib.h>.

<ctime> Contains function prototypes and types for manipulating the time and date. This header file replaces header file <time.h>. This header file is used in Section 6.7.

<vector>, <list>, <deque>, <queue>, <stack>, <map>, <set>, <bitset>

These header files contain classes that implement the C++ Standard Library containers. Containers store data during a program's execution. The <vector> header is first introduced in Chapter 7, Arrays and Vectors. We discuss all these header files in Chapter 23, Standard Template Library (STL).

<cctype> Contains function prototypes for functions that test characters for certain properties (such as whether the character is a digit or a punctuation), and function prototypes for functions that can be used to convert lowercase letters to uppercase letters and vice versa. This header file

Page 48: ITP Lab Manual

C++ Standard Library header files.

C++ Standard Library header file Explanation

replaces header file <ctype.h>. These topics are discussed in Chapter 8, Pointers and Pointer-Based Strings, and Chapter 22, Bits, Characters, C-Strings and structs.

<cstring> Contains function prototypes for C-style string-processing functions. This header file replaces header file <string.h>. This header file is used in Chapter 11, Operator Overloading; String and Array Objects.

<typeinfo> Contains classes for runtime type identification (determining data types at execution time). This header file is discussed in Section 13.8.

<exception>, <stdexcept>

These header files contain classes that are used for exception handling (discussed in Chapter 16).

<memory> Contains classes and functions used by the C++ Standard Library to allocate memory to the C++ Standard Library containers. This header is used in Chapter 16, Exception Handling.

<fstream> Contains function prototypes for functions that perform input from files on disk and output to files on disk (discussed in Chapter 17, File Processing). This header file replaces header file <fstream.h>.

<string> Contains the definition of class string from the C++ Standard Library (discussed in Chapter 18).

<sstream> Contains function prototypes for functions that perform input from strings in memory and output to strings in memory (discussed in Chapter 18, Class string and String Stream Processing).

<functional> Contains classes and functions used by C++ Standard Library algorithms. This header file is used in Chapter 23.

<iterator> Contains classes for accessing data in the C++ Standard Library containers. This header file is used in Chapter 23, Standard Template Library (STL).

<algorithm> Contains functions for manipulating data in C++ Standard Library containers. This header file is used in Chapter 23.

<cassert> Contains macros for adding diagnostics that aid program debugging. This replaces header file <assert.h> from pre-standard C++. This header file is used in Appendix F, Preprocessor.

<cfloat> Contains the floating-point size limits of the system. This header file replaces header file <float.h>.

<climits> Contains the integral size limits of the system. This header file replaces header file <limits.h>.

<cstdio> Contains function prototypes for the C-style standard input/output library functions and information used by them. This header file replaces header file <stdio.h>.

<locale> Contains classes and functions normally used by stream processing to process data in the natural form for different languages (e.g., monetary formats, sorting strings, character presentation, etc.).

<limits> Contains classes for defining the numerical data type limits on each computer platform.

<utility> Contains classes and functions that are used by many C++ Standard Library header files.

Page 49: ITP Lab Manual

Functions

// Example08_a.cpp // mathematical calculation using cmath header file #include<iostream> #include<conio.h> #include<cmath> using std::cout; using std::cin; using std::endl; class Function { public: void power (void) { double a,b; cin>>a>>b; cout<<"power is "<<pow (a,b); squareroot ( a ); } void squareroot (double x) { cout<<"\nsquareroot is "<< sqrt (x)<<"\n"; } double exponent (void) { double y; cin>>y; return exp (y); } double logrithum (double c) { double d; d=log(c ); return d ; } }; int main() { Function mathFunction; double a; mathFunction.power (); cin>>a; cout<<"log is "<<mathFunction.logrithum ( a )<<"\n"; cout<<"\nexponent is "<<mathFunction.exponent ()<<endl; getch(); return 0; }

Page 50: ITP Lab Manual

In the above program classes, function and math library files are used to do some mathematical calculation. Function are called from main and calculations are done in class.

Recursion

// Example08_b.cpp // Testing the recursive factorial function #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; unsigned long factorial( unsigned long ); // function prototype int main() { // calculate the factorials of 0 through 10 for ( int counter = 0; counter <= 10; counter++ ) cout << setw( 2 ) << counter << "! = " << factorial( counter ) << endl; return 0; // indicates successful termination } // end main // recursive definition of function factorial unsigned long factorial( unsigned long number ) { if ( number <= 1 ) // test for base case return 1; // base cases: 0! = 1 and 1! = 1 else // recursion step return number * factorial( number - 1 ); } // end function factorial  

The above code demonstrates the factorial function using recursion.

// Example08_c.cpp // Testing the recursive fibonacci function. #include <iostream> using std::cout; using std::cin; using std::endl; unsigned long fibonacci( unsigned long ); // function prototype int main() { // calculate the fibonacci values of 0 through 10 for ( int counter = 0; counter <= 10; counter++ )

Page 51: ITP Lab Manual

cout << "fibonacci( " << counter << " ) = " << fibonacci( counter ) << endl; // display higher fibonacci values cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl; cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl; cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl; return 0; // indicates successful termination } // end main // recursive method fibonacci unsigned long fibonacci( unsigned long number ) { if ( ( number == 0 ) || ( number == 1 ) ) // base cases return number; else // recursion step return fibonacci( number - 1 ) + fibonacci( number - 2 ); } // end function fibonacci

The above code demonstrates printing of fibonacci series using recursion.

TASKS

1. Make a program that take 5 digit number from the user and print the some of them using loop and recursion. e.g 12345=1+2+3+4+5=15.

2. Recode Example08_c.cpp using loops. 3. Recode fig number Example08_b.cpp using loops.