Thread: How to reset every element in array to zero ?

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    1

    How to reset every element in array to zero ?

    So I have to write a programm to count how often every digit appears in a string. I've managed to make that work but now I want to be able to do this with more strings. So I need to reset the digits to zero and that function is not working...Here's my code:


    #include <stdio.h>

    void calc_occurrences(char s[], int occurrences[]);
    void print_occurrences(int occurrences[]);
    void reset_occurrences(int occurrences[]);

    int main(int argc, char * argv[])
    {
    int parameters = argc - 1;
    int occurrences[10] = {0};
    static int i;

    if (parameter_anzahl == 0) {
    printf("Error, zero Parameters entered\n");
    return 1;
    }
    for (i = 1; i <= argc - 1; i++) {
    printf("\n\n");
    printf("Parameter %i: %s\n", i, argv[i]);
    calc_occurrences(argv[i], occurrences);
    print_occurrences(occurrences);
    reset_occurrences(occurrences);
    }
    return 0;
    }

    void calc_occurrences(char s[], int occurrences[])
    {
    int i = 0;
    while (s[i]) {
    if (s[i] >= '0' && s[i] <= '9') {
    ++occurrences[s[i] - '0'];
    }
    ++i;
    }
    }

    void print_occurrences(int occurrences[])
    {
    int k;
    for (k = 0; k < 10; k++) {
    printf("%i: %i\n", k, occurrences[k]);
    }
    }

    void reset_occurrences(int occurrences[])
    {
    int i = 0;
    while (occurrences[i]) {
    occurrences[i] = 0;
    i++;
    }
    }
    Attached Images Attached Images How to reset every element in array to zero ?-capture-jpg 
    Last edited by saty; 12-02-2018 at 07:58 AM.

  2. #2
    Registered User
    Join Date
    Jun 2017
    Posts
    157

  3. #3
    Registered User
    Join Date
    Dec 2018
    Posts
    8
    The cause of the problem might be the while statement:

    while(occurrences[i) etc.

    if occurrences[i] has the value 0, all the following elements in the array won't be reset. Try a for-loop instead and see if it works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Best way to reset array to zeros?
    By telmo_d in forum C Programming
    Replies: 23
    Last Post: 01-20-2016, 09:29 PM
  2. Insert element after the last element in array in c
    By amaturequestion in forum C Programming
    Replies: 3
    Last Post: 04-09-2015, 08:29 AM
  3. change element in array
    By izhamzamli17 in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2014, 12:17 AM
  4. array of ptrs vs constant ptr to an first element of array
    By monkey_c_monkey in forum C Programming
    Replies: 5
    Last Post: 08-30-2012, 11:39 PM
  5. size of an array poited by array element
    By mitofik in forum C Programming
    Replies: 7
    Last Post: 12-24-2010, 12:09 AM

Tags for this Thread