Learning C from Kevin Lynch_2

He use an investment.c as an example to illustrate some properties in C. here is the codes:

/*Modular, Readability, 
Track the growth of a portfolio 
Need to enter investment, growth rate, number of yrs(up to 100)*/

/* 2. PREPROCESSOR COMMANDS*/

#include <stdio.h>
#define MAX_YEARS 100

/* 3. DATA TYPE DEFINITIONS */

typedef struct {
    double inv0; 
    double growth;
    int years;
    double invarray[MAX_YEARS+1];       
  } Investment;

/*To make it convenient as a package we can use in the future of this data type structure, named Investment.*/

/* 5. HELPER FUNCTION PROTOTYPES */

int getUserInput(Investment *invp);
void calculateGrowth(Investment *invp);
void sendOutput(double *arr, int years);

/*The first one means we gonna take a pointer *invp to a type of Investment defined earlier in typedef struct. The second one spit out nothing hence void, it takes a pointer *invp to type of Investment too. The third one take a pointer *arr to type double, also takes integer years, note the array here is the first element of an array the rest builds up. */
 
/* 6. MAIN FUNCTION */

int main(void) {
    Investment inv;
    while(getUserInput(&inv)) {
    inv.invarray[0] = inv.inv0;
    calculateGrowth(&inv);
    sendOutput(inv.invarray, 
                inv.years);
    }
    return(0);  
    }
/*The only nuanced part here is the ampstand sign, it’s the referencing sign, reference operator, returning a pointer/address. So here it returns inv’s address/pointer, that’s exactly what the helper function getUserIngput requires.*/

/* HELPER FUNCTIONS */

void calculateGrowth(Investment *invp) {
    
    int i;
    for (i=1; i <= invp->years; i=i+1) {
        invp->invarray[i] = invp->growth * invp->invarray[i-1];
        }
}

int getUserInput(Investment *invp) {
    
    int valid;
    printf("Enter investment, growth rate, number of yrs (up to %d): ", MAX_YEARS);
    scanf("%lf %lf %d", &(invp->inv0), &(invp->growth), &(invp->years));
    valid = (invp->inv0>0) && (invp->growth>0) && (invp->years>0) && (invp->years <= MAX_YEARS);
    printf("valid input? %d\n", valid);
    if (!valid) {
        printf("invalid; exiting.\n");
    }
    return(valid);
}

void sendOutput(double *arr, int yrs) {

    int i;
    char outstring[100];
  
    printf("\nRESULTS:\n\n");
    for (i=0; i<=yrs; i++) {

        sprintf(outstring, "Year %3d: %10.2f\n", i, arr[i]);
}
  
printf("\n");
}
 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.