71
CGS 3460 Unix Commands man – manual (man gcc) ls – list directory contents (ls) pwd – prints working directory (pwd) cd – change directory (cd <subdirectory>) mkdir – create directory (mkdir <new directory> rm – remove a file (rm <file to remove>) Use –r if removing a directory

CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

Embed Size (px)

Citation preview

Page 1: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Unix CommandsUnix Commands man – manual (man gcc) ls – list directory contents (ls) pwd – prints working directory (pwd) cd – change directory (cd <subdirectory>) mkdir – create directory (mkdir <new directory> rm – remove a file (rm <file to remove>)

Use –r if removing a directory

Page 2: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Unix Commands(cont)Unix Commands(cont) cp–copy a file (cp <source><destination>)

Use –r if copying a directory mv–move or rename files (mv <source> <destination>) jpico – text editor (jpico <file to edit>) gcc – compiler (gcc sourceFile.c)

-o option Directory shortcuts

~ home directory .. parent directory . sub directory

Page 3: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Declaration of VariablesDeclaration of Variables

type name = initial_value;type name1 = initial_value1, name2 = initial_value2, …;

{int v1, v2, sum;v1 = 50;v2 = 30;sum = v1 + v2;

}

{int v1= 50, v2 = 30, sum;

sum = v1 + v2;}

Page 4: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Summary of Data TypeSummary of Data TypeType Examples Printf

char ‘a’, ‘\n’ %c

_Bool 0, 1 %i, %u

short int 1,100, -5 %hi, %hx, %ho

unsigned short int 1, 39, 100 %hu, %hx, %ho

int -1, 5, 0XAF, 0177 %i, %x, %o

unsigned int 5u, 0XAFu, 0177U %u, %x, %o

long int 0xffffL, 12l %li, %lx, %lo

unsigned long int 0xffffUL, 12ul %lu, %lx, %lo

Page 5: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Summary of Data Type – cont.Summary of Data Type – cont.Type Examples Printf

long long int 0xffffLL, 12ll %lli, %llx, %llo

unsigned long long int 0xffffULL, 12ull %llu, %llx, %llo

float 12.3f, 3.1e-5f, 0x1.5p10

%f, %e, %g

%a

double 12.3, 3.1e-5, 0x1.5p10

%f, %e, %g

%a

long double 12.3l, 3.1e-5l %Lf, %Le, %Lg

Page 6: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Operations for int typeOperations for int type Declaration

int x, y, z;

Assignment y = 10; z = 6;

Calculation Plus: +

• x = y + z; Minus: -

• x = y – z; Multiply: *

• x = y * z; Divide: /

• x = y / z; Modulus

• x = y % z;

result of y/z will be truncated

Page 7: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Operations for float typeOperations for float type Declaration

float x, y, z;

Assignment y = 10.00; z = 5.8;

Calculation Plus: +

• x = y + z; Minus: -

• x = y – z; Multiply: *

• x = y * z; Divide: /

• x = y / z; result of y/z will NOT be truncated

Page 8: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Assignment OperatorsAssignment Operators Join the arithmetic operators

Format: op=

Examples:

count = count + 10; count += 10;

count = count - 5; count -= 5;

a /= b + c; a = a / (b + c);

Page 9: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Unary OperatorsUnary Operators Unary plus / minus

+ / - Example: -a

Unary increment/decrement ++ / --

M = M + 1; M += 1;

++M;

M++;

Page 10: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

PrecedencePrecedenceFIRST

() (3 + 5) * 8

++, -- x++

(Unary) +, - -x * 7

*, /, % 5 * 8

(Binary) +, - 3 + 5

= x = 4

LAST

Page 11: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Operator Return Types (z = x ? y)Operator Return Types (z = x ? y)

x y z

int int int

float float float

int float float

float int float

Page 12: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Getting InputGetting Input Need input from user

scanf• Same format as printf, except put “&” in front of variable names• scanf(“%i”, &count);• “&” means the "address of“

• to store whatever the user enters into the memory address where number is stored

• Leaving out the & will cause your program to work incorrectly!

• Exception: double uses %lf in scanf and %f in printf

Page 13: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

If statementIf statement Consists of keyword if

Followed by condition in parenthesis Followed by the body of the if statement

• This is what is executed if the condition evaluates to true• Body can consist of multiple statements if they are enclosed with { }

Operator Meaning Example

== Equal to var == 10

!= Not equal to var != 10

< Less than var < 10

<= Less than or equal to var <= 10

> Greater than var > 10

>= Greater than or equal to var >= 10

Page 14: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

The if StatementThe if Statement Format

if ( condition )program statement;

orif ( condition ){

program statement(s);}

Condition satisfied?

Program statement

Yes

No

Page 15: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

The if-else StatementThe if-else Statement Format

if ( condition )program statement 1;

else

program statement 2;

Orif ( condition )

{

program statement(s) 1;

}

else

{

program statement(s) 2;

}

Condition satisfied?

Program statement 1

Yes

No

Program statement 2

Page 16: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

The else if StatementThe else if Statement Format

if ( condition1 )

program statement 1;

else if (condition2)

program statement 2;

Flow

Condition 1 satisfied?

Program statement 1

Yes

No

Condition 2 satisfied?

No

Program statement 2

Yes

Page 17: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Logical OperatorsLogical Operators Why

Make a decision based on multiple conditions

What are they

Operator Example Description

|| x < 0 || x > width logical OR

&& x >= 0 && x <= width logical AND

! !(x < 0) Logical NOT

Page 18: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Logical ORLogical OR Returns false only if both

expressions are false Example: (4 > 5 || 6 <= 10) (4 <= 5 || 6 == 10) (4 >= 5 || 6 > 10) (4 < 5 || 6 != 10)

A B A || B

True True True

True False True

False True True

False False False

1101

Page 19: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Logical ANDLogical AND Returns true only if both expressions

are true Examples: (4 > 5 && 6 <= 10) (4 <= 5 && 6 == 10) (4 >= 5 && 6 > 10) (4 < 5 && 6 != 10)

A B A && B

True True True

True False False

False True False

False False False

0001

Page 20: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Logical NOTLogical NOT Inverts the Boolean value of an

expression Example:

_Bool a = 0;

if (!a) {

printf(“a is a false value (0)\n”);

}

a = 1;

if (a) {

printf(“a is a true value (1)\n”);

}

A !A

True False

False True

Page 21: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

The switch StatementThe switch Statement When to use

The value of a variable successively compared against different values

Formatswitch( expression ) {

case value 1: program statement 1; break;

case value 2: program statement 2; break; ׃׃

case value n: program statement n; break;

default : program statement n+1; break;

}

== value 1

evaluate expression

statement 1Y

N

== value 2

== value n

N

Nstatement n+1

Ystatement 2

Ystatement n

Page 22: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

More on switch StatementMore on switch Statementcase value 1:

program statement 1;

case value 2: program statement 2;

break;

== value 1 statement 1Y

N

== value 2

N

Ystatement 2

Page 23: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

for loopfor loop Format: for( init_expression; loop_condition; loop_expression )

{ program statement; }

Flow:

Condition satisfied?

No

Initial Expression

Yes

Program statement

loop expressionloop expression

Page 24: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

ExampleExample If we want to print following pattern*

**

***

****

*****

******

*******

********

*********

**********

Print n stars at the nth line

Print 1 star at the 1st line

Print 2 stars at the 2nd line

Print 3 stars at the 3rd line

Page 25: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

CodeCode#include <stdio.h>

int main(void)

{

int row, col;

for (row = 1; row <= 5; row++)

{

for (col = 1; col <= row; col++)

{

printf("*");

}

}

}

printf("\n");

Page 26: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

while loopwhile loop Format

while (loop_condition) { program statement; }

Flow

Condition satisfied?

Program statement

Yes

No

Page 27: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

for loop vs while loopfor loop vs while loop

Condition satisfied?

No

Initial Expression

Yes

Program statement

loop expressionloop expression

Condition satisfied?

Program statement

Yes

No

for loop while loop

Page 28: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Convert for loop to while loopConvert for loop to while loopwhile (loop_condition) { program statement; }

for( init_expression; loop_condition; loop_expression )

{ program statement; }

program statement; loop_expression;

init_expression;while(loop_condition){

}

Page 29: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

do-while loopdo-while loop Format

do {     program statement } while (loop_condition);

Condition satisfied?

Program statement

YesNo

Page 30: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

while and do-while loopwhile and do-while loop

In while loop, program statement may never be evaluated. While in do-while loop, it is evaluated at least once

Condition satisfied?

Program statement

YesNo

while (loop_condition) { program statement; }

do {     program statement } while (loop_condition);

Condition satisfied?

Program statement

Yes

No

Page 31: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

breakbreak Used to break out of a loop immediately

Possibly due to detection of an error

int i;

for(i=0; i < 3; i++){ printf(“here\n”); break; printf(“there\n”);}

here

Page 32: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

continuecontinue Used to continue at the next point

Possibly due to detection of an error

int i = 0;

for(i=0; i < 3; i++){ printf(“here\n”); continue; printf(“there\n”);}

hereherehere

Page 33: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

ArrayArray What is an array

Data structure that holds a group (list) of homogenous elements of a specific type

• Associate a set of values with a single variable name• All of these values must be of the same data type• Think grades for example

Why? Process a group of values using a loop Consider dealing with grades of 50 students

• Without arrays you would declare 50 variables for each student

Page 34: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

How to DefineHow to Define Declaration

type <var_name>[size];

Example To define an integer array called numbers

of size 5• int numbers[5];

• Compare to normal integer declaration

• Each number is called an element• Indexed from 0 to N-1 (4)

numbers 0

1

2

3

4

Page 35: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

How to UseHow to Use How to refer to an individual

element of an array Accessed by their position in the array,

e.g.• numbers[1] = 2;• Set the element at index 1 of numbers

to 2 Do this for any element (0 – 4)

Operation on element in an array Same as normal variable

numbers[0]

numbers[1]

numbers[2]

numbers[3]

numbers[4]

2

Page 36: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

22

Array ManipulationArray Manipulation

numbers[0]

numbers[1]

numbers[2]

numbers[3]

numbers[4]

12

int first, i;int numbers[5];numbers[0] = 12;numbers[1] = 14;numbers[2] = 6;numbers[3] = 8;numbers[4] = 7;first = numbers[0]; //first becomes 12numbers[1] = numbers[0] + 10; numbers[3] = numbers[0] + numbers[1] + numbers[2]; i = 2; numbers[i] = 50; numbers[i-1] = numbers[i]; numbers[i] = numbers[i] + numbers[i+1];

146

8740

505090

Page 37: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Initializing ArraysInitializing Arrays Initializing an array using a

comma-separated list of values in { }

int number[ ] = { 5, 7, 2 };• Size of an array is automatically

set as the number of elements within { }

numbers[0]

numbers[1]

numbers[2]

572

Page 38: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Initializing ArraysInitializing Arrays Initializing part of an array, and

other numbers will set to 0 int numbers[5] = { 3, 1};

310

numbers[0]

numbers[1]

numbers[2]

numbers[3]

numbers[4]

00

Page 39: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Initializing ArraysInitializing Arrays Initializing part of an array, and

other numbers will set to 0 int numbers[5] = { [0] = 3, [2] = 1};

3

10

numbers[0]

numbers[1]

numbers[2]

numbers[3]

numbers[4]

00

Page 40: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Character ArraysCharacter Arrays You can have an array of characters

char word[ ] = {‘H’,’e’,’l’,’l’,’o’,’!’}

H e l l o !

word[0]

Page 41: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

StringsStrings A sequence of characters delimited by “ “ (not part of the

string) “hello” “Neko” “This is some random sentence that I typed!”

C does not have a string type It uses an array of characters

Array contains a null character (‘\0’) to denote the end of the string

Uses %s to print

Page 42: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Getting String InputGetting String Input Several ways – scanf is simplest but most dangerous Example take input and print it

// demonstrates string input #include <stdio.h>

main () { // variables declaration char name[11]; // get input from user printf ("Your name (10 letters max):\n"); scanf ("%s", &name); printf ("Hello %s \n", name); }

Your name (10 letters max):NekoHello Neko

Page 43: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Declaring and DefiningDeclaring and Defining Declaring a function – must be done before main if used

return_value_type function_name( parameter-list);

How to define a function If you declare the function, you can define it after main If you don’t declare the function you must define it before main

return_value_type function_name( parameter-list)

{

Declarations & Definitions;

Statements;

}

Parameter-list formattype1 variable_name1, type2 variable_name2,…typeN variable_nameN

Page 44: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

ExamplesExamples

Definitionsint main() { …;}

double calcMax(double a, double b) {…;}

Special cases Use void for return_value_type if no value is needed to be returned. Don’t need to put anything for parameter-list if no parameters are

needed to pass to the function (you can add void if you like)

Page 45: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

ArgumentsArguments Arguments:

Specific values for a particular function call Parameters – variables passed in to a function

Exampledouble CalcMax(double a[10]);

The values assigned to the array a are passed to the function at runtime Increase usefulness and flexibility

Page 46: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Function – IIIFunction – III How to return a value in a function

return; // for void return type return expression; // to return the value to expression to the caller

How to call/invoke a function function_name(…);

// for function with no return value variable_name = function_name(…);

// for function with return value

Page 47: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Calculating Area - ExampleCalculating Area - Example Create a function to calculate the area of a rectangle

given its length and width What does it need to calculate the area?

• Length• floating point type

• Width • floating point type

What will it give back• Area

• floating point type

CalcArea( ); length, widthdouble double double

Page 48: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Example: Area Calculation - 1Example: Area Calculation - 1double CalcArea(double height, double width) {

return height * width;}

int main(){

double h, w, area;

printf(“Please input height and width\n”);scanf(“%f, %f”, &h, &w);area = CalcArea(h, w);printf(“The area is %f”, area);

return 0;}

Page 49: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Example: Area Calculation - 2Example: Area Calculation - 2double CalcArea(double height, double width) ;

int main(){

double h, w, area;

printf(“Please input height and width\n”);scanf(“%f, %f”, &h, &w);area = CalcArea(h, w);printf(“The area is %f”, area);

return 0;}

double CalcArea(double height, double width) {

return height * width;}

Page 50: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Pass by ValuePass by Value Passing a copy of the value as an argument

Parameters receive a distinct copy of the caller's arguments, as if the parameters were assigned from the arguments

Changes made to parameters have no effect on the caller’s arguments

Examples:

h = 3; w = 4;

area = CalcArea(h, w);

double CalcArea(double height, double width) { …;}

height = 3, width = 4

3, 4

Page 51: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Local Variables – ILocal Variables – I What is local variables

Variables declared within a function Example:

double CalcMax(double a[10]) {

int i;double maxValue;…;

}int main() {

int i;double a[10]double maxValue;maxValue = CalcMax(a) ;

}

Local variables

Local variables

Page 52: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Local Variables - 3Local Variables - 3#include <stdio.h>

void foo(int x);

int main(){ int x = 3, y = 2;

printf("x1: %i\t\ty1: %i\n", x, y); foo(x); printf("x4: %i\t\ty4: %i\n", x, y); printf("z: %i\n", z);

return 0;}

void foo(int x){ int y = 8, z = 12; printf("x2: %i\t\ty2: %i\t\tz2: %i\n", x, y, z); x = 7; printf("x3: %i\t\ty3: %i\t\tz3: %i\n", x, y, z);}

x1: 3 y1: 2x2: 3 y2: 8 z2: 12x3: 7 y3: 8 z3: 12x4: 3 y4: 2Syntax

Error

Page 53: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Array as Parameters – Example 1Array as Parameters – Example 1#include <stdio.h>

void foo(int x[10]);

int main(){ int x[10] = {[4] = 5, [3]= 4,[2] = 2};

printf("x1: %i\n", x[0]); foo(x); printf("x4: %i\n", x[0]); return 0;}

void foo(int x[10]){ printf("x2: %i\n", x[0]); x[0] = 7; printf("x3: %i\n", x[0]);}

x1: 0x2: 0x3: 7x4: 7

Page 54: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Pass by Reference Pass by Reference Passing the address itself rather than the value

Changes to parameters will affect the caller's arguments as well, for they are the same variable

Used for array, variable address• Use ‘&’ to get the location of a particular variable

Example

int values[100], minVal;

minVal = minimum(values);double minimum(int a[100]) { …;}

values

a

int b, c;

swap(&b, &c);void swap(int *v1, int *v2) { …;}

Page 55: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Automatic and static variablesAutomatic and static variables By default, all variables defined within function are

automatic local variables Static variables

Using keyword static Does not disappear after function call Initialized only once

Page 56: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

ExampleExamplevoid auto_static(void)

{

int autoVar = 1;

static int staticVar = 1;

printf("automatic = %i, static = %i\n", autoVar, staticVar);

autoVar++;

staticVar++;

}

int main()

{

int i;

for(i = 0; i < 5; i++)

auto_static();

return 0;

}

automatic = 1, static = 1automatic = 1, static = 2automatic = 1, static = 3automatic = 1, static = 4automatic = 1, static = 5

Page 57: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Formatting OutputFormatting Output Sometimes you would like your output to have nice

tabular output Conversion specification (%i, %f, etc) allows for

formatting text Format : %[flags][width][.prec][hlL]type

[] mean its optional Only % and type are mandatory

Page 58: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

FlagsFlags

Flag Meaning- Left – justify value

+ Precede value with + or -

(space) Precede positive value with space character

0 Zero fill numbers

# Precede octal value with 0, hexadecimal value with 0x; display decimal point for floats; leave trailing zeroes for g or G format

Page 59: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Width and PrecisionWidth and Precision

Specifier Meaningnumber Minimum size of field

* Take next argument to printf as size of field

.number Minimum number of digits to display for integers; number of decimal places for e or f formats; maximum number of significant digits to display for g; maximum number of characters for s format

.* Take next argument to printf as precision

Page 60: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

DeclarationsDeclarations Three ways

struct date{int day;char

month[10];int year;

};

struct date today;

typedef struct {int day;char

month[10];int year;

} date;

date today;

struct {int day;char

month[10];int year;

} today;

Page 61: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

InitializationInitialization

struct {

int day;

char month[10];

int year;

} today = {15, “June”, 2007};

typedef struct {int day;char month[10];int year;

} date;

date today = {15, “June”, 2007};

struct date{int day;char month[10];int year;

};

struct date today = {15, “June”, 2007};

Page 62: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

How to useHow to use To access the members in the

structure specify the variable name, followed by a

period and the member name• today.day = 15;• today.year = 2007; • today.month[0]=‘J’;• today.month[1]=‘u’;• today.month[2]=‘n’;• today.month[3]=‘e’;• today.month[4]=‘\0’;

OR• today.day = 15;• today.year = 2007; • today.month=“June”;

15

‘J’

‘u’

‘n’

‘e’

‘\0’

2007

.month

.day

.year

today

Page 63: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Main MemoryMain Memory Main memory of computers (also called RAM or Random Access

Memory) is made up of bytes. The number of bytes in a computer with 512 MB of RAM is: 512 *

1024 * 1024 = 5,3687,0912 bytes Each byte in the main memory has a unique binary address that can

be used to refer to it. Earlier computers used to have a 16-bit address. Nowadays, most

computers have a 32-bit (or even 64-bit) addressing system. The range of integers that can be stored in 32 bit address is 0

through 4,294,967,295. Thus, in a 32-bit machine, we can have only 4 GB of addressable main memory (since we can only represent that many bytes with unique addresses)

Page 64: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Addresses in a 4 bit ComputerAddresses in a 4 bit ComputerByte Number Binary Address Hex Equivalent

0 0000 0x0

1 0001 0x1

2 0010 0x2

3 0011 0x3

4 0100 0x4

5 0101 0x5

6 0110 0x6

7 0111 0x7

8 1000 0x8

9 1001 0x9

10 1010 0xA

11 1011 0xB

12 1100 0xC

13 1101 0xD

14 1110 0xE

15 1111 0xF

Page 65: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Pointer variablePointer variable A pointer variable is simply a variable that can be used to

hold memory addresses (location) of another variable. An integer pointer variable can be used to store the

memory address of an integer variable. A char pointer variable can be used to store the memory

address of a character variable. A float pointer variable can be used to store the memory

address of a float type variable.

Page 66: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Declaring a pointer variableDeclaring a pointer variable A pointer variable should be declared before usage.

Declaring an integer pointer variable p: int *p;

* informs the compilier that variable p is a pointer variable.

int tells the compiler that variable p will be used to store memory address of integer variables (i.e. a pointer to an int).

Page 67: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

Initializing a pointer variableInitializing a pointer variable Before we can use a pointer, we should initialize it using the assignment operator. For an integer pointer, we can only assign the address of some other integer variable. The example below assigns the address of integer variable a to the pointer p

main (){ int a = 10; // integer variable initialized to value 10 int *p; // integer pointer p = &a; // store address of a in p }

Page 68: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

What this doesWhat this doesmain (){ int a = 10; // integer variable initialized to value 10 int *p; // integer pointer p = &a; // store address of a in p }

a p

10

Page 69: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

DereferencingDereferencing Pointers store memory addresses. Can access the contents of the memory address stored

in a pointer. (access the value a pointer points to) This is called dereferencing a pointer Done using the operator *

Page 70: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

* Operator* Operator Returns the value stored at an address Place in front of a pointer to return the value stored at the pointers address

int a = 7;

int *p = &a; p 0x7e473d (the location of a) *p 7(the value stored at the location of a) Note that if p is a pointer variable, then *p is an alias for the object to which p

currently points to.

Page 71: CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd

     

CGS 3460

DemonstrationDemonstrationmain () { int a = 10; // integer variable initialized to value 10 int *p1, *p2, *p3; // 3 integer pointers p1 = &a; // store address of a in p1 p2 = p1; // copy value in p1 (address of a) to p2 p3 = p2; // copy value in p2 (address of a) to p3 int c = *p3; // dereference p2 (value of a) and assign it to c printf (" %d %d %d \n", *p1, *p2, c); // output will be 10 10 10 }

1336 13371335

10

a

p2 p3

1557 1843

p1

1445

1336 1336 1336

2032 20332031

10

c10 10 10