Upload
elmer-porter
View
218
Download
3
Embed Size (px)
Citation preview
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
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 “+“, “-“, “\“,“*“ )
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);}
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
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++;
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
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
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);
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
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; }
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)
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
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++;}
Arrays: Pointers
o \0leh l
char str[]=“hello“;
int i=0;while(str[i]!=‘\0‘){ printf(“%c\n“, str[i]); i++;}
...str
Arrays: Pointers
while(*str!=‘\0‘){printf(“%c\n“,*(str++));}
o \0leh l...str
Indirection and Address Operators (*, &): Examples
int x=1, y=2, z[10];
int *ip=&x;
y=*ip;
*ip=0;
ip= &z[3];
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
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]
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“);}
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.
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; }
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)
Memory allocation#include<stdlib.h>
int *results;
main(){ results=malloc(100*sizeof(integer));
factorial(3);factorial(44); factorial(100);
free(results);}
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
Standard libraries stdio.h
standard input and output printf, scanf, fprintf, fscanf, fopen, flcose, ...
string.h string processing
Strlen, strcpy, strcat, strcmp, ...
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,...
Compilation with makefiles Makefiles consist of
macro definitions
rules of compilation
dependences declaration
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
....