Question of The Day: 2D1350 Programeringsparadigm
Question of The Day: 2D1350 Programeringsparadigm
Question of The Day: 2D1350 Programeringsparadigm
2D1350 Programeringsparadigm
n
n
http://www.nada.kth.se/kurser/kth/2D1350/progp02/index.html#period2
n
Labs:
n Game Playing in C (lab description on course webpage)
C-Programming
n
Books
n
n
n
Tutorials
n
n
C Programming Basics
Links
n
n
C-FAQ: http://www.faqs.org/faqs/C-faq
C at Google:
http://www.google.com/Top/Computers/Programming/Languages/C
Structured Programming
n
n
n
n
Function B:
Function C:
local data
local data
local data
global data Y
global data Z
global data X
Variable Declaration
header file
source file
helloworld.c
stdio.h
#include <stdio.h>
compiler
object file helloworld.o
gcc c helloworld.c
gcc o helloworld helloworld.o
linker
helloworld
executable file
int b;
double x;
unsigned int a;
char c;
n C is a typed language that means a variable has a
n name
n type
n C standard types
n int, double, char, float, short, long, long double
n unsigned char, unsigned short, unsigned int,
unsigned long
Primitive Data-Types
integer data-types :
char, short, int, long, unsigned char, unsigned short,
floating point data-types :
float, double, long double
character data-type :
char
character constants in single quotes : a, \n
Primitive Data-Types
Type
char
Low
High
-128
Digits of
Precision
Bytes
127
short
-32768
32767
int
-2147483648
2147483647
long
-2147483648
2147483647
float
3.4x10-38
3.4x1038
double
1.7x10-308
1.7x10308
15
long double
3.4x10-4932
3.4x104932
19
10
Variable Definitions
A declaration introduces a variables name into a
program and specifies its type
A definition is a declaration which also sets asides
memory for that variable (which is usually the case)
In C it is possible to initialize a variable at the same
time it is defined, in the same way one assigns a value
to an already defined variable.
Examples of variable definitions:
int a;
double x = 5.9;
char answer = n;
double y=x;
Comments
comments are always a good thing to use because
not everyone is as smart as you are and needs more
explanation in order to understand your program
you may not be as smart next month when you have
to change your program
comments should clarify your code and explain the
rational behind a group of statements
comment syntax (C style) /* */
/* this is a comment
which can go across multiple
lines of code */
Constants
constants can be specified using the preprocessor
directive #define
example:
#define PI 3.14159
the preprocessor replaces the identifier PI by the text
3.14159 throughout the program
the major drawback of #define is that the data type of
the constant is not specified
the preprocessor merely replaces all occurences of the
string PI with 3.14159
this can be dangerous!! APPLEPIE APPLE3.1459E
convention: reserve CAPITAL letters for constants and use
small caps for variables and functions
Type Conversions
C is a hard-typed language, meaning that each variable has
a fixed type that does not change and which determines the
possible assignments and applicable operators
double pi=3.14;
char c=x;
Some type conversions occur automatically for example int
to float or float to double, but also char to int
int i = 17;
float x = i; /* assigns 17 to x */
int j = 2;
float y = i/j; /* assigns 17/2 = 8 to y not 8.5 */
Type conversions can be forced by a programmer through
a type cast
float z = (float) i / j; /* casts i into float before division */
Library Functions
Header Files
#include myprog.h
compiler
object file
myprog.o
library file
linker
executable file
myprog
libm.a
Input / Output
#include < stdio.h>
int main()
{
int a;
double x;
char c;
printf(Enter integer:);
scanf(%d,&a);
printf(\nEnter double:);
scanf(%lf,&x);
printf(\nEnter character:);
scanf(%c,&c);
printf(\nThe value of a is %d, of x is %lf, of c is %c\n,a,x,c);
}
Input / Output
Input / Output
standard
output
device
stdout
printf(%d,a);
variable a
standard
input
device
stdin
scanf(%d,&a);
variable a
Input / Output
n
n
n
integer %d
long %ld
float %f
double %lf
char %c
string %s
Arithmetic Operators
multiplication, summation, subtraction, division
int i = 1/3; /* integer division result 0 */
float x = 1.0/3; /* floating point division result 0.3333 */
int j = 7 % 3; // modulo operator remainder of 7/3
prefix and postfix-increment operator ++
int i=3;
int j=7;
printf(%d,10 * i++); /* outputs 30, i has value 4 afterwards */
Printf(%d,10 * ++j); /* outputs 80, j has value 8 afterwards */
arithmetic assignment operators
float x=6.0;
x+=3.5;
is equivalent to
x=x+3.5;
Relational Operators
a relational operator compares two values of primitive
in data types such as char, int, float
typical relationships are equal to, less than and greater than
the result of a comparison is either true or false, where 0 is
false and any value different from 0 is true
C provides the following relational operators
<, >, ==, !=, <=, >=
example:
int x=44;
int y=12;
(x == y) /* false */
(x >= y) /* true */
(x != y) /* true */
Relational Operators
n
Loops
a loop causes a section of the program to be repeated
multiple times while the loop condition remains true
C knows three kinds of loops
for loop
while loop
do loop
the for loop repeats a code segment a fixed number of times
the for statement contains three expressions usually
refering to the same loop variable separated by semicolons
for ( i=0; i<15; i++ )
initialization expression
test expression
increment expression
For Loop
For Loop
false
exit
true
body of loop
increment
expression
For Loop
for (i=0; i<10; i++)
n initialization expression : i=0;
the initialization statement is called once when the loop
first starts. It gives the loop variable an initial value.
n Test expression : i<10;
the test statement is called each time through the loop,
the body of the loop is executed as long as the test
statement is true
n Increment expression : i++
The increment expression is called at the end of the
loop and changes the value of the loop variable
#include <stdio.h>
int main()
{
int a;
int i;
a=1;
for (i=0;i<10;i++)
{
printf(2 ^ %d = %d\n,i,a);
a*=2;
}
}
For Loop
#include <stdio.h>
int main()
{
int number;
int i;
long fact;
fact=1;
printf(Enter number:);
scanf(%d,&number);
for (i=number; i>0; i--)
fact*=i;
printf(Factorial of %d is %ld\n,number,fact);
}
While Loop
}
n the body of the loop is executed as long as the test
statement is true (possibly zero times)
do
{
} while (a>b);
n the body of the loop is executed and then repeated as
long as the test statement is true (at least once)
While Loop
test expression
while ( c != y )
{
}
test
expression
true
body of loop
false
exit
#include <stdio.h>
int main()
{
int number;
int i;
long fact
fact=1;
printf(Enter number:);
scanf(%d,&number);
i=number;
while (i>0)
fact*=i--;
printf(Factorial of %d is %ld\n,number,fact);
}
While Loop
the while loop is used when the number of iterations
is unknown before the loop is started
the while loop is repeated as long as the test expression
remains true
Do Loop
do
{ }
while ( c != y );
char c=n;
while ( c != y)
{
printf(Do you want to continue: (y/n)\n);
scanf(%c,&c);
}
test expression
body of loop
test
expression
false
exit
true
Do - While Loop
#include <stdio.h>
int main()
{
i=number;
do
{
fact*=i--;
} while (i>0); /* do not forget the semicolon */
printf(Factorial of %d is %ld\n,number,fact);
}
Do Loop
in the do loop the test expression is evaluated at the
end of the loop, therefore the body is executed at
least once
char c;
do
{
printf(Do you want to continue: (y/n)\n);
scanf(%c,&c);
}
while ( c != y);
10
If Else Statement
if ( x > 100)
{
}
else
{
If Else Statement
test expression
false
test
expression
true
body of if
body of else
int x;
Printf(Enter a number: );
Scanf(%d,&x);
if ( x > 100)
printf(%d is greater than 100\n,x);
else
printf(%d is smaller or equal than 100\n,x);
exit
IfElse Statement
#include <stdio.h>
int main()
{
int a,b;
scanf(%d %d,&a,&b);
if (a>b)
printf(%d is larger than %d\n,a,b);
else
if (a==b)
printf(%d is equal to %d\n,a,b);
else
printf(%d is smaller than %d\n,a,b);
}
IfElse Statement
if (a>b)
{
}
else
{
}
n the if part is executed if the test statement is true,
otherwise the else part is executed.
11
Switch Statement
variable
equals
const 1
Switch Statement
the switch statement is used if there are more than
two alternatives and the decision depends on the value
of the same variable
the switch statement can replace a ladder of multiple
nested if..else statements
true
first case body
false
variable
equals
const 2
false
Logical Operators
true
second case body
default body
exit
switch(<variable>)
{
case <constant1>:
break;
case <constant2>:
break;
default :
12
Switch Statement
Scope of Variables
a block is a section of code delimited by a pair
of brackets { }
a declaration introduces a variable into a scope
( a specific part of program text)
the scope of a variable is the block within which
the variable is declared
a variable declared outside a function is global
a declaration of a variable in an inner block can hide
a declaration in an enclosing block or a global variable
char c;
printf(Enter your choice (a/b/c) : );
Scanf(%c,&c);
switch (c)
{
case a:
printf(You picked a! \n);
break;
case b:
printf(You picked a!\n);
break;
case c:
printf(You picked a!\n);
break;
default:
printf(You picked neither a,b,c ! \n);
}
Scope of Variables
int i;
/* global variable */
visibility of outer i
lifetime of outer i
int main()
{
int i=3; /* local variable */
{
int j=5; /* local variable */
int i=7; /* local i hides outer i */
printf(%d\n i); /* outputs 7 */
} /* end of scope of j and inner i */
printf(%d\n i); /* outputs 3 */
} /* end of scope of outer i */
Functions
a function groups a number of program statements
into a unit and gives it a name
the function can be invoked from other parts of the program
dividing a program into functions is one way to structure
your program (structured programming)
a function declaration specifies the name of the function
the type of the value returned and the number and
type of arguments that must be supplied in a call of
the function
a function definition contains the body of the function
typically function declarations take place in header files (.h)
whereas the function definitions are stored in source
files (.c)
13
Functions
Functions
almost
14
Pointers
n
Pointers
n
int i;
address of i
char c;address of c
short s; address of s
Pointer Variables
A pointer variable is a variable that holds address values
Each data type has its own pointer variable, pointer to
int, pointer to double, pointer to char,
n C uses the address-of operator & to get the address of
an variable
n C uses the indirection or contents-of operator * to
access the value of the variable pointed by
int i=17;
int* ptr; /* defines a pointer variable for integer variables */
ptr= &i; /* assign the address of i to pointer */
printf(the value of i can be printed as %d or %d\n, *ptr, i);
printf(the address of i is %d\n, ptr);
n
n
0x1054
0x1055
0x1056
0x1057
0x1058
0x1059
0x1060
10101011
00001111
10001000
11100011
00111011
10111100
11001100
Pointer Variables
int i;
int *ptr;
ptr=&i;
0x1054
f
o
ss
dre
of
ad
nts
e
t
n
co
17
printf(value of i = %d\n,*ptr);
15
Pointer Variables
int v; // defines variable v of type int
int w; // defines variable w of type int
int *p; // defines variable p of type pointer to int
p=&v; // assigns address of v to pointer p
v=3; // assigns value 3 to v
*p=7; // assigns value 7 to v
p=&w; // assigns address of w to pointer p
*p=12; // assigns value 12 to w
n
Passby-Value
when passing arguments by value, the function creates
new local variables to hold the values of the variable
argument
the value of the original variable are not changed
void f(int val) /* the parameter val holds a local copy of the
variable argument */
{
val++;
}
int x=4;
f(x); /* call function f passing x by value */
printf(x=%d\n,x); /* x still has the value 4 */
Pass-by-Reference
void swap( double* ptr1, double* ptr2)
{
double tmp=*ptr1;
*ptr1=*ptr2; /* de-referencing pointer */
*ptr2=tmp;
}
int main()
{
double a=3.0;
double b=5.0
swap(&a, &b); /* call by reference using the addresses of a and b */
printf(a=%lf, b=%lf \n,a,b);
}
16
Arrays
n
Arrays
double avg(int sz, double array[]); /* function definition*/
double x[5]={1.2, 2.5, 1.7, 4.2, 3.9} /* initialize array */
printf(average is %lf\n,avg(5,x));
double avg(int sz, double array[])
{
int i;
double sum;
for (i=0; i<sz; i++)
sum+=array[i];
return sum/sz;
}
Arrays
int poweroftwo [10]; /*array definition */
int poweroftwo [0]=1; /* first element has index number 0 */
int i;
for (i=1;i<10,i++)
poweroftwo [i]=poweroftwo [i-1]*2;
for (i=0;i<10,i++)
printf(2 ^ %d = %d\n,i,poweroftwo [i]);
Multi-Dimensional Arrays
#define ROWS 5
#define COLS 6
double matrix[ROWS][COLS];
double a[COLS];
double b[ROWS];
int i,j;
for(i=0;i<ROWS,i++)
{
b[i]=0.0;
for(j=0;j<COLS;j++)
b[i]+=matrix[i][j]*a[j];
}
17
BubbleSort
void bsort (double *ptr, int n)
{
int j,k;
for (j=0; j<n-1; j++) /* outer loop */
for(k=j+1; k<n; k++) /* inner loop */
if(*(ptr+j) > *(ptr+k))
swap(ptr+j,ptr+k);
}
double array[6] = { 2.3, 4.5, 1.2, 6.8, 0.8, 4.9 };
bsort(array,n); /* sort the array */
#include <strings.h>
char lastname[256]=Hansen;
char firstname [256]=Ole;
char fullname [512];
strcpy(fullname,firstname );
strcat(fullname , );
strcat(fullname ,lastname );
printf(full name is %s\n,fullname);
Structures
n
18
Makefile
A Makefile is a recipe for how to cook a product
The necessary operations are divided into single steps which partially
depend on each other
n Example: Change a flat tire on a car
Actions:
get_jack, get_spare_tire, lift_car, remove_flat_tire, attach_spare_tire,
lower_car, stow_away_jack, stow_away_flat_tire, drive_away
Dependencies:
lift_car : get_jack
remove_flat_tire : lift_car
attach_spare_tire : get_spare_tire
stow_away_flat_tire : remove_flat_tire
lower_car : attach_spare_tire
stow_away_jack : lower_car
drive_away : stow_away_flat_tire stow_away_jack
n
n
Makefile
Assume you have two source files tools.c and lab1.c
from which you are supposed to create a program a.out
all: a.out
# lab1.o depends on lab1.c and tools.h
lab1.o: lab1.c tools.h
gcc -c lab1.c
#tools.o depends on tools.c and tools.h
tools.o: tools.c mat.h
gcc -c tools.c
# a.out depends on lab1.o, tools.o and libm.a
a.out: lab1.o tools.o
gcc tools.o lab1.o -lm
n
Makefile
# define a variable CC for the name of the compiler
CC=gcc
# define compiler flags for warnings and debugging
CCFLAGS=-Wall -g
# define a variable OBJS for the objects needed to build
the program
OBJS=tools.o lab1.o
# overall target
all: a.out
# explain for all c source files how to build an object file
%.o : %.c
$(CC) $(CCFLAGS) -c $<
a.out: $(OBJS)
$(CC) $(OBJS) -lm
19