Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

to choose condition for if-statement

I want to make changes to an inventory balance. By simple logic if I input a number > 0 it should add and subtract if the number is < 0 subtract. So far it works fine.

Now to the issue. If the number that user types is less than inventory balance itself the program should set the value of inventory balance to 0.

For example if the invetory balance is 17 and we type number -18 it should be 0 and not -1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my code so far.

printf("Increase or decrease by: ");
scanf("%d", &n);

if(n >= 0){
    a[i].inventory = a[i].inventory+n;
}else{
    a[i].inventory = a[i].inventory+n;   // +- = -
    if(n < a[i].inventory){
        a[i].inventory = a[i].inventory- a[i].inventory;
    }

I tried adding the last if-statement, but considering the "bad" logic of if condition, it does not work.
bad logic: if inventory is 17 and I want to subtract 2, it will always be less than a[i].inventory and it will jump over else and run the last if-statement.

>Solution :

You are over-complicating a simple task.

a[i].inventory += n; /* n can be negative too. */

if (a[i].inventory < 0)
    a[i].inventory = 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading