edited by
338 views
0 votes
0 votes
#include<stdio.h>
void main(){
    char loop;
    do{
        char c;
        printf("Enter a character: ");
        scanf("%c",&c);
        printf("ASCII value of %c is %d",c,c);
        printf("\nAnother test: (y/n)? ");
        scanf("%c",&loop);
    }while(loop=='y');
}



Please anyone explain why this code is not working properly. Actually loop exits after just one iteration.

 

But Code written below is working fine:-->
 

#include<stdio.h>
void main(){
    int a,b,sum;
    int loop=0;
    do{
        printf("Enter two numbers: ");
        scanf("%d%d",&a,&b);
        sum=a+b;
        printf("Sum of this two numbers %d",sum);
        printf("\nOne more time: (0/1)?");
        scanf("%d",&loop);
    }while(loop==1);
}
edited by

1 Answer

2 votes
2 votes

%d skips white spaces and special characters that's why 2nd code is working fine but  %c does not skip white spaces and special characters. It reads them as input. After the 1st scanf new line character is present in the input buffer and %c is taking it as input so it's not reading the input from the user that's why 1st code is not working correctly. 

Replace your 2nd scanf with scanf(" %c",&loop); (space before %c).
By doing this it will skip white space and code will work fine atleast once.
But when you replace 2nd scanf with scanf(" %s",&loop) code will work correctly. 

Good Read

Related questions

212
views
0 answers
0 votes
Sai Bhargav 1 asked Dec 22, 2017
212 views
For suppose in a programming language a variable is having the life time is entire runtime of the program.So if the memory address occupied by that variable is not used will that be a bounded variable or free variable
272
views
0 answers
1 votes
Angkit asked Oct 11, 2017
272 views
Q1. How many Binary Tree possible with n nodes ?Q2. How many Ordered Binary Tree possible with n nodes ?Q3. How may BinarySearch Tree possible with n nodes ?
98
views
0 answers
0 votes
ENTJ007 asked Apr 2
98 views
Anyone have taken two consecutive years of combine (GO+Go classes )Test series ? I wanted to know if question are repeated or all new question will be ... my money will be lost ..So please help me in this regard@DeepakPoonia @SachinMittal 1
87
views
0 answers
0 votes