16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C Programming – Basics<br />

e.g.<br />

i += 2 adds 2 to i<br />

7. Increment - Decrement Operators {++, --}<br />

a++ is equivalent to a = a+l<br />

++a is equivalent to a = a+l<br />

b = a++ is equivalent to b = a; a = a+l;<br />

b = ++a is equivalent to a = a+l; b = a;<br />

Functions<br />

A function in C is very similar to a function in FORTRAN.<br />

e.g.: a max function<br />

int max(a,b)<br />

/* A function to compute <strong>the</strong> maximum of two<br />

integers */<br />

int a,b ;<br />

{<br />

if a > b<br />

return(a) ;<br />

else<br />

return(b) ;<br />

}<br />

Notes:<br />

- <strong>the</strong> type of <strong>the</strong> function appears first.<br />

- <strong>the</strong>re is no semicolon between <strong>the</strong> function header and <strong>the</strong> formal<br />

- parameter declarations.<br />

- results are passed back using <strong>the</strong> return statement.<br />

- all parameter passing is call by value.<br />

The default type for a function is int and so can be omitted in this case. Even if a function has no parameters its<br />

name must be followed by paren<strong>the</strong>ses,<br />

e.g.<br />

void say_hello()<br />

{<br />

printf ("Hello World\n");<br />

}<br />

Control Structures<br />

! Binary Decision<br />

if (expression)<br />

statement1<br />

else<br />

statement2<br />

Notes:<br />

- <strong>the</strong> expression must be enclosed in paren<strong>the</strong>ses<br />

- <strong>the</strong> expression is considered false if it evaluates to 0 and true, o<strong>the</strong>rwise<br />

- as in Pascal, elses associate <strong>with</strong> <strong>the</strong> nearest ifs<br />

- as <strong>the</strong> semicolon is a terminator in C <strong>the</strong>y will occur before elses<br />

! General Loops<br />

while (expression) statement: provides a pretested loop.<br />

C also provides a for statement which is a useful shorthand for an often occurring while statement form.<br />

These two constructs are equivalent<br />

for (exprl;expr2;expr3) | exprl;<br />

statement;<br />

| while (expr2)<br />

| {<br />

| statement<br />

28

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!