c++ programs

Post Section A Syllabus related query

c++ programs

Postby mrs poonam » Thu Jul 15, 2010 12:11 pm

Paint program in C
Description : This project is a good program for understanding basics of Graphics in C Shailesh & Nirgun

/* This programs are four seperate programs which combinely output as
Paint .........



#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <process.h>
#include <dos.h>


#include"c:paintmainscre.c"

# define RBACK_GND_ICON 0
# define BACK_GND_ICON 0
# define MAXX 40
# define MAXY 32
# define EXP_FACTOR 4
# define SKIP 1
# define BACK_GND_GRID 1
# define DRAW 0
# define ERASE 2
# define FORE_GND 3


unsigned char icon_image [MAXX][MAXY] ;

int scan ;

iconcreater()
{
int gm = CGAC3, gd = CGA ;
char fname[30] ;

initgraph ( &gd, &gm, "c:\tc\bgi" ) ;

init_icon() ;

display_icon() ;

display_grid() ;

while ( 1 )
{
gotoxy ( 2, 25 ) ;
printf ( "F1-Draw F2-Load F3-Save F4-Quit" ) ;

getkey() ;

switch ( scan )
{
case 59 : /* F1 key */

edit_icon() ;
break ;

case 60 : /* F2 key */

/* collect the file name */
gotoxy ( 6, 21 ) ;
printf ( "Enter file name: " ) ;
gets ( fname ) ;

/* erase the message line */
icleartext ( 21 ) ;

load_icon ( fname ) ;
display_icon() ;
display_grid() ;
break ;

case 61 : /* F3 key */

save_icon() ;
break ;

case 62 : /* F4 key */

closegraph() ;
restorecrtmode() ;
mainscreen() ;
mainmenu1();
//exit ( 0 ) ;
}
}
}


load_icon ( char *name )
{
FILE *fp ;


if ( ( fp = fopen ( name, "rb" ) ) == NULL )
{
gotoxy ( 1, 21 ) ;
printf ( "Unable to open file! Press any key..." ) ;
getch() ;

icleartext ( 21 ) ;
return ;
}

fread ( icon_image, sizeof ( icon_image ), 1, fp ) ;
fclose ( fp ) ;
return;
}


icleartext ( int row )
{
int col ;

for ( col = 1 ; col <= 39 ; col++ )
{
gotoxy ( col, row ) ;
printf ( " " ) ;
}
return;
}


init_icon()
{
int x, y ;

for ( x = 0 ; x < MAXX ; x++ )
{
for ( y = 0 ; y < MAXY ; y++ )
icon_image[x][y] = BACK_GND_ICON ;
}
return;
}


display_icon()
{
int x, y ;

setcolor ( 3 ) ;
rectangle ( 0, 0, 41, 33 ) ;

for ( x = 0 ; x < MAXX ; x++ )
{
for ( y = 0 ; y < MAXY ; y++ )
putpixel ( x + 1, y + 1, icon_image[x][y] ) ;
}
return;
}


display_grid()
{
int x, y, xgrid, ygrid ;

for ( x = 0 ; x < MAXX ; x++ )
{
for ( y = 0 ; y < MAXY ; y++ )
{
xgrid = 100 + x * EXP_FACTOR ;
ygrid = y * EXP_FACTOR ;

if ( icon_image[x][y] == 0 )
putpixel ( xgrid, ygrid, 1 ) ;
else
putpixel ( xgrid, ygrid, icon_image[x][y] ) ;
}
}
return;
}



edit_icon()
{
int x = 0, y = 0, xgrid = 100, ygrid = 0, flag = SKIP ;


gotoxy ( 1, 25 ) ;
printf ( "F1-Draw F2-Skip F3-Erase F4-Wipe F5-End" ) ;

while ( 1 )
{

idrawcursor ( xgrid, ygrid, FORE_GND ) ;

getkey() ; /* receive key */


idrawcursor ( xgrid, ygrid, BACK_GND_ICON ) ;


if ( icon_image[x][y] == 0 )
putpixel ( xgrid, ygrid, BACK_GND_GRID ) ;
else
putpixel ( xgrid, ygrid, icon_image[x][y] ) ;

switch ( scan )
{
case 59 : /* F1 key */

flag = DRAW ;
break ;

case 60 : /* F2 key */

flag = SKIP ;
break ;

case 61 : /* F3 key */

flag = ERASE ;
break ;

case 62 : /* F4 key */

init_icon() ;
display_icon () ;
display_grid() ;
break ;

case 63 : /* F5 key */

icleartext ( 25 ) ;
return ;

case 75 : /* left arrow key */

x-- ;
break ;

case 77 : /* right arrow key */

x++ ;
break ;

case 72 : /* up arrow key */

y-- ;
break ;

case 80 : /* down arrow key */

y++ ;
break ;

case 71 : /* Home key */

x-- ;
y-- ;
break ;

case 73 : /* End key */

x++ ;
y-- ;
break ;

case 79 : /* PgUp key */

x-- ;
y++ ;
break ;

case 81 : /* PgDn key */

x++ ;
y++ ;
break ;

default : /* any other key */

printf ( "a" ) ;
}



if ( x < 0 )
x++ ;

if ( y < 0 )
y++;

if ( x == MAXX )
x-- ;

if ( y == MAXY )
y-- ;

if ( flag == DRAW )
icon_image[x][y] = FORE_GND ;

if ( flag == ERASE )
icon_image[x][y] = BACK_GND_ICON ;


putpixel ( x + 1, y + 1, icon_image[x][y] ) ;


xgrid = 100 + x * EXP_FACTOR ;
ygrid = y * EXP_FACTOR ;


if ( icon_image[x][y] == 0 )
putpixel ( xgrid, ygrid, BACK_GND_GRID ) ;
else
putpixel ( xgrid, ygrid, icon_image[x][y] ) ;
}
}


save_icon()
{
FILE *fp ;
char fname[30] ;


gotoxy ( 6, 21 ) ;
printf ( "Enter the file name: " ) ;
gets ( fname ) ;


icleartext ( 21 ) ;


if ( ( fp = fopen ( fname, "wb" ) ) == NULL )
{
gotoxy ( 1, 21 ) ;
printf ( "Unable to open file! Press any key..." ) ;
getch() ;

icleartext ( 21 ) ;
return ;
}

fwrite ( icon_image, sizeof ( icon_image ), 1, fp ) ;
fclose ( fp ) ;
return;
}


idrawcursor ( int xgrid, int ygrid, int color )
{
int xx, yy ;

for ( xx = xgrid - 2 ; xx <= xgrid + 2 ; xx++ )
putpixel ( xx, ygrid, color ) ;

for ( yy = ygrid - 2 ; yy <= ygrid + 2 ; yy++ )
putpixel ( xgrid, yy, color ) ;
return;
}
//////////////////////////////////////////////////////////////////////////
////


# include "stdio.h"
# include "process.h"
# include "string.h"
# include "stdlib.h"
# include "ctype.h"
# include "conio.h"
# include "fcntl.h"
//# include "types.h"
//# include "stat.h"
# include "dir.h"
# include "dos.h"

# include "c:paintmp1.c"


char *menu[] = {
"^Paint Application",
"^Icon Creater ",
"^Accessories ",
"A^bout Us ",
"^Exit "
} ;

char *accessories[] = {
"^Indian Flag ",
"^Animation ",
"^Screen Saver 1 ",
"Screen Saver 2 ",
"Screen Saver 3 ",
"^Return "
} ;



char *messages[] = {
" PAINT AND ACCESSORIES ",
" Select using Enter or Hot key ",
"Create a new paint application",
"Create a new Icon",
"Different accessories",
"Information about Developer",
"Exit the application",
"Display Indian Flag",
"Display Animation",
"Display screen saver first",
"Display screen saver second",
"Display screen saver third",
"Return to main menu",
"Display memory size",
"Display love calculator",
"Display screen saver third",
"Display screen saver fourth",
"Return to main menu",
"Remove an existing directory",
"List existing directory contents",
"Display directory tree",
"Display calendar of any month & year",
"Display Ascii values & characters",
"Display equipment list",
"A video game",
"Display base memory size",
"Display base memory size",
"Return to main menu ",
" Press any key to continue... ",
" Insufficient space! Press any key... ",
" Developed By : ",
" Rathi Radheshyam G."
} ;



char far *vid_mem;
int ascii, scan ;

void main()
{

int mm_choice ;


#ifdef MA

vid_mem = ( char far * ) 0xb0000000L ;
setmode ( 7 ) ;

#else

vid_mem = ( char far * ) 0xb8000000L ;
setmode ( 3 ) ;

#endif

showmouseptr();
mainscreen() ;
about();
mainmenu1();

}


mainmenu1()
{
int mm_choice;
while ( 1 )
{

mm_choice = popupmenu ( menu, 5, 4, 29, "FDMX", 2 ) ;


switch ( mm_choice )
{
case 1 :
mainpaint() ;
break ;

case 2 :
iconcreater() ;
break ;

case 3 :
access();
break ;

case 4 :
clear();
about();
break;

case 5 :
size ( 6, 7 ) ;
clrscr() ;
exit ( 1 ) ;

case 27 :
size ( 6, 7 ) ;
clrscr() ;
exit ( 1 ) ;
}
}
}




setmode ( int mode )
{
union REGS i, o ;

i.h.ah = 0 ; /* service no. */
i.h.al = mode ; /* video mode */
int86 ( 16, &i, &o ) ; /* issue interrupt */

return;
}

clear()
{
int r,c;
for(r=18;r<=22;r++)
{
for(c=10;c<=70;c++)
{
writechar(r,c,177,113); //non work scrren setting
}
}
return;
}



mainscreen()
{
/*int i, j ;

drawbox ( 1, 0, 23, 79, 7 ) ;
drawbox ( 3, 0, 21, 79, 7 ) ;

writechar ( 3, 0, 204, 7 ) ;
writechar ( 3, 79, 185, 7 ) ;
writechar ( 21, 0, 204, 7 ) ;
writechar ( 21, 79, 185, 7 ) ;

for ( i = 4 ; i <= 20 ; i++ )
{
for ( j = 1 ; j <= 78 ; j += 2 )
{
writechar ( i, j, 177, 7 ) ;
writechar ( i, j + 1, 177, 7 ) ;
}
}

writestring ( messages[0], 2, 32, 112 ) ;
writestring ( messages[1], 22, 14, 112 ) ;*/


int r,c,er,ec;
//int count=6,sr=2,sc=1,

size ( 32, 0 ) ;

//background color setting
for( r=0;r<=23;r++)
{
for( c=0;c<=79;c+=2)
{
writechar(r,c,' ',7);
writechar(r,c+1,' ',7);
}
}

for(r=0;r<=24;r++)
{
for(c=0;c<=80;c++)
{
writechar(r,c,177,113); //non work scrren setting
}
}

//status bar & title bar setting
for( c=0;c<=79;c++)
{
r=0; writechar(r,c,' ',90); //title bar
// r=1; writechar(r,c,' ',112); //menu bar
//r=23; writechar(r,c,' ',23);
r=24; writechar(r,c,' ',23); //status bar
}

//mainmenu(mmenu,count,sc,sr); //write main menu item
writestring(messages[0],0,28,95+123-128); //write on title bar
writestring(messages[30],24,1,28);
writestring(messages[31],24,16,28);
writestring ( "Project Guide : ", 24, 49, 26 ) ;
writestring ( "Prof. Auti A.G.", 24, 65, 26+128 ) ;

//about();
return;
}


about()
{
int area ;
char *p ;

size ( 32, 0 ) ; /* hide cursor */
//music(3);

/* allocate memory, if unsuccessful terminate execution */
area = ( 17 - 6 + 1 ) * ( 60 - 19 + 1 ) * 2 ;
p = malloc ( area ) ;
if ( p == NULL )
exit(0) ;

/* create dialogue box */
savevideo ( 6, 19, 17, 60, p ) ;
menubox ( 6, 19, 16, 58, 9, 0 ) ;
drawbox ( 6, 19, 16, 58 , 10+128 ) ;

writestring ( "PAINT AND ACCESSORIES ", 7, 29,9 ) ;
writestring ( "Version 1.00", 8, 33,8 ) ;
writestring ( "* Developed By * ", 10, 31, 9 ) ;
writestring ( "RATHI RADHESHYAM GOVARDHANDAS ", 12, 25, 10 ) ;
writestring ( " B.C.S. 3rd Year ", 13, 30, 8 ) ;
writestring ( "R. S. College, Latur ", 14, 29, 8 ) ;
// writestring ( "S. R. T. University, Nanded ", 15, 26, 8 ) ;
writestring ( "Project Guide : Prof. Auti A.G.", 15, 24, 8 ) ;
music(1);
//writestring(messages[28],24,13,26);
//scout("B.C.S. 3rd YEAR",15,32,31);
//scout("RAJARSHI SHAHU COLLEGE,LATUR",17,26,31);
//scout("S.R.T. UNIVERSITY,NANDED",19,28,31);
//writestring ( "Rathi Radheshyam G.", 12, 29, 9 ) ;
//writestring(messages[31],24,59,26);

/* display OK button */
/*menubox ( 14, 36, 15, 43, 32, -1 ) ;
writestring ( "OK", 14, 38, 4 ) ;*/

/* continue till either Esc is hit or OK is selected */
while ( 1 )
{
getkey() ;

if ( ascii == 27 || ascii != 'O' || ascii == 'o' )
// exit(0);
break ;
}

restorevideo ( 6, 19, 17, 60, p ) ;
free ( p ) ;

//size ( 5, 7 ) ; /* show cursor */

return;
}

writechar ( int r, int c, char ch, int attb )
{
char far *v ;

v = vid_mem + r * 160 + c * 2 ; /* calculate address in VDU memory
corresponding to row r and column c */

*v = ch ; /* store ascii value of character */
v++ ;
*v = attb ; /* store attribute of character */

return;
}



writestring ( char *s, int r, int c, int attb )
{
while ( *s != '

Graphics in C Language
We will restrict our discussion on Graphics in C Language to 16 bit C programming and MS DOS environment. In a C Program first of all you need to initialize the graphics drivers on the computer. This is done using the initgraph method provided in graphics.h library. In the next few pages we will discuss graphics.h library in details. Important functions in graphic.h library will be discuees in details and samples programmes will be provided to show the power of C programming language.
Graphics mode Initialization
First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.
void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into
graphics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.
*graphdriver
Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.
*graphmode
Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.
*pathtodriver
Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.
1. If they're not there, initgraph looks in the current directory.
2. If pathtodriver is null, the driver files must be in the current directory.
*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or you'll get unpredictable results. (The exception is graphdriver = DETECT.)
After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to the current graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode.
Normally, initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem), then loading the appropriate .BGI file from disk.As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file.
Here is a sample program that initializes the graphics mode in C Language.
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
/* draw a line */
line(0, 0, getmaxx(), getmaxy());
/* clean up */
getch();
closegraph();
return 0;
}
The graphics programming in c language is discussed in brief to provide an over view to the beginner.
/* Sample program to draw a circle*/
#include<graphics.h>
#include<conio.h>
main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,""); /* initialization of graphic mode */
circle(150,150,100);
getch();
closegraph(); /* Restore orignal screen mode */
}
/* End of program */
Normally the screen which u view in DOS is in the text mode which means it is meant for text. And for graphics u need to initialize graphics mode. And for this to happen u need to include ?graphics.h?.
circle(x coordinate ,y coordinate , radius);
The circle command takes a X coordinate which means Vertical axis and Y coordinate which means Horizontal axis. And the last one is the radius of the circle. closegraph();
With out this function the screen mode will still remain in graphic mode and when u come out, to DOS u will see a different screen, which is not in the text mode.
/*A program to draw a space with stars*/
#include<graphics.h>
main()
{
int gd=DETECT,gm;
int i,x,y;
initgraph(&gd,&gm,"");
line(0,0,640,0);
line(0,0,0,480);
line(639,0,639,480);
line(639,479,0,479);
for(i=0;i<=1000;i++)
{
x=rand()%639;
y=rand()%480;
putpixel(x,y,15);
}
getch();
closegraph();
}
/* End of program */
/*Here a sample program to illustrate how to use BARS which are used for visual statistics */
#include<graphics.h>
main() {
int gd=DETECT,gm,maxx,maxy,x,y,button;
initgraph(&gd,&gm,"");
line(80,150,200,150);
line(80,150,80,50);
settextstyle(1,HORIZ_DIR,1);
outtextxy(100,153,"<-X axis");
settextstyle(1,VERT_DIR,1);
outtextxy(60,50,"<-Y axis");
bar(100,100,120,150);
bar(130,120,150,150);
getch();
closegraph();


What is Operator Overloading
Operator Overloading enables us to make the standard operators, like +, -, * etc, to work with the objects of our own data types. So what we do is, write a function which redefines a particular operator so that it performs a specific operation when it is used with the object of a class.
Operator overloading does not allow to make new operators or change the precedence of the operator. There are some operators which can not be overloaded.
Operator Description
:: The scope resolution operator
:? The conditional operator
sizeof The sizeof operator
. The direct member selection operator
.* The de-reference pointer to class member operator
Example of Operator Overloading
C++ allows you to overload operators. This means, for example we can redefine the > operator so that, when it is used with the object of a class ShoeBox (Discussed Here), it would return true if the first ShoeBox had the greater volume than the second ShoeBox object.
class ShoeBox
public: . . .
bool operator>(ShoeBox& aBox) const;
//rest of the class definition
};
Here operator< id overloaded for ShoeBox.
Here is the code that shows how we can compare two ShoeBox objects.
int(box1 > box2)
cout<<endl<<"ShoeBox1 is greater than ShoeBox2";
And here is the code which actually implements the overloading process.
bool ShoeBox::operator>(const ShoeBox& aBox) const
{
return this -> CalcVolume() > sBox.CalcVolume();
}
There are two things to understand here.
1. We have given the reference parameter to th function to avoid unnecessary copying
2. As the function does not alter any this so we can declare it as const.
Many books show the syntax for declaring overloaded operators, but few offer guidelines for keeping the amount of code you write to a minimum and for avoiding code duplication. The guidelines in this tutorial do not necessarily result in the most efficient code from an execution standpoint, but development efforts are minimized --- efficiency and maintainability from a coding standpoint is emphasized. Of course once you've succeed in implementing overloaded operators you can then concentrate on making things efficient.


What is a Function?
Functions are the building blocks of any programming language.
A Function is a self contained block of code with a specific purpose. It has a name that is used to identify and call it for execution. The function name is global, but it is not necessarily unique in C++. Ivor Hoprton.
Declaration of a Function
The standard form of declaration of a function is
return_type function_name(parameters list)
{
body of the function
}
Structure of a Function
There are two main parts of the function. The function header and the function body.
int sum(int x, int y)
{
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans //return the answer
} Function Header
In the first line of the above code
int sum(int x, int y)
It has three main parts
1. The name of the function i.e. sum
2. The parameters of the function enclosed in paranthesis
3. Return value type i.e. int
Function Body
What ever is written with in { } in the above example is the body of the function.
Function Prototypes
The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like
int sum (int x, int y);
The only difference between the header and the prototype is the semicolon ;, there must the a semicolon at the end of the prototype.
Function: Return Statement
The return statement in a function has two main purposes.
1. It can be used to exit the function at any time during the exection of a function. e.g. it returns the control back to the calling code.
2. It can also be used to return a value.
void ShowData(int m)
{
for(int i=0;i<m;i++)
{
cout << "Value of M is = " << m;
}
}
This function returns the control back to the calling function when the for loop finishes execution.
Mostly function do not use this method toterminate execution. Most of the functions returns a value on specified conditions. Here is an example that will show how to terminate the function upon some condition.
int ShowData(int m)
{
for(int i=0;i<m;i++)
{
cout << "Value of M is = " << m;
if (m == 3) return m;
}
return 0;
}
This function returns the indicator after its execution. We can have a function which returns the calculated valuse.
int sum(int x, int y)
{
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans //return the answer
}


PROTOTYPES
Examine the file named PROTYPE1.CPP for our first look at a prototype and an illustration of how it is used.
// prototype1.cpp
#include <iostream.h>
void do_stuff(int wings, float feet, char eyes);

main()
{
int arm = 2;
float foot = 1000.0;
char lookers = 2;

do_stuff(3, 12.0, 4);
do_stuff(arm, foot, lookers);
}

void do_stuff(int wings, float feet, char eyes)
{
cout << "There are " << wings << " wings." << "\n";
cout << "There are " << feet << " feet." << "\n";
cout << "There are " << (int)eyes << " eyes." << "\n\n";
}

// Result of execution
//
// There are 3 wings.
// There are 12 feet.
// There are 4 eyes.
//
// There are 2 wings.
// There are 1000 feet.
// There are 2 eyes.
The prototyping used in C++ is no different than that used in ANSI-C. Actually, many C programmers take a rather dim view of prototyping and seem reluctant to use it, but with C++ it is considerably more important and is in much heavier use. In fact, prototyping is required to be used in some situations in C++.
A prototype is a limited model of a more complete entity to come later. In this case, the full function is the complete entity to come later and the prototype is illustrated in line 4. The prototype gives a model of the interface to the function that can be used to check the calls to the function for the proper number of parameters and the correct types of parameters. Each call to the function named do_stuff() must have exactly three parameters or the compiler will give an error message. In addition to the correct number of parameters, the types must be compatible or the compiler will issue an error message. Notice that when the compiler is working on lines 12 and 13, the type checking can be done based on the prototype in line 4 even though the function itself is not yet defined. If the prototype is not given, the number of parameters will not be checked, nor will the types of the parameters be checked. Even if you have the wrong number of parameters, you will get an apparently good compile and link, but the program may do some very strange things when it is executed. To write the prototype, simply copy the header from the function to the beginning of the program and append a semicolon to the end as a signal to the compiler that this is not a function but a prototype. The variable names given in the prototype are optional and act merely as comments to the program reader since they are completely ignored by the compiler. You could replace the variable name wings in line 4 with your first name and there would be no difference in compilation. Of course, the next person that had to read your program would be somewhat baffled with your choice of variable names.
In this case, the two function calls to this function, given in lines 12 and 13, are correct so no error will be listed during compilation.
Even though we wish to use the char type for eyes in the function, we wish to use it as a number rather than as a character. The cast to int in line 20 is required to force the printout of the numerical value rather than an ASCII character. The next example program is similar but without the cast to int.

Object Oriented Programming
The data types we have applied so far to our variables were used to identify individual items. To create more advanced and complete objects, C++ allows you to group these identifiers and create a newly defined object.
An object, such as a CD Player, a printer, a car, etc, is built from assembling various parts. In the same way, C++ allows you to group various variables and create a new object called a class.
What is a Class?
A class is an orgnisation of data and functions which operate on them. Data structures are called data members and the functions are called member functions, The combination of data members and member functions constitute a data object or simply an object.
Imagine a company that manufactures shoe boxes hires you to write a program that would help design and identify those shoe boxes. A shoe box is recognized for its dimensions (length, width, height), color, and shoe size that a particular box can contain, etc. The variables that characterize such an object could be:
double Length, Width, Height;
char Color;
float ShoeSize;
A Class Example
class ShoeBox
{
double Length, Width, Height;
char Color[12];
float ShoeSize;
};The items that compose a class are called members of the class.
And the program that defines a shoe box object could be:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Define the characteristics of a shoe box
// The following characteristics are COMPLETELY random
double Length(12.55), Width(6.32), Height(8.74);
string Color("Yellow Stone");
float ShoeSize = 10.50;

// Display the characteristics of the shoe box
cout << "Characteristics of this shoe box";
cout << setiosflags(ios::fixed) << setprecision(2);
cout << "\n\tLength = " << Length << "\n\tWidth = " << Width
<< "\n\tHeight = " << Height << "\n\tVolume = " << Length * Width * Height
<< "\n\tColor = " << Color << "\n\tSize = " << ShoeSize << "\n\n";

return 0;
}
The program would produce:
Characteristics of this shoe box
Length = 12.55
Width = 6.32
Height = 8.74
Volume = 693.22
Color = Yellow Stone
Size = 10.50
Press any key to continue...
Unless dealing with one shoe box, this program would be rudimentary to run for each object. The solution is to create an object called box that groups everything that characterizes the object


Classes and Member Functions
The primary motivation of using classes in a program is to create objects as complete as possible. An object must be able to handle its own business so that the other objects of the program or of another program would only need to know which object can take care of a particular need they have.
A regular variable, as a member of an object, cannot handle assignments; this job is handled by particular functions declared as members of a class. A function as a member of a class is also called a Method. In this book, the words “method” and “function”, when associated with a class, will refer to the same thing: a member function of the class.
Declaring Member Functions
A member function is declared like any of the functions we have used so far; it could or could not return a value.
The shoe box we have been using so far needs a volume that would be used to determine what size can fit in the box. Therefore, we will use a member function that can perform that calculation. Our object, when including methods could be structured as follows:
class ShoeBox
{
public:
double Length;
double Width;
double Height;
string Color;
float ObtainShoeSize();
double CalcVolume();
private:
};
When using functions on a class, the variables are used to hold or store values, called data, of the object, while member functions are used to perform assignments as related to the objects. One way you can control the data held by variables is to hide data from the "external world". To achieve this, you should declare the member variables in the private section. After doing this, use the methods in the public section to help the class interact with the other objects or functions of the program. At this time, our ShoeBox object would look like this:
class ShoeBox
{
public:
float ObtainShoeSize();
double CalcVolume();
string Color;
private:
double Length;
double Width;
double Height;
};
There are at least two techniques you can use to implement a method member.


Creating a Class
To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class declaration ends with a semi-colon. The name of a class follows the rules we have applied so far for variable and function names. To declare a class called ShoeBox, you would type the following:
class ShoeBox;
As a name that represents a group of items, a class has a body that would be used to define the items that compose it. The body of a class starts with an opening curly bracket "{" and ends with a closing one "}". Therefore, another way to create a class is:
class ClassName{};
This could also be created as:
class ClassName {
};
or
class ClassName
{
};
Either of these techniques produces the same effect.
Since a class is built from combining other identifiers, you will list each variable inside of the body of the class. Each item that composes the class is represented as a complete variable declared with a data type and a name. As a variable, each declaration must end with a semi-colon.
Continuing with our shoe box object, you could create it using the class as follows:
class ShoeBox
{
double Length, Width, Height;
char Color[12];
float ShoeSize;
};The items that compose a class are called members of the class.


What is a Pointer
We can say the pointer as a variable which holds the memory address of another variable. If one variable contains the address of another variable, the first variable is said to point to the second.
Declaring a Pointer
If a variable is holding the address of another variable then we can declare it as
var_type *varName;
Here var_type is the valid C++ Language data type and varName is the name of the pointer variable. The type of a variable defines that which variable type a pointer can hold.
There are two types of pointer operators; * and &. the & is a unary operator that returns the memory address of its operand. e.g.
varName = &newVar;
The * operator is the compliment of the & operator. It returns the value of the variable located at the address thta follows. e.g.
varName = *newVar;
Pointer Example
Examine the program named POINTERS.CPP for a simple example of the use of pointers.
// pointers.cpp
#include <iostream.h>

main()
{
int *pt_int;
float *pt_float;
int pig = 7, dog = 27;
float x = 1.2345, y = 32.14;
void *general;

pt_int = &pig;
*pt_int += dog;
cout << "Pig now has the value of " << *pt_int << "\n";
general = pt_int;

pt_float = &x;
y += 5 * (*pt_float);
cout << "y now has the value of " << y << "\n";
general = pt_float;

const char *name1 = "John"; // Value cannot be changed
char *const name2 = "John"; // Pointer cannot be changed
}

// Result of execution
//
// Pig now has the value of 34
// y now has the value of 38.3125
This is a pointer review and if you are comfortable with the use of pointers, you can skip this example program completely. A pointer in either ANSI-C or C++ is declared with an asterisk preceding the variable name. The pointer is then a pointer to a variable of that one specific type and should not be used with variables of other types. Thus pt_int is a pointer to an integer type variable and should not be used with any other type. Of course, an experienced C programmer knows that it is simple to coerce the pointer to be used with some other type by using a cast, but he must assume the responsibility for its correct usage.
In line 12 the pointer named pt_int is assigned the address of the variable named pig and line 13 uses the pointer named pt_int to add the value of dog to the value of pig because the asterisk dereferences the pointer in exactly the same manner as standard C. The address is used to print out the value of the variable pig in line 14 illustrating the use of a pointer with the stream output operator cout. Likewise, the pointer to float named pt_float is assigned the address of x, then used in a trivial calculation in line 18.
If you are not completely comfortable with this trivial program using pointers, you should review the use of pointers in any good C programming book or Coronado Enterprises C tutorial before proceeding on because we will assume that you have a thorough knowledge of pointers throughout the remainder of this tutorial. It is not possible to write a C program of any significant size or complexity without the use of pointers.


• Zakri says - hii...
May 12, 2008 at 22:32Post Reply
class Test {public: int a; int b; Test(int temp1 = 0, int temp2 = 0) { a=temp1 ; b=temp2 ; } int getA() { return a; } int getB() { return b; } virtual ~Test();};int main() { Test obj(5, 10);// Changing a and b int* pInt = (int*)&obj; *(pInt+0) = 100; *(pInt+1) = 200; cout << "a = " << obj.getA() << endl; cout << "b = " << obj.getB() << endl; return 0;}


soalannya kenapa program di atas tidak dapat di jalan kan....harap balas....email..zakrie3@Yahoo.com
• Zakri says - helooo
May 12, 2008 at 22:21Post Reply
kenape kebanyakan program tidak dapat d jalankan..?
• Asadullah ansari says - Detail about Vptr, Virtual table,virtual function
Mar 12, 2008 at 08:39Post Reply
Assumption: machine is 32-bit .
Here I am going to explain How Virtual table, Virtual pointer for Virtual functions are internally working.

First we have understand memory layout.

Example 1: How the class's memory layout

class Test
{
public:
int data1;
int data2;
int fun1();
};

int main()
{
Test obj;
cout << "obj's Size = " << sizeof(obj) << endl;
cout << "obj 's Address = " << &obj << endl;
return 0;
}

Output:

Sobj's Size = 8
obj 's Address = 0012FF7C

Note: Any Plane member function does not take any memory.


Example 2: Memory Layout of Derived class

class Test
{
public:
int a;
int b;
};

class dTest : public Test
{
public:
int c;
};

int main()
{
Test obj1;
cout << "obj1's Size = " << sizeof(obj1) << endl;
cout << "obj1's Address = " << &obj1 << endl;
dTest obj2;
cout << "obj2's Size = "<< sizeof(obj2) << endl;
cout << "obj2's Address = "<< &obj2 << endl;
return 0;
}

OUTPUT:
obj1's Size = 8
obj1's Address = 0012FF78
obj2's Size = 12
obj2's Address = 0012FF6C

Example 3: Memory layout If we have one virtual function.

class Test
{
public:
int data;
virtual void fun1()
{
cout << "Test::fun1" << endl;
}
};

int main()
{
Test obj;
cout << "obj's Size = " << sizeof(obj) << endl;
cout << "obj's Address = " << &obj << endl;
return 0;
}

OUTPUT:

obj's Size = 8
obj's Address = 0012FF7C

Note: Adding one virtual function in a class takes 4 Byte extra.

Example 4: More than one Virtual function

class Test
{
public:
int data;
virtual void fun1() { cout << "Test::fun1" << endl; }
virtual void fun2() { cout << "Test::fun2" << endl; }
virtual void fun3() { cout << "Test::fun3" << endl; }
virtual void fun4() { cout << "Test::fun4" << endl; }
};

int main()
{
Test obj;
cout << "obj's Size = " << sizeof(obj) << endl;
cout << "obj's Address = " << &obj << endl;
return 0;
}

OUTPUT:

obj's Size = 8
obj's Address = 0012FF7C

Note: Adding more virtual functions in a class, no extra size taking i.e. Only one machine size taking(i.e. 4 byte)

Example 5:

class Test
{
public:
int a;
int b;
Test(int temp1 = 0, int temp2 = 0)
{
a=temp1 ;
b=temp2 ;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
virtual ~Test();
};

int main()
{
Test obj(5, 10);

// Changing a and b
int* pInt = (int*)&obj;
*(pInt+0) = 100;
*(pInt+1) = 200;

cout << "a = " << obj.getA() << endl;
cout << "b = " << obj.getB() << endl;
return 0;
}

OUTPUT:
a = 200
b = 10

If we Change the code as then

// Changing a and b
int* pInt = (int*)&obj;
*(pInt+1) = 100; // In place of 0
*(pInt+2) = 200; // In place of 1

OUTPUT:
a = 100
b = 200

Note: Who sits 1st place of Class : Answer is VPTR
VPTR - 1st placed in class and rest sits after it.



Example 6:

class Test
{
virtual void fun1()
{
cout << "Test::fun1" << endl;
}
};

int main()
{
Test obj;
cout << "VPTR's Address " << (int*)(&obj+0) << endl;
cout << "VPTR's Value " << (int*)*(int*)(&obj+0) << endl;
return 0;
}

OUTPUT:

VPTR's Address 0012FF7C
VPTR's Value 0046C060

NOTE: This VPTR's value is a address of Virtual table. Lets see in next Example.

Example 7:

#include <iostream>
using namespace std;

class Test
{
virtual void fun1()
{
cout << "Test::fun1" << endl;
}
};
typedef void (*Fun)(void);

int main()
{
Test obj;
cout << "VPTR's Address " << (int*)(&obj+0) << endl;
cout << " VIRTUAL TABLE 's Address " << (int*)*(int*)(&obj+0) << endl; // Value of VPTR
cout << "Value at first entry of VIRTUAL TABLE " << (int*)*(int*)*(int*)(&obj+0) << endl;

Fun pFun = (Fun)*(int*)*(int*)(&obj+0); // calling Virtual function
pFun();
return 0;
}

OUTPUT:
VPTR's Address 0012FF7C
VIRTUAL TABLE 's Address 0046C0EC
Value at first entry of VIRTUAL TABLE 0040100A
Test: fun1


Example 8:

class Test
{
virtual void fun1() { cout << "Test::fun1" << endl; }
virtual void func1() { cout << "Test::func1" << endl; }
};

int main()
{
Test obj;

cout << "VPTR's Address " << (int*)(&obj+0) << endl;
cout << "VIRTUAL TABLE 's Address"<< (int*)*(int*)(&obj+0) << endl;

// Calling Virtual table functions
cout << "Value at 1st entry of VTable " << (int*)*((int*)*(int*)(&obj+0)+0) << endl;
cout << "Value at 2nd entry of VTable " << (int*)*((int*)*(int*)(&obj+0)+1) << endl;

return 0;
}

OUTPUT:

VPTR's Address 0012FF7C
VIRTUAL TABLE 's Address 0046C0EC
Value at first entry of VIRTUAL TABLE 0040100A
Value at 2nd entry of VIRTUAL TABLE 004012


Example :9

class Test
{
virtual void fun1() { cout << "Test::fun1" << endl; }
virtual void func1() { cout << "Test::func1" << endl; }
};

typedef void(*Fun)(void);

int main()
{
Test obj;
Fun pFun = NULL;

// calling 1st virtual function
pFun = (Fun)*((int*)*(int*)(&obj+0)+0);
pFun();

// calling 2nd virtual function
pFun = (Fun)*((int*)*(int*)(&obj+0)+1);
pFun();

return 0;
}

OUTPUT:

Test::fun1
Test::func1

Example 10: multiple Inheritance

class Base1
{
public:
virtual void fun();
};

class Base2
{
public:
virtual void fun();
};

class Base3
{
public:
virtual void fun();
};

class Derive : public Base1, public Base2, public Base3
{
};

int main()
{
Derive obj;
cout << "Derive's Size = " << sizeof(obj) << endl;
return 0;
}

OUTPUT:

Derive's Size = 12


Example 11: Calling Virtual Functions in case of Multiple Inheritance

class Base1
{
virtual void fun1() { cout << "Base1::fun1()" << endl; }
virtual void func1() { cout << "Base1::func1()" << endl; }
};

class Base2 {
virtual void fun1() { cout << "Base2::fun1()" << endl; }
virtual void func1() { cout << "Base2::func1()" << endl; }
};

class Base3 {
virtual void fun1() { cout << "Base3::fun1()" << endl; }
virtual void func1() { cout << "Base3::func1()" << endl; }
};

class Derive : public Base1, public Base2, public Base3
{
public:
virtual void Fn()
{
cout << "Derive::Fn" << endl;
}
virtual void Fnc()
{
cout << "Derive::Fnc" << endl;
}
};

typedef void(*Fun)(void);

int main()
{
Derive obj;
Fun pFun = NULL;

// calling 1st virtual function of Base1
pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+0);
pFun();

// calling 2nd virtual function of Base1
pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+1);
pFun();

// calling 1st virtual function of Base2
pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+0);
pFun();

// calling 2nd virtual function of Base2
pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+1);
pFun();

// calling 1st virtual function of Base3
pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+0);
pFun();

// calling 2nd virtual function of Base3
pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+1);
pFun();

// calling 1st virtual function of Drive
pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+2);
pFun();

// calling 2nd virtual function of Drive
pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+3);
pFun();

return 0;
}

OUTPUT:

Base1::fun
Base1::func
Base2::fun
Base2::func
Base3::fun
Base3::func
Drive::Fn
Drive::Fnc


Virtual Functions in C++
Once again we are into a completely new topic with terminology which will be new to you. If you are new to object oriented programming, you should follow along in this tutorial very carefully because every attempt has been made to define every detail of this new and somewhat intimidating topic.
One term which must be defined is polymorphism, a rather large word that simply means similar when used in the context of object oriented programming. Objects are polymorphic if they have some similarities but are still somewhat different. We will see how it is used in the context of object oriented programming as we proceed.
We have already studied operator overloading and function overloading in this tutorial, and they are a subtle form of polymorphism since in both cases, a single entity is used to refer to two or more things. The use of virtual functions can be a great aid in programming some kinds of projects as you will see in these two chapters.
So what is a Virtual Function?
A Virtual function is a function whic is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
Declaration of a virtual function
class BaseClass{
public:
virtual void who(void)
{
cout << "Base\n";
}
};
class Derived1 : public BaseClass
{
public:
void who (void)
{
cout << "Derived Class 1 \n";
}
};

class Derived2 : public BaseClass
{
public:
void who (void)
{
cout << "Derived Class 2\n";
}
};

int main(void)
{
BaseClass b;
BaseClass *bp;
Derived1 d1;
Derived2 d2;

bp = &b;
bp ->who(); //Executes the base class who function

bp = &d1;
bp ->who(); //Executes the Derived1 class who function

bp = &d2;
bp ->who(); //Executes the Derived2 class who function
}
//Out put
//Base
//Derived Class 1
//Derived Class 2

Here in this example who(); function is called on the basis of the object. So if the object is of the base class then who(); function called is defined in base class.


What is an Array in C Language?
An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.
An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can't have an array of 10 numbers, of which 5 are ints and 5 are floats.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.
Declaration of an Array
Arrays must be declared before they can be used in the program. Standard array declaration is as
type variable_name[lengthofarray];
Here type specifies the variable type of the element which is going to be stored in the array. In C programmin language we can declare the array of any basic standard type which C language supports. For example
double height[10];
float width[20];
int min[9];
char name[20];
In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C Language treats the name of the array as if it were a pointer to the first element This is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accesed any where from with in the program. So
m=height[0];
variable m will have the value of first item of array height.
The program below will declare an array of five integers and print all the elements of the array.
int myArray [5] = {1,2,3,4,5};
/* To print all the elements of the array
for (int i=0;i<5;i++){
printf("%d", myArray[i]);
}
Initializing Arrays
Initializing of array is very simple in c programming. The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name. Here is an example which declares and initializes an array of five elements of type int. Array can also be initialized after declaration. Look at the following C code which demonstrate the declaration and initialization of an array.
int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;
Performing operations on Arrays
Here is a program that will demonstrate the simple operations of the array.
#include <stdio.h>
void oneWay(void);
void anotherWay(void);
int main(void) {
printf("\noneWay:\n");
oneWay();
printf("\nantherWay:\n");
anotherWay();
}

/*Array initialized with aggregate */
void oneWay(void) {
int vect[10] = {1,2,3,4,5,6,7,8,9,0};
int i;
for (i=0; i<10; i++){
printf("i = %2d vect[i] = %2d\n", i, vect[i]);
}
}

/*Array initialized with loop */
void anotherWay(void) {
int vect[10];
int i;
for (i=0; i<10; i++)
vect[i] = i+1;
for (i=0; i<10; i++)
printf("i = %2d vect[i] = %2d\n", i, vect[i]);
}

/* The output of this program is
oneWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 0

antherWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 10
*/
Here is a more complex program that will demonstrate how to read, write and traverse the integer arrays
#include <stdio.h>
void intSwap(int *x, int *y);
int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
void reverseIntArray(int a[], int n);

int main(void) {
int x[10];
int hmny;

hmny = getIntArray(x, 10, 0);
printf("The array was: \n");
printIntArray(x,hmny);
reverseIntArray(x,hmny);
printf("after reverse it is:\n");
printIntArray(x,hmny);
}

void intSwap(int *x, int *y)
/* It swaps the content of x and y */
{
int temp = *x;
*x = *y;
*y = temp;
}


/* n is the number of elements in the array a.
* These values are printed out, five per line. */
void printIntArray(int a[], int n){
int i;
for (i=0; i<n; ){
printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

/* It reads up to nmax integers and stores then in a; sentinel
* terminates input. */
int getIntArray(int a[], int nmax, int sentinel)
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] : ", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

/* It reverse the order of the first n elements of array */
void reverseIntArray(int a[], int n)
{
int i;
for(i=0;i<n/2;i++){
intSwap(&a[i],&a[n-i-1]);
}
}

Copy one array into another
There is no such statement in C language which can directly copy an array into another array. So we have to copy each item seperately into another array.
#include <stdio.h>
int main()
{
int iMarks[4];
short newMarks[4];
iMarks[0]=78;
iMarks[1]=64;
iMarks[2]=66;
iMarks[3]=74;
for(i=0; i<4; i++)
newMarks[i]=iMarks[i];
for(j=0; j<4; j++)
printf("%d\n", newMarks[j]);
return 0;
}

To summarize, arrays are provides a simple mechanism where more than one elements of same type are to be used. We can maintain, manipulate and store multiple elements of same type in one array variable and access them through index.
Discuss this tutorial here
• Forum: Arrays and Strings (Total 73 Messages)Send New Message
1. First | Prev | Next | Last
• Walle says - Will someone here help me to make a program using array ?please..
Jul 29, 2008 at 23:49Post Reply
write a c++ program that recieves 5 integer from the user and display, sum, average, max and min the integer in a single line.

Thanks,
• Indu says - need of a array pgm
Jul 28, 2008 at 00:29Post Reply
Read a 3 subject marks of 4 students to find total marks of each student using 2D arrays
• Mainak replies - Entering deta into an array at eney position
Sep 17, 2008 at 00:00Post Reply


-
User avatar
mrs poonam
Super Member
Super Member
 
Posts: 34
Joined: Sat Jul 10, 2010 10:53 am
membership: NA

ad
 

Re: c++ programs

Postby praveen » Mon Jul 19, 2010 9:43 pm

oh.. big post.. if you can attach in doc or pdf version of this programs are good to all members.
Regards,
Praveen
AMIE Study

ImageImage
-------------------------------------------------------------------------------------------
Work from Home | AMIE Online Coaching
User avatar
praveen
Site Admin
 
Posts: 989
Joined: Thu Oct 23, 2008 1:42 pm
Location: Mumbai
membership: Senior Technician of The Institution of Engineers (India)- ST

Re: c++ programs

Postby logan99 » Mon Jul 19, 2010 10:43 pm

yep its too hard to read and follow this way , pls upload it as doc file
User avatar
logan99
Super Member
Super Member
 
Posts: 51
Joined: Fri Mar 19, 2010 8:23 pm
membership: Technician of The Institution of Engineers (India)- T

Re: c++ programs

Postby anupinder » Tue Aug 24, 2010 9:57 pm

brother nice idea......
User avatar
anupinder
Super Member
Super Member
 
Posts: 37
Joined: Tue Aug 24, 2010 9:34 pm
membership: Senior Technician of The Institution of Engineers (India)- ST


Return to Section A Syllabus

Who is online

Users browsing this forum: No registered users and 0 guests