Luna
Luna

Reputation: 73

Looping for using while

Does anyone know what is the problem with this code? Even after inputting >1 line, the program will end prematurely at the end of the code without allowing the nested while to repeat. Thank you.

#include <stdio.h>
int main() {
        int line;
        unsigned int sum = 0;
        int input;
        float average;
        printf("Enter number of input lines:");
        scanf("%d", & line);
        while (line > 0) {

            while (input != -1) {
                printf("Enter input line:");
                scanf("%d", & input);
                sum += input;
                printf("sum is %d", sum);
                printf("Line is %d", line);
            }
            line--;
            printf("Line is %d", line);
        }
        return 0;
    }

Upvotes: 0

Views: 45

Answers (1)

Deepu
Deepu

Reputation: 7610

In your program the inner loop condition is based on the variable input. But it's value is set as -1 inside the inner loop before exiting the inner loop. But the value of variable input never changes once it becomes -1.

Modify as follows to enter the inner loop on each iteration of the outer loop,

printf("Enter number of input lines:");
scanf("%d",&line);
while (line>0) {
input = 0;    /* This line is additional */
while (input != -1) {
    printf("Enter input line:");
    scanf("%d",&input);
    sum += input;
    printf("sum is %d",sum);
    printf("Line is %d",line);
    }
    line--;
    printf("Line is %d",line);
}

Upvotes: 1

Related Questions