Professional Documents
Culture Documents
marcok@nada.kth.se
Marco Kupiainen
Lecture 3
Selection statements allow the program to select different execution Logical expressions
paths depending on data. There are two selection statements in C: Logical expressions are formulated using (a
Relational operators
Symbol Meaning
< less than
> greater than
Example, computing absx = |x|:
Logical operators
Symbol Meaning
if and switch.
absx = -x;
absx = x;
logical negation
if (x > 0)
!
expression,
|| logical OR
NADA
Marco Kupiainen
marcok@nada.kth.se
NADA
Introductory Course in Scientific Programming Lecture 3 (3) Introductory Course in Scientific Programming Lecture 3 (4)
Introductory Course in Scientific Programming Lecture 3 (7) Introductory Course in Scientific Programming Lecture 3 (8)
do loops
do statement while ( expression ) for loops
do loops are essentially while loops, but the for ( expr1 ; expr2 ; expr3 )
controlling expression is tested after the statement
statement is executed. The syntax of for loops is more complicated
than that of while and do loops, but compilers
Example, do loop written as while loop: will often produce faster executables.
int i=1;
The expressions should be interpreted as
while ( i ) {
follows:
statement
expr1 Executed before starting iteration.
i = expression ;
expr2 Iterate while expression is true.
}
expr3 Executed at end of each iteration
Example, powers of 2 revisited:
int n=0; Example, for loop written as while loop:
int pow=1; expr1 ;
do { while ( expr2 ) {
printf("%3d %3d\n", n, pow); statement
n = n+1; expr3 ;
pow *= 2;; }
} while (pow < 100)
for (n=0,pow=1 ; pow<100 ; n++,pow*=2) Linking The object code is linked with external
printf("%3d %3d\n", n, pow); libraries to produce an executable (gcc, cc,
ld).
A loop can be terminated by using the break Debugging Make sure the program works as expected.
statement within the loop body even if the Correct possible mistakes (gdb).
controlling expression is true. The first step is the most important! By
considering the problem carefully the
debugging time can be significantly reduced.
Introductory Course in Scientific Programming Lecture 3 (11) Introductory Course in Scientific Programming Lecture 3 (12)
Editor emacs, vi
Compiling & linking (cont.)
There are two different C compilers at Nada:
file1.c file2.c file3.c Text files cc (Sun) and gcc (GNU). Both can be used for
preprocessing, compiling and linking small
Preprocessor programs in a single command.
cc, gcc cc, gcc cc, gcc
gcc smallfile.c -o runme generates an
executable runme from the source code in
cc, gcc cc, gcc cc, gcc smallfile.c.
Compiler
The object files are linked with the most
common libraries, including stdio and stdlib.
file1.o file2.o file3.o Object files If compiling a program is tedious (several
different files, many options, different
programming languages, . . . ) it is convinent to
Linker cc, gcc, ld External libraries use makefiles. These will be covered in lecture
9.
a.out Executable