- #1
DiamondV
- 103
- 0
Homework Statement
Write a program that reads in any characters from the keyboard, sums up only characters corresponding to a digit and prints the result on the screen. The program will exit when the character 'Q' is entered (upper or lowercase).
Example:
Input = 9 8 q
Output = The total is 17.
Homework Equations
The Attempt at a Solution
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
char input;
int total = 0;
scanf("%c", &input);
while(input!='q' && input!='Q'){
if(input>'9' || input<'0'){ //Input is not a valid integer
printf("Input is not a digit\n");
}
else{//Input is a valid integer
//ASCII value for 0 is 48 .
total = total + (input-48); // Takes previous total and adds new valid integer onto it
}
scanf(" %c", &input);//Scans for new Input
}
printf("The total is %d\n", total);
return 0;
}This is my code that works perfectly, I don't understand one thing though. At the line that is bold I have said that while the input is not q AND not Q. Initially I used a || there, so it was while the input is not Q or q, that didnt work. Its not working as an OR(||) but its working as AND(&&). Why is that? Surely the input can't be Q and q at the same time? I mean only 1 would need to appear to stop the code, so why is it && and not ||.