0

c program is not asking value at a scanf funtion, it just going forward without asking Here is my code....

#include <stdio.h>

int main() {

    float p, r, t, si;
    char A;

    printf("Principle Amount : ");
    scanf("%f", &p);

    printf("Rate of Intrest : ");
    scanf("%f", &r);

    printf("Time Period : ");
    scanf("%f", &t);

    si = ( p * r * t ) / 100;

    printf("Simple Intrest = %.2f \n", si);
    
    printf("Do you want to know the incremented amount ?\n");
    printf("Y for yes & N for no : ");
    scanf("%c", &A);

    if (A == 'Y') {
        printf("Incremented amount will be = %f", p + si);
    }
    else if (A == 'N') {
        printf("Thank You 4 using :-) ");
    }
    else {
        printf("INVALID INPUT");
    }
    return 0;
}

Log:

Principle Amount : 10000
Rate of Intrest : 5
Time Period : 2
Simple Intrest = 1000.00 
Do you want to know the incremented amount ?
Y for yes & N for no : INVALID INPUT  

It should ask me Y or N after "Y for yes & N for no : ", but it is abruptly taking the else condition.

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    You need to add a space before the `%` like this `scanf(" %c", &A);` because `%c` does not filter whitespace unless specifically told. It reads *every character*. – Weather Vane Sep 09 '22 at 11:52
  • 1
    Your first lesson in debugging would be to print the *numeric* value of the character that was received. – Weather Vane Sep 09 '22 at 11:57
  • you can put `fflush(stdin);` to flush the buffer after each `scanf`. . but remember that `scanf` is a bad practice , even my compiler gives me warning about it – abdo Salm Sep 09 '22 at 11:58
  • 1
    @abdoSalm... `scanf(stdin)` is UB in many implementations. – pmg Sep 09 '22 at 11:59
  • @abdoSalm if your compiler tells you not to use `scanf` that could be MS Visual c who want you to use their own `scanf_s` functions instead, which are no safer. Add `#define _CRT_SECURE_NO_WARNINGS` before `#include ` to get rid of the warning. Using `scanf` *isn't* bad practice in itself, although there are other, perhaps better, ways. What is bad is when `scanf` is used incorrectly. – Weather Vane Sep 09 '22 at 12:11

0 Answers0