2
#include<stdio.h>
void main()
{
 char letter;
 int num;
 do
 {
   printf("Enter any number: ");
   scanf("%d",&num);
   printf("Square of %d is %d\n",num,num*num);
   printf("you want to enter another no y/n ");
   scanf("%c",&letter);
 }while(letter=='y');
}

After executing this program, it didn't ask for second scanf function so it terminates after 3rd printf statement printf("you want to.."); help me correct it!

abhiarora
  • 9,743
  • 5
  • 32
  • 57
Siddy Mta
  • 43
  • 5

3 Answers3

3

The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass.

You can probably rescue it by using " %c" instead of "%c"for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character

Or you can use getchar() function

Shashi Kundan
  • 343
  • 1
  • 11
  • [Given the information in this question](https://stackoverflow.com/q/47049709/472495), the answer here appears to have been copied from an answer from Jonathan Leffler, which was made on Mar 5 '12 at 7:05. However, I cannot find the original, and I wonder if it has been deleted. – halfer May 04 '19 at 09:20
1

Either change the first scanf to

scanf("%d\n", &num);

or change the second scanf to

scanf(" %c", &letter);

to ignore the newline character(s).

Another alternative (will read until valid integers are entered)

#include <stdio.h>

int main() {
    int n;
    while(1) {
        printf("Enter any number: ");
        if (scanf("%d", &n) != 1)
            break;
        printf("Square of %d is %d\n", n, n * n);
    }
}

Input

2
3
5

Output

Enter any number: 2
Square of 2 is 4
Enter any number: 3
Square of 3 is 9
Enter any number: 4
Square of 4 is 16
Enter any number: 
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

I modified your code a little bit:

#include<stdio.h>
    #inlcude <conio.h>
    void main()
    {
     char letter;
     int num;
    clrscr();
     do
     {
       printf("Enter any number: ");
       scanf(" %d",&num);
       printf("Square of %d is %d\n",num,num*num);
       printf(" you want to enter another number? y/n");
       scanf(" %c",&letter);
     }while(letter=='y');
}

I just added spaces on your scanf to cancel out whitespaces before the scanf reads the integer. %d will only read integers, so having a text/char there cancels out the program. hope it helps!

Edit: I forgot to tell you, I added another #include for the clrscr(); to clear the screen when you re-run the program.