C++ Programs Example
C++ Programs Example
Minimum Value in a Range This Min() function is used to find the maximum value in a list
int Min(const int *Numbers, const int Count) { int Minimum = Numbers[0];
for(int i = 0; i < Count; i++) if( Minimum > Numbers[i] ) Minimum = Numbers[i];
return Minimum; }
double Min(const double *Numbers, const int Count) { double Minimum = Numbers[0];
for(int i = 0; i < Count; i++) if( Minimum > Numbers[i] ) Minimum = Numbers[i];
return Minimum; }
int main() { int Nbrs[] = { 12, 483, 748, 35, 478 }; int Total = sizeof(Nbrs) / sizeof(int);
int Minimum = Min(Nbrs, Total); cout << "Minimum: " << Minimum << endl;
return 0; }
c. #include <iostream>using namespace std;double Abs(double Nbr){// return (Nbr >= 0) ? Nbr : -Nbr; if( Nbr >= 0 ) return Nbr; else return -Nbr;}int main(){ double Number = -88; double Nbr = Abs(Number); cout << "The absolute value of " << Number << " is " << Nbr << endl; return 0;}
d. #include <iostream> using namespace std; void main() { unsigned int Miles; const double LessThan100 = 0.25; const double MoreThan100 = 0.15; double PriceLessThan100, PriceMoreThan100, TotalPrice; cout << "Enter the number of miles: "; cin >> Miles; if(Miles <= 100) { PriceLessThan100 = Miles * LessThan100; PriceMoreThan100 = 0; } else {
PriceLessThan100 = 100 * LessThan100; PriceMoreThan100 = (Miles - 100) * MoreThan100; } TotalPrice = PriceLessThan100 + PriceMoreThan100; } cout << "\nTotal Price = $" << TotalPrice << "\n\n";
Here is an example of running the program: Enter the number of miles: 75 Total Price = $18.75 Press any key to continue
e. // // File name: ~ftp/pub/class/cplusplus/Functions/Absolute1.cpp // Purpose: This program find the absolute value of an integer // without using a function // #include <iostream> using namespace std; int main() { int number; int abs_number; // Ask for input cout << "This program finds the absolute value of an integer." << endl; cout << "Enter an integer (positive or negative): "; cin >> number; // Find the absolute value if(number >= 0) { abs_number = number; } else abs_number = -number; // Print out output cout << "The absolute value of " << number << " is " << abs_number; cout << endl; return 0; }
Running session:
mercury[50]% CC -LANG:std Absolute1.cpp -o Absolute1 mercury[51]% Absolute1 This program finds the absolute value of an integer. Enter an integer (positive or negative): -45 The absolute value of -45 is 45 mercury[52]% Absolute1 This program finds the absolute value of an integer. Enter an integer (positive or negative): 0 The absolute value of 0 is 0 mercury[53]% Absolute1 This program finds the absolute value of an integer. Enter an integer (positive or negative): 9 The absolute value of 9 is 9 mercury[54]%