Sample Programs

 

Those of you who have asked for sample programs, here they are:

 

/*   This program asks the user for a guess of a number

     and terminates when the user guesses correct,

     notifying him “You win!”

*/

 

#include <stdio.h>

 

// function prototypes

int promptForNumber();

 

// global constants

const int correctGuess = 5;

 

int main()

{

printf(“Guessing game!\n\n”);

     do

     {

}

while(promptForNumber() != correctGuess);

printf(“You win!\n”);

     return 0;

}

 

// function bodies

int promptForNumber()

{

     int guess;

     printf(“Please enter a number between 1 and 100: ”);

     scanf(“%d”, &guess);

     return guess;

}

 


/*   A program that will compute the standard deviation

of a list of numbers that the user enters

*/

 

/*   #define values – try to avoid these, since they won’t show

     up in the debugger, and we don’t want to use pointers

     to allocate memory

*/

    

#include <stdio.h>

#include <math.h>

 

#define NUM_NUMBERS 15

#define NumberType unsigned int

#define TRUE       1

#define FALSE      0

 

// formula: std_dev = sqrt(variance)

// variance = sum of (xiavg)2

 

// function prototypes

int populateList(NumberType[NUM_NUMBERS] list);

double average(NumberType[NUM_NUMBERS] list);

double variance(NumberType[NUM_NUMBERS] list);

 

int main()

{

NumberType lst[NUM_NUMBERS] = {0}; // initialize the array

 

if (populateList(lst) == TRUE)

{

          printf(“The standard deviation of the list is: %lf\n”,

                   sqrt(variance(lst));

}

else return 1; // ERROR!

 

     return 0;

}

 

// function bodies (implementation)

double variance(NumberType[NUM_NUMBERS] list)

{

int i = 0;

double avg = average(list);

double varnc = 0;

 

for (i = 0; i < NUM_NUMBERS; i++)

{

     varnc += pow(list[i] – avg, 2);

}

return varnc;

}

 

double average(NumberType[NUM_NUMBERS] list)

{

     double sum = 0;

     for (i = 0; i < NUM_NUMBERS; i++)

{

     sum += list[i];

}

return sum / NUM_NUMBERS;

}

 

int populateList(NumberType[NUM_NUMBERS] list)

{

     int i = 0;

    

printf(“You will be prompted for a list of %d numbers\n”,

NUM_NUMBERS);

 

     for (i = 0; i < NUM_NUMBERS; i++)

{

     unsigned int num;

 

     printf(“Enter a number: ”);

     scanf(“%d”, &num);

     printf(“\n”); // go to the next line

}

return TRUE;

}