2

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);
    }
1
  • 1
    Your program will hang if the user enters an invalid digit, as you never give the user the opportunity to enter a new char. Commented Apr 7, 2014 at 8:28

4 Answers 4

3

Change

i = c*i;

to

i = (c - '0')*i;

What is happening here is the variable c contains the ascii value of the number not the number. So, '0' is 48, '1' is 49 and so forth. So when you enter 12, you will not get 1x2 but 49x50.

Take a look at the ascii chart. http://www.asciitable.com/

Sign up to request clarification or add additional context in comments.

1 Comment

There's more wrong with the code than just the failure to convert the characters to their corresponding integers.
2

Remove the curly braces from inner if block

#include <stdio.h>
main() {
    int c,i;

    c = getchar();
    i = 1;
    while (c!= '\n'){
        if (c>=48 && c<=57)              
        i = (c-'0')*i;
        c=getchar(); 
    }
    printf("%d",i);
}

Comments

2

You have to convert the characters that you have read into their corresponding numeric values. Since you are only using single digits, you can exploit/abuse the fact that the ASCII characters for '0' to '9' are in order (from 48 to 57).

Using a do { } while(), rather than while() { } obviates the need to “preset” c outside the loop.

The correct header for main is either int main(void) or int main(int argc, char *argv[]), and you should return a value from main.

The following should work, although I admit that I haven't compiled or tested it:

#include <stdio.h>

int main(void)
{
    int c;     /* Character read */
    int i = 1; /* Product */

    do {
        c = getchar();
        if (c>='0' && c<='9'){
            i *= (c-'0');
        }
    } while( c != '\n' );

    printf("Product: %d\n",i);

    return 0;
}

Comments

0

2 things to be taken care of : (1). Remove curly braces of if block. (2). Take care of conversion from ascii code to number. i = (c - '0') * i;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.