Practical Work Book
Practical Work Book
Practical Work Book
Name:
Roll Number:
Batch:
Department:
Year:
Prepared By:
Reviewed By:
Approved By:
accomplishment of the assigned tasks. Every lab is provided with the syntax of the statements
or commands which will be used to make the programs of exercises. In order to facilitate the
students some program segments are also provided explaining the use of commands. For a
wide scope of usage of the commands several examples are also given so that the students
The conditions, limitations and memory allocation are also mentioned where necessary. This
book starts the programming of C Language from the scratch and covers most of the
programming structures of C-Language. For some commands or structures more than one lab
are designed so that the students can thoroughly understand their use. This lab book leads the
students to the Object Oriented Programming C++. One lab on Object Oriented Programming
C++ is given in the last which gives the basic idea of OOP.
Programming with C-Language
CONTENTS
Lab No. 01
OBJECT
THEORY
1
Programming With C-Languages Lab No. 01
NED University of Engineering and Technology- Department of Electronics Engineering
Default Directory
The default directory of Turbo C compiler is c:\tc\bin.
Using Menus
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select
different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke
the selection by pressing the key combination for the specific menu.
Writing a Program
When the Edit window is active, the program may be typed. Use the certain key combinations
to perform specific edit functions.
Saving a Program
To save the program, select save command from the file menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name
of the file. Provide an appropriate and unique file name. You can save the program after
compiling too but saving it before compilation is more appropriate.
2
Programming With C-Languages Lab No. 01
NED University of Engineering and Technology- Department of Electronics Engineering
All the above steps can be done by using Run option from the menu bar or using key
combination Ctrl+F9 (By this linking & compiling is done in one step).
It can be done by selecting Compile option from menu bar or using key combination Alt+F9.
Executing a Program
If the program is compiled and linked without errors, the program is executed by selecting
Run from the Run Menu or by pressing the [Ctrl+F9] key combination.
Whatever type of bug you find, you must fix it, and that involves editing your source code,
recompiling and relinking, and then rerunning the program.
3
Programming With C-Languages Lab No. 01
NED University of Engineering and Technology- Department of Electronics Engineering
Correcting Errors
If the compiler recognizes some error, it will let you know through the Compiler window.
You’ll see that the number of errors is not listed as 0, and the word “Error” appears instead of
the word “Success” at the bottom of the window. The errors are to be removed by returning to
the edit window. Usually these errors are a result of a typing mistake. The compiler will not
only tell you what you did wrong; they’ll point you to the exact place in your code where you
made the mistake.
Exiting IDE
An Edit window may be closed in a number of different ways. You can click on the small
square in the upper left corner, you can select close from the window menu, or you can press
the [Alt][F3] combination. To exit from the IDE, select Exit from the File Menu or press
[Alt][X] Combination.
EXERCISE
1. Type the following program in C Editor and execute it. Mention the Error.
void main(void)
{
printf(“ This is my first program in C ”);
}
4
Programming With C-Languages Lab No. 01
NED University of Engineering and Technology- Department of Electronics Engineering
2. Add the following line at the beginning of the above program. Recompile the
program. What is the output?
#include<stdio.h>
3. Make the following changes to the program. What Errors are observed?
i. Write Void instead of void .
5
Programming Languages Lab No. 02
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 02
OBJECT
C Building Blocks
THEORY
Format Specifiers
Format Specifiers tell the printf statement where to put the text and how to display the text.
The various format specifiers are:
%d => integer
%c => character
%f => float etc.
Escape Sequences
Escape Sequence causes the program to escape from the normal interpretation of a string, so
that the next character is recognized as having a special meaning. The back slash “\” character
is called the Escape Character” . The escape sequence includes the following:
\n => new line
\t => tab
\b => back space
\r => carriage return
\” => double quotations
\\ => back slash etc.
6
Programming Languages Lab No. 02
NED University of Engineering and Technology- Department of Electronics Engineering
Operators
There are various types of operators that may be placed in three categories:
Basic: + - * / %
Assignment: = += -= *= /= %=
(++, -- may also be considered as assignment operators)
Relational: < > <= >= == !=
Logical: && , || , !
EXERCISE
1. Write a program which shows the function of each escape sequence character.
eg printf(“alert ring bell rings like \a\a\a\a\a\a\a\a\a\a\a\a\a\a”);
printf(“the tab is inserted like \t this”);etc
ii. x = a 2 +2ab+b 2
3. What will be the out put of the mix mode use of integers and float.
a=5/9;
7
Programming Languages Lab No. 02
NED University of Engineering and Technology- Department of Electronics Engineering
b=5.0/9;
printf(“%f,%f”,a,b);
5. Write some simple statements to check the working of logical and relational
operators.
8
Programming With C-Language Lab No.03
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 03
OBJECT
THEORY
Types of Loops
There are three types of Loops:
1) for Loop
i. simple for loop
ii. nested for loop
2) while Loop
i. simple while loop
ii. nested while loop
3) do - while Loop
i. simple do while loop
ii. nested do while loop
9
Programming With C-Language Lab No.03
NED University of Engineering and Technology- Department of Electronics Engineering
EXERCISE
10
Programming With C-Language Lab No.03
NED University of Engineering and Technology- Department of Electronics Engineering
5. Write a program to enter the numbers till the user wants and at the end it should display
the count of positive, negative and zeros entered.
6. Write a program to find the range of a set of numbers. Range is the difference between
the smallest and biggest number in the list.
11
Programming With C-Language Lab No.04
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.04
OBJECT
Nested looping
THEORY
Types of Loops
There are three types of Loops:
1) for Loop
i. simple for loop
ii. nested for loop
2) while Loop
i. simple while loop
ii. nested while loop
3) do - while Loop
i. simple do while loop
ii. nested do while loop
Nesting may extend these loops.
12
Programming With C-Language Lab No.04
NED University of Engineering and Technology- Department of Electronics Engineering
This loop runs as long as the condition in the parenthesis is true. Note that there is a
semicolon after the “while” statement. The difference between the “while” and the “do-while”
statements is that in the “while” loop the test condition is evaluated before the loop is
executed, while in the “do” loop the test condition is evaluated after the loop is executed. This
implies that statements in a “do” loop are executed at least once. The inner loop runs as many
times as there is the limit of the condition of the external loop. This loop runs as long as the
condition in the parenthesis is true. We can nest many loops inside as there is the requirement.
EXERCISE
13
Programming With C-Language Lab No.04
NED University of Engineering and Technology- Department of Electronics Engineering
ABCDEFGFEDCBAA
BCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
14
Programming Languages Lab No. 05
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.05
OBJECT
THEORY
Normally, your program flows along line by line in the order in which it appears in your
source code. But, it is sometimes required to execute a particular portion of code only if
certain condition is true; or false i.e. you have to make decision in your program. There are
three major decision making structures. The ‘if’ statement, the if-else statement, and the
switch statement. Another less commonly used structure is the conditional operator.
The if statement
The if statement enables you to test for a condition (such as whether two variables are equal)
and branch to different parts of your code, depending on the result or the conditions with
relational and logical operators are also included..
The simplest form of an if statement is:
if (expression)
statement;
else
{
statement/s;
}
EXERCISE
1.Write a program which takes three sides a, b and c of a triangle input and calculates its area
if these conditions are satisfied a+b>c, b+c>a, a+c>b
(Help a= vs(s-a)(s-b)(s-c), where s=(a+b+c)/2
33
Programming Languages Lab No. 05
NED University of Engineering and Technology- Department of Electronics Engineering
3. Write a program which takes a character input and checks whether it is vowel or consonant
4. According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year
st
is input through the keyboard write a program to find out what is the day on 1 January
of this year.
33
Programming Languages Lab No. 06
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.06
OBJECT
THEORY
Normally, your program flows along line by line in the order in which it appears in your
source code. But, it is sometimes required to execute a particular portion of code only if
certain condition is true; or false i.e. you have to make decision in your program. There are
three major decision making structures. The ‘if’ statement, the if-else statement, and the
switch statement. Another less commonly used structure is the conditional operator.
Conditional Operator
The conditional operator ( ?: ) is C’s only ternary operator; that is, it is the only operator to
take three terms.
33
Programming Languages Lab No. 06
NED University of Engineering and Technology- Department of Electronics Engineering
This line is read as "If expression1 is true, return the value of expression2; otherwise, return
the value of expression3." Typically, this value would be assigned to a variable.
EXERCISE
1.Write a program which takes a text input counts total number of vowels, consonants and
other special characters and prints the result
3. Write a program which takes 10 integers as input and prints the largest one.
33
Programming Languages Lab No. 07
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 07
OBJECT
THEORY
One of the most innovative and useful features of Turbo C++ is the integration of debugging
facilities into the IDE.
Even if your program compiles perfectly, it still may not work. Such errors that cause the
program to give incorrect results are called Logical Errors. The first thing that should be done
is to review the listing carefully. Often, the mistake will be obvious. But, if it is not, you’ll
need the assistance of the Turbo C Debugger.
Our intention in this program is that when number is between 0 and 100, answer will be 1,
when the number is 100 or greater, answer will be 0 , and when number is less than 0,
answer will retain its initialized value of –1. When we run this program with a test value of
-50 for number, we find that answer is set to 0 at the end of the program, instead of staying
–1.
We can understand where the problem is if we single step through the program. To do this,
simply press the [F7] key. The first line of the program will be highlighted. This highlighted
line is called the run bar . Press [F7] again. The run bar will move to the next program line.
The run bar appears on the line about to be executed. You can execute each line of the
program in turn by pressing [F7]. Eventually you’ll reach the first ifstatement:
33
Programming Languages Lab No. 07
NED University of Engineering and Technology- Department of Electronics Engineering
This statement is true (since number is –50); so, as we would expect the run bar moves to the
second if statement:
if(num>0)
This is false. Because there’s no else matched with the second if, we would expect the run bar
to the printf( ) statement. But it doesn’t! It goes to the line
answer = 0;
Now that we see where the program actually goes, the source of the bug should become clear.
The else goes with the last if, not the first if as the indenting would lead us to believe. So, the
else is executed when the second if statement is false, which leads to erroneous results. We
need to put braces around the second if, or rewrite the program in some other way.
Watches
Single stepping is usually used with other features of the debugger. The most useful of these
is the watch (or watch expression). This lets you see how the value of variable changes as the
program runs. To add a watch expression, press [Ctrl+F7] and type the expression.
Breakpoints
It often happens that you’ve debugged part of your program, but must deal with a bug in
another section, and you don’t want to single-step through all the statements in the first part to
get to the section with the bug. Or you may have a loop with many iterations that would be
tedious to step through. The way to do this is with a breakpoint. A breakpoint marks a
statement where the program will stop. If you start the program with [Ctrl][F9], it will execute
all the statements up to the breakpoint, then stop. You can now examine the state of the
variables at that point using the watch window.
Installing breakpoints
To set a breakpoint, first position the cursor on the appropriate line. Then select Toggle
Breakpoint from the Debug menu (or press [Ctrl][F8]). The line with the breakpoint will be
highlighted. You can install as many breakpoints as you want. This is useful if the program
can take several different paths, depending on the result of if statements or other branching
constructs.
Removing Breakpoints
You can remove a single breakpoint by positioning the cursor on the line with the breakpoint
and selecting Toggle breakpoint from the Debug menu or pressing the [Ctrl][F8] combination
(just as you did to install the breakpoint). The breakpoint highlight will vanish.
You can all set Conditional Breakpoints that would break at the specified value only.
33
Programming Languages Lab No. 07
NED University of Engineering and Technology- Department of Electronics Engineering
EXERCISE
1. Add watches to the entire variable in a program and follow their values line by
line.
2. Type in the following program and find out the error using the Turbo C Debugger.
#include<stdio.h>
void main(void)
{
int a=4,b=5,i;
for(i=1;i<=10;i++);
{
a++;
b--;
}
printf(“%d”,i);
printf(“%d”,a);
printf(“%d”,b);
}
Mention the error. Correct this program by locating the error through the debugger
and rewrite the correct program statements
33
Programming Languages Lab No. 08
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 08
OBJECT
THEORY
Functions are used normally in those programs where some specific work is required to be
done repeatedly and looping fails to do the same.
Three things are necessary while using a function.
Before defining a function, it is required to declare the function i.e. to specify the function
prototype. A function declaration is followed by a semicolon ‘ ;’. Unlike the function
definition only data type are to be me ntioned for arguments in the function declaration.
There are certain functions that you have already used e.g:getche( ), clrscr( ), printf( ), scanf( )
etc.
There are four types of functions depending on the return type and arguments:
• Functions that take nothing as argument and return nothing.
• Functions that take arguments but return nothing.
• Functions that do not take arguments but return something.
• Functions that take arguments and return something.
A function that returns nothing must have the return type “void”. If nothing is specified then
the return type is considered as “int”.
33
Programming Languages Lab No. 08
NED University of Engineering and Technology- Department of Electronics Engineering
EXERCISE
1. Write a program to print the find the sum of the given series, take first 8 terms
A=1! +2! +3! +4! +……..
33
Programming Languages Lab No. 08
NED University of Engineering and Technology- Department of Electronics Engineering
sin(x)= x - x 3 + x 5 - x7 + x 9 - …….
3! 5! 7! 9!
4. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are
A(x1, y1), B(x2, y2), and C(x3, y3). Use these functions to develop a function
which returns a value 1 if the point (x, y) lines inside the triangle ABC, otherwise a value 0.
5. Given three variables x, y, z write a function to circularly shift their values to right.
In other words if x = 5, y = 8, z = 10 after circular shift y = 5, z = 8, x =10 after
circular shift y = 5, z = 8 and x = 10. Call the function with variables a, b, c to circularly
shift values.
33
Programming Languages Lab No. 09
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.09
OBJECT
Preprocessor Directives
THEORY
Preprocessor directives are actually the instructions to the compiler itself. They are not
translated but are operated directly by the compiler.
The most common preprocessor directives are
i. include directive
ii. define directive
i. include directive: The include directive is used to include files like as we include header
files in the beginning of the program using #include directive like
#include<stdio.h>
#include<conio.h>
ii. define directive: It is used to assign names to different constants or statements which are
to be used repeatedly in a program. These defined values or statement can be used by main or
in the user defined functions as well.
They are used for
a. defining a constant b.
defining a statement
c. defining a mathematical expression
for example
#define pi 3.142
#define p printf(“enter a new number”);
#define for(a) (4/3.0)*pi*(a*a*a);
1. Write a program which calculates and returns the area and volume of a sphere using define
directive .
33
Programming Languages Lab No. 09
NED University of Engineering and Technology- Department of Electronics Engineering
2. Write a program which takes four integers a, b, c, d as input and prints the largest one using
define directive.
3. Which of the following are correctly formed #define statements: #define INCH PER FEET 12
#define SQR (X) ( X * X )
#define SQR(X) X * X
#define SQR(X) ( X * X )
33
Programming With C-Language Lab No. 10
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 10
OBJECT
THEORY
An array is a collection of data storage locations, each of which holds the same type of data.
Each storage location is called an element of the array. You declare an array by writing the
type, followed by the array name and the subscript. The subscript is the number of elements in
the array, surrounded by square brackets. For example,
long LongArray[25];
declares an array of 25 long integers, named Long Array. When the compiler sees this
declaration, it sets aside enough memory to hold all 25 elements. Because each long integer
requires 4 bytes, this declaration sets aside 100 contiguous bytes of memory
EXERCISE
1. Write a program that takes input for array int a[5] and array int b[5] and exchanges
their values.
2. Write a program that takes 10 integers as input and prints the largest integer and its
location in the array.
33
Programming With C-Language Lab No. 10
NED University of Engineering and Technology- Department of Electronics Engineering
3. Write a program which takes a string as input and counts total number of vowels in that.
5. Write a program to copy the contents of one array into another in the reverse order.
main( )
{
static int a[5] ;
int i ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "\n%d", a[i] ) ;
}
33
Programming With C-Language Lab No. 11
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.11
OBJECT
Arrays in C (Multidimensional)
THEORY
A Multidimensional array is a collection of data storage locations, each of which holds the
same type of data. Each storage location is called an element of the array. You declare an
array by writing the type, followed by the array name and the subscript. The subscript is the
number of elements in the array, surrounded by square brackets. For example,
int a[5][10]
declares an array of 50 integers, named a. Its declaration shows that array a comprises of 5
one dimensional arrays and each one dimensional array contains 10 elements.
When the compiler sees this declaration, it sets aside enough memory to hold all 50 elements.
Because each integer requires 2 bytes, this declaration sets aside 100 contiguous bytes of
memory.
EXERCISE
1. Write a program that adds up two 4x4 arrays and stores the sum in third array.
2. Write a program which takes names of five countries as input and prints them in
alphabetical order.
3. A 6 x 6 matrix is entered through the keyboard and stored in a 2-dimensional array mat[7][7].
Write a program to obtain the Determinant values of this matrix.
33
Programming Languages Lab No. 12
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 12
OBJECT
THEORY
There are two ways to view the display screen in Turbo C graphics model:
All the ANSI codes start by the character \x1B[ after which, we mention codes specific to
certain operation. Using the #define directive will make the programs easier to write and
understand.
33
Programming Languages Lab No. 12
NED University of Engineering and Technology- Department of Electronics Engineering
EXERCISE
3. Which header file is required to be included while working in (a) text mode (b)
graphics mode?
33
Programming Languages Lab No. 13
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 13
OBJECT
Structures
THEORY
If we want a group of same data type we use an array. If we want a group of elements of
different data types we use structures. For Example: To store the names, prices and number of
pages of a book you can declare three variables. To store this information for more than one
book three separate arrays may be declared. Another option is to make a structure. No
me mory is allocated when a structure is declared. It simply defines the “form” of the
structure. When a variable is made then memory is allocated. This is equivalent to saying that
there is no memory for “int” , but when we de clare an integer i.e. int var; only then me mory
is allocated.
The structure for the above mentioned case will look like
Struct books
{char bookname[20];
float price;
int pages;}
struct book[50];
EXERCISE
1. Write a program to maintain the library record for 100 books with book name,
author’s name, and edition, year of publishing and price of the book.
2. Write a program to make a tabulation sheet for a class of 50 students with their names, seat
nos, marks, percentages and grades.
33
Programming Languages Lab No. 13
NED University of Engineering and Technology- Department of Electronics Engineering
4. Write a program that compares two given dates. To store date use structure say date
that contains three members namely date, month and year. If the dates are equal then
display message as "Equal" otherwise "Unequal".
main( )
{
struct employee
{
char name[25] ;
int age ;
float bs ;
};
struct employee e ;
strcpy ( e.name, "Hacker" ) ;
age = 25 ;
printf ( "\n%s %d", e.name, age ) ;
}
33
Programming Languages Lab No. 14
NED University of Engineering and Technology- Department of Electronics Engineering
Programming Languages Lab No. 14
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 14
OBJECT
Pointers in C-Language
THEORY
EXERCISE
1. Write down the number of bytes allocated for the following pointer variables:
int *x;
char *y;
float *z;
4. Write a program which adds two arrays with the help of their pointers.
40
Programming Languages Lab No. 15
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No. 15
OBJECT
THEORY
}
}
void add(int *p,int x)
{int j;
for (j=0;j<x;j++)
{
*p=*p+5;
p++;
}
}
Similarly string arrays and multidimensional arrays can also be passed to functions by
their addresses and size.
40
Programming Languages Lab No. 16
NED University of Engineering and Technology- Department of Electronics Engineering
EXERCISE
1. Write a program to pass an integer array of 10 elements to a function which returns the
same array after sorting it in descending order. Print the array.
2. Write a program which passes a string to a function and the function changes its case
without using any library function.
main( )
{
int i = 35, *z ;
z = function ( &i ) ;
printf ( "\n%d", z ) ;
}
function ( int *m )
{
return ( m + 2 ) ;
}
40
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No 16
OBJECT
Filing in C-Language
THEORY
Data files
Many applications require that infor mation be “ written & read” fro m an auxiliary
storage device.
This information is written in the form of Data Files .
Data files allow us to store information permanently and to access and alter that
information whenever necessary.
Types of Data files
Standard data files .(stream I/O)
System data files. (low level I/O)
Standard I/O
Easy to work with, & have different ways to handle data.
Four ways of reading & writing data:
1. Character I/O.
2. String I/O.
3. Formatted I/O.
4. Record I/O.
File Protocol
1. fopen
2. fclose
fopen:-
It is used to open a file .
Syntax:
fopen (file name , access-mode ).
“r” open a file for reading only.
“w” open a file for writing.
“a” open a file for appending .
“r+” open an existing file for reading & writing.
“w+” open a new file for reading &writing.
“a+” open a file for reading & appending & create a new file if it does exist.
Example:-
#include <stdio.h>
main
{
FILE*fpt;
40
Programming Languages Lab No. 18
NED University of Engineering and Technology- Department of Electronics Engineering
Standard I/O:
Four way s of reading and writing data:
Character I/O.
String I/O.
Formatted I/O.
Record I/O.
Character I/O:
In normal C program we used to use getch, getchar and getche etc.
In filling we use putc and getc.
putc( );
It is used to write each character to the data file.
Putc requires specification of the stream pointer *fpt as an argument.
Syntax:
putc(c, fp);
c = character to be written in the file .
fp = file pointer .
putch or putchar writes the I/P character to the consol while putc writes to the file.
Example (1):
Reading the Data File:
#include < stdio.h >
main( )
{
FILE*fpt;
Char c;
fpt = fopen ( “ star.dat”,”r”);
if( fpt = = NULL);
printf( “Error- cant open”);
else
do
putchar(c=getc(fpt) );
while(c!=‘\n’ );
40
Programming Languages Lab No. 19
NED University of Engineering and Technology- Department of Electronics Engineering
fclose( fpt );
}
Exercise:
1. What will be the output of the given program
#include < stdio.h >
main( )
{
FILE*fpt;
Char c;
fpt = fopen ( “ star.dat”,”n”); [ a new file is made
]
do
putc((c=getchar( ) ); fpt );
while(c!=‘\n’ ); or ‘\r’
fclose( fpt );
}
40
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
Lab No.17
OBJECT
THEORY
C++ i s a superset of C, that is, it incorporates all the operators and syntax of ordinary C,
but adds additional features.
Object-Oriented Programming
Its important understands that object-oriented programming is an approach to organizing
programs, it is not primarily concerned with the detail of program code; its focus is the
overall structure of the program. A prerequisite for writing object oriented programs
understands the philosophy of OOP. OOP has the greatest potential for simplify ing
program conceptualization, coding, debugging, and maintenance.
Object-Oriented Organization
Object-oriented programming attempts to solve some of the procedural approach. OOP
gives data a more central position in program organization, and ties the data more closely
to the functions that act on it. In the procedural approach, the organizational units are
functions. In OOP, the organizational units contain both the data and the functions that
act on that data. These units are called objects.
Objects
In QOP, a program is organized into objects. As we noted, an object consists of data and
the functions that operate on that data. In a typical situation only the functions in the
object can access the object’s data; it cannot be accessed by functions in other objects.
A New Vocabulary
The functions in an object are called methods, they do something to the objects data, and
the binding together of the data with the functions that operate on it is called
encapsulation. The fact that the data in an object cannot be accessed by other objects is
called data hiding Encapsulation and data hiding are key elements in OOP.
Classes
In OOP, objects are members of classes. A class in OOP has the same relationship to an
object that the declaration of struct.
45
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
Inheritance
An important feature of C++ is inheritance. Inheritance means making objects out of
other objects.
Data
The central data structure in this program is an array of floating point numbers to hold the
expenses.
Declaring a Class
We mentioned that declaring a class is so mewhat like declaring a structure. It specifies
what objects of this class will look like. Here's the declaration of class ledger:
Class ledge // declaration of class ledger
{
private:
float list[100J; // define array for items
int count; //define numb er of items entered
public:
void initCountvoid; // declare method
void enterItem(voia); // declare method
};
Defining Methods
Here are the definitions for the methods initCount( ), enterItem( ), and printTotal( ).
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ledger:: initCount(void) // a function in class ledger
{ // initializes count to 0
count = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
45
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
Lets put the C++ co mponents we discussed above into a complete C++ program. This
example program permits the user to record amou nts in the list and print out the total.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// expense.cpp
// object oriented expense ledger
#include <iostream.h>.
// for cout, cin, etc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class ledger // declaration of, class ledger
{
private:
float list[100]; // array for items
int count; // number of items entered
public:
void initCount(void); // declare function
void enterltem( void); // declare function
void printTotal(void); // declare function
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ledger::initCount(void) // a function in class ledger
{ // initializes count to 0
count = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ledger: :interItem(void) // a function in c lass, ledger, '
{ // puts entry in list
cout <<”\nEnter amount: ";
cin >> list[count++];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ledger::printTotal(void) // a function in class ledger
{ // prints total of all entries
float total=0.0;
for( int j = 0; j<count; j++)
total += list[j];
tout <<”\n\nTotal is: “ <<total <<"\n";
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ledger expenses; // an instance of class ledger
45
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main( ) // main --handles user interface
{ // uses object expenses
char option;
expenses.initCount( ); // initialize count
do
{ // display options
cout <<"\nOptions are: e --enter expense"
<<"\n E --print total expenses"
<<"\n q --quit (terminate program)”
<<"\nType option letter: “;
cin >>option; // get option from user
switch (option)
{ // act on Option selected
case 'e': expenses.enterItem( ); break;
case 'E': expenses.printTotal( ); break;
case 'q': break;
default: cout <<"\nUnknown co mmand\n”;
}
} while(option != 'q');
} // end main
EXERCISE:
45
Programming Languages Lab No. 17
NED University of Engineering and Technology- Department of Electronics Engineering
45