Another C mathematical program


Disclaimer: For the non geeky programming lovers out there, sorry for spamming you with this bunch of incomprehensible lines of text!

The first time I wrote some kind of program was back in high school with a Ti80 calculator which had some sort of BASIC programming language. After reading the manual I spent hours making small mathematical programs to speedup my problem solving study. I must say the programs were not that useful to math because in the tests I had of course to show all the calculation I did… Then I forgot most things about programming… Until some years ago :).

Anyways, what does this have to do with the code below? Almost nothing! The code bellow calculates the mode of n numbers provided by a user. It dynamically creates an n size array and checks with value is seen more often. I still haven’t done a python version this time, if someone wan’ts to do it in python or any other language, please do! 😀

Here it goes.

#include 
#include 

/*Create a n sized array*/
int* makearray(int n)
{
    int* v;
    int i;
    
    v = (int*) malloc(n*sizeof(int)); /*Alocates n int numbers*/
    printf("Array elements:\n");
    for (i = 0; i < n; i++){ /*Fill the array with user input*/
        scanf("%d", &v[i]);
    }
    
    return v;    
}

/*Get the size of an array*/
int arraylen(int v[])
{
    int i=0;
    while(v[i]) i++;
    return i;
}

/*Count how many times a given element is repeated in an array*/
int countelem(int v[], int num)
{
    int i, n=0;

    for (i=0; i < arraylen(v); i++){
        if (v[i] == (int) num){
            n++;
        }
    }
    return n;
}

int main()
{
    int n, i, count = 0, mode;
    int* v;
    
    printf("Size of the array?\n");
    /*We don't wan't anyone creating a oversized array: DANGER'*/
    /*So we limit it's' size. Here I randomly defined 100*/
    do{
        scanf("%d", &n);

    } while(n > 100);
    
    v = makearray(n);
    /*Update the wich value is repeated more ofted -> Mode*/
    for (i = 0; i < n; i++){
        if (countelem(v, v[i]) > count){
            count = countelem(v, v[i]); /*Update the value of the maximum number of repeats*/
            printf("%d\n", count);
            mode = v[i]; /*Update mode*/
        } 

        
    }

    printf("Mode: %d\n", mode);
    return 0;

}

EDIT: There was a little bug with my code, it’s fixed now :).

One of my colegues made a python version :D. Hope he doesn’t mind if I publish it 🙂

#!/bin/sh python
#-*- coding: utf-8 -*-


def makearray(v):
  """Creates the dictionary with the elements input by the user
  """
  print "Array elements (end with empty line):"
  while(1):
    s = raw_input("-> ")    # get an element
    if not s:
      break
    try:
      i = int(s)
      if v.has_key(i):      # if already exists, increment frequency
        v[i] += 1
      else:                 # if not, create it
        v[i] = 1
    except:                 # error handling
       print "not an integer"


#-----------------------------------------------------------------------
# program

# instead of a vector or array, we do this with a dictionary
# that way we can keep the frequency count with each entry
v = {}
makearray(v)

# get the mode
if len(v):
  mode = 0
  maxfreq = 0

  for i in v.keys():
    if v[i] > maxfreq:
      mode = i
      maxfreq = v[i]

  print "Mode %d, with frequency %d" % (mode, maxfreq)

else:
  print "Empty array"



3 comentários a “Another C mathematical program”

  1. I don’t mind at all — I would have published it myself if it was possible to post formatted code in comment. Anyway, I just noticed two minor errors in the comments of the program:

    1. Where it reads “error and exit handling” should be just “error handling”;
    2. Where it reads “with do this with a dictionary” should read “we do this with a dictionary”.

  2. […] dias o meu colega António Lima publicou um artigo com um programa para calcular a moda de um array em C, no qual pedia uma implementação em Python.  Fiz o programa em Python, usando um dicionário […]

Deixe um comentário

Este site utiliza o Akismet para reduzir spam. Fica a saber como são processados os dados dos comentários.