ManuMontesino
ManuMontesino

Reputation: 15

How can i terminate a while loop with scanf?

im making a program to sum five values, with the option of sum less than five values, the program works right until i want to exit the while loop with this option("Do you want to charge another value?(y/n)", when i hit n, the program keeps asking to introduce another value?, i tried to do this: scanf(" %c", &option), but its the same, here is the code:

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

void main(){
    float vector[5];
    float suma;
    int con, i;
    char opcion;

    suma = 0;
    con = 0;
    i = 1;

    opcion = 's';

    printf("Sumador de hasta 5 valores");
    while(opcion == 's' || con < 5){
        printf("\nIngrese valor %i:",i++);
        scanf("%f",&vector[con]);
        suma = suma + vector[con];
        con++;
        printf("\nDesea cargar otro valor?(s/n):");
        scanf(" %c",&opcion);
    }

    if(opcion == 's'){
        printf("\nSe supero el limite de valores permitidos");
    }
        printf("\nLa suma es: %.2f", suma);
}

Output of the program

Upvotes: 0

Views: 52

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The loop condition opcion == 's' || con < 5 is true whenever con < 5 is true.

You should use AND opcion == 's' && con < 5 to break the loop when opcion == 's' becomes false.

Upvotes: 1

Related Questions