0

i'm trying to count how many times a user inputs a certain digit and assign total number of instances to a location in a 10 row array (0-9). For instance if the user inputs 888, it will assign 3 to location arr1[8].

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int arr1[10] = {0};
    int c;

    while ((c = getchar()) != '\n'){
        for (int i = 0; i <= 9; i++){
            if (c == i) // This isn't doing what I want it to do
                arr1[i] += 1;
        }
    }
    for (int i = 0; i <= 9; i++)
    printf ("%c ", arr1[i]);
}

The trouble seems to be the line that i've added to comment above. The line if (c == i) is intended to compare a user inputed digit (as it's entered by the user, not the ASCII value) and compare it with i.

So how can I compare c and i as the same type? I've tried changing the type of getchar() to char, signed int, unsigned int but it doesn't seem to make any difference.

Martin
  • 1,060
  • 2
  • 16
  • 28

4 Answers4

2
  1. You have to substract '0'.
  2. You are printing char using %c for count.
  3. You are incrementing by the count by i in the loop rather you wanted to increment by 1 for each character.

Corrected code:

    int main(void){
        int arr1[10] = {0};
        int c;
        while ((c = getchar()) != '\n'){
            for (int i = 0; i <= 9; i++){
                if (c - '0'  == i) 
                    arr1[i] += 1;
            }
        }
        for (int i = 0; i <= 9; i++)
        printf ("%d ", arr1[i]);
    }
P.P
  • 117,907
  • 20
  • 175
  • 238
1

You have to perform the following operation to convert the ASCII value to corresponding integer,

c=c-48;

Inside your for loop,

arr1[i] += i;

should be,

arr1[i] += 1;
Deepu
  • 7,592
  • 4
  • 25
  • 47
0

getchar will return ASCII code for c, not the numerical value. Simplest solutions exploits the fact that numbers 0-9 are sequential in the ASCII table, just subtract the offset:

int number = getchar() - '0';
if (number == i) {
    //....
}

This is just an example, always check the return value of getchar for error codes.

Finally, in this line:

printf ("%c ", arr1[i]);

Use %d as format specifier instead: you want to print a number, not a character.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
0
#include <stdio.h>

int main(void){
    int arr1[10] = {0};
    char table[] = "0123456789";
    int c;

    while ((c = getchar()) != '\n'){
        for (int i = 0; i <= 9; i++){
            if (c == table[i])//or table[i] --> "0123456789"[i]
                arr1[i] += 1;
        }
    }
    for (int i = 0; i <= 9; i++)
        printf ("%d ", arr1[i]);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70