user2771151
user2771151

Reputation: 421

Is here any logical error?

void mul()   
{  
    int x,y,sum = 0;
    scanf("%d",&x);
    scanf("%d",&y);
    while (x != 0){
        if (x%2 != 0)
            sum = sum + y; 
        x = x/2;
        y = 2*y;
    }
    printf("%d",sum);
}

int main()   
{   
    char c;
    printf("Enter two numbers and y to exit");
    //mul();
    scanf("%c",&c);
    while (c != 'y'){
        mul();
    }
    return 0;
}

On running this program it is not getting exit on giving input 'y'. Why?

Upvotes: 0

Views: 85

Answers (3)

Rajeshkumar
Rajeshkumar

Reputation: 75

Try this code or just add "static int main" in your code.

 int Main() 
{
   char c;
   printf("Enter y to exit");
   scanf("%c",&c);
   while (c != 'y')
     {
        mul();
      } return 0;   }

void mul()   {  
printf("Enter two numbers");  
int x,y,sum = 0;  
scanf("%d",&x);  
scanf("%d",&y);   ................    }

Upvotes: 0

Sadique
Sadique

Reputation: 22823

You are not scanning in the while loop. Do this:

char c = 'n';
while (c != 'y')
{
    printf("Enter two numbers and y to exit");
    scanf("%c",&c);
    mul();
}

Just to point out something extra, when you enter a character like y or n and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) are placed in the input buffer.The first character gets consumed by the scanf but the newline remains in the input buffer.

Solution is to consume the extra newline by using:

scanf(" %c", &c);
       ^<------------Note the space

Upvotes: 2

david
david

Reputation: 3218

Better you do this way

do{
    scanf("%c",&c);
    mul();
}while (c != 'y');

Upvotes: 0

Related Questions