43
1 Dart The DART is a fun program which randomly generates an invisible dart and allows you to enter a shot. If you hit the centre you hit the “bull’s eye”! #include<iostream.h> #include<math.h> #include<stdlib.h> #include<stdio.h> #include<conio.h> void main() { for(;;) { clrscr(); int r=(random(5)+2)*2-1; int c=(random(5)+2)*2-1; int a,b; char dart[15][15]; cout<<"\nA NEW DART IS READY!!\n"; cout<<"ENTER A SHOT---->\n"; cout<<"INPUT ROW NO.:"; cin>>a; cout<<"INPUT COLUMN NO.:"; cin>>b; if(a==(r+1)/2 && b==(c+1)/2) { cout<<"BULLS EYE!!\n"; } else if(a>r || b>c) { cout<<"OUT OF DART\n"; } else { cout<<"BAD SHOT\n"; } for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { if(!(j==b-1 && i==a-1)) cout<<"*"; else cout<<" "; } cout<<"\n"; } getch(); } }

C++ Short Example Programs

Embed Size (px)

DESCRIPTION

This contains 20 C++ programs of 12thstandard, which I had submitted to the CISCE.If you are searching for some brainstormingstuffs, with all outputs and variable listing, foryour C++ project then your search ends here.You can also download my free Sudoku Solverand Calendar bundled together as Utility from:http://sharecash.org/download.php?file=106116Check it out...

Citation preview

Page 1: C++ Short Example Programs

1

Dart The DART is a fun program which randomly generates an invisible dart and

allows you to enter a shot. If you hit the centre you hit the “bull’s eye”!

#include<iostream.h>

#include<math.h>

#include<stdlib.h>

#include<stdio.h>

#include<conio.h>

void main()

{

for(;;)

{

clrscr();

int r=(random(5)+2)*2-1;

int c=(random(5)+2)*2-1;

int a,b;

char dart[15][15];

cout<<"\nA NEW DART IS READY!!\n";

cout<<"ENTER A SHOT---->\n";

cout<<"INPUT ROW NO.:";

cin>>a;

cout<<"INPUT COLUMN NO.:";

cin>>b;

if(a==(r+1)/2 && b==(c+1)/2)

{

cout<<"BULLS EYE!!\n";

}

else if(a>r || b>c)

{

cout<<"OUT OF DART\n";

}

else

{

cout<<"BAD SHOT\n";

}

for(int i=0;i<r;i++)

{

for(int j=0;j<c;j++)

{

if(!(j==b-1 && i==a-1))

cout<<"*";

else

cout<<" ";

}

cout<<"\n";

}

getch();

}

}

Page 2: C++ Short Example Programs

2

Algorithm

1. A dart of random dimensions is created (dart[ ][ ]) ranging from 3-11 odd

numbers

2. The user is allowed to input the coordinates of the target point.

3. If the coordinates match the centre of the dart the program prints “bull’s eye” and

other messages for an unsuccessful shot.

4. The dart is finally printed with the missing point where the dart is shot.

Output

A NEW DART IS READY!! ENTER A SHOT ---- > INPUT ROW NO.:3 INPUT COLUMN NO.:4 OUT OF DART *** *** *** A NEW DART IS READY!! ENTER A SHOT ---- > INPUT ROW NO.:4 INPUT COLUMN NO.:5 BULL'S EYE!! ********* ********* ********* ********* **** **** ********* ********* ********* ********* *********

Variable Listing

VARIABLE

TYPE

SCOPE

DESCRIPTION

r int main() stores random numbers from 3-11

c int main() stores random odd numbers from 3-11

a int main() takes row input from user

b int main() takes column input from user

dart int[ ][ ] main() ----------------------------------------

i int main() iterative variable

j int main() 2nd iterative variable

Page 3: C++ Short Example Programs

3

Date The DATE program asks for a date input in the general date format (dd/mm/yyyy). It

then asks for the first weekday of the year and gives the weekday for the entered date

(“A pretty simple program!”).

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<stdio.h>

#include<string.h>

#include<ctype.h>

//--------------------------------------------------------------------------

int date[]={31,0,31,30,31,30,31,31,30,31,30,31};

char

days[][10]={"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};

//==========================================================================

void main()

{

clrscr();

int isLeap(int);

cout<<"Enter today's Date: ";

char* d,temp[10];

cin>>d;

d[strlen(d)]='/'; //[1]

int day,month,year;

//--------------------------------------------------------------------------

strset(temp,'\0'); //[2]

for(int i=0,count=1;i<strlen(d);i++)

{

if(!isdigit(d[i]))

{

if(count==1)

day=atoi(temp);

if(count==2)

month=atoi(temp);

if(count==3)

year=atoi(temp);

count++;

strset(temp,'\0');

}

else

temp[strlen(temp)]=d[i];

}

//--------------------------------------------------------------------------

if(isLeap(year)) //[3]

date[1]=29;

else

date[1]=28;

//--------------------------------------------------------------------------

cout<<"Enter the weekday of 1st January of this year: ";

cin>>d;

//--------------------------------------------------------------------------

int sumd=0; //[4]

Page 4: C++ Short Example Programs

4

for(int j=0;j<month-1;j++)

sumd+=date[j];

sumd+=day;

for(int k=0;k<7;k++)

if(strcmp(strlwr(d),days[k])==0)

sumd+=(k-1);

sumd=sumd%7;

//--------------------------------------------------------------------------

cout<<"Oh I see! Today is "<<days[sumd]<<endl;

getch();

}

//==========================================================================

int isLeap(int year) //[5]

{

if(year%100==0 && year%400==0)

return 1;

else

if(year%4==0)

return 1;

return 0;

}

//==========================================================================

Algorithm

1. Two global arrays store the no of days for each month and the name of each weekday. The user is allowed to enter a date and a slash is added for an easier extraction of the date, month and year.

2. A temporary variable of null string type is created which is used to extract the required fields.

3. The year is checked for leap year and accordingly the number of days for February is set.

4. The day is calculated and the index of the weekday is stored in sumd which is printed out.

5. The leap year function is a function which checks if the passed integer is a leap year or not.

Output

Enter today’s Date: 17/10/2008

Enter the weekday of 1st January of the year: Tuesday

Oh I see! Today is Friday

Page 5: C++ Short Example Programs

5

Variable Listing

VARIABLE

TYPE

SCOPE

DESCRIPTION

date int[ ] global stores no. of days for each month

days char[ ][ ] global stores name of weekdays

d char* main() takes the date input

temp char* main() temporarily stores the date parameters

day int main() stores the day parameter

month int main() stores the month parameter

year int main() stores the year parameter

count int main() provides an indication for the type of parameter

i,j,k int main() iterative variables

sumd int main() the required index of the weekday is stored

year int isLeap() accepts the year passed

Page 6: C++ Short Example Programs

6

Calendar

This is an interesting program which asks for the month and the year from the user and prints the respective calendar. The calculation of the first day of the year needs a complicated derivation which ultimately lands up into a formula which can exactly give the first weekday of any month of any year taking the general leap years in calculation too! By general leap years I mean leap years for every year divisible by 4 except those which are divisible by 100 but not by 400. (I would thus guarantee the efficiency of the program for ±millennium taking 2000 as the base year.) #include<iostream.h>

#include<string.h>

#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

int m,y,count,i=0;

cout<<"Enter Month: ";

cin>>m;

cout<<"Enter Year: ";

cin>>y;

//-------------------------------------------------------------------------------------

//CALCULATION OF THE FIRST DAY OF THE INPUTTED MONTH AND YEAR (fstdm)

//-------------------------------------------------------------------------------------

int ds[]={0,31,59,90,120,151,181,212,243,273,304,334,365};

int x=(732676+(y-1)/100-(y-1)/4-(y-1)/400-y*365);

int fstdy=y<2006?7-x%7:(-x)%7;

int fstdm=(frstdy+(--m>1 && (y%100!=0 && y%4==0 || y%100==0 && y%400)?ds[m]+1:ds[m]))%7;

//-------------------------------------------------------------------------------------

//PRINTING OF THE CALENDAR

//-------------------------------------------------------------------------------------

cout<<"\n<----------CALENDAR--------->\n\n SUN MON TUE WED THU FRI SAT\n";

for(;i<fstdm;i++)

cout<<" ";

for(count=1;i<fstdm+9;i++)

{

cout<<" "<<count++;

if((i+1)%7==0)

cout<<endl;

}

for(;count<=ds[m+1]-ds[m];)

{

cout<<" "<<count++;

if((i+++1)%7==0)

cout<<endl;

}

if(m==1 && (y%100!=0 && y%4==0 || y%100==0 && y%400))

cout<<" 29";

//-------------------------------------------------------------------------------------

getch();

}

Page 7: C++ Short Example Programs

7

Algorithm

1. The program first calculates the first weekday of the year and stores it in frstdy.

2. It then calculates the first weekday of the month using the data of the total number of days in the array ds[ ].

3. The printing of the calendar is then an easy job once the first weekday (frstdm) of the month is known! The spaces are counted and printed, single digit numbers are printed with 2 spaces before and two digit numbers with one space before.

Output

Enter Month: 2

Enter Year: 2008

<----------CALENDAR--------->

SUN MON TUE WED THU FRI SAT

1 2

3 4 5 6 7 8 9

10 11 12 13 14 15 16

17 18 19 20 21 22 23

24 25 26 27 28 29

Enter Month: 12

Enter Year: 2101

<----------CALENDAR--------->

SUN MON TUE WED THU FRI SAT

1 2 3 4 5

6 7 8 9 10 11 12

13 14 15 16 17 18 19

20 21 22 23 24 25 26

27 28 29 30 31

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

m int main() stores the inputted month

y int main() stores the inputted year

ds int[ ] main() stores the sum of days of all the 12 months

x int main() temporarily stores a part of the calculation of frstdy

fstdy int main() stores the first week day of the year

fstdm int main() stores the first weekday of the month

count int main() keeps a count of the elements during calendar printing

i int main() iterative variable

Enter Month: 12

Enter Year: 1990

<----------CALENDAR--------->

SUN MON TUE WED THU FRI SAT

1

2 3 4 5 6 7 8

9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

Enter Month: 12

Enter Year: 2008

<----------CALENDAR--------->

SUN MON TUE WED THU FRI SAT

1 2 3 4 5 6

7 8 9 10 11 12 13

14 15 16 17 18 19 20

21 22 23 24 25 26 27

28 29 30 31

Page 8: C++ Short Example Programs

8

Diamond The program asks for a string and prints the string in a diamond shape as shown

in the output.

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<process.h>

#include<string.h>

void main()

{

while(1)

{

clrscr();

cout<<"GIVE YOUR NAME: ";

char s[100];

gets(s);

if(s[0]=='\0')//if nothing is entered the program exits

{

cout<<"BYE! BYE!!";

exit(0);

}

//the following for loop prints the required pattern

for(int i=0,n=strlen(s)*2-1;i<n;i++)

{

for(int j=0,x=-1;j<n;j++)

//condition for printing the diamond

if(i+j<n+n/2 && i+j>n-2-n/2 && i<=j+n/2 && i>=j-n/2)

cout<<s[j<(n+1)/2?++x:--x];//conditional printing

else

cout<<' ';

cout<<'\n';

}

getch();

}

}

Algorithm

1. The user is prompted for his/her name.

2. The respective diamond is printed by a condition within a nested loop which restricts the printing of characters upto the diamond shape.

3. The condition in the print statement checks for the deviation of characters required from the mean position.

Page 9: C++ Short Example Programs

9

Output GIVE YOUR NAME: humayun

h

huh

humuh

humamuh

humayamuh

humayuyamuh

humayunuyamuh

humayuyamuh

humayamuh

humamuh

humuh

huh

h

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

s char[ ] main() Takes the user name

i int main() Iterative variable for the rows

n int main() Stores length of the string

j int main() Iterative variable for the columns

x int main() Position of cursor with respect to the central axis of the diamond pattern

Page 10: C++ Short Example Programs

10

Pythagorean Triplets

A pythagorean triplet is a set of three numbers in which the sum of the square of the first two numbers is a perfect square whose square root is the third number eg, 3,4,5 (32+42=52). The program Pythagorean Triplets asks for a limit and prints all possible pythagorean triplets upto that limit.

#include<iostream.h>

#include<conio.h>

#include<math.h>

#include<string.h>

#include<stdio.h>

int isPerfectSqr(int n)

{

if(n==(int)pow((int)sqrt(n),2))

return 1;

return 0;

}

void main()

{

int isPerfectSqr(int);

while(1)

{

clrscr();

cout<<"GIVE THE RANGE OF PYTHAGOREAN TRIPLETS: ";

int n;

cin>>n;

for(int i=1,x=1;i<=n;i++)

for(int j=1;j<n;j++)

if(isPerfectSqr(i*i+j*j) && i<j && sqrt(i*i+j*j)<=n)

{

cout<<"PYTHAGOREAN TRIPLETS "<<x++<<": ";

cout<<i<<", "<<j<<", "<<(int)sqrt(i*i+j*j)<<endl;

}

getch();

}

}

Algorithm

1. The program asks for a range and prints pythagorean triplets within that range.

2. It makes a check whether a2+b2=c2 using the function isPerfect(int) to check for perfect squares.

3. It then prints all pythagorean triplets such that a,b,c none does exceed the limit given by the user.

Page 11: C++ Short Example Programs

11

Output

GIVE THE RANGE OF PYTHAGOREAN TRIPLETS: 60

PYTHAGOREAN TRIPLETS 1: 3, 4, 5

PYTHAGOREAN TRIPLETS 2: 5, 12, 13

PYTHAGOREAN TRIPLETS 3: 6, 8, 10

PYTHAGOREAN TRIPLETS 4: 7, 24, 25

PYTHAGOREAN TRIPLETS 5: 8, 15, 17

PYTHAGOREAN TRIPLETS 6: 9, 12, 15

PYTHAGOREAN TRIPLETS 7: 9, 40, 41

PYTHAGOREAN TRIPLETS 8: 10, 24, 26

PYTHAGOREAN TRIPLETS 9: 12, 16, 20

PYTHAGOREAN TRIPLETS 10: 12, 35, 37

PYTHAGOREAN TRIPLETS 11: 14, 48, 50

PYTHAGOREAN TRIPLETS 12: 15, 20, 25

PYTHAGOREAN TRIPLETS 13: 15, 36, 39

PYTHAGOREAN TRIPLETS 14: 16, 30, 34

PYTHAGOREAN TRIPLETS 15: 18, 24, 30

PYTHAGOREAN TRIPLETS 16: 20, 21, 29

PYTHAGOREAN TRIPLETS 17: 20, 48, 52

PYTHAGOREAN TRIPLETS 18: 21, 28, 35

PYTHAGOREAN TRIPLETS 19: 24, 32, 40

PYTHAGOREAN TRIPLETS 20: 24, 45, 51

PYTHAGOREAN TRIPLETS 21: 27, 36, 45

PYTHAGOREAN TRIPLETS 22: 28, 45, 53

PYTHAGOREAN TRIPLETS 23: 30, 40, 50

PYTHAGOREAN TRIPLETS 24: 33, 44, 55

PYTHAGOREAN TRIPLETS 25: 36, 48, 60

PYTHAGOREAN TRIPLETS 26: 40, 42, 58

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

n int main() takes the limit from the user

i int main() iterative variable

x int main() serial number of triplets

j int main() iterative variable

n int isPerfectSqr() variable to be checked for perfect square

Page 12: C++ Short Example Programs

12

Time The program asks for the hour and minute input in a 12 hr format (though it does not matter whether time is entered in 12 hr or 24 hr format!). The time in words is printed out.

#include<iostream.h>

#include<conio.h>

#include<math.h>

void main()

{

start:

clrscr();

int hour,min;

cout<<"BEFORE STARTING PLEASE KEEP IN MIND THAT THIS PROGRAM IS BASED \n";

cout<<"ON 12 HOUR CLOCK TIMINGS. YOUR HOUR ENTRY CAN BE FROM 1-12 ONLY!!\n";

cout<<"Enter Hour: ";

cin>>hour; cout<<"Enter Minutes: ";

cin>>min;

hour=(hour-1)%12+1;

if(hour==0) hour=12;

min=min%60;

//the follwing array stores the numbers from 1-29 in words

char words[][13]={"one","two","three","four","five",

"six","seven","eight","nine","ten",

"eleven","twelve","thirteen","fourteen",

"quarter","sixteen","seventeen","eighteen",

"nineteen","twenty","twenty one","twenty two",

"twenty three","twenty four","twenty five",

"twenty six","twenty seven",

"twenty eight","twenty nine"};

if (min==15)

cout<<"quarter past "<<words[hour-1];

else if(min==45)

cout<<"quarter to "<<words[hour%12];

else if(min==0)

cout<<words[hour-1]<<" o'clock";

else if(min==30)

cout<<"half past "<<words[hour-1];

else if(min<30)

cout<<words[min-1]<<" minutes past "<<words[hour-1];

else

cout<<words[60-min-1]<<" minutes to "<<words[hour%12];

getch();

goto start;

}

Algorithm

1. The user is asked for the hour and minutes input.

2. The words for the minutes and hours are stored in an array.

3. The respective words are printed to display the time in words.

Page 13: C++ Short Example Programs

13

Output BEFORE STARTING PLEASE KEEP IN MIND THAT THIS PROGRAM IS BASED

ON 12 HOUR CLOCK TIMINGS. YOUR HOUR ENTRY CAN BE FROM 1-12 ONLY!!

Enter Hour: 12

Enter Minutes: 32

twenty eighttwenty nine minutes to one

BEFORE STARTING PLEASE KEEP IN MIND THAT THIS PROGRAM IS BASED

ON 12 HOUR CLOCK TIMINGS. YOUR HOUR ENTRY CAN BE FROM 1-12 ONLY!!

Enter Hour: 3

Enter Minutes: 18

eighteen minutes past three

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

hour int main() takes hour input

min int main() takes minute input

words char[ ][ ] main() stores number in words

Page 14: C++ Short Example Programs

14

Reflection The program is a practical application of geometry. This program also includes a short derivation which lands into a formula which calculates the coordinates of the reflected point of a point entered by the user, along a line also entered by the user. #include<iostream.h>

#include<conio.h>

#include<stdlib.h>

void main()

{

while(1)

{

clrscr();

double m,c,x,y,x1,x2;

cout<<"ENTER THE COORDINATES OF YOUR POINT-->\n";

cout<<"X-COORDINATE:";

cin>>x;

cout<<"Y-COORDINATE:";

cin>>y;

cout<<"ENTER THE ATTRIBUTES OF THE LINE-->\n";

prompt:

clrscr();

cout<<"Is your line parallel to Y-axis?(Y/N): ";

char choice=getch();

cout<<"\nOKAY!!\n\n";

if(choice=='Y' || choice=='y')

{

cout<<"ENTER X-INTERCEPT(ie. X=?):";

cin>>c;

x1=2*c-x;

x2=y;

cout<<"THE REFLECTED POINT ALONG THE LINE X="<<c<<" IS("<<x1<<","<<x2<<").";

}

else if(choice=='N' || choice=='n')

{

cout<<"ENTER THE Y-INTERCEPT: ";

cin>>c;

cout<<"ENTER THE SLOPE:";

cin>>m;

x1=(2*m*(y-c)-x*(m*m-1))/(m*m+1);

x2=((2*m*x+c)-y*(m*m-1))/(m*m+1);

cout<<"THE REFLECTED POINT ALONG THE LINE Y="<<m<<"X+"<<c<<" IS ("<<x1<<","<<x2<<")";

}

else

goto prompt;

getch();

clear:

clrscr();

cout<<"continue? (Y/N): ";

choice=getch();

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y');

else

goto clear;

}

}

Page 15: C++ Short Example Programs

15

Algorithm

1. The program asks for the equation of the mirror line taking slope and the Y-intercept as the input if the line is not parallel to Y-axis else it asks for the X-intercept and the coordinates of the required point.

2. If the mirror line is parallel to Y-axis, then the reflected point is (x1,x2) x1=2c-x x2=y where c=X-intercept and (x,y) is the point

3. If the mirror line is not parallel to Y-axis, then the reflected point is (x1,x2) 2m(y-c)-x(m2-1) m2+1 (2mx+c)-y(m2-1) m2+1

Output ENTER THE COORDINATES OF YOUR POINT-->

X-COORDINATE:3

Y-COORDINATE:4

Is your line parallel to Y-axis?(Y/N): y

OKAY!!

ENTER X-INTERCEPT(ie. X=?):5

THE REFLECTED POINT ALONG THE LINE X=5 IS(7,4).

continue? (Y/N): y

ENTER THE COORDINATES OF YOUR POINT-->

X-COORDINATE:2

Y-COORDINATE:7

Is your line parallel to Y-axis?(Y/N): n

OKAY!!

ENTER THE Y-INTERCEPT: 4

ENTER THE SLOPE:-1.5

THE REFLECTED POINT ALONG THE LINE Y=-1.5X+4 IS (-3.53846,-3.30769)

continue? (Y/N): n

x1=

x2= where, m is the slope c=Y-intercept (x,y)=the given point

Page 16: C++ Short Example Programs

16

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

m double main() slope

c double main() intercept

x double main() x-coordinate

y double main() y-coordinate

x1 double main() abscissa of reflected point

x2 double main() ordinate of reflected point

choice char main() accepts the choice for continuation

Page 17: C++ Short Example Programs

17

Least Difference The program asks the user to enter 10 numbers and finds the first two pair of

numbers having the least difference.

#include<iostream.h>

#include<conio.h>

#include<process.h>

#include<math.h>

void main()

{

while (1)

{

clrscr();

int a[10],i;

cout<<"ENTER 10 NUMBERS--->\n";

for(i=0;i<10;i++)

cin>>a[i];

int diff=abs(a[0]-a[1]),large=a[0],small=a[1];

for(i=0;i<9;i++)

for(int j=i+1;j<10;j++)

if(diff>abs(a[i]-a[j]))

{

diff=abs(a[i]-a[j]);

large=a[i]>a[j]?a[i]:a[j];

small=a[i]<a[j]?a[i]:a[j];

}

cout<<"THE FIRST PAIR OF NOS HAVING THE LEAST DIFFERENCE ARE: "<<large<<" & "<<small; getch();

clear:

clrscr();

cout<<"continue?(Y/N):";

char choice;

cin>>choice;

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y');

else

goto clear;

clrscr();

}

}

Algorithm

1. The program asks for 10 numbers.

2. The numbers are compared by their difference and stored and each time a lesser difference is found the two numbers are updated.

3. Finally the two numbers are printed.

Page 18: C++ Short Example Programs

18

Output

ENTER 10 NUMBERS--->

10

34

-32

56

12

-1

456

78

-101

29

THE FIRST PAIR OF NOS HAVING THE LEAST DIFFERENCE ARE: 12 & 10

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

a int[ ] main() integer array to store 10 numbers

i int main() iterative variable

j int main() iterative variable

diff int main() stores the diff between two numbers

large int main() stores the largest of the two numbers

small int main() stores the smallest of the two numbers

choice char main() accepts choice for continuation

Page 19: C++ Short Example Programs

19

Smith Number

A smith number is a number whose sum of digits is equal to the sum of digits all its prime factors eg, 852 (852=17*3*2*2; 8+5+2=15 & 1+7+3+2+2=15).

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<stdio.h>

void main()

{

clrscr();

int isPrime(long);

long sumDig(long);

long n,copy;

cout<<"Enter a Number: ";

cin>>n;

copy=n;

long sumdig=sumDig(n),sumf=0;

for(long i=2;n>1;)

if(n%i==0 && isPrime(i))

{

sumf+=sumDig(i);

n/=i;

}

else

i++;

if(sumf==sumdig)

cout<<copy<<" is a Smith Number!";

else

cout<<copy<<" is not a Smith Number!";

getch();

}

long sumDig(long n)

{

long sumdig=0;

while(n!=0)

{

sumdig+=n%10;

n/=10;

}

return sumdig;

}

int isPrime(long n)

{

if(n<2)

return 0;

for(long i=2;i<=n/2;i++)

if(n%i==0)

return 0;

return 1;

}

Page 20: C++ Short Example Programs

20

Algorithm

1. The program accepts a number from the user and finds out its prime factors.

2. Using the function sumDig(long) it finds out the sum of all the digits of the number and stored in sumdig.

3. Using the same function once again the sum of the digits of all the prime factors is found out and stored in sumf.

4. Sumdig and sumf are compared which if equal then the number is smith else not.

Output

Enter a Number: 852

852 is a Smith Number!

Enter a Number: 4937775

4937775 is a Smith Number!

Enter a Number: 345

345 is not a Smith Number!

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

n long main(),isprime() stores a number as input

sumdig long sumdig(),main() stores sum of digits

sumf long main() stores sum of digits of prime factors

i long all iterative variable

Page 21: C++ Short Example Programs

21

Alphabet The program prints a triangle of the english alphabet not in a general way by rowwise cursor movement but by the movement of the cursor in principle diagonal direction.

#include<iostream.h>

#include<iostream.h>

#include<stdlib.h>

#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

cout<<"enter number of rows:";

int n;

cin>>n;

char a[200][200];//array in which the pattern is created

int alpha=0;

//the following for loop fills in the required spaces

for(int k1=0;k1<n;k1++)

for(int k2=0;k2<n;k2++)

a[k1][k2]=' ';

//the following for loop fills in the characters diagonally

for(int i=0;i<n;i++)

for(int j=0;j<n;j++)

a[i+j][j]=(char)(alpha++%26+65);

//printing of the array--->

for(int p=0;p<n;p++)

{

for(int q=0;q<n;q++)

cout<<a[p][q];

cout<<endl;

}

getch();

}

Algorithm

1. A 2-D array of maximun size 200 is created.

2. The number of rows is taken from the user.

3. The spaces are filled in the array using a conditional loop and then the alphabets by using another conditional loop in the required pattern.

4. The array is finally printed to display the pattern.

Page 22: C++ Short Example Programs

22

Output

enter number of rows:20

A

UB

OVC

IPWD

CJQXE

WDKRYF

QXELSZG

KRYFMTAH

ELSZGNUBI

YFMTAHOVCJ

SZGNUBIPWDK

MTAHOVCJQXEL

GNUBIPWDKRYFM

AHOVCJQXELSZGN

UBIPWDKRYFMTAHO

OVCJQXELSZGNUBIP

IPWDKRYFMTAHOVCJQ

CJQXELSZGNUBIPWDKR

WDKRYFMTAHOVCJQXELS

QXELSZGNUBIPWDKRYFMT

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

n int main( ) stores the number of rows

a char[ ][ ] main( ) empty array to store the alphabet and spaces

alpha int main( ) iterative counter for the letters

k1 int main( ) iterative variable

k2 int main( ) iterative variable

i int main( ) iterative variable

j int main( ) iterative variable

p int main( ) iterative variable

q int main( ) iterative variable

Page 23: C++ Short Example Programs

23

Fraction Simplify

This program accepts the numerator and the denominator from the user, simplifies it and prints it in the simplest fraction form. #include<iostream.h>

#include<conio.h>

#include<process.h>

#include<stdio.h>

void main()

{

while(1)

{

clrscr();

int num,den,dvsr;

cout<<"ENTER NUMERATOR: ";

cin>>num;

cout<<"ENTER DENOMINATOR: ";

cin>>den;

dvsr=num;

for(int dvnd=den,rem=0;dvnd%dvsr!=0;rem=dvnd%dvsr,dvnd=dvsr,dvsr=rem);

int HCF=dvsr;

cout<<num<<"/"<<den<<"="<<num/HCF<<"/"<<den/HCF;

getch();

clear:

clrscr();

cout<<"continue?(Y/N):";

char choice;

choice=getch();

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y');

else

goto clear;

clrscr();

}

}

Algorithm

1. The program asks for the numerator and the denominator and stores them in num and den.

2. It then calculates the HCF(highest common factor) and stores it in the variable HCF.

3. The numerator and the denominator are divided by the HCF.

4. The above process simplifies the fraction and the output is printed as desired.

Page 24: C++ Short Example Programs

24

Output

ENTER NUMERATOR: 45

ENTER DENOMINATOR: 12

45/12=15/4

continue?(Y/N):y

ENTER NUMERATOR: 94

ENTER DENOMINATOR: 47

94/47=2/1

continue?(Y/N):n

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

num int main() Stores the numerator from the user

den int main() Stores the denominator from the user

dvsr int main() Stores the divisor in the course of finding HCF

dvnd int main() Stores the dividend while finding the HCF

rem int main() Stores the remainder while finding the remainder

HCF int main() Finally stores the highest common factor

choice char main() Stores the choice for continuation

Page 25: C++ Short Example Programs

25

Hcf and Lcm

This program finds out the hcf and lcm of any number of values. #include<iostream.h>

#include<conio.h>

#include<process.h>

#include<stdio.h>

void main()

{

int hcfOf(int,int);

int lcmOf(int,int);

while(1)

{

clrscr();

int *num,dvsr,n;

cout<<"HOW MANY NUMBERS: ";

cin>>n;

num=new int[n];

cout<<"ENTER THE NUMBERS: ";

for(int k=0;k<n;)

cin>>num[k++];

//=================================================

//calculation of highest common factor

//-------------------------------------------------

int HCF=num[0];

for(int i=1;i<n;HCF=hcfOf(HCF,num[i++]));

//=================================================

//calculation of lowest common multiple

//-------------------------------------------------

int LCM=num[0];

for(int j=1;j<n;LCM=lcmOf(LCM,num[j++]));

//=================================================

cout<<"LCM="<<LCM<<" HCF="<<HCF;

getch();

//=================================================

//the following code comprehends the users choice

//-------------------------------------------------

clear:

clrscr();

cout<<"continue?(Y/N):";

char choice;

choice=getch();

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y');

else

goto clear;

}

}

int hcfOf(int n1,int n2)

{

int dvsr=n1;

for(int dvnd=n2,rem=0;dvnd%dvsr!=0;rem=dvnd%dvsr,dvnd=dvsr,dvsr=rem);

return dvsr;

}

int lcmOf(int n1,int n2)

{

int hcfOf(int,int);

int HCF=hcfOf(n1,n2);

return n1*n2/HCF;

}

Page 26: C++ Short Example Programs

26

Algorithm

1. The program finds the highest common factor of the given numbers by division method performed between two numbers at a time.

2. The lowest common multiple is found out by the simple formula “lcm(a,b)=a*b/hcf(a,b)” which is applied consecutively with every number.

3. After finding the L.C.M. and H.C.F. the necessary output is printed.

Output

HOW MANY NUMBERS: 4

ENTER THE NUMBERS:

12

78

24

6

LCM=312 HCF=6

continue?(Y/N):n

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

num int* main() Stores the numbers entered by the user

n int main() The number of elements to be entered by the user

k int main() Iterative variable while taking inputs

HCF int main() Stores the highest common factor of two numbers

i int main() Iterative variable while calculating HCF

LCM int main() Stores the lowest common multiple of two numbers

j int main() Iterative variable while calculating LCM

choice char main() Takes the choice for continuation

n1 int hcfOf(), lcmOf() One of the two numbers passed either to get HCF or LCM

n2 int hcfOf(), lcmOf() The other number passed to get HCF or LCM

dvsr int hcfOf() Divisor to find HCF by division method

dvnd int hcfOf() The dividend in division method

rem int hcfOf() The remainder in division method

Page 27: C++ Short Example Programs

27

Integer to Words This program converts an integer into words. The program strictly works with a

long int and does not work with any other datatype.

#include<iostream.h>

#include<conio.h>

void digitConvert(int n)//to convert a two digit number to words

{

char dig[][11]={"","one ","two ","three ","four ","five ","six ","seven ",

"eight ","nine ","ten ","eleven ","twelve ","thirteen ","fourteen ",

"fifteen ","sixteen ","seventeen ","eighteen ","nineteen "};

char tens[][9]={"twenty ","thirty ","forty ","fifty ","sixty ","seventy ","eighty ","ninety "};

if(n<20)

cout<<dig[n];

else

{

cout<<tens[n/10-2];

if(n%10)

cout<<dig[n%10];

}

}

void toWords(long N)//to convert a number into words

{

if(N==0)

cout<<"zero";

if(N/10000000>99)

{

toWords(N/10000000);

cout<<"crore ";

}

else if(N/10000000)

{

digitConvert(N/10000000);

cout<<"crore ";

}

N%=10000000;

if(N/100000)

{

digitConvert(N/100000);

cout<<"lakh ";

}

N%=100000;

if(N/1000)

{

digitConvert(N/1000);

cout<<"thousand ";

}

N%=1000;

if(N/100)

{

digitConvert(N/100);

cout<<"hundred ";

}

if(N%100)

digitConvert(N%100);

}

void main()

{

clrscr();

cout<<"Enter a number: ";

long n;

cin>>n;

toWords(n);

getch();

}

Page 28: C++ Short Example Programs

28

Algorithm

1. The program accepts a number in long int form.

2. The digitConvert() function simply converts a two digit number into its word equivalent and prints it.

3. The toWords() function breaks up the long integer inputted into numerical bifragments converts them into words using the above function. The crore, lakhs, thousand etc... suffixes are printed at the respective places along with the conversions.

Output

Enter a number: 638294567

sixty three crore eighty two lakh ninety four thousand five hundred sixty seven

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

dig char[][] digitConvert() Array to store the word equivalent from 1-19

tens char[][] digitConvert() Array to store word equivalent of 20,30,40,....80,90

n int digitConvert() Accepts the two digit number as parameter

N long toWords() The long integer number passed as parameter

n int main() The long integer used to take input from the user

Page 29: C++ Short Example Programs

29

Spiral This program prints a square matrix with the english alphabets in a clockwise

spiral form. #include<iostream.h>

#include<conio.h>

#include<process.h>

void main()

{

start:

clrscr();

cout<<"HOW MANY ROWS: ";

int n;

cin>>n;

char arr[100][100];

//=====================================================

//the following nested for loop puts the alphabet into

//the array in the desired clockwise spiral form

//-----------------------------------------------------

for(int i=0,j=0,count=0,k=n-1,x;count<n*n;k-=2,i++,j++)

{

if(k==0)

arr[i][j]='A'+(count++)%26;

for(x=0;x++<k;arr[i][j++]='A'+(count++)%26);//left-->right

for(x=0;x++<k;arr[i++][j]='A'+(count++)%26);//top-->bottom

for(x=0;x++<k;arr[i][j--]='A'+(count++)%26);//right-->left

for(x=0;x++<k;arr[i--][j]='A'+(count++)%26);//bottom-->top

}

//=====================================================

//The following code prints the matrix

//-----------------------------------------------------

for(int a=0;a<n;a++)

{

cout<<endl;

for(int b=0;b<n;b++)

cout<<arr[a][b];

}

getch();

//=====================================================

//the following code comprehends the users choice

//-----------------------------------------------------

clear:

clrscr();

cout<<"continue?(Y/N):";

char choice;

choice=getch();

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y')

goto start;

else

goto clear;

}

Page 30: C++ Short Example Programs

30

Algorithm 1. The program uses a very simple logic. The alphabets are filled in a circular way

i.e. from ‘Z’ it jumps back to ‘A’. 2. If the matrix is of n×n order, then for the first filling it inserts the alphabet every

n-1 spaces in the order leftrightbottomtop completing one clockwise loop. 3. The next loops are filled with two spaces less every time. 4. Special care is taken towards exceptions in case of odd matrix.

Output

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

arr char[][] main() Stores the letters entered in the spiral form

n int main() Order of the matrix

i int main() Index of the row

j int main() Index of the column

k int main() Number of spaces to filled in a particular direction

count int main() Keeps a count over the alphabet

x int main() Iteretive variable used for the filling of spaces in a particular direction

a int main() Iterative row index for printing the matrix

b int main() Iterative column index for printing the matrix

choice char main() Takes the choice from the user for continuation

HOW MANY ROWS: 9

ABCDEFGHI

FGHIJKLMJ

EDEFGHINK

DCTUVWJOL

CBSBCXKPM

BARAZYLQN

AZQPONMRO

ZYXWVUTSP

YXWVUTSRQ

continue?(Y/N):n

HOW MANY ROWS: 6

ABCDEF

TUVWXG

SFGHYH

REJIZI

QDCBAJ

PONMLK

continue?(Y/N):y

HOW MANY ROWS: 8

ABCDEFGH

BCDEFGHI

AVWXYZIJ

ZUHIJAJK

YTGLKBKL

XSFEDCLM

WRQPONMN

VUTSRQPO

continue?(Y/N):y

Page 31: C++ Short Example Programs

31

Number of Words

The program calculates the number of words in any kind of sentence...be the words seperated by a blank space or a tab space. #include<iostream.h>

#include<conio.h>

#include<string.h>

#include<stdio.h>

void main()

{

clrscr();

cout<<"Enter a sentence: ";

char* str;

gets(str);

strcat(str," x");

int len=strlen(str);

int i,count;

//====================================================================

//the following for loop helps in calculating

//any spaces in the beginning

//--------------------------------------------------------------------

for(i=0;i<strlen(str) && (str[i]==' ' || str[i]=='\t');i++);

//====================================================================

//the following loop counts the number of words

//--------------------------------------------------------------------

for(;i<len-1;i++)

if((str[i]!=' ' && str[i]!='\t') && (str[i+1]==' ' || str[i+1]=='\t'))

count++;

//--------------------------------------------------------------------

cout<<"Number of words: ";

cout<<count;

getch();

}

Algorithm

1. The program accepts a string and then appends “ x” to it.

2. This is done to equal the number of spaces and words.

3. To ensure that spaces in front, if present, are not taken into count, the first occurence of a non space is checked and counting is started from that index.(We need not bother about the last spaces because we are already appending “ x” to it).

4. The counting is done by checking if a space and an alphanumeral are next to each other or not.

Page 32: C++ Short Example Programs

32

Output

Enter a sentence: I am a good boy

Number of words: 5

Enter a sentence:

Number of words: 0

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

str char* main() The variable containing the inputted sentence

len int main() Stores the length of the string

i int main() iterative variable

count int main() holds the number of words

Page 33: C++ Short Example Programs

33

Piglatin A piglatin is a kind of encrypted sentence in which the first consonants get shifted

to the last with the addition of “ay”. #include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<string.h>

void main()

{

int isConsonant(char);

clrscr();

cout<<"Enter a sentence: ";

char* str;

gets(str);

strcat(str," x");

int len=strlen(str);

int i;

for(i=0;i<len && (str[i]==' ' || str[i]=='\t');i++);

int pos=i;

for(;i<len-1;i++)

{

if((str[i]!=' '&& str[i]!='\t') && (str[i+1]==' ' || str[i+1]=='\t'))

{

char arr[50];

int k;

for(k=0;pos<i+1 && isConsonant(str[pos]);arr[k++]=str[pos++]);

arr[k]='\0';

for(;pos<i+1;pos++)

cout<<str[pos];

cout<<arr<<"ay ";

}

if((str[i]==' '|| str[i]=='\t') && (str[i+1]!=' ' || str[i+1]!='\t'))

pos=i+1;

}

getch();

}

int isConsonant(char c)

{

char vowelupr[]={'A','E','I','O','U'};

char vowellwr[]={'a','e','i','o','u'};

for(int i=0;i<5;i++)

if(c==vowelupr[i] || c==vowellwr[i])

return 0;

return 1;

}

Page 34: C++ Short Example Programs

34

Algorithm

1. The sentence is entered and the spaces are checked for identifying each word.

2. Each word is scanned for the first occurence of a vowel, which if found, the remeining part of it is printed.

3. The letters before the vowel are printed behind the word with a suffix of “ay”.

Output

Enter a sentence: Humayun Kabir likes to play with Strings

umayunHay abirKay ikeslay otay ayplay ithway ingsStray

Enter a sentence: computer science

omputercay iencescay

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

str char* main() Takes the user string input

len int main() Stores the length of the string

i int main() iterative variable

arr char[] main() temporary array to store the consonants preceeding the vowels

k int main() iterative variable

pos int main() index of the begenning of every word

vowelupr char[] isConsonant Stores uppercase vowels

vowellwr char[] isConsonant Stores lowercase vowels

Page 35: C++ Short Example Programs

35

Matrix Multiply This program accepts two matrices from the user, multiplies them and prints the

resultant matrix. #include<iostream.h>

#include<conio.h>

#include<math.h>

int r,rc,c;

int A[50][50], B[50][50], C[50][50];

void main()

{

int i,j,k;

clrscr();

cout<<"\n=============================================\n";

cout<<"Enter the dimensions of the first Matrix---->\n";

cout<<"Enter number of rows: ";

cin>>r;

cout<<"Enter number of columns: ";

cin>>rc;

cout<<"\n=============================================\n";

cout<<"Enter the dimensions of the second Matrix---->\n";

cout<<"Enter number of rows: "<<rc;

cout<<"\nEnter number of columns: ";

cin>>c;

//======================================================

//Entering of elements in the matrix

//======================================================

clrscr();

cout<<"\n::Enter the elements of MATRIX A::\n\n";

for(i=0;i<r;i++)

{

cout<<"ROW "<<i+1<<"--->\n";

for(j=0;j<rc;j++)

{

cout<<" Element in column "<<j+1<<": ";

cin>>A[i][j];

}

}

clrscr();

cout<<"\n::Enter the elements of MATRIX B::\n\n";

for(i=0;i<rc;i++)

{

cout<<"ROW "<<i+1<<"--->\n";

for(j=0;j<c;j++)

{

cout<<" Element in column "<<j+1<<": ";

cin>>B[i][j];

}

}

//======================================================

//multiplication of the matrices

//======================================================

for(i=0;i<r;i++)

for(k=0;k<c;k++)

for(j=0;j<rc;C[i][k]+=A[i][j]*B[j++][k]);

//======================================================

//the following code prints the matrices

//======================================================

void print();

clrscr();

cout<<"\nThe solution matrix AxB is as follows--->\n\n";

print();

getch();

}

Page 36: C++ Short Example Programs

36

void print()

{

int size(int);

int i,j,great=size(C[0][0]);

for(i=0;i<r;i++)

for(j=0;j<c;j++)

if(great<size(C[i][j]))

great=size(C[i][j]);

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{

cout<<C[i][j];

for(int x=0;x<=great-size(C[i][j]);x++)

cout<<" ";

}

cout<<endl;

}

}

int size(int n)

{

int count=0;

for(int temp=n;abs(temp)>0;temp/=10,count++);

return (n>0?count:count+1);

}

Algorithm

1. The matrices are accepted from the user defined by the user himself.

2. Multiplication is done mathemetically.

3. The printing of the resultant is then done by adjusting the width according to the widest sized number.

Output

=============================================

Enter the dimensions of the first Matrix---->

Enter number of rows: 2

Enter number of columns: 2

=============================================

Enter the dimensions of the second Matrix---->

Enter number of rows: 2

Enter number of columns: 2

::Enter the elements of MATRIX A::

ROW 1--->

Element in column 1: 1

Element in column 2: 0

ROW 2--->

Element in column 1: 0

Element in column 2: 1

Page 37: C++ Short Example Programs

37

::Enter the elements of MATRIX B::

ROW 1--->

Element in column 1: 12

Element in column 2: 67

ROW 2--->

Element in column 1: 5

Element in column 2: -123

The solution matrix AxB is as follows--->

12 67

5 -123

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

r int global Number of rows in matrix A

rc int global Column & row of matrix A & B respectively

c int global Column of matrix B

A,B,C int[][] global The three matrices

i,j,k int main(),print() Iterative variables

great int print() The number in matrix C with greatest width

count int print() Tracks the number of spaces while printing C

x int print() Iterative variable for printing the spaces

n int size() parameter passed to size()

temp int size() temporary variable to hold the value of n

Page 38: C++ Short Example Programs

38

Saddle Point A saddle point is an element in amatrix which is the greatest in its column and

smallest i its row. A matrix may have no saddle point. But in case there exists a saddle point, it will be one and unique. #include<iostream.h>

#include<conio.h>

#include<process.h>

int A[50][50];

int r=0,c=0;

void main()

{

int maxInColumn(int,int);

int minInRow(int,int);

clrscr();

int i,j;

cout<<"Enter no. of rows: ";

cin>>r;

cout<<"Enter no. of columns: ";

cin>>c;

cout<<"==================================\n";

cout<<"ENTER THE ELEMENTS INTO THE MATRIX\n";

cout<<"==================================\n";

for(i=0;i<r;i++)

{

cout<<"ROW "<<i+1<<"--->\n";

for(j=0;j<c;j++)

{

cout<<" Element in column "<<j+1<<": ";

cin>>A[i][j];

}

}

//---------------------------------------------

//checking for saddle point

//---------------------------------------------

for(i=0;i<r;i++)

for(j=0;j<c;j++)

if(maxInColumn(i,j) && minInRow(i,j))

{

cout<<endl<<A[i][j]<<" is the saddle point!!";

getch();

exit(0);

}

cout<<"\nSorry!! There exists no saddle point!";

getch();

}

int maxInColumn(int i,int j)

{

for(int k=0;k<r;k++)

if(A[i][j]<A[k][j])

return 0;

return 1;

}

int minInRow(int i,int j)

{

for(int k=0;k<c;k++)

if(A[i][j]>A[i][k])

return 0;

return 1;

}

Page 39: C++ Short Example Programs

39

Algorithm

1. The matrix is accepted from the user.

2. A nested loop scans through each element.

3. At each scanning it is checked if the element is maximum in its column and minimum in its row or not.

4. If an element matching the criteria is found it is displayed else there is no saddle point.

Output

Enter no. of rows: 3

Enter no. of columns: 3

==================================

ENTER THE ELEMENTS INTO THE MATRIX

==================================

ROW 1--->

Element in column 1: 4

Element in column 2: 16

Element in column 3: 14

ROW 2--->

Element in column 1: 4

Element in column 2: 7

Element in column 3: 9

ROW 3--->

Element in column 1: 1

Element in column 2: 4

Element in column 3: 23

4 is the saddle point!!

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

A int[][] global The array to take the user’s matrix

r,c int main() row and column size

i,j int main() iterative variables

k int main() iterative variable while testing maximum or minimum

Page 40: C++ Short Example Programs

40

Ace Card The progam prints the pattern of an ace card of diamond.

#include<iostream.h>

#include<conio.h>

#include<process.h>

void main()

{

int n,i,j;

start:

clrscr();

cout<<"Enter an odd number: ";

cin>>n;

if(n%2==0)

{

cout<<"Please Enter only an odd number!\n";

goto clear;

}

//-------------------------------------------------------

//printing of the card pattern

//-------------------------------------------------------

cout<<"\n\n\t";

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

if(i+j<=n/2 || i<=j-n/2 || i+j>n-2+n/2 || i>=j+n/2)

cout<<"*";

else

cout<<" ";

cout<<"\n\t";

}

//-------------------------------------------------------

getch();

clrscr();

clear:

cout<<"continue?(Y/N):";

char choice;

choice=getch();

if(choice=='N' || choice=='n')

exit(0);

else if(choice=='Y' || choice=='y')

goto start;

else

{

clrscr();

goto clear;

}

}

Page 41: C++ Short Example Programs

41

Algorithm

1. The width of the card is taken.(It is to be noted that the width must be odd).

2. A nested for loop implements the moving cursor within a square region on the console.

3. A condition decides the printing of stars or spaces in the square region.

Output

Enter an odd number: 8 Please Enter only an odd number! continue?(Y/N):y Enter an odd number: 13 ************* ****** ****** ***** ***** **** **** *** *** ** ** * * ** ** *** *** **** **** ***** ***** ****** ****** ************* continue?(Y/N):n

Variable Listing

VARIABLE TYPE SCOPE DESCRIPTION

n int main() Size of the card

i int main() iterative row variavle

j int main() iterative column variable

choice char main() takes the choice from the user

Page 42: C++ Short Example Programs

42

Date Calculator The program asks for any two dates in british order and calculates the difference between them in days. #include<iostream.h>

#include<conio.h>

#include<string.h>

#include<stdio.h>

#include<stdlib.h>

#include<ctype.h>

int day[]={0,31,59,90,120,151,181,212,243,273,304,334};

class Date

{

public:

int dd,mm,yy;

void input()

{

char *d,temp[10];

gets(d);

//------------------------------------------------

//Extraction of the date elements from string form

//------------------------------------------------

strcat(d,"/");

strset(temp,'\0');

for(int i=0,count=1;i<strlen(d);i++)

{

if(!isdigit(d[i]))

{

if(count==1)

dd=atoi(temp);

if(count==2)

mm=atoi(temp);

if(count==3)

yy=atoi(temp);

count++;

strset(temp,'\0');

}

else

temp[strlen(temp)]=d[i];

}

}

int daysNum()

{

int days=dd+day[mm-1];

return mm>2&&(yy%100!=0 && yy%4==0 || yy%100==0 && yy%400==0)?days+1:days;

}

};

Page 43: C++ Short Example Programs

43

void main()

{

int daysYear(int,int);

clrscr();

Date d1,d2;

cout<<"Enter a date: ";

d1.input();

cout<<"Enter another date: ";

d2.input();

if(d1.yy*366+d1.mm*31+d1.dd>d2.yy*366+d2.mm*31+d2.dd)

{

Date temp=d1;

d1=d2;

d2=temp;

}

int diff=daysYear(d1.yy,d2.yy)+d2.daysNum()-d1.daysNum();

getch();

exit(0);

}

int daysYear(int y1,int y2)

{

int leap=(y2-1)/4-(y1-1)/4+(y2-1)/400-(y1-1)/400-(y2-1)/100+(y1-1)/100;

return (y2-y1)*365+leap;

}

Algorithm

1. A class Date is defined which has a function input() to accept the date given by the user and a function daysNum() to calculate the number of days of dn1, dn2 of the two dates from1st January.

2. Outside the class a function daysYear() calculates the number of days dny between two years.

3. The difference of two dates comes from dny+dn2-dn1.

Output

Enter a date: 1/1/2008

Enter another date: 3/5/2010

Difference between the dates is 853 days

Variable Listing

variable type scope description

day int[] global Stores number of days of every month from 1st Jan dd,mm,yy int Date day, month, and year d char* Date;input() string in which the date is taken temp char[] Date;input() temporary string count int Date;input() used to track the slashes in date input days int Date;daysNum() total number of days of a date fom the 1st Jan d1, d2 Date main() Date variable inputs temp Date main() Temporary Date variable for swapping

leap int daysYear() Stores the number of leap years