29
Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Embed Size (px)

Citation preview

Page 1: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Introduction to C

For the participants of Practical Course „Scientific Computing

and Visualization“

Page 2: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Contents Getting Started: the first program

data input and result output compilation and execution

Variables, expressions, types, functions Control program flow

loops, conditional statements Arrays and pointers Standard C libraries Preprocessing Makefiles

Page 3: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Getting started: C Program structure Any C programm consists of

functions variables

Functions consist of

statements (a=b+c, function call, etc.)

Statements includes expressions builtwith operations (for example, arithmetical

expressoins with “+“, “-“, “\“,“*“ )

Page 4: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Getting Started: Input and Output of Data#include <stdio.h>

main(){

int a, b, result;

printf(“Input a,b:\t“);scanf(“%d,%d“,&a,&b);

result=a+b;

printf(“%d plus %d is equal to %d \n“, a,b,result);}

Page 5: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Getting Started: Compilation

In order to execute the programm, compile itwith

gcc filename

The executable file a.out will be produced,start it with:

a.out

Page 6: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Operators and Expressions

in C binary (-,+,*,/,%,&&,||)

x+y; year % 4; b && true

Unary (-,+,*,&)

int a=+2; int *pointer_to_a = &a; int b=-a; int sum = * pointer_to_a + b;

postfix and prefix operators (++,--)

a=2; b=++a; c=a++;

Page 7: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Variables and their Types There are following main types in C :

bool (1 byte) char (1 byte) int (4 bytes) long, short, signed, unsigned int (4, 8 bytes) float (4 bytes) double (8 bytes) void

For example:

bool b=true; long int a; char c =`a`; a = 232334; 971

Memory:

......

reserved for a

Page 8: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Types of Expressions and Casting

The types of single variables schould be declared by programmer:

float f_number = 3.141592; double d_number = 3.14159265358; int i_number=3;

Many operations cause automatic conversions of operands, in order to bring them to common type:

i_number+f_number; -> 6.141592 int -> float

sizeof(f_number + d_number)==8 float -> double

sizeof(f_number + (float)d_number)==4 double -> float

Page 9: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Functions

The function definition in C:

ret_type name (arg_type1 arg_name1, ...,arg_typeN argnameN){ ...}

double parabola(double x) { //declare the new variable, that will be returned return x*x;}

double f0 = parabola(0); double f1 = parabola(1);

Page 10: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Are functions computing arithmetic expressins powerfull enough ?

Now let us try to define the well-known factorial function

in C. This function can be specified as follows:

01

0)1()(

n

nnnfnf

1*...*)1(*)( nnnf

Page 11: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Flow control: Conditional Statement To test logical conditions and make decisions use conditional

statement IF-ELSE:

if (condition){ ... Statemen_block1 ...}else{ ... Statemen_block1 ... }

For example: int f(int n){ if ( n>0 ) return n*f(n-1); else return 1; }

Page 12: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Loops: While and For

for (init; cond; post){ ...} for (i=1; i<=n; i++){

fac=fac*i;}

while (cond){ ...}

while (i<=n){ fac=fac*i; i=i+1; }

int i = 1;int fac = 1;

do{ ...}while (cond)

do{ fac=fac*i; i=i+1; }while (i<=n)

Page 13: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays: Vectors and Matrices

float x[3]={1,3,5};

#include <math.h>;

float vector_norm=sqrt(x[1]*x[1]+x[2]*x[2]+x[3]*x[3]);

float matrix_trace = A[1][1]+A[2][2]+A[3][3];

float A[3][3]={{1,2,3}, {3,2,1}, {5,6,7}};

5

3

1

x

765

123

321

A

Page 14: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays : Strings Strings can be represented in C as arrays of

characters (type char):

For example:

Memory:

o \0leh l

char str[]=“hello“;

int i=0;while(str[i]!=‘\0‘){ printf(“%c\n“, str[i]); i++;}

Page 15: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays: Pointers

o \0leh l

char str[]=“hello“;

int i=0;while(str[i]!=‘\0‘){ printf(“%c\n“, str[i]); i++;}

...str

Page 16: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays: Pointers

while(*str!=‘\0‘){printf(“%c\n“,*(str++));}

o \0leh l...str

Page 17: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Indirection and Address Operators (*, &): Examples

int x=1, y=2, z[10];

int *ip=&x;

y=*ip;

*ip=0;

ip= &z[3];

Page 18: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Indirection and Address Operators (*, &): Examples

void swap (int a, int b){

int tmp=a;

a=b;

b=tmp;

}

swap(a,b); // wrong

Swap(&a,&b); // correct

Page 19: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Multidimensional Arrays: Pointers to Pointers

765

123

321

Afloat A[3][3]={{1,2,3}, {3,2,1}, {5,6,7}};

2 ...321 3A[2] ...A[1]

Page 20: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Multidimensional arrays

2 ...321 3A[2] ...A[1]

for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(“%f “, y[i][j]); } printf(“\n“);}

Page 21: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays: Dynamic Programming

As another example, let us implement the factorial calculation in a more efficient way.

The main idea is to reuse once calculated results.We store them in an array.

Page 22: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Arrays: Dynamic Programming

#include <stdio.h>

// the computed f(n)// will be stored hereint results[10];

main(){ int i;

/* Array initialization: write 0 in each field */ for(i=0; i<10;i++){ results[i]=0; } factorial(3);factorial(4); factorial(10);}

int factorial(int n){

int res=1; for(i=n; i>0; i--) { // has the result been // already computed ?

if(results[i]==0){ res=res*i; results[i]=res;} else return results[i];

}return fac; }

Page 23: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Memory allocation C provides a number of functions

to allocate memory to store data in“stdlib.h“

void *malloc(unsigned int nbytes);

void free(void *ap)

Page 24: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Memory allocation#include<stdlib.h>

int *results;

main(){ results=malloc(100*sizeof(integer));

factorial(3);factorial(44); factorial(100);

free(results);}

Page 25: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Preprocessing File inclusion

#include <filename> #include “filename“

Macro substitutions #define max(A,B) (A)>(B) ? (A):(B) #define CONSTANT = 25

Conditional inclusion #ifndef __HELPER_H__#define __HELPER_H__

...#endif

Page 26: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Standard libraries stdio.h

standard input and output printf, scanf, fprintf, fscanf, fopen, flcose, ...

string.h string processing

Strlen, strcpy, strcat, strcmp, ...

Page 27: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Standard libraries stlib.h

memory allocation, random numbers,type conversion

atof, atoi, rand, alloc, malloc, free

math.h mathematical functions

sin, cos, sqrt, strcmp, remainder,...

Page 28: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Compilation with makefiles Makefiles consist of

macro definitions

rules of compilation

dependences declaration

Page 29: Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“

Compilation with makefiles

CC=gccCFLAGS = -Wall –pedanticOBJ = helper.o init.o boundary.o uvp.o main.o

all: $(OBJ) $(CC) $(CFLAGS) –o sim $(OBJ) –lmclean: rm $(OBJ)

helper.o : helper.hinit.o : helper.h init.h

....