Home > Mobile >  Why can't I break while command here?
Why can't I break while command here?

Time:03-27

I am writing an online shopping code in C, I don't know why but my code goes into an infinite loop and the scanf function in the block does not work. Even if I add if (b <= a){break;}. My friend tried to run it on Linux and got a different result. It just writes "insufficient margin please add" several times depending on the input. Here's my code;

int a;
int b = 100;
int add;
scanf("%d",&a);
while(a < b)
{
    printf("unsiffcent margin please add");
    scanf("add%d",&add);
    a = a   add;
}

I tried adding if(b <= a){break;} but doesn't work. I want a code that ask me to add to a number until number is greater than a value.

CodePudding user response:

There are errors in your code:

  • while(a\<b) will cause a syntax error. you probably meant while (a <= b).
  • a is not declared in your code.

Here is what you want to do:

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

int main(void)
{
    int max = 100, a = 0, add = 0;
    
    printf("Enter a number: ");
    scanf("%d", &a);
    
    while(a <= max) {
        printf("Unsufficient margin please add another number: ");
        scanf("%d", &add);
        a  = add;
    }
    
    printf("a = %d\n", a);
}

You have to provide a prompt message so the user knows he is supposed to do something. And better, give your variables meaningful names.


Side note: scanf() is not recommended to ask for user input.

CodePudding user response:

scanf("%d",&add); will solve your problem

  • Related