C++ Classes
In C++, classes are the building blocks of object-oriented programming. A class is similar to a structure, except that a class is designed to include function members, as well as data members. A well-designed class can be used as easily as a predefined data type. Instances of a class are called objects. We have used predefined classes and objects in the previous discussion. For example, we used the cin object and the cout object to perform standard input and output operations. These objects are also called functions, including precision and setf.
Defining a Class Data Type
A class definition consists of two parts: a class declaration and a class implementation.
Class declaration: the name of the class is specified using the keyword class. The body of the class declaration consists of type declaration statements for the data members and function prototypes for the function members.
class sample
{
public:
void print();
double variable();
};
Suppose we want to define a data type to represent a data point that is represented in rectangular coordinates; thus, the data type is represented by an x-coordinate and a y-coordinate, as shown below. When designing a class type, we need to consider the data members that are required to represent the new data type, as well as the operations that we would like to define for the data type.
The class design includes function members to implement the desired operations. Consider the class declaration that we present for the xy_coordinate class, which consists of
two data members to define the point and two member functions that operate on the coordinates to determine the radius r and the angle q, as at right. We will add additional member functions to the design of the xy_coordinate class later in this section. The class declaration, is typically stored in a header file, as shown in the following code:
// These statements define a class for xy-coordinates.
// This declaration is stored in xy_coordinate.h.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare function prototypes for public members.
public:
void input();
void print();
double radius();
double angle();
private:
// Declare private data members.
double x, y;
};
The xy_coordinate class has two data members and four function members. The keywords public and private are used to control access to the members of the class.
PUBLIC: Members that are specified as public members may be referenced anywhere in the user program.
PRIVATE: Members that are specified as private members may only be referenced by member functions of the xy_coordinate class. This restricted access is known as information hiding. If modifications are made to the data representation of a class, only the member functions need to be modified; no change to the user program is required. Any private member functions can only be called by other member functions. These private member functions are often referred to as helper functions because they are designed to help the other member functions.
CLASS IMPLEMENTATION consists of all the member function definitions. When defining a member function, the scope resolution operator (::) is used in the function definition. This operator is placed between the class name and the function name to specify that the function is a member of the class. When writing a member function definition, first specify the type of value being returned by the function. The class name, the scope resolution operator, the name of the function, and the parameter list will follow. Recall that all member functions have direct access to the data members, so the data members do not appear in the parameter list. Helper functions can also be called directly by a member function. A class implementation can also be stored in a separate file.
// These statements define implementation of an
// xy_coordinate class. They are stored in xy-coordinate.h.
// This function reads the xy coordinates from the keyboard.
void xy_coordinate::input()
{
cin >> x >> y;
}
// This function prints the xy coordinates to the screen.
void xy_coordinate::print()
{
cout << "(" << x << "," << y << ")" << "\n";
}
// This function computes the radius.
double xy_coordinate::radius()
{
return sqrt(x*x + y*y);
}
// This function computes the angle in radians.
double xy_coordinate::angle()
{
// Compute angle of polar form.
double z, pi=3.141593;
if (x >= 0)
z = atan(y/x);
if (x<0 && y>0)
z = atan(y/x) + pi;
if (x<0 && y<=0)
z = atan(y/x) - pi;
if (x==0 && y==0)
z = 0;
return z;
}
We now present a program to test this new data type.
// This program demonstrates the use of
// the xy_coordinate class and its functions.
#include <iostream>
#include <cmath>
#include "xy_coordinate.h"
using namespace std;
int main(void)
{
// Declare and initialize variables.
xy_coordinate pt1;
// Read input point.
cout << "Enter x and y coordinates:" << endl;
pt1.input();
// Print coordinate in xy form and polar form.
cout.setf(ios::fixed);
cout.precision(2);
cout << "Coordinate in xy form:" << endl;
pt1.print()
cout << "Coordinate in polar form:" << endl;
cout << "magnitude: " << pt1.radius() << endl;
cout << "phase (in degrees)" << pt1.angle()*180/3.141593 << endl;
// Exit program.
return 0;
}
At this point we will have you install the DEV C++ compiler and walk you through getting this program working with the compiler.
To execute this program, you need to be sure that the xy_coordinate header file and the xy_coordinate implementation file are accessible to the compiler, along with the program file. This separation of the components allows us to build our own libraries for programmer- defined classes. These libraries can be used by many application programs in the same way that the standard libraries, such as iostream are used. The application program must include the declarations file and be linked to the implementation file. Using these files, we can now test the program. Here is a sample output from the program:
Enter x and y coordinates:
4 4
Coordinate in xy form:
(4.00,4.00)
Coordinate in polar form:
magnitude: 5.66
phase (in degrees): 45.00
Constructor Functions
When we define a variable, we often want to assign an initial value to the variable, as in
double sum=0;
If we do not initialize a variable at the time we define it, the variable holds an unknown value until valid data is assigned. Constructor functions are special member functions that are called automatically when an object of that class is declared. The constructor function is used to initialize the data members of the object being defined. When designing a class, a complete set of constructor functions should be provided. Constructor functions have three unique properties:
* a constructor is called automatically when an object of that class is declared;
* the name of a constructor function is the name of the class;
* no return value is associated with a constructor function, and it is not a void function.
To illustrate, we define two constructor functions to initialize the class members. One function initializes x and y to zero; the other initializes x and y to values in the declaration statement. The two declarations are the first ones in the public declaration list in the following code:
// These statements define a class for xy-coordinates.
// Assume that this declaration is stored in xy_coordinate.h.
// The update is the addition of two constructor functions.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare two constructor functions and six function
// prototypes for public members.
public:
xy_coordinate();
xy_coordinate(double a, double b);
void input();
void print();
double radius();
double angle();
// Declare private data members.
private:
double x, y;
};
The default constructor is called automatically whenever an object is defined in a declaration as follows:
xy_coordinate pt1;
Thus pt1 is an object of the class xy-coordinate. The data members of the object pt1 are initialized to the values assigned by the default constructor function xy-coordinate(). The constructor function with parameters is called automatically whenever an object is defined in a declaration statement as follows:
xy_coordinate pt2(3,4);
The data members of the object pt2 will be initialized to the values passed through the parameter list using the constructor function xy-coordinate(double a, double b). Thus, x is given the value 3 and y is given the value 4.
Constructor functions are programmer-defined functions. Here are the constructor functions that should be added to the class implementation file:
// This constructor function initializes x and y to zero.
xy_coordinate::xy_coordinate()
{
x = 0;
y = 0;
}
// This constructor function initializes x and y to parameters.
xy_coordinate::xy_coordinate(double a, double b)
{
x = a;
y = b;
}
Class Operators
The assignment operator is defined for objects of the same class type. If pt1 and pt2 are both xy_coordinate objects, then this statement is a valid statement:
pt1 = pt2;
Each data member of the object pt1 is assigned the value of the corresponding data member of the object pt2. However, the C++ arithmetic operators and relational operators cannot automatically be used with a programmer-defined class type. This comparison is not valid:
if (pt1 == pt2) (invalid comparison)
A class definition can include a set of operators to be used with objects of the class. The ability to overload operators is a powerful feature in C++. Overloading operators allows a programmer-defined data type to be used as easily as any predefined data type. As an example, consider the arithmetic operators defined in C++. These operators are defined to operate on all predefined data types. However, they are not defined for objects from programmer-defined data types. When designing a class data type, a set of arithmetic operators that work on objects of the class may be included. Operators are included in a class definition in the same way as member functions, except that the keyword operator is used. It is followed by the name of the function, where the name of the function is one of the predefined C++ operators. Only predefined operators may be overloaded. You may not, for example, define a new operator ** to perform exponentiation since this operator is not one of the predefined operators in C++. Next lecture, we illustrate the use of overloaded operators in the definition of a complex number class that includes the arithmetic operators (i.e., + , -, *, /).
Homework:
Define a class to represent a date. A date is defined using three integer variables: month, day, and year. Include member function definitions to
• input a date;
• print a date as month/day/year (10/1/1999);
• print a date as month day, year (October 1, 1999);
• initialize a date object.
Write a sample program that allows the user to enter the date using the date input function and prints the data in each of the defined forms using the class member functions.
Engineering 6 N.Maggard
Wednesday, December 12, 2018
Day 25 11/27/18
These problems relate to the program developed in this section for comparing hand measurements.
1. Modify the program so that it reads the unknown measurement from the keyboard.
2. Modify the program so that it reads the known measurement from a data file and contains a loop that
compares the unknown to all measurements in the file.
3. Modify the program in problem 2 so that it also prints the minimum distance measurement.
4. Modify the program in problem 3 so that it prints the entry number with the minimum distance, as in
“Known 4 has best match.”
5. Modify the program in problem 4 so that it prints all entries with the minimum distance.
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define FILENAME "known.txt"
int main(void)
{
ifstream known;
known.open(FILENAME);
if (known.fail()){
cout << "Error opening input file." << endl;
}
//Declare and initialize variables.
int k=0;
double minimum1=100;
double minimum2=100;
double unknown[5], known1[5];
double distance(double hand_1[5],double hand_2[5]);
cout << "Enter the 5 unknown values:" << endl;
for(int b=0;b<5;b++){
cin >> unknown[b];
}
while(!known.eof()){
known >> known1[k];
k++;
}
for(int c=0;c<5;c++){
if(unknown[c]<minimum1){
minimum1 = unknown[c];
}
}
for(int d=0;d<5;d++){
if(known1[d]<minimum2){
minimum2 = known1[d];
}
}
if(minimum1<minimum2){
minimum2 = minimum1;
}
// Compute and print distance.
cout << "Distance: " << distance(unknown,known1) << endl;
cout << "minimum:" << minimum2 << endl;
known.close();
// Exit program.
return 0;
}
//-----------------------------------------------------------------
// This function computes the distance between two hand measurements.
double distance(double hand_1[5],double hand_2[5])
{
// Declare variables.
int a;
double sum=0;
// Compute sum of absolute value differences.
for (a=0; a<=4; a++)
sum = sum + fabs(hand_1[a]-hand_2[a]);
// Return distance value.
return sum;
}
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define FILENAME "known.txt"
int main(void)
{
ifstream known;
known.open(FILENAME);
if (known.fail()){
cout << "Error opening input file." << endl;
}
//Declare and initialize variables.
int k=0;
double minimum1=100;
double minimum2=100;
double unknown[5], known1[5];
double distance(double hand_1[5],double hand_2[5]);
cout << "Enter the 5 unknown values:" << endl;
for(int b=0;b<5;b++){
cin >> unknown[b];
}
while(!known.eof()){
known >> known1[k];
k++;
}
for(int c=0;c<5;c++){
if(unknown[c]<minimum1){
minimum1 = unknown[c];
}
}
for(int d=0;d<5;d++){
if(known1[d]<minimum2){
minimum2 = known1[d];
}
}
if(minimum1<minimum2){
minimum2 = minimum1;
}
// Compute and print distance.
cout << "Distance: " << distance(unknown,known1) << endl;
cout << "minimum:" << minimum2 << endl;
known.close();
// Exit program.
return 0;
}
//-----------------------------------------------------------------
// This function computes the distance between two hand measurements.
double distance(double hand_1[5],double hand_2[5])
{
// Declare variables.
int a;
double sum=0;
// Compute sum of absolute value differences.
for (a=0; a<=4; a++)
sum = sum + fabs(hand_1[a]-hand_2[a]);
// Return distance value.
return sum;
}
Day 22 11/8/18
These problems relate to the program developed in this section to analyze tsunami data.
1. Modify the program to find and print the number of tsunamis in the file during the same
year as the maximum wave height.
2. Modify the program to find and print the date of the tsunami with the largest number of
fatalities.
3. Modify the program to find and print the locations for all tsunamis with over
100 fatalities.
4. Modify the program so that it counts the number of tsunamis that occurred during the
month of July.
5. Modify the program so that it prints the number of tsunamis in Peru. Assume that the
location might also include the city in Peru, so you will need to search the character
string for the substring "Peru".
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "waves2.txt"
// Define structure to represent a tsunami.
struct tsunami
{
int mo, da, yr, fatalities;
double max_height;
char location[20];
};
int main(void)
{
// Declare variables.
int k=0, npts;
double max=0, sum=0, ave, maxheight[10];
char location1[10];
struct tsunami tk[100];
FILE *waves;
// Read and print information from the file. /
waves = fopen(FILENAME,"r");
if (waves == NULL)
printf("Error opening data file. \n");
else
{
for(int a=0;a<10;a++){
fscanf(waves,"%d %d %d %s %lf %d",&tk[a].mo,&tk[a].da,&tk[a].yr,&tk[a].location,&tk[a].max_height,&tk[a].fatalities);
sum += tk[a].max_height;
if (tk[a].max_height > max){
max = tk[a].max_height;
}
maxheight[a]=tk[a].max_height*3.28;
k++;
npts = k;
}
ave = sum/npts;
printf("Summary Information for Tsunamis \n");
printf("Maximum Wave Height (in feet): %.2f \n",max*3.28);
printf("Average Wave Height (in feet): %.2f \n",ave*3.28);
printf("Tsunamis with greater than average heights: \n");
for (k=0; k<npts; k++){
if(maxheight[k]>ave*3.28){
printf("%s \n",tk[k].location);
}}
fclose(waves);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "waves2.txt"
// Define structure to represent a tsunami.
struct tsunami
{
int mo, da, yr, fatalities;
double max_height;
char location[20];
};
int main(void)
{
// Declare variables.
int k=0, npts;
double max=0, sum=0, ave, maxheight[10];
char location1[10];
struct tsunami tk[100];
FILE *waves;
// Read and print information from the file. /
waves = fopen(FILENAME,"r");
if (waves == NULL)
printf("Error opening data file. \n");
else
{
for(int a=0;a<10;a++){
fscanf(waves,"%d %d %d %s %lf %d",&tk[a].mo,&tk[a].da,&tk[a].yr,&tk[a].location,&tk[a].max_height,&tk[a].fatalities);
sum += tk[a].max_height;
if (tk[a].max_height > max){
max = tk[a].max_height;
}
maxheight[a]=tk[a].max_height*3.28;
k++;
npts = k;
}
ave = sum/npts;
printf("Summary Information for Tsunamis \n");
printf("Maximum Wave Height (in feet): %.2f \n",max*3.28);
printf("Average Wave Height (in feet): %.2f \n",ave*3.28);
printf("Tsunamis with greater than average heights: \n");
for (k=0; k<npts; k++){
if(maxheight[k]>ave*3.28){
printf("%s \n",tk[k].location);
}}
fclose(waves);
}
return 0;
}
Day 21 11/6/18
Modify
1. Modify the program so that it prints the long string and the short string.
2. Modify the program so that it allows the user to enter the long string and the short string.
3. Modify the program so that the long string is read from a data file and the short string is input from
the user.
4. Modify the program so that it will work with either lowercase or uppercase characters.
5. Modify the program so that it checks to be sure that the length of the short string is less than the
length of the long string.
/* This program initializes a long character string and a short */
/* character string. It then prints the locations of the short */
/* string in the long string. It also prints the number of */
/* occurrences of the short string in the long string. */
#include <stdio.h>
#include <string.h>
#define FILENAME "DNA1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare and initialize variables. */
FILE *dna;
dna = fopen(FILENAME,"r");
if (dna == NULL){
printf("Error opening input file. \n");
}
else{
int count=0;
int size1;
int size2;
int val = 0;
char long_str[MAX_SIZE], short_str[MAX_SIZE];
while(val==0){
printf("how long is the long string?\n");
scanf("%i", &size1);
printf("how long is the short string?\n");
scanf("%i", &size2);
if(size2>size1){
printf("Error short string cannot be larger than long string, please reenter all credentials\n");
}
if(size1>=size2){
val++;
}
}
for(int a = 0;a<size1;a++){
fscanf(dna,"%c",&long_str[a]);
}
printf("enter the short string\n");
for(int b = 0;b<size2;b++){
scanf("%s", &short_str[b]);
if(short_str[b]==97){
short_str[b]=65;
}
if(short_str[b]==99){
short_str[b]=67;
}
if(short_str[b]==116){
short_str[b]=84;
}
if(short_str[b]==103){
short_str[b]=71;
}
}
char *ptr1=long_str, *ptr2=short_str;
/* Count the number of occurrences of short_str in long_str. */
/* While the function strstr does not return NULL, increment */
/* count and move ptr1 to next character of the long string. */
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
printf("location %i \n",ptr1-long_str+1);
count++;
ptr1++;
}
/* Print number of occurrences. */
printf("number of occurrences: %i \n",count);
printf("Long string: ");
for(int c = 0;c<size1;c++){
printf("%c", long_str[c]);
}
printf("\nShort string: ");
for(int d = 0;d<size2;d++){
printf("%c", short_str[d]);
}
}
/* Exit program. */
fclose(dna);
return 0;
}
These problems relate to the program developed in this section. 1. Modify the program so that it also counts and prints the number of whorls for the hand. 2. Modify the program so that it also counts and prints the number of arches for the hand. 3. Modify the program so that it also counts and prints the number of loops for the hand. 4. Modify the program so that it combines problems 1, 2, and 3 and thus prints the numbers of the three different categories for the fingertips. 5. Modify the program in problem 4 so that it prints the percentages of the three different categories for the fingertips.
/* This program stores fingerprint information in a structure. */
/* It then references a function to compute the overall category.*/
#include <stdio.h>
#include <math.h>
/* Define a structure for the fingerprint information. */
/* The order for fingertips is right hand, thumb to pinky, */
/* and left hand, thumb to pinky. The codes are L for loops, */
/* W for whorls, and A for arches. */
struct fingerprint
{
int ID_number;
double overall_category;
char fingertip[10];
};
int main(void)
{
/* Declare and initialize variables. */
struct fingerprint new_print;
double compute_category(struct fingerprint f);
void count(struct fingerprint f);
/* Specify information for the new fingerprint. */
new_print.ID_number = 2491009;
new_print.overall_category = 0;
new_print.fingertip[0] = 'W';
new_print.fingertip[1] = 'L';
new_print.fingertip[2] = 'L';
new_print.fingertip[3] = 'W';
new_print.fingertip[4] = 'A';
new_print.fingertip[5] = 'L';
new_print.fingertip[6] = 'L';
new_print.fingertip[7] = 'W';
new_print.fingertip[8] = 'A';
new_print.fingertip[9] = 'L';
/* Reference function to compute overall category. */
new_print.overall_category = compute_category(new_print);
/* Print overall category computed by the function. */
printf("Fingerprint Analysis for ID: %i \n",new_print.ID_number);
printf("Overall Category: %.2f \n",new_print.overall_category);
count(new_print);
/* Exit program. */
return 0;
}
/*--------------------------------------------------------------*/
/* This function computes the overall category */
/* for a fingerprint. */
double compute_category(struct fingerprint f)
{
/* Declare and initialize variables. */
double Rt=0, Ri=0, Rm=0, Rr=0, Rp=0, Lt=0, Li=0, Lm=0, Lr=0,
Lp=0, num, den;
/* Set values based on whorls. */
if (f.fingertip[0] == 'W')
Rt = 16;
if (f.fingertip[1] == 'W')
Ri = 16;
if (f.fingertip[2] == 'W')
Rm = 8;
if (f.fingertip[3] == 'W')
Rr = 8;
if (f.fingertip[4] == 'W')
Rp = 4;
if (f.fingertip[5] == 'W')
Lt = 4;
if (f.fingertip[6] == 'W')
Li = 2;
if (f.fingertip[7] == 'W')
Lm = 2;
/* Compute the numerator and denominator for overall category. */
num = Ri + Rr + Lt + Lm + Lp + 1;
den = Rt + Rm + Rp + Li + Lr + 1;
return num/den;
}
void count(struct fingerprint f){
int countw=0, countl=0, counta=0;
float percentl, percenta, percentw;
if (f.fingertip[0] == 'W'){
countw++;
}
if (f.fingertip[1] == 'W'){
countw++;
}
if (f.fingertip[2] == 'W'){
countw++;
}
if (f.fingertip[3] == 'W'){
countw++;
}
if (f.fingertip[4] == 'W'){
countw++;
}
if (f.fingertip[5] == 'W'){
countw++;
}
if (f.fingertip[6] == 'W'){
countw++;
}
if (f.fingertip[7] == 'W'){
countw++;
}
if (f.fingertip[8] == 'W'){
countw++;
}
if (f.fingertip[9] == 'W'){
countw++;
}
percentw=((countw*100)/10);
printf("the number of whorls is %i \nthe percentage of the fingertips being whorls is %f%%\n", countw, percentw);
if (f.fingertip[0] == 'L'){
countl++;
}
if (f.fingertip[1] == 'L'){
countl++;
}
if (f.fingertip[2] == 'L'){
countl++;
}
if (f.fingertip[3] == 'L'){
countl++;
}
if (f.fingertip[4] == 'L'){
countl++;
}
if (f.fingertip[5] == 'L'){
countl++;
}
if (f.fingertip[6] == 'L'){
countl++;
}
if (f.fingertip[7] == 'L'){
countl++;
}
if (f.fingertip[8] == 'L'){
countl++;
}
if (f.fingertip[9] == 'L'){
countl++;
}
percentl=((countl*100)/10);
printf("the number of loops is %i \nthe percentage of the fingertips being loops is %f%%\n", countl, percentl);
if (f.fingertip[0] == 'A'){
counta++;
}
if (f.fingertip[1] == 'A'){
counta++;
}
if (f.fingertip[2] == 'A'){
counta++;
}
if (f.fingertip[3] == 'A'){
counta++;
}
if (f.fingertip[4] == 'A'){
counta++;
}
if (f.fingertip[5] == 'A'){
counta++;
}
if (f.fingertip[6] == 'A'){
counta++;
}
if (f.fingertip[7] == 'A'){
counta++;
}
if (f.fingertip[8] == 'A'){
counta++;
}
if (f.fingertip[9] == 'A'){
counta++;
}
percenta=((counta*100)/10);
printf("the number of arches is %i \nthe percentage of the fingertips being arches is %f%%\n", counta, percenta);
return;
}
/* This program initializes a long character string and a short */
/* character string. It then prints the locations of the short */
/* string in the long string. It also prints the number of */
/* occurrences of the short string in the long string. */
#include <stdio.h>
#include <string.h>
#define FILENAME "DNA1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare and initialize variables. */
FILE *dna;
dna = fopen(FILENAME,"r");
if (dna == NULL){
printf("Error opening input file. \n");
}
else{
int count=0;
int size1;
int size2;
int val = 0;
char long_str[MAX_SIZE], short_str[MAX_SIZE];
while(val==0){
printf("how long is the long string?\n");
scanf("%i", &size1);
printf("how long is the short string?\n");
scanf("%i", &size2);
if(size2>size1){
printf("Error short string cannot be larger than long string, please reenter all credentials\n");
}
if(size1>=size2){
val++;
}
}
for(int a = 0;a<size1;a++){
fscanf(dna,"%c",&long_str[a]);
}
printf("enter the short string\n");
for(int b = 0;b<size2;b++){
scanf("%s", &short_str[b]);
if(short_str[b]==97){
short_str[b]=65;
}
if(short_str[b]==99){
short_str[b]=67;
}
if(short_str[b]==116){
short_str[b]=84;
}
if(short_str[b]==103){
short_str[b]=71;
}
}
char *ptr1=long_str, *ptr2=short_str;
/* Count the number of occurrences of short_str in long_str. */
/* While the function strstr does not return NULL, increment */
/* count and move ptr1 to next character of the long string. */
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
printf("location %i \n",ptr1-long_str+1);
count++;
ptr1++;
}
/* Print number of occurrences. */
printf("number of occurrences: %i \n",count);
printf("Long string: ");
for(int c = 0;c<size1;c++){
printf("%c", long_str[c]);
}
printf("\nShort string: ");
for(int d = 0;d<size2;d++){
printf("%c", short_str[d]);
}
}
/* Exit program. */
fclose(dna);
return 0;
}
These problems relate to the program developed in this section. 1. Modify the program so that it also counts and prints the number of whorls for the hand. 2. Modify the program so that it also counts and prints the number of arches for the hand. 3. Modify the program so that it also counts and prints the number of loops for the hand. 4. Modify the program so that it combines problems 1, 2, and 3 and thus prints the numbers of the three different categories for the fingertips. 5. Modify the program in problem 4 so that it prints the percentages of the three different categories for the fingertips.
/* This program stores fingerprint information in a structure. */
/* It then references a function to compute the overall category.*/
#include <stdio.h>
#include <math.h>
/* Define a structure for the fingerprint information. */
/* The order for fingertips is right hand, thumb to pinky, */
/* and left hand, thumb to pinky. The codes are L for loops, */
/* W for whorls, and A for arches. */
struct fingerprint
{
int ID_number;
double overall_category;
char fingertip[10];
};
int main(void)
{
/* Declare and initialize variables. */
struct fingerprint new_print;
double compute_category(struct fingerprint f);
void count(struct fingerprint f);
/* Specify information for the new fingerprint. */
new_print.ID_number = 2491009;
new_print.overall_category = 0;
new_print.fingertip[0] = 'W';
new_print.fingertip[1] = 'L';
new_print.fingertip[2] = 'L';
new_print.fingertip[3] = 'W';
new_print.fingertip[4] = 'A';
new_print.fingertip[5] = 'L';
new_print.fingertip[6] = 'L';
new_print.fingertip[7] = 'W';
new_print.fingertip[8] = 'A';
new_print.fingertip[9] = 'L';
/* Reference function to compute overall category. */
new_print.overall_category = compute_category(new_print);
/* Print overall category computed by the function. */
printf("Fingerprint Analysis for ID: %i \n",new_print.ID_number);
printf("Overall Category: %.2f \n",new_print.overall_category);
count(new_print);
/* Exit program. */
return 0;
}
/*--------------------------------------------------------------*/
/* This function computes the overall category */
/* for a fingerprint. */
double compute_category(struct fingerprint f)
{
/* Declare and initialize variables. */
double Rt=0, Ri=0, Rm=0, Rr=0, Rp=0, Lt=0, Li=0, Lm=0, Lr=0,
Lp=0, num, den;
/* Set values based on whorls. */
if (f.fingertip[0] == 'W')
Rt = 16;
if (f.fingertip[1] == 'W')
Ri = 16;
if (f.fingertip[2] == 'W')
Rm = 8;
if (f.fingertip[3] == 'W')
Rr = 8;
if (f.fingertip[4] == 'W')
Rp = 4;
if (f.fingertip[5] == 'W')
Lt = 4;
if (f.fingertip[6] == 'W')
Li = 2;
if (f.fingertip[7] == 'W')
Lm = 2;
/* Compute the numerator and denominator for overall category. */
num = Ri + Rr + Lt + Lm + Lp + 1;
den = Rt + Rm + Rp + Li + Lr + 1;
return num/den;
}
void count(struct fingerprint f){
int countw=0, countl=0, counta=0;
float percentl, percenta, percentw;
if (f.fingertip[0] == 'W'){
countw++;
}
if (f.fingertip[1] == 'W'){
countw++;
}
if (f.fingertip[2] == 'W'){
countw++;
}
if (f.fingertip[3] == 'W'){
countw++;
}
if (f.fingertip[4] == 'W'){
countw++;
}
if (f.fingertip[5] == 'W'){
countw++;
}
if (f.fingertip[6] == 'W'){
countw++;
}
if (f.fingertip[7] == 'W'){
countw++;
}
if (f.fingertip[8] == 'W'){
countw++;
}
if (f.fingertip[9] == 'W'){
countw++;
}
percentw=((countw*100)/10);
printf("the number of whorls is %i \nthe percentage of the fingertips being whorls is %f%%\n", countw, percentw);
if (f.fingertip[0] == 'L'){
countl++;
}
if (f.fingertip[1] == 'L'){
countl++;
}
if (f.fingertip[2] == 'L'){
countl++;
}
if (f.fingertip[3] == 'L'){
countl++;
}
if (f.fingertip[4] == 'L'){
countl++;
}
if (f.fingertip[5] == 'L'){
countl++;
}
if (f.fingertip[6] == 'L'){
countl++;
}
if (f.fingertip[7] == 'L'){
countl++;
}
if (f.fingertip[8] == 'L'){
countl++;
}
if (f.fingertip[9] == 'L'){
countl++;
}
percentl=((countl*100)/10);
printf("the number of loops is %i \nthe percentage of the fingertips being loops is %f%%\n", countl, percentl);
if (f.fingertip[0] == 'A'){
counta++;
}
if (f.fingertip[1] == 'A'){
counta++;
}
if (f.fingertip[2] == 'A'){
counta++;
}
if (f.fingertip[3] == 'A'){
counta++;
}
if (f.fingertip[4] == 'A'){
counta++;
}
if (f.fingertip[5] == 'A'){
counta++;
}
if (f.fingertip[6] == 'A'){
counta++;
}
if (f.fingertip[7] == 'A'){
counta++;
}
if (f.fingertip[8] == 'A'){
counta++;
}
if (f.fingertip[9] == 'A'){
counta++;
}
percenta=((counta*100)/10);
printf("the number of arches is %i \nthe percentage of the fingertips being arches is %f%%\n", counta, percenta);
return;
}
Day 19/20 10/30/18-11/1/18
Modify your seismic program so that it can work with arbitrarily large data files without the use of a
header line! A data file will be posted on edmodo for your to process.
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
Subscribe to:
Comments (Atom)