Calculate the sum over a container

From CodeCodex

Revision as of 23:35, 29 August 2007 by 219.138.204.162 (Talk)

riforma del codice di procedura civile libro bimbo il gusto del vino foto ostaggi nepalesi gunny bunny pranzo al ritz mx150 plantronics m i a the end volare mp3 www actionchat dm 12 4 96 karma malo www via michelin it singole maggiorate il drago degli abissi trani italia ovni biglietti per concerto incontro lerici nokia 6610i mms univison com gojko mitic leticia spiler adler thermae com brother mfc 7420 celebridades lesbianas congedo parentale florida mappa everyone be somebody voli per djerba kaitec top66 supporto per palmari da auto el confidente mercedes c 250 td esprit il presagio indios tabajara mutuo fisso tastiera ad infrarossi gl wireless sd jun kunimura atack caricabatteria nimh dural spa trasmissione dati cerco cavalli colin firth riscaldamento casa allison and williams la genesi di un maestro gps tomtom nokia 6600 hanno ucciso il gioco calcio mp3 tv sony plasma 42 pollici saucony grid el oro media hard disk e floppy barreto jr boris karloff foto uomini col cazzo duro il messaggio di mettete dei fiori nei vostri cannoni virginia ristorante il primo premio si chiama irene world golf in english corsi rumba torino apple dock fotocamere yakumo salvados por la campana kiloutou oakley accessori la figa di monica bellucci executive service kesenai tsumi how would u feel teen sex videos comune di treviso bari vibo valentia telecomando meliconi foto offspring lettori audio mp3 il cuore come amore duel masters vol 2 revolucion micro maniacs inmortal fotos de claveles www cinema ugc fr i manga a 128 bit gadget sportivi java free www ciee org br winzip per windows xp incredimail gutterball universita dams jeonju pentax optio mx grand theft auto psp le metropole chiarly midnight club 3 la prossima settimana in italia micene epson stylus photo 810 pensiline celestina cartelle infermieristiche cockatil videoregistratore super vhs carpentier y valmont alejo teac 40gb torino manila timer caffettiera tm 8100 mondo erotico www bambola club it fabra pompeu pinocchia concorsi carabinieri riservato volontari tachicardia principessina braun frullatore ram 133mhz 256mb doom 3 mod lavoro a legnago siti di streghe biliardo classics casi hong nhung tn 11 www virgilio it linksys ag241 modem apple imac g5 17 takeshi kitano adidas scarpe skateboard www foxx equipment com cazzi di cavallo registratore di minidisc dragostea din tei mid www sat com kenwood autoradio con dvd stampante hp designjet 110 plus ratchet gladiator ipod cellulari ddr2 memoria ram attrezzatura campeggio hp xeon computer le cap i gocha lifeview duo scheda asus video croak una data per ace combat 4 hattaway change your heart golf iv volkswagen rock roll is dead robotics modem fax 56 web mail tamburo rullante oasis all around the world frontalino sony monika brodka mp3 elenco partecipanti miss italia 2004 hp business inkjet 2800 grazie per quel caldo dicembre pesca tripode ospedale de best di milano amplificatori classe video strani le motorizzate que es la administracion herrera ragazze di salerno canon 3200 rs dv multi media card manifestazioni sanremo abbigliamento uomo pelle albergo stella jeans vita bassa uomo dsl modem firewall hepu bert veneto moto usate quattro nuovi dvd super auto gas macchine gare stefania belmondo siti amatoriali hp all in one a3 like a payer accessori fujifilm s5000 nubira gpl danger zone 2 dagostea tea din tei athlon 64 3200 core venice inchiostri solidi roma delhi biglietti aerei volo last minute canarie trucci bad moon rising rio diablos

Related content:

This code demonstrates how to calculate the sum of a container (most often an array or similar structure).

See also

Implementations

Algol 68

The following function computes the sum of the elements of the array passed to it. The type of the array elements is called NUM, which can be defined as any suitable integer or real type.

MODE NUM = INT; # type of array element #

PROC sum = ([] NUM a) NUM :
    BEGIN
        NUM result := 0;
        FOR i FROM LWB a TO UPB a DO
            result  := a[i]
        OD;
        result
    END

For instance, the call

sum((3, 4, 5, 6))

returns 18.


C

Total of a series function. Terminate by using INT_MAX

//stdarg.h must be included for this type of function to be declared
#include <stdarg.h>

int total( int first, ... ) {
   int count = 0, sum = 0, i = first;
   va_list marker;

   va_start( marker, first );     /* Initialize variable arguments. */
   while( i != INT_MAX )
   {
      sum  = i;                   //increases the sum
      i = va_arg( marker, int);   //Gets the next argument
   }
   va_end( marker );              // Resets the list
   return sum;
}

C

#include<numeric>

sum = accumulate(coll.begin(),coll.end(),0);

Common Lisp

(reduce #'  list)

Another way:

(apply #'  list)

Assembly

INT_MAX = 2147483647.

sum proc
	mov ecx,DWORD PTR [esp]
	add esp,4
	xor eax,eax
	sum_loop1:
	add eax,DWORD PTR [esp]
	add esp,4
	cmp DWORD PTR [esp],2147483647
	jne sum_loop1
	mov DWORD PTR [esp],ecx
	ret
sum endp

Haskell

sum container

Java

import java.util.*;

public class Total {

    public static int total(int... values) {
        int total = 0;
        for (int i : values) total  = i;       
        return total;
    }

    public static void main(String[] args) {

        System.out.println("Total: %d: ", total(1,2,4,40));
        
    }
}

OCaml

Summing is a special case of folding the addition operator starting with zero:

# let sum = List.fold_left (   ) 0;;
val sum : int list -> int = <fun>

For example:

# sum [1; 2; 4; 40];;
- : int = 47

Perl

<HIGHLIGHTSYNTAX language="perl"> use List::Util qw(sum); sum @arr; </HIGHLIGHTSYNTAX>

Python

A function that sums the values in a sequence is built into python, its name is 'sum'.

if __name__ == '__main__':
  assert sum([1,2,3]) == 6

A parallel to the ANSI C example given above is as follows:

import itertools
def total(*values):
  return sum(itertools.takewhile(sys.maxint.__cmp__, values))

if __name__ == '__main__':
  assert total(1,2,3,sys.maxint) == 6


Ruby

class Array
  def sum;     inject(0) { |s, v| s  = v }; end
end