Naar inhoud springen

Programmeren in C/Struct

Uit Wikibooks

Programmeren in C

Inleiding
Inleiding Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
De compiler Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007

Bewerkingen

Basis Goed ontwikkeld. Revisiedatum: 23 oktober 2007
Stijl en structuur Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
Datatypes Goed ontwikkeld. Revisiedatum: 11 november 2007
Berekeningen In ontwikkeling. Revisiedatum: 23 oktober 2007
If en loops Goed ontwikkeld. Revisiedatum: 23 oktober 2007
Arrays en pointers Redelijk ontwikkeld. Revisiedatum: 24 oktober 2007
Functies Goed ontwikkeld. Revisiedatum: 23 oktober 2007
File handling In ontwikkeling. Revisiedatum: 23 oktober 2007

Overige

Bestanden Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
C-Preprocessor Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
Struct
Expressies

Het commando "struct" maakt het mogelijk om variabelen te groeperen. Zo is het mogelijk om bijvoorbeeld complexe getallen voor te stellen en er bewerkingen mee uit te voeren (zie voorbeeld hieronder).

#include <stdio.h>
#include <conio.h>

struct complex 
{
int r;
int i;
};

struct complex lees(void);
struct complex som(struct complex a, struct complex b);
struct complex product(struct complex a, struct complex b);
void schrijf(struct complex c);

int main (void)
{
	struct complex c1;
	struct complex c2;
	char d;

	c1 = lees();
	c2 = lees();
	printf("\nSom=\n");
	schrijf(som(c1,c2));
	printf("\nProduct=\n");
	schrijf(product(c1,c2));
	printf("\n");

	d=getch(); /*Pause, zodat je zelf beslist wanneer het venster sluit*/
	return 1;
}

struct complex lees(void)
{
	struct complex c;
	printf("Geef een complex getal (vb. 3+5i)\n");
	scanf("%d+%di",&c.r,&c.i);
	return c;
}
struct complex som(struct complex a, struct complex b)
{
	struct complex c;
	c.r = a.r + b.r;
	c.i = a.i + b.i;
	return c;
}

struct complex product(struct complex a, struct complex b)
{
	struct complex c;
	c.r = a.r*b.r -  a.i*b.i;
	c.i = a.r*b.i +  a.i*b.r;
	return c;
}

void schrijf(struct complex c)
{
	printf(" %d+%di ", c.r, c.i);
}
Informatie afkomstig van Wikibooks NL, een onderdeel van de Wikimedia Foundation.