Reputation: 51
I'm trying to write a program which given a certain number of input will output the product of the listed input (only accounting inputs of 0-9 and ignoring other).
For example:
input:345 would result output: 60, or another example would be, input: 3t4 and output: 12
I have given it many attempts and this is what I'm stuck with :
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '\n'){
if (c>=48 && c<=57){
i=c*i;
c=getchar();
}
}
printf("%d",i);
}
How can i do this ?
Upvotes: 0
Views: 151
Reputation: 107
int i,c;
i = 1;
while (i){
c=getchar();
if(c == '\n')
{
break;
}
if (c < 48 || c > 57)
{
i = -1;
break;
}
i = i * (c-48);
}
if (i == -1)
{
printf("Error. Non-Number Entered\n\n");
}
else {
printf("%d\n\n",i);
}
Upvotes: 0
Reputation: 7118
Use i=(c-48)*i;
instead of i = c*i
. So, the changed program would be:
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '$'){
// printf("%c\n", c);
if (c>=48 && c<=57){
i=(c-48)*i;
}
c=getchar();
}
printf("%d",i);
}
This will ensure that you are using the numeric value of the digit, 0
not as ascii code of 0
but as simple 0
.
use c=getchar()
outside the if block. This should work.
Upvotes: 0
Reputation: 6864
Couple of issues in your code.
c=getchar()
should be outside the if
blockchar
variable c
. It should be converted to the actual number and then be multiplied. In your code you are multiplying its ascii value. Hence (c-48)*i
instead of c*i
Upvotes: 1