Programmeren in C/Struct

Uit Wikibooks

Programmeren in C

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

Bewerkingen

  1. Basis Goed ontwikkeld. Revisiedatum: 23 oktober 2007
  2. Stijl en structuur Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
  3. Datatypes Goed ontwikkeld. Revisiedatum: 11 november 2007
  4. Berekeningen In ontwikkeling. Revisiedatum: 23 oktober 2007
  5. If en loops Goed ontwikkeld. Revisiedatum: 23 oktober 2007
  6. Arrays en pointers Redelijk ontwikkeld. Revisiedatum: 24 oktober 2007
  7. Functies Goed ontwikkeld. Revisiedatum: 23 oktober 2007
  8. File handling In ontwikkeling. Revisiedatum: 23 oktober 2007

Overige

  1. Bestanden Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
  2. C-Preprocessor (CPP) Redelijk ontwikkeld. Revisiedatum: 23 oktober 2007
  3. Struct
  4. 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 https://nl.wikibooks.org Wikibooks NL.
Wikibooks NL is onderdeel van de wikimediafoundation.