1

Here is the average program I created.

#include <stdio.h>
#include <stdlib.h>

 int main()
 {
    float f1,f2,f3;

    /* Program to calculate averages. */

    /*Asks for the numbers.*/

    printf(" Please enter three numbers.\n");
    printf ("\t" "First number please.\n");
    scanf("%f", &f1);
    printf ("\t" "Second number please.\n");
    scanf ("%f", &f2);
    printf("\t" "Third number please.\n");
    scanf("%f", &f3);

    /* Now it averages it.*/
    printf(" Thank you, wait one.\n");
    printf(" Excellent, your sum is.\n");
    printf("%f""\n", f1+f2+f3);


    printf("Your average of the sum is now!!!!\n");
    printf("%f", (f1+f2+f3)/3);

    return 0;
}

Now would I turn this into a do-while? Or an if else?

7
  • int i = 0; do{printf... scanf... i = i + 1}while(i < 3); have a 'sum' variable which will aggregate the sum of your numbers and divide it by 3 at the end (instead of three variables which is kind of bad idea). Commented Apr 27, 2013 at 5:56
  • In addition to @sashkello's point, you can automatically keep a sum of the entered values, as well as a count of how many have been entered. Then you can do the appropriate math at the end (careful of divide by 0, and if it were a real world project then be careful of value overflows). for (i = 0; i < COUNT; ++i) { /* ... */ } would be better if you actually know the count up front. Commented Apr 27, 2013 at 5:58
  • 1
    @pickypg edited comment the moment you submitted yours :) Commented Apr 27, 2013 at 5:58
  • Learning C by trial and error is a bad idea, because C has a concept known as "undefined behaviour", which allows mistakes to go relatively unnoticed because the code appears to work. Coincidentally, upgrades to a compiler or porting the code to other systems reveals that undefined behaviour breaks in devastating ways, and you want to avoid it! Reading a book is a great way to learn how to write well defined code. Which book are you reading? Commented Apr 27, 2013 at 5:59
  • So like int sum sum = my numbers divided by three? As I said, extremely novice and apologize for the amount of questions I might ask. Why would you do i=i+1? And would that be (i=i+1) At the end of the syntax before I star the while (1<3);? Jeesh if that even makes sense what I'm asking. Commented Apr 27, 2013 at 6:00

3 Answers 3

6

If you want to repeat the whole entry and averaging process, you can wrap a loop around the code:

#include <stdio.h>

int main(void)
{
    float f1,f2,f3;

    while (1)
    {
        printf("Please enter three numbers.\n");
        printf("\tFirst number please.\n");
        if (scanf("%f", &f1) != 1)
            break;
        printf("\tSecond number please.\n");
        if (scanf("%f", &f2) != 1)
            break;
        printf("\tThird number please.\n");
        if (scanf("%f", &f3) != 1)
            break;

        printf("Your sum     is %f\n", f1+f2+f3);
        printf("Your average is %f\n", (f1+f2+f3)/3);
    }

    return 0;
}

Note that this code checks the return value from scanf() each time it is used, breaking the loop if there's a problem. There's no need for string concatenation, and a single printf() can certainly print a string and a value.

That's a simple first stage; there are more elaborate techniques that could be used. For example, you could create a function to prompt for and read the number:

#include <stdio.h>

static int prompt_and_read(const char *prompt, float *value)
{
    printf("%s", prompt);
    if (scanf("%f", value) != 1)
        return -1;
    return 0;
}

int main(void)
{
    float f1,f2,f3;

    while (printf("Please enter three numbers.\n") > 0 &&
           prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
           prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
           prompt_and_read("\tThird number please.\n", &f3) == 0)
    {
        printf("Your sum     is %f\n", f1+f2+f3);
        printf("Your average is %f\n", (f1+f2+f3)/3);
    }

    return 0;
}

If you want to get away from a fixed set of three values, then you can iterate until you encounter EOF or an error:

#include <stdio.h>

static int prompt_and_read(const char *prompt, float *value)
{
    printf("%s", prompt);
    if (scanf("%f", value) != 1)
        return -1;
    return 0;
}

int main(void)
{
    float value;
    float sum = 0.0;
    int   num = 0;

    printf("Please enter numbers.\n");

    while (prompt_and_read("\tNext number please.\n", &value) == 0)
    {
        sum += value;
        num++;
    }

    if (num > 0)
    {
        printf("You entered %d numbers\n", num);
        printf("Your sum     is %f\n", sum);
        printf("Your average is %f\n", sum / num);
    }

    return 0;
}

You might also decide to replace the newline at the ends of the prompt strings with a space so that the value is typed on the same line as the prompt.

If you want to check whether to repeat the calculation, you can use a minor variant on the first or second versions of the code:

#include <stdio.h>

static int prompt_and_read(const char *prompt, float *value)
{
    printf("%s", prompt);
    if (scanf("%f", value) != 1)
        return -1;
    return 0;
}

static int prompt_continue(const char *prompt)
{
    printf("%s", prompt);
    char answer[2];
    if (scanf("%1s", answer) != 1)
        return 0;
    if (answer[0] == 'y' || answer[0] == 'Y')
    {
        int c;
        while ((c = getchar()) != EOF && c != '\n')      // Gobble to newline
            ;
        return 1;
    }
    return 0;
}

int main(void)
{
    float f1,f2,f3;

    while (printf("Please enter three numbers.\n") > 0 &&
           prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
           prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
           prompt_and_read("\tThird number please.\n", &f3) == 0)
    {
        printf("Your sum     is %f\n", f1+f2+f3);
        printf("Your average is %f\n", (f1+f2+f3)/3);
        if (prompt_continue("Do you want to try again?") == 0)
            break;
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

5 Comments

:/ I think my question wasn't asked properly, my apologies, and I appreciate this immensely. What i want is, after the average is made, is for my program to say something like printf("Would you like to use this program again? y/n?" Then loop the program after a user input.
Oh man, Jonathan Leffler you definitely just answered my question right on the dot! I appreciate it so much, and while it IS complicatedly over my head, I will study this, and look up certain keywords, aka void, static int, etc. And I will learn this inside out, thank you so much!
I'm wondering if the numbers can be store in an array, to be sorted further down the code? I don't regularly use C, but I need to implement your examples along with an insertion sort, if possible. I have the sort already but am having trouble with the inputs from stdin. I may post a question in a minute.
@RichardScriven: yes, you could. You'd probably use a loop, and something like: for (int i = 0; i < 10; i++) { if (prompt_and_read("Next number please: ", &a[i]) != 0) { …handle error… } }.
Mine is a bit like that. I've posted a question
1

You can do this:

int main()
{
    float number, sum=0.0f;
    int index=0;
    do
    {
        printf ("\t" "Enter number please.\n");  //Asking for a number from user
        scanf("%f", &number); //Getting a number from a user
        sum+=number; //Add number entered to the sum
        i++;
    } while (i < 3);
    printf("Excellent, your average is %f\n", sum/3);
    return 0;
}

3 Comments

I appreciate all of your responses, and I am glad that you guys have helped me in this, I will take these examples and build programs around them. Thanks everyone!
@MarkusAndrewWhite : there are many ways to improve you code, don't be afraid take your time to get improved
@Houssem Bdr Thanks so much, I actually was scared at first because I've seen people get torn apart on here on how "stupid" they are, but I work hard every night at this and I actually really really enjoy all of this.
0
#include <stdio.h>
#include <stdlib.h>

int main()
{
float f1,f2,f3;
char c='Y';

/* Program to calculate averages. */

/*Asks for the numbers.*/
do
{

printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);

/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);

printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);

printf ("Do you wana continue [Y/N]...\n");
scanf("%c", &c);

}while(c!='N'&&c!='n');


return 0;
}

1 Comment

One concern with this solution is that the scanf("%c", &c) is going to pick up the newline left in the input by the previous scanf("%f", &f3), and the newline is not going to be either N or n so the loop will continue (indeed, it won't wait for the user to type before continuing). That's why my analogous code uses %1s for the format instead; the %s conversion specifier skips leading white space (such as newlines) which %c does not. You could also put a blank in the format before the %c: scanf(" %c", &c). You should really check the value returned by scanf() too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.