cloopsdo-while

loop 2 taking input automatically


My code is behaving weirdly. In in the first loop iteration it is working perfectly but in the second iteration it is automatically printing ASCII value 10.

#include<stdio.h>

int main(){
    char c;
    int loop =1;

    do{

        printf("\nLoop = %d\nWrite character of which you want to find acii values: ", loop);
        scanf("%c", &c);
        printf("\nASCII value of %c is %d.", c, c);
        loop++;

    }while(c != 'Z');

    printf("\n******END*****");
    
    return 0;

}

Solution

  • 10 is ASCII for newline. You are reading whitespace, which you can avoid by using

    scanf(" %c", &c);
    

    Note the additional blank before the character specifier. It instructs scanf to ignore white space.