Monday, August 26, 2019

An Averager In C

So I am taking a C course and I intentionally didn't want to look at the stuff early to see how fast I can pick up the course material relative to the class. Today is the first day. I've coded this. So now my questions are:

  1. How do I have it such that the outputted value is a float without having to define the input values as floats?
  2. How do I directly define elementArray[i] without having to use a placeholder?
  3. Is there a way to type in integers as "12" instead of having to write "12.0" if I do have to define them as floats in order for the output to be a float?
This is what a sample output looks like:



Here's what the code looks like. Note, this is built on Windows 8.1 in CodeBlocks.



#include <stdlib.h>
#include <stdio.h>
#define ISTRUE 1
#define ISFALSE 0

int main() {

    int elementCount;
    printf("How many elements do you want to average?\n");
    scanf("%d", &elementCount);
    printf("\n");

    int elementArray[elementCount];

    int veracity = ISTRUE;
    int i = 0;


    while (veracity == ISTRUE) {


        if (i < elementCount) {
            int placeholder;
            printf("Enter a value.\n");
            scanf("%d", &placeholder);
            elementArray[i] = placeholder;
            i++;

        }

        if (i >= elementCount){
            veracity = ISFALSE;
        }
    }
    int totalSum = 0;
    for (int i = 0; i < elementCount; i++) {
        totalSum = totalSum + elementArray[i];
    }
    printf("The average of your numbers is %d", totalSum/elementCount);

}