N
N
nkorobkov2016-04-18 13:46:49
C++ / C#
nkorobkov, 2016-04-18 13:46:49

Why does the program (work with strings in C) not work?

Task: The user enters a string of 20 characters. We need to determine how many times each digit occurs in it. I decided to do like this (for some reason it doesn't work):

#include <stdio.h>
#include <stdlib.h>
#define N 20
int main()
{
    int i, j;
    char string[N];
    int numbers[10];
    for(i = 0; i < 10; i++){
        numbers[i] = 0; //Заполняем массив результатов нулями
    }
    for(i = 0; i < N; i++){
        string[i] = getchar(); //Вводим строку из 20 символов
    }
    for(i = 0; i < N; i++){
        putchar(string[i]); //Выводим строку на экран
    }

    for(i = 0; i < 10; i++){
        for(j = 0; j < N; j++)
            if(string[j] == (char)i) numbers[i]++; //Определяем частоту, с которой встречается каждая цифра
    }

    for(i = 0; i < 10; i++){
        printf("\nNumbers[%d] = %d", i, numbers[i]); //Выводим массив результатов
    }
    return 0;
}

What did I do wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
diskconnect, 2016-04-18
@nkorobkov

You have a small error in comparing characters to numbers:
if(string[j] == (char)i) numbers[i]++; //Determine the frequency with which each digit occurs
The numbers you enter from the console are written to memory not as decimal digits, but as ASCII characters, i.e. if you enter the character '0' from the keyboard and you read it with getchar(), then it will be stored as the ASCII value of the character '0' (in decimal it is the number 48). To make the program work as you intended, you need to subtract the 'offset' zero in the ASCII table from the entered character:
if((string[j] - '0') == i) numbers[i]++; //Determine the frequency with which each digit occurs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question