0

I want to find square of different numbers . I am using do while loop so that after calculating square of 1st number it will ask me to whether I want to find squre of another number or not.

But problem is when I give answer choice as 'y' or 'Y' or any character,it returns to editor window only without calculating sqaure of 2nd number and showing no error. So what's wrong in my program ?

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

void main()
{
    int num,sqr;
    char ans;
    do
    {
        printf("enter the number:\n");
        scanf("%d",&num);
        sqr=num*num;

        printf("square is %d",sqr); 
        printf("\ndo you want to continue?");
        scanf("%c",&ans);
    }while(ans=='y'|| ans=='Y');

    getch();
}

enter image description here

sagar
  • 201
  • 1
  • 8

1 Answers1

1

The problem with your code is that in first scanf you entered the number to get the square. Since we know that stdin stream buffer is a line buffered means the input data will be sent out from the stream buffer to your variable only when the stream buffer encounters a newline or EOF character. As soon as you hit the Enter key data is assigned to your variable, but the newline character(Enter key) is still into the stdin stream buffer. So in immediate scanf/getch function this newline character will be flushed. In your case the second scanf fun is reading the previously entered Newline character(means asn='\n') and the while loop is evaluating it as false condition and coming out of loop. please see the below piece of code I have modified by just adding a line to flush out any newline or EOF character from stdin stream buffer. Run the code and verify it.

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

void main()
{
    int num,sqr;
    char ans;
    do
    {
        printf("enter the number:\n");
        scanf("%d",&num);
        sqr=num*num;

        printf("square is %d",sqr);
        while((getchar() != '\n') && (getchar() != EOF));
        printf("\ndo you want to continue?");
        scanf("%c",&ans);
    }while(ans=='y'|| ans=='Y');

    getchar();
}
Ravi
  • 140
  • 6
  • Do you really want to use two calls to `getchar()` in a single logical comparison statement? ( `while((getchar() != '\n') && (getchar() != EOF));` ) – ryyker Mar 16 '18 at 12:21