You are on page 1of 43

simple test for primality, it uses a "division test" each number is tested for primarily by

using the previous stored prime numbers as divisors. the test is repeated till one of the
following situations occurs: a factor was found, so the number is composite. The current
divisor is bigger than the square root of the number to be tested, so this number is prime.

#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cassert>
using std::fstream;
using std::vector;

vector<int> prime_number_list;
unsigned int list_size = 0;

bool isPrime(int nNum);

int main()
{
int thisNumber;
fstream fout("prime numbers.txt", std::ios::out);
if(fout.fail())
{
std::cerr << "Error while opening \"prime numbers.txt\"" << std::endl;
assert(fout.good());
}
// generating the first 10000 prime numbers and saving them
// as a table into a file
fout << "Prime Number Table (first 10000 prime numbers)\n\n";
for(int i = 2; list_size < 10000; ++i)
{
thisNumber = i;
list_size = prime_number_list.size();
if(isPrime(thisNumber))
{
prime_number_list.push_back(thisNumber);
fout.width(10);
fout << thisNumber;
if((list_size + 1) % 10 == 0)
{
fout << std::endl;
}
}
}
fout.flush();
fout.close();
return 0;
}

bool isPrime(int nNum)


{
int maxFactor = sqrt(nNum), thisFactor;
bool bRetVal = true;
for(int i = 0; i < list_size; ++i)
{
thisFactor = prime_number_list[i];
if(thisFactor > maxFactor)
{
break;
}
if(nNum % thisFactor == 0)
{
bRetVal = false;
break;
}
}
return bRetVal;
}
To get the binary code one must take the decimal number in question, take it and
divide it by two repeatedly, save the remainder (which will become the binary number),
save the whole number, divide by two, and repeat the whole process until 0 is reached.
This if-else statement serves this functionality, by getting the remainder of the ascii
code, storing it in the array and then dividing the int ascii by two
#include <iostream>
using namespace std;
#include <cstring>
#include <cstdlib>

char *entry, letter, choice[2];


int ascii, len, binary[8], total;
void prog();

int main()
{
prog();
return 0;
}

void prog()
{
entry = new char[501];
/* entry should be dynamic, otherwise a new
string entry of 501 chars would be created
each time function is called!
Talk about memory hog! */
cout<<"Enter string to convert (up to 500 chars): ";
cin.getline(entry, 500);
len = strlen(entry); /* get the number of characters in entry. */
/* this loop is executed for each letter in the string. */
for(int i = 0; i<len; i++)
{
total = 0;
letter = entry[i]; /* store the first letter */
ascii = letter; /* put that letter into an int, so we can
see its ASCII number */
while(ascii>0) /* This while loop converts the ASCII # into binary,
stores it backwards into the binary array. */
{

if((ascii%2)==0)
{
binary[total] = 0;
ascii = ascii/2;
total++; /* increasing by one each time will yeild the
number of numbers in the array. */
}
else
{
binary[total] = 1;
ascii = ascii/2;
total++;
}
}
while(total>=0)
{
cout<<binary[total];
total--;
}
}
delete[] entry; /* free up the memory used by entry */
cout<<endl<<"Do again(1 = yes, 2= no)?: ";
cin.getline(choice,3);
if(choice[0] == '1')
prog(); /* program is recursive, it calls itself. It's kinda
like a function loop of sorts. */
else
exit(0); /* quits the program */
}
This program allows the user to enter to fraction and then. The program will print the
fraction added together and reduced
#include<iostream.h>

void ReadFraction(int &Num, int &Denom, int &Num2, int &Denom2)


/* This function will allow the user to enter two fraction. */
{
cout << "Enter the numerator for the first fraction: ";
cin >> Num;
cout << "Enter the denominator for the first fraction: ";
cin >> Denom;
cout << endl;
cout << "Enter the numerator for the second fraction: ";
cin >> Num2;
cout << "Enter the denominator for the second fraction: ";
cin >> Denom2;
cout << endl;

void Reduce(int &Num, int &Denom, int &Num2, int &Denom2)


/* This function is called after ReadFraction(). This function will
reduce the two fractions.
Pre: Two Fractions
Post: Two reduced fractions */
{
int a, b, c, d, i, j = 0;

a = Denom;
b = Num;
c = Denom2;
d = Num2;

for (i = a * b; i > 1; i--)


{
if ((a % i == 0) && (b % i == 0))
{
a /= i;
b /= i;
}
}

for (j = 50; j > 1; j--)


{
if ((c % j == 0) && (d % j == 0))
{
c /= j;
d /= j;
}
}

Denom = a;
Num = b;
Denom2 = c;
Num2 = d;

void Reduce(int &Num, int &Denom)


/* This function is called from AddFraction(). The fraction added in
AddFraction() is reduced here.
Pre: One fraction added from two
Post: A reduced fraction */
{
int a = 0;
int b = 0;
int i = 0;

a = Denom;
b = Num;

for (i = 50; i > 1; i--)


{
if ((a % i == 0) && (b % i == 0))
{
a /= i;
b /= i;
}
}

Denom = a;
Num = b;
}

void AddFraction(int &Num, int &Denom, int &Num2, int &Denom2)


/* This function is called after Reduce. This function adds the two
fractions Reduce() reduced
Pre: Two Fractions
Post: One reduced fraction */
{
if (Denom != Denom2)
{

Num = Num * Denom2;


Num2 = Num2 * Denom;
Denom = Denom * Denom2;
Denom2 = Denom2 * Denom;
Num = Num + Num2;
}
else
{
Num = Num + Num2;
}

Reduce(Num, Denom);
}

void DisplayFraction(int &Num, int &Denom)


/* This function displays the reduced and added fraction. This
function is called after AddFraction()
Post: Prints fraction */
{
cout << "The reduced and added fraction is " << Num << "/" << Denom << endl;
}

int main()
{
char an;

do
{
int Num, Denom, Num2, Denom2 = 0;

ReadFraction(Num, Denom,Num2,Denom2);
Reduce(Num, Denom, Num2, Denom2);
AddFraction(Num, Denom, Num2, Denom2);
DisplayFraction(Num, Denom);
cout << endl;

cout <<"Would you like to do another fraction? ";


cin >> an;
cout << endl;
} while ((an == 'y') || (an == 'Y'));

return(0);
}
This code show how to declare and use an array of an object

How many sample labels do you want? 2


Enter the dimensions of the label
Height: 3.25
Width: 3.25
Enter the dimensions of the label
Height: 2.15
Width: 4.55

Here are the characteristics of your labels


Label No. 0
Height = 3.25
Width = 3.25
Perimeter = 12.5625
Area = 10.5625

Label No. 1
Height = 2.15
Width = 4.55
Perimeter = 11.7825
Area = 9.7825
#include <iostream.h>

struct Paper
{
public:
void GetDimensions();
void Properties();
private:
double Perimeter() const;
double Area() const;
double Height;
double Width;
};

void Paper::GetDimensions()
{
cout << "Enter the dimensions of the label\n";
cout << "Height: ";
cin >> Height;
cout << "Width: ";
cin >> Width;
}

void Paper::Properties()
{
cout << "\n\tHeight = " << Height;
cout << "\n\tWidth = " << Width;
cout << "\n\tPerimeter = " << Perimeter();
cout << "\n\tArea = " << Area();
cout << "\n\n";
}

double Paper::Perimeter() const


{
return 2 + (Height * Width);
}

double Paper::Area() const


{
return Height * Width;
}

void main()
{
int Samples;
Paper Label[100];

cout << "How many sample labels do you want? ";


cin >> Samples;

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


Label[i].GetDimensions();

cout << "\n\nHere are the characteristics of your labels\n";


for(int j = 0; j < Samples; ++j)
{
cout << "Label No. " << j;
Label[j].Properties();
}
}
This illustrates the technique used to pass arguments by value to a function.
#include <iostream>
#include <string>
using namespace std;

string GetName()
{
string FirstName, LastName, FN;

cout << "Employee's First Name: ";


cin >> FirstName;
cout << "Employee's Last Name: ";
cin >> LastName;

FN = FirstName + " " + LastName;


return FN;
}

int main()
{
string FullName;
double Hours;
double GetHours(string FullName);

FullName = GetName();
Hours = GetHours(FullName);

cout << "\nEmployee's Name: " << FullName;


cout << "\nWeekly Hours: " << Hours << " hours\n\n";

return 0;
}

double GetHours(string FullName)


{
double Mon, Tue, Wed, Thu, Fri, TotalHours;

cout << endl << FullName << "'s Weekly Hours\n";


cout << "Monday: ";
cin >> Mon;
cout << "Tuesday: ";
cin >> Tue;
cout << "Wednesday: ";
cin >> Wed;
cout << "Thursday: ";
cin >> Thu;
cout << "Friday: ";
cin >> Fri;
TotalHours = Mon + Tue + Wed + Thu + Fri;
return TotalHours;

}
The computer generates a random number between 1 and MAX_RANGE. The user must
guess the number. Each time the user
makes an attempt the computer tells if the number is greater or less than.
#include <iostream.h>
#include <stdlib.h>
#include <time.h>

// Define the greatest possible value:


#define MAX_RANGE 100

main ()
{
int counter=0;
long value,input;

srand ( time (NULL) ); // Initialize random generator


value = rand()%MAX_RANGE+1; // Get random between 1 and MAX_RANGE

cout << "\nInsert a value between 1 and " << MAX_RANGE << " : ";

do {

cin >> input; // Get user input


counter++; // increase attempts counter

if (value>input) // is value grater than the input?


cout << "Value is greater than " << input << ". Try again : ";

else if (value<input) // if not, is it less?


cout << "Value is less than " << input << ". Try again : ";

else { // else it is the correct number!


cout << "That's right! Value was " << input;
cout << "\nYou have needed " << counter <<" attempts.";
}

} while (value!=input);
return 0;
}
The program sorts a series of numbers. The sorting method used is to
repetitively swap list items, the higher ones to the end, the lowers to
the beginning until the list is sorted.
#include <iostream.h>

void SwapMembers (int items[], int index1, int index2)


{
int temp;
temp=items[index1];
items[index1]=items[index2];
items[index2]=temp;
}

main ()
{
int n,m;
int numbers [] = {102,21,83,42,11,10,9,3,20,27,15,92,2};

// now a trick to get the number of items in an ARRAY:


// divide the size of the array by the size of one of its members:
const int size = sizeof(numbers) / sizeof(numbers[0]);

// n: specifies the location in the array that has to be adequately set,


// starting from the end (the greater)
// m: each iteration of m stores in position n the greater number found
// form position 0 to position n.
for (n=size-1; n>0; n--)
for (m=0; m<n; m++)
if ( numbers[m] > numbers[m+1] )
SwapMembers (numbers, m, m+1 );

// Output the sequence


for (n=0;n<size;n++)
cout << numbers[n] << ", ";

return 0;
}
The user has to discover all the letters in a secret keyword.
Each letter said that is in the keyword is shown in its rightful location.
He/She has the opportunity to fail up to FAILS_ALLOWED times.
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define N_KEYS 12
#define KEY_MAX_WIDTH 20
#define FAILS_ALLOWED 7

// Possible keywords. You may inser new ones if you increase N_KEYS.
char possiblekeys [N_KEYS][KEY_MAX_WIDTH] = {
"mushroom", "pineapple", "neighborhood", "citizen",
"programming", "darkness", "fundamental", "encyclopedia",
"businessman", "restaurant", "observatory", "civilization"
};

// This will store the key


char key [KEY_MAX_WIDTH];

// This will store the string shown on screen with letters already discovered.
char outstring [KEY_MAX_WIDTH];

int CheckLetter (char letter);

main ()
{
char input;
int valid;
int fails = FAILS_ALLOWED;
unsigned int discovered = 0;
unsigned int n;

// Select a key.
srand ( time (NULL) ); // Initialize random number generator
int value = rand()%N_KEYS; // Get random between 0 and NKEYS-1
strcpy (key,possiblekeys[value]); // Copy key

// Set outstring to '-' characters plus terminating null-character


for (n=0; n<strlen(key); n++) outstring[n]='-';
outstring[n]='\0';

do {
// Prompt user
cout << "\nDiscover the secret key: " << outstring << "\n";
cout << "Enter a letter (You may fail " << fails << " times): ";
cin >> input; cin.ignore (100,'\n');

// check if letter is valid


valid = CheckLetter (input);

// it it is valid, increase dicovered letters counter.


// if not, decrease allowed fails
if (valid!=0) discovered+=valid;
else fails--;

} while (discovered < strlen(key) && fails>0);


// The loop ends if key is discovered or fails are exhausted.

// Display CORRECT! only if key was discovered.


if (discoverd == strlen(key)) cout << "CORRECT! ";

cout "Key was '" << key <<"'.\n";


return 0;
}

// Function that checks if letter is in key.


// returns the number of times the letter was found in key
int CheckLetter (char letter)
{
unsigned int n;
int found=0;
for (n=0; n<strlen(key); n++)
if (key[n]==letter && outstring[n]=='-')
{
found++;
outstring[n]=key[n];
}
return found;
}
Integer Test

we need a way to test the user input to know if it is an integer, to see if the input contain
the numeric values from 0 to 9 if so it is said that the input is a number. Here you will
fine a more precise way to test the user input for knowing if it is an integer
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// This is the function that makes the integer test


bool IsInteger( char *number )
{
int len = strlen( number );
bool isnumber = true;
int i = 0;

if( len == 0 || len > 9 ) // if the user did not enter an input
{ // or if the input is too big to be
return false; // a "long" value.
}

while( i < len && isnumber ) // scanning the the input


{
if( isdigit( number[i] ) == 0 ) // check if there is a none digit character in the input
{
if( number[i] == '+' || number[i] == '-' ) // if so we verify if it is "+" or "-"
{
if( i + 1 > len - 1 || i - 1 >= 0 ) // check the position of "+" or "-"
{ // this signs could only be infront of
isnumber = false; // the number,no where else.
}
}
if( number[i] != '+' && number[i] != '-' ) // if it's not "+" or "-" than
{ // the expression is not a number
isnumber = false;
}
}
i++;
}

return isnumber;
}

void main()
{
char number[20]; // buffer for storing number

printf("Enter a number: "); // geting a number from the user


gets(number);

if( IsInteger( number ) == false ) // testing the input number


{
printf("This is not an integer.\nOr maybe this expression is too big "
"to be tested.\n");
}
else
{
printf("Thanks for entering an integer !\n");
}
program proceed to do this is to first record the time delays between each keyboard hit,
those time delays are saved into and array and later, they are saved into a file. Once the
time delays are saved the program can use them for writing any given text.
#include "graphics.h"
#include <string>
#include <ctime>
#include <vector>
#include <conio.h>
using std::string;
using std::vector;

#define WAIT(x) sleep((double)(x));


#define SPEED 2.0f
// buffer for saving the string entered by the user
string sBuffer = "";
unsigned int numOfLines = 0;
//===========================
// generates a random number
//===========================
int Random( const int val ) {
srand( ( unsigned )time( NULL ) );
if( val == 0 ) return 0;
else {
return rand() % val;
}
}

//====================
// chronometing time
//====================
double countTime(void)
{
LARGE_INTEGER liFreq;
LARGE_INTEGER liStart;
LARGE_INTEGER liStop;

QueryPerformanceCountes(&liStart);-
QueryPerformanceFrequency(&liFreq);

while(!kbhit())
{
}

QueryPerformanceCounter(&liStop);
return ((double)(liStop.QuadPart - liStart.QuadPart)/liFreq.QuadPart);
}

//==============================================
// pause for a specific number of milliseconds
//==============================================
void sleep( double goal )
{
LARGE_INTEGER liFreq;
LARGE_INTEGER liStart;
LARGE_INTEGER liStop;

QueryPerformanceCounter(&liStart);
QueryPerformanceFrequency(&liFreq);

double clock = 0.0f;


while( clock < goal )
{
QueryPerformanceCounter(&liStop);
clock = (double)(liStop.QuadPart - liStart.QuadPart)/liFreq.QuadPart;
}
}

//========================================
// records and saves time delays to file
//========================================
void save_delay(void)
{
FILE *ft = fopen("time records.txt", "w");
if(!ft) perror("time records.txt");
sBuffer.erase();
int key = 0;
numOfLines = 0;
vector<double> delay;
// recording time delays
for(int i = 0; (key = getche()) != 9; ++i)
{
if(key == 13)
{
key = '\n';
cprintf("\r\n ");
numOfLines++;
}
delay.push_back(countTime());
sBuffer += (char)key;
}
// saving time delays to file
for(int j = 1; j < i; ++j)
{
fprintf( ft, "%lf ", delay[j] );
if( j > 0 && !(j % 10)) putc('\n', ft);
}
fflush(ft);
fclose(ft);
}
//=============================
// reads time delays from file
//=============================
void read_time_delay( vector<double> &time_delay, int &delay_num )
{
FILE *ft = fopen("time records.txt", "r");
if(!ft) perror("time records.txt");
double delay = 0.0f;
for( int i = 0; fscanf( ft, "%lf ", &delay ) != EOF; ++i )
{
time_delay.push_back(delay);
}
delay_num = i + 1;
fclose(ft);
}

//==============================================================
// printing the given string by using prerecorded time delays
//==============================================================
void print_string(const char *string, vector<double> time_delay, int delay_num) {
int start = 0;
int x = 0, y = numOfLines + 17;
for( int i = 0, j = start, counter = 0; string[i] != 0; ++i, ++j, ++counter ) {
if(string[i] == 8 && x > 0) {
--x;
} else {
++x;
}
gotoxy(x, y);
if( j >= delay_num - 1 ) {
int back_pos = j;
j = Random(delay_num);
if( delay_num > 2 ) {
int diff = abs(j - back_pos);
while( diff < 2 ) {
j = Random(delay_num);
diff = abs(j - back_pos);
}
}
}
double delay = time_delay[j]/SPEED;
WAIT(delay);
if((string[i] == '\n')) {
x = 0; y++;
gotoxy(x, y);
}
printf("%c", string[i]);
}
}

int main()
{
vector<double> time_delay;
int delay_num;
printf("\n\t\t\t\tKeyboard Recorder Application\n\n");
printf("\nOnce you start typing,press <Tab> to stop the recording\n");
printf("If you are ready,press any key to start the recording...\n\n");
getch();
printf("Start typing\n ");
save_delay();
printf("\n\n\nRecording process stoped\n");
printf("The time delays were saved to the file \"time records.txt\",they can be
use\n");
printf("subsequently by the program to print any given text of an arbitrary
length\n");
printf("Press any key to continue...\n\n");
getch();
printf("\n");
read_time_delay(time_delay, delay_num);
print_string(sBuffer.c_str(), time_delay, delay_num);
return 0;
}
This program can determine very accurately the nature of the user input,
it detects whether it is an integer, a float, a number in scientific notation
or simply an invalid input. To be capable of doing this the program uses a simple FSM
(FINITE STATE MACHINE) to represent the possible states of the input.( INT,
FLOAT )
#include <iostream>
using std::cin;
using std::endl;
using std::cout;

//==============================================================
=============
// the list of all the possible states for the current FSM
//==============================================================
=============
enum STATE{ START, INT, FLOAT, SCIENTIFIC, EXPONENT, S1, S2, INVALID }
state;

STATE Transition( char *str );


void PrintState( STATE state );

int main() {
// declaring buffer variable
char buffer[32] = {0};
// geting input from the user
cout << "\nPlease enter a number: ";
cin.getline( buffer, 32 );
// compute final state
STATE FINAL_STATE = Transition(buffer);
// prints the final state
PrintState(FINAL_STATE);
return 0;
}

//================================================
// makes the transition from one state to another
//================================================
STATE Transition( char *str ) {
int NEXT_SYMBOL;
for( ; *str && state != INVALID; str++ ) {
NEXT_SYMBOL = *str;
switch(state) {
case START:
if(isdigit(NEXT_SYMBOL)) {
state = INT;
}
else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = S1;
}
else if( NEXT_SYMBOL == '.' ) {
state = FLOAT;
}
else {
state = INVALID;
}
break;
case S1:
if(isdigit(NEXT_SYMBOL)) {
state = INT;
}
else if( NEXT_SYMBOL == '.' ) {
state = FLOAT;
}
else if(!isdigit(NEXT_SYMBOL)) {
state = INVALID;
}
break;
case INT:
if( NEXT_SYMBOL == '.' ) {
state = FLOAT;
}
else if(!isdigit(NEXT_SYMBOL)) {
state = INVALID;
}
break;
case FLOAT:
if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) {
state = S2;
}
else if(!isdigit(NEXT_SYMBOL)) {
state = INVALID;
}
break;
case S2:
if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = EXPONENT;
}
else {
state = INVALID;
}
break;
case EXPONENT:
if(isdigit(NEXT_SYMBOL)) {
state = SCIENTIFIC;
}
else {
state = INVALID;
}
break;
case SCIENTIFIC:
if(!isdigit(NEXT_SYMBOL)) {
state = INVALID;
}
break;
}
}
return state;
}

//=====================================
// prints the current state of the FSM
//=====================================
void PrintState( STATE state ) {
cout << "\nFSM state: ";
switch(state) {
case INT:
cout << "INT ";
break;
case FLOAT:
cout << "FLOAT ";
break;
case SCIENTIFIC:
cout << "SCIENTIFIC ";
break;
case INVALID:
cout << "INVALID ";
break;
}
}
Prime Number Generator

Threw history, prime numbers has always be a great fascination for mathematicians.
Even in modern times, primes numbers continues to fascinate many people.
Probably the main reason why prime numbers continues to create such great interest
would be because of the difficulty to prove that any given arbitrary number is prime.
This is call the primality test. Most of the test for primality arm probalistic rather
than deterministic, because probalistic test are much more quicker than the deterministic
ones. When testing the primality of a given number,one of the theorem that is very
largely used is Fermat's little theorem: if "p" is a prime number that is not a factor
of a given integer "a", then pow(a, p - 1) = 1 (mod p) or pow(a, p - 1) % p = 1
One of the main application of prime numbers nowadays is cryptography ,the RSA
algorithm for encrypting and decrypting messages is based on prime numbers.
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <cassert>
using std::fstream;
using std::vector;

vector<int> prime_number_list;
unsigned int list_size = 0;

bool isPrime(int nNum);

int main()
{
int thisNumber;
fstream fout("prime numbers.txt", std::ios::out);
if(fout.fail())
{
std::cerr << "Error while opening \"prime numbers.txt\"" << std::endl;
assert(fout.good());
}
// generating the first 10000 prime numbers and saving them
// as a table into a file
fout << "Prime Number Table (first 10000 prime numbers)\n\n";
for(int i = 2; list_size < 10000; ++i)
{
thisNumber = i;
list_size = prime_number_list.size();
if(isPrime(thisNumber))
{
prime_number_list.push_back(thisNumber);
fout.width(10);
fout << thisNumber;
if((list_size + 1) % 10 == 0)
{
fout << std::endl;
}
}
}
fout.flush();
fout.close();
return 0;
}

bool isPrime(int nNum)


{
int maxFactor = sqrt(nNum), thisFactor;
bool bRetVal = true;
for(int i = 0; i < list_size; ++i)
{
thisFactor = prime_number_list[i];
if(thisFactor > maxFactor)
{
break;
}
if(nNum % thisFactor == 0)
{
bRetVal = false;
break;
}
}
return bRetVal;
}
A calculator Program
#include <iostream>
#include <iomanip>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
void main()
{
long double sum,sub,mult,divide;
double a,b,c;
char x = 'q';
const double PI=3.14159265358979;
cout <<"\t\t"<<" **************"<<endl;
cout <<"\t\t"<<" * Calculator *"<<endl;
cout <<"\t\t"<<" **************"<<endl;
cout <<setw(11)<<"[1] +"<<setw(9)<<"[2] -"<<setw(8)<<"[3]
*"<<setw(9)<<"[4] /"<<setw(9)<<"[5] %"<<endl;
cout <<setw(18)<<"[6] sqrt"<<setw(12)<<"[7] sqr"<<setw(12)<<"[8]
X^y"<<endl;
cout <<setw(17)<<"[s] sin"<<setw(13)<<"[c] cos"<<setw(12)<<"[t]
tan"<<endl;
cout <<setw(32)<<"[q] To QUIT"<<endl;
cin >> x;

while ( x != 'q' && x !='Q'){// a condition for quit from cal.


switch ( x ) {
case '1':
cout <<"\t"<<"Summation"<<endl;
cin >> a >> b;
sum = a + b;
cout <<"The result is : "<<sum<<"\n"<<"Choose another
Operation :"<<endl;
break;

case '2':
cout <<"\t"<<"Subtraction"<<endl;
cin>> a >> b;
sub(= a - b;
cout <<"Tie result is : "<<sub<<"\n"<<"Choose another
Operation :"<<endl;
break;

case '3' :
cout <<"\t"<<"Multiplication"<<endl;
cin >> a >> b;
mult = a * b;
cout <<"The result is : "<<mult<<"\n"<<"Choose another
Operation :"<<endl;
break;

case '4':
cout <<"\t"<<"Division"<<endl;
cin >> a >> b;
divide = a / b;
if (b != 0)
cout <<"The result is : "<<divide<<"\n"<<"Choose another
Operation :"<<endl;
else
cout <<"Does Not Exist"<<"\n"<<"Choose another
Operation :"<<endl;
break;

case '5':
cout <<"\t"<<"Remained of x/y"<<endl;
cin >> a >> b ;
cout <<"The result is : "<< fmod( a,b )<<"\n"<<"Choose
another Operation :"<<endl;
break;

case '6':
cout <<"\t"<<"Square Root of x"<<endl;
cin >> c ;
if (c >= 0)
cout <<"The result is : "<< sqrt( c )<<"\n"<<"Choose
another Operation :"<<endl;
else
cout <<"Does Not Exist"<<"\n"<<"Choose another
Operation :"<<endl;
break;

case '7':
cout <<"\t"<<"Square of x"<<endl;
cin >> c ;
cout <<"The result is : "<< pow( c,2 )<<"\n"<<"Choose
another Operation :"<<endl;
break;

case '8':
cout <<"\t"<<"X to Power Y"<<endl;
cin >> a >> b ;
cout <<"The result is : "<< pow( a,b )<<"\n"<<"Choose
another Operation :"<<endl;
break;
case 'S':
case 's':
cout <<"\t"<<"Sine"<<endl;
cin >> c ;
cout <<"The result is : "<< sin( c *(PI/180) )
<<"\n"<<"Choose another Operation :"<<endl;
break;

case 'C':
case 'c':
cout <<"\t"<<"Cosine"<<endl;
cin >> c ;

cout <<"The result is : "<< cos( c *(PI/180) )


<<"\n"<<"Choose another Operation :"<<endl;
break;

case 'T':
case 't':
cout <<"\t"<<"Tangent"<<endl;
cin >> c ;
cout <<"The result is : "<< tan( c *(PI/180) )
<<"\n"<<"Choose another Operation :"<<endl;
break;

default :
cout <<"Invaild!"<<"\n"<<"Choose a no./char. from the
menu above"<<endl;
break;
}//end switch
cin >>x;

}//end while
cout <<"\n\n"<<" Thanks for using me. "<<endl;
cout <<" _________________________"<<endl;
cout <<"]"<<endl;
cout <<" ~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
}//end main

You might also like