user130431
user130431

Reputation: 51

Basic C programming

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);
    }

Upvotes: 2

Views: 321

Answers (4)

Emmet
Emmet

Reputation: 6421

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;
}

Upvotes: 2

Ritesh Chandora
Ritesh Chandora

Reputation: 8650

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);
}

Upvotes: 2

Chirag Bansal
Chirag Bansal

Reputation: 84

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;

Upvotes: 0

unlimit
unlimit

Reputation: 3752

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/

Upvotes: 3

Related Questions