Programs with functions: 2020-09-10

Name:

Most code examples from the 2pm section:

bmi.c and helpers.c

/* BMI calculator example */
#include <stdio.h>

float fi2m(int, double);
float lbs2k(float lb);
float calc_bmi(float m, float k);

int main(int argc, char **argv)
{
    int feet;
    float inches;
    float pounds;

    printf("Enter height (ft, in) and weight (lbs): ");
    scanf(" %d %f %f", &feet, &inches, &pounds);

    float meters = fi2m(feet, inches);
    float kilos = lbs2k(pounds);

    float bmi = calc_bmi(meters, kilos);

    printf("BMI: %.1f\n", bmi);
    return 0;
}
//--------------------------------------------------------------------
float fi2m(int f, double i)
{
    i += 12 * f;
    return 0.0254 * i;
}


float lbs2k(float lb)
{
    return lb / 2.205;
}


float calc_bmi(float m, float k)
{
    return k / (m*m);
}

Function with side effects; Use of Command-line arguments

unsigned numVowels(char *s)
{
    unsigned count = 0;
    for (int i = 0;  s[i] != '\0'; i++) {
        switch( s[i] ) {
          case 'a':
          case 'e':
          case 'i':
          case 'o':
          case 'u':
            count++;
            s[i] = 'X' ;        // nasty side effect!
            break;
        }
    }
    return count;
}
// use numVowels
// 2020-09-10
#include <stdio.h>

unsigned numVowels(char *s);

int main(int argc, char **argv)
{
    printf("program: %s\n", argv[0]);

    for (int i = 1; i < argc; i++) {
        unsigned n = numVowels( argv[i] );
        printf("%u vowels in %s\n", n, argv[i]);
    }
    return 0;
}

trigplotter.c — with a beginning for drawplot()

/*
| Trig plotter
| 2020-09-10
*/
#include <stdio.h>
#include <math.h>       // sin(), cos()
#include <unistd.h>     // usleep()
#include <stdlib.h>     // atof(), atoi()

#define NUMSTEPS        90
#define BEATS           4.3
#define MINRADIANS      0.0

void drawplot(double *v, int n, int w) ;


double trigfunct(double x)
{
    return sin(x) * cos(BEATS * x);
}


int main(int argc, char **argv)
{
    if (argc != 3) {
        printf("usage: %s <maxradians> <width>\n", argv[0]);
        return 1;
    }

    double maxradians = atof( argv[1] );
    int width = atoi( argv[2] );

    double fvalues[ NUMSTEPS ];
    double stepsize = (maxradians - MINRADIANS) / NUMSTEPS;

    int step;
    double x;
    for ( step = 0, x = MINRADIANS ; step < NUMSTEPS ; step++, x += stepsize ) {
        fvalues[step] = trigfunct( x );
    }

    drawplot(fvalues, NUMSTEPS, width);

    return 0;
}
/*
| plotting functions for the trigplotter program.
| 2020-09-10
*/
void drawplot(double *s, int n, int w)
{
    for (int r = 0; r < n; r++) {

        int colwidth = s[r] * w;  // this needs work!

        for (int c = 0; c < colwidth; c++) {
            printf("*");
        }
        printf("%.3lf\n", s[r]);
        usleep(1e5);    // 100,000 microseconds = 1 millisecond
    }
}
//----------------------------------------------------------------