Home > Back-end >  How to make C accept if y==0
How to make C accept if y==0

Time:11-12

#include <stdio.h>

int main() {
    int x,y,add,subtraction,multiplication,division;
   printf("Write x:");
    scanf("%d",&x);
   printf("Write y:");
    scanf("%d",&y);
    add = x y;
    printf("Add=%d\n",add);
    subtraction = x-y;
    printf("subtraction = %d\n",subtraction);
    multiplication = x*y;
    printf("multiplication = %d\n",multiplication);
    division = x/y;
    if  (y == 0)
        printf("Operation not permitted");
    else
        printf("division = %d\n",division);
    return 0;
}

So When i'm printing y=0 nothing happens No "Operation not permitted" or answer of division What should i do?

CodePudding user response:

Just place this statement

division = x/y;

inside the if statement like

if  (y == 0)
{
    printf("Operation not permitted");
}
else
{
    division = x/y;
    printf("division = %d\n",division);
}

return 0;

CodePudding user response:

Make the division happen in the else. Like this:

#include <stdio.h>

int main() 
{
    int x,y,sum,roz,iloczyn,iloraz;
   printf("Wprowadz x:");
    scanf("%d",&x);
   printf("Wprowadz y:");
    scanf("%d",&y);
    sum = x y;
    printf("Suma=%d\n",sum);
    roz = x-y;
    printf("roznica = %d\n",roz);
    iloczyn = x*y;
    printf("iloczyn = %d\n",iloczyn);
    
    if  (y == 0)
    {
        printf("Operation not permitted");
        exit(0);
    }
    else
    {
        iloraz = x/y;
        printf("iloraz = %d\n",iloraz);
        return 0;
    }
}
  • Related