Sean
Sean

Reputation: 3450

Basic While Loop Precedence (C)

I'm new to coding and am learning C. I just had a question regarding while loops.

#include <stdio.h>

int main(void) {
    int integer1, integer2, number, sum, largest, smallest;
    float average;

    integer1 = 0;
    number = 0;
    sum = 0;
    largest = integer1;
    smallest = integer1;

    while (integer1 != -1) {
        printf("Enter the number: ");
        scanf_s("%d", &integer1);
        number++;
        sum = sum + integer1;

        if (integer1 >= largest) {
            largest = integer1;
        }
        if (integer1 <= smallest) {
            smallest = integer1;
        }
    }

    average = (float) sum / number;

    printf("The number of user's input: %d.\n", number);
    printf("The sum of input numbers: %d.\n", sum);
    printf("The average of input numbers: %.2f.\n", average);
    printf("The largest number is: %d.\n", largest);
    printf("The smallest number is %d.\n", smallest);

    return 0;
}

The objective of the code I've written is to:

  1. Read integer values from the user.
  2. Terminate the while loop when the user enters '-1'.
  3. Output the printf statements with their corresponding values.

Here's the problem: All of the integer variables that I've declared should NOT include the value of '-1; inputted by the user. I assume that this has to do with an issue of precedence regarding the while loop, but I can't seem to pinpoint what it is. Any help or insight is greatly appreciated.

Thank you!

Upvotes: 2

Views: 261

Answers (3)

Hari Lamichhane
Hari Lamichhane

Reputation: 530

In order to achieve what you want you need to add one line.

 //use infinite loop
  while (1) {
        printf("Enter the number: ");
        scanf_s("%d", &integer1);
        //jump out of the loop because the loop has already started.
        //but the value was -1
        if (integer == -1) break;
        number++;
        sum = sum + integer1;

        if (integer1 >= largest) {
            largest = integer1;
        }
        if (integer1 <= smallest) {
            smallest = integer1;
        }
    }

Upvotes: 1

Blessen George
Blessen George

Reputation: 270

Just add your scanf() statement prior to your while loop.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

Sometimes neither while nor do/while loop fit your needs, because the decision to exit the loop must be made in the middle of loop's body.

Reading values and deciding what to do after the read presents one of such situations. A common solution is to set up an infinite loop, and exit it from the middle on a break:

for (;;) {
    printf("Enter the number: ");
    scanf_s("%d", &integer1);
    if (integer1 == -1) {
        break;
    }
    ... // The rest of your code
}

Upvotes: 4

Related Questions