hYde
hYde

Reputation: 33

Reading out Array Elements gives weird number back;

As I started my apprenticeship in programming almost a year ago now, I was playing around with arrays in C.

This is the code I have been writing:

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

#define WARY 1000

int main() {
  srand(time(0));  // Initialisierung des Algorithmus für rand()
  int a = 0, zahl = 0, rep = 0, wertmin, wertmax, eins, zwei, drei, vier, fuenf,
      sechs, sieben, acht, neun, zehn;
  int zary[WARY];
  for (a = 0; a < WARY; ++a) {
    zary[a] = rand() % 10 +
              1;  // Befüllen des Arrays mit Zufallszahlen (Bereich von 1-10)
  }
  for (a = 0; a < WARY; ++a)  // Ausgabe aller Elemente des Arrays
  {
    printf("Inhalt von zary[%i]", a);
    printf("ist: %i \n", zary[a]);
  }

  a = 0;  // Initialisierung min/max mit Element der 1.Stelle des Arrays
  wertmax = zary[a];
  wertmin = zary[a];

  for (a = 0; a < WARY; ++a)  // Durchsuchen des Arrays nach Min/Max
  {
    if (wertmin > zary[a]) wertmin = zary[a];
    if (wertmax < zary[a]) wertmax = zary[a];
  }

  printf("Das kleinste Element der Tabelle ist %i\n", wertmin);
  printf("Das groesste Element der Tabelle ist %i\n", wertmax);

  for (a = 0; a < WARY; ++a)  // Zählen der Häufigkeit aller Elemente des Arrays
  {
    switch (zary[a]) {
      case 1:
        eins++;
        break;
      case 2:
        zwei++;
        break;
      case 3:
        drei++;
        break;
      case 4:
        vier++;
        break;
      case 5:
        fuenf++;
        break;
      case 6:
        sechs++;
        break;
      case 7:
        sieben++;
        break;
      case 8:
        acht++;
        break;
      case 9:
        neun++;
        break;
      case 10:
        zehn++;
        break;
      default:
        printf("Fehler\n");
    }
  }
  printf(
      "Elemente des Arrays sind:\n %i (1)er\n; %i (2)er\n; %i (3)er\n; %i "
      "(4)er\n; %i (5)er\n; %i (6)er\n; %i (7)er\n; %i (8)er\n; %i (9)er\n; %i "
      "(10)er\n",
      eins, zwei, drei, vier, fuenf, sechs, sieben, acht, neun, zehn);

  return 0;
}

Last intention of this code was to fill the array with random numbers between 1-10 and then read out the elements of the array and how often they appear.

It works rather fine, but everytime it says there is over 4.000.000 times the number 7.

Where is my mistake?

Upvotes: 0

Views: 124

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

You are incrementing your variables (e.g. eins) before initialising them. Technically, this is undefined behaviour.

You need to write int eins = 0; etc. or include the line

eins = zwei = drei /*etc */ = 0;

after the declaration but before any ++.

Upvotes: 3

GoldRoger
GoldRoger

Reputation: 1263

You need to initialize all the eins,zwei,drei,vier,fuenf,sechs,sieben,acht,neun,zehn to 0 before switch block.

eins = 0;

and so on.

Upvotes: 5

Related Questions