[go: up one dir, main page]

0% found this document useful (0 votes)
10 views107 pages

Lecture1-C-Review

Uploaded by

vysl.genc01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views107 pages

Lecture1-C-Review

Uploaded by

vysl.genc01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Review: Algorithms & Programming

Part 1:
Intro, Variables, Operators, Control Structures, Loops

Assoc. Prof. Dr. Fatih ABUT


Software
 The act of designing and perfecting a program is referred to as
programming. More recently, the techniques of design have become
formalized in the study of software engineering.
 Software takes many forms and uses:
 Operating systems
 Application programs
 Editors, word processors
 Email, ftp, communications
 Engineering, Science, Social Science, Finance …..
 Data structures (protocols)
 File systems
Compilers and Linkers
 Machine code is the representation of code that a compiler generates by
processing a source code file.

 Note: Different compilers for different OSs.

 A linker is typically used to generate an executable file by linking object


files together.

 Object files often also contain data for use by the code at runtime,
relocation information, program symbols (names of variables and
functions) for linking and/or debugging purposes, and other debugging
information.
Programming paradigms and languages
 Many different programming languages have been developed
(including only a few):
 C Pascal Modula
 PL/I COBOL Ada SQL
 LISP MirandaSimula Prolog
 Java C++ SmallTalk
 These languages are often grouped into conceptual
paradigms (ways of thinking and planning):
 Procedural Functional Declarative
 Logic Object Oriented ... and others
C is an example of a strongly typed, procedural
programming language.

It is sometimes also called a systems programming


language.
Simple Data types in C
 Only really four basic types:
 char
 int (short, long, long long, unsigned)
Type Size (bytes)
 float
char 1
 double int 4
short 2

 Sizes of these types can vary from long 8


one machine to another! long long 8
float 4
double 8
 No Boolean or String types!

5
Enumerated Types in C
 C provides the enum as a list of named constant integer values (starting a 0
by default)
 Names in enum must be distinct
 Often a better alternative to #define

 Example
enum boolean { FALSE, TRUE };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP,
OCT, NOV, DEC };
enum colors { RED, WHITE, BLACK, YELLOW };

enum boolean bool = TRUE;


enum months my_month = DEC;
enum colors my_color = RED;
Overview of C Operators
+ Addition ! Logical NOT
- Subtraction && Logical AND
* Multiplication || Logical OR
/ Division ~ Bitwise NOT
% Modulus & Bitwise AND
++ Increment | Bitwise OR
-- Decrement << Bitwise Left Shifting
== Equality >> Bitwise Right Shifting
!= Inequality ?: Conditional Selection

Possible categorizations of C operators


Assignment

▪ Unary
 Arithmetic
▪ Binary
 Relational
 Logical
▪ Ternary
 Bitwise
Assignment Operator
 The set equal to symbol is used to denote the concept of assignment of a value to a
variable
 This also means that data is being stored in RAM

 The assignment operator must be used with care and attention to detail
◦ Avoid using = where you intend to perform a comparison for equivalence (equality) using ==
◦ You may use = more than once in a statement

 This may be confusing and should be avoided when it is necessary to assure clarity of codes.

 Coding standards
 X == 5 -> not recommended
 5 == X -> recommended
Arithmetic Operators
 Arithmetic operators are used to express the logic of numerical operations
◦ This logic may depend on data type

 The operators may be grouped as follows:


◦ Addition and Subtraction : + -
◦ Multiplication : *
◦ Integer Division : / %
◦ Floating point Division : /
◦ Auto-Increment and Auto-Decrement
 ++ and --
 Pre- versus Post-
Arithmetic Operators : + - *

 Unary versus Binary


 It is meaningful to say –X (negative X) so C permits use of the minus
symbol (hyphen) as a unary operator. It also permits use of + as unary.
 Ex. A = -3 ;
 Clearly, multiplication (*) of numbers does not make sense as a unary
operator, but we will see later that * does indeed act unarily on a
specific data type
 All operators have typical use as binary operators in arithmetic expression
units of the general form
 Operand1 arith_op Operand2
Arithmetic Operators : ++ --
 A common programming statement involves adding (or subtracting) 1 to
(from) a variable used for counting
 The addition of 1 to an integer variable is called incrementation
 Similarly, subtracting 1 from an integer variable is called decrementation

 The C language supports two operators that automatically generate


increment or decrement statements on integer variables
 Auto-Increment ++
 Auto-Decrement --

 Examples: (Equivalent statements)


Explicit Post-auto Pre-auto
 N = N+1; N++ ; ++N ;
 N = N–1; N-- ; --N ;
Arithmetic Operators : ++ --
 There is a very important difference between using these operators before versus
after a variable symbol

◦ AFTER (POST) :
 If an expression contains N++, the expression is evaluated using the value
stored at the location N. After the expression is evaluated, the value at N is
incremented by 1.

◦ BEFORE (PRE) :
 If an expression contains ++N, the value at N is incremented by 1 and stored
at N, before any other parts of the expression are evaluated. The
expression is then evaluated using the new value at N.
Arithmetic Operators : ++ --
 Assume the declarations with initial values specified
◦ int A, B, N = 4, M = 3 ;

 What are the final values of A, B, N and M ?

◦ A = N++ ;
◦ B = ++M + N-- ; /* watch out ! */
◦ A = --A ;

◦ ANSWER: A=3 B=9 N=4 M=4


Augmented Assignment Operators
 Operator augmentation involves combining two operator symbols to form a new
symbol with extended meaning

 Arithmetic Assignment operators combine the expressiveness of arithmetic and


assignment and permit abbreviation of coding

◦ += and -=
◦ *=
◦ /= and %=
◦ In some cases they may lead to hardware optimization of
executable code.
Augmented Assignment Operators
 Although these operations have a certain kind of elegance, they may create
ambiguity.
◦ However, programmers should ensure that programs have clarity.

◦ Examples:
◦ Longhand Shorthand
 X=X+Y; X += Y ;

 X=X*Y; X *= Y ;

 X=X%Y; X %= Y ;
Relational Operators
 Relational operators are used to express the concept of comparison of two values
◦ Based on the Boolean notions of True and False

 This is vital to decision making logic where we do something – or not – based on


evaluating an expression

◦ while ( Age > 0 ) .....

◦ if ( Num <= 0 ) .....


Relational Operators
 Formally, these operators are defined as

 Equivalence (Equal to) : ==


 Non-equivalance (Not equal to) : !=

 Open Precursor (Less than) : <


 Closed Precursor (Less than or equal to) : <=

 Open Successor (Greater than) : >


 Closed Successor (Greater than or equal to) : >=
Logical Operators
 Boolean Set Theory defines several operations that act on values 0 and 1
◦ These values apply to relational expressions and also integer variables
(limited to these two values)

 Complement (Not) : !
◦ Unary !(X<Y)

 Intersection (And) : &&


◦ Binary ( X < Y ) && ( Age > 20 )

 Union (inclusive Or) : ||


◦ Binary ( X < Y ) || ( Age > 20 )
C has a Ternary Operator ! ?:

 C is one of only a few languages that contains a ternary operator, an operator


that acts on three operands

 This operator is used for simplified expression of decision logic intended to


provide a result

 (A > B ) ? 10 : 20

 If it is true that A > B, the expression evaluates to 10 – otherwise 20.


Expressions
 Complex expressions can be constructed using the various operators
seen so far
 Such expressions must be constructed with care, taking into
account the issue of data type compatibility
 It is also important to avoid ambiguity in how the expression is to
be interpreted (both by the compiler and by the programmer)

 Parentheses ( ) are often used to encapsulate sub-expression terms


 Sub-expressions within parentheses are compiled before other
terms.
Expressions

 When an expression is constructed using parenthesized sub-expressions,


these sub-expressions themselves may be further broken down into
parenthesized sub-sub-expressions

 This is referred to as nesting of expressions


 Innermost nested sub-expressions are evaluated first by compilers
(and during execution)
Expressions

 Example:

 (1+5)*3–(4–2)%3
Expressions

 Example:

 (1+5)*3–(4–2)%3

 (6)*3 - (2)%3

 18 - 2

 16
Expressions
 Example:

 (1+5)* (3–(4–2)/(5–1))%3
Expressions
 Example:

 (1+5)* ( 3–(4–2)/(5–1)) %3

 (6) * ( 3- (2) / (4) )%3

 6 * ( 3 - 0 ) % 3

 6 * 3%3

 18 % 3 = 0
C
Operator
Precedence
Program Control Structures
▪ Decision control
- (Nested) if-else control structures
- (Nested) switch control structure

▪ Repetition control
- While and do-while control structures
- The for control structure
If-Else If-Else Structure
 If Statement is simple, using brace is not a must
 if ( condition )
Statement ;

 If Statement is compound, use braces and indentation

 if ( condition ) {
Statement1 ;
......
StatementN ;
}

 Indentation improves the readability (hence, understanding) of the code for humans.
Many styles exist – use one style consistently in program
code.

Review If ( condition ) {
T_stmts ;
} else {
 Selection: F_stmts ;
}

 if ( condition1 )
T_statement ; /* do when condition1 is True */

 else if ( condition2 )
T_statement ; /* do when condition2 is True */
else
F_statement ; /* do when all previous conds are False
*/

 Once again, if using compound statements, or if placing a simple statement


on a following line, use indentation to improve code readability.
 This is an either-or situation – perform EITHER the True clause OR the False
clause, but not both!
Multiple selection : switch
 Solution using switch :

printf ( “Enter operation code >” ) ;

scanf ( “%d”, &Code ) ;

switch ( Code ) {
case 1 : C = A + B ;
break ;
case 2 : C = A – B ;
break ;
case 3 : C = A * B ;
break ;
case 4 : C = A / B ;
break ;
default : printf ( “Error in input\n” ) ;
break ;
}
If - else if - else switch - case
Nested if-else control
structures

 Problem:
 Enter three integer values
and find out the smallest
one
 All values inputted are
distinct
Repetition Control
 Repetition logic may be of two forms
 Pre-condition testing : enter, or re-enter, the loop body if the
condition is true.
 Post-condition testing : enter the loop body in all cases (performing
the body a minimum of once), then repeat the loop body only if the
condition is true.

 C supports three forms of repetition control structures


 while
 do-while
 for
Repetition : while

 while ( condition_expression )
statement ;
FALSE
cond
 while ( condition_expression ) {
statement1 ; TRUE
......
process
statementN ;
}
Repetition : do-while

 do
statement ;
while ( condition_expression ) ;
process
 do {
statement1 ; TRUE
......
statementN ; cond
} while ( condition_expression ) ;

FALSE
 MUST execute the body (process) at least once!
Repetition : for

 for ( init_stmt ; cond_expr ; update_stmt )


statement ;
INITIALIZE

 for ( init_stmt ; cond_expr ; update_stmt ) {


statement1 ;
...... UPDATE COND
statementN ; F
}
T

PROCESS
Repetition: While and Do While Examples
Repetition: For – Example Note:
Greatest Common Divisor (GCD) for(;;)
Nested if-else and for
control structures

 Problem:
 Check whether an
integer is prime or not
Break and Continue
 C defines two instruction statements that cause immediate, non-sequential
alteration of normal sequential instruction processing

 Break Logic
 Execution of a break ; statement at any location in a loop-structure causes
immediate exit from the loop-structure. Break is also used to exit from a
switch structure.

 Continue Logic
 Execution of a continue ; statement at any location in a loop-structure
causes execution to continue at the beginning of the loop structure (at the
next loop iteration) while skipping the remaining statements.
Break and Continue
 Continue Logic
 Execution of a continue ; statement at any location in a loop-
structure causes execution to continue at the beginning of the loop
structure (at the next loop iteration) while skipping the remaining
statements.

 for ( k = 0 ; k < 5 ; k++ ) {


if ( k == 3 ) continue ;
printf ( “%d, ”, k ) ;
}

 Produces output : ?
Break
 Break Logic
 Execution of a break ; statement at any location in a loop-structure
causes immediate exit from the loop-structure

 for ( k = 0 ; k < 10 ; k++ ) {


if ( k == 5 ) break ;
printf ( “%d, ”, k ) ;
}

 Produces output : ?
Break
 Break Logic
 Execution of a break ; statement at any location in a switch-structure
causes immediate exit from the switch-structure

 switch ( cond ) {
......
Case 53 : Stmt ; .....
break ;
......
}
Break – Example
Least Common Multiple
Review: Algorithms & Programming

Part 2:
Arrays, Structs, Functions, Header Files, Pointers
ARRAYS
▪ An array is a collection of elements of the same type that
are referenced by a common name.
▪ Compared to the basic data type (int, float & char) it is
an aggregate or derived data type.
▪ All the elements of an array occupy a set of contiguous
memory locations.
▪ Why need to use array type?
▪ Consider the following issue:

"We have a list of 1000 students' marks of an


integer type. If using the basic data type (int),
we will declare something like the following…"

int studMark0, studMark1, studMark2, ..., studMark999;

49
ARRAYS
▪ By using an array, we just declare like this,

int studMark[1000];

▪ This will reserve 1000 contiguous memory locations for storing


the students’ marks.
▪ Graphically, this can be depicted as in the following figure.

50
ARRAYS
One Dimensional Array: Declaration

▪ Dimension refers to the array's size, which is how big the


array is.
▪ A single or one dimensional array declaration has the
following form,
array_element_data_type array_name[array_size];

▪ Here, array_element_data_type define the base type of


the array, which is the type of each element in the array.
▪ array_name is any valid C / C++ identifier name that
obeys the same rule for the identifier naming.
▪ array_size defines how many elements the array will hold.
51
ARRAYS
▪ For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
▪ Which can be depicted as follows,

▪ In this statement, the array character can store


up to 30 characters with the first character
occupying location cName[0] and the last
character occupying cName[29].
▪ Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
▪ So, take note the difference between the array
size and subscript/index terms. 52
ARRAYS
▪ Examples of the one-dimensional array declarations,
int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];

▪ The first example declares two arrays named xNum and yNum of type
int. Array xNum can store up to 20 integer numbers while yNum can
store up to 50 numbers.
▪ The second line declares the array fPrice of type float. It can
store up to 10 floating-point values.
▪ fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
▪ The third line declares the array chLetter of type char. It can store a
string up to 69 characters.
▪ Why 69 instead of 70? Remember, a string has a null terminating
character (\0) at the end, so we must reserve for it.
53
ARRAYS
▪ArrayAn array may be initialized at the time of declaration.
Initialization

▪ Initialization of an array may take the following form,


type array_name[size] = {a_list_of_value};

▪ For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0’};

▪ The first line declares an integer array idNum and it immediately assigns the values 1,
2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.

▪ The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1],
and so on.

▪ Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1],
and so on. Note again, for characters we must use the single apostrophe/quote (') to
54
enclose them. Also, the last character in chVowel is NULL character ('\0').
Example #1: Finding the
smallest element in an array

55
Example #2: Finding the second
largest element in an array

56
ARRAYS
Two Dimensional/2D Arrays
▪ A two dimensional array has two subscripts/indexes.
▪ The first subscript refers to the row, and the second, to the column.
▪ Its declaration has the following form,
data_type array_name[1st dimension size][2nd dimension size];

▪ For examples,
int xInteger[3][4];
float matrixNum[20][25];

▪ The first line declares xInteger as an integer array with 3 rows and
4 columns.
▪ Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.

57
ARRAYS
▪ For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for

array_name[x][y];

▪ The array size is = First index x second index = xy.


▪ This also true for other array dimension, for example three-dimensional
array,

array_name[x][y][z]; => First index x second index y third index z


▪ For example,

ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.

▪ And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.

58
AP1 AP2 OOP SWENG

Ahmet 43 31 12 32

Mehmet 66 5 6 7

Ayşe 8 4 10 11

Example
2-dimensional
Array

59
Structs
Definition, Nested Structs, Struct Arrays

60
Structures
 There is no class in C, but we may still want non-homogenous structures
 So, we use the struct construct
 struct for structure

 A struct is a data structure that comprises multiple types, each known as


a member
 each member has its own unique name and a defined type

 Example:
 A student may have members: name (char[ ]), age (int), GPA (float or double),
sex (char), major (char[ ]), etc

61
The struct Definition
 struct is a keyword for defining a structured declaration
 Format:
struct name {
name1 and name2
type1 name1; are members of name
type2 name2;

};

 name represents this structure’s tag and is optional


 we can either provide name
 or after the } we can list variables that will be defined to be this
structure
 We can also use typedef to declare name to be this structure and
use name as if it were a built-in type
 typedef will be covered later in these notes
62
Examples
struct point { struct { struct point {
int x; int x; int x;
int y; int y; int y;
}; } p1, p2; } p1, p2;

struct point p1, p2; p1 and p2 both same as the other


have the defined two versions, but
p1 and p2 are both structure, containing united into one set
points, containing an an x and a y, but of code, p1 and p2
x and a y value do not have a tag have the tag point

For the first and last sets of code, point is a defined tag and can be used later (to
define more points, or to declare a type of parameter, etc) but in the middle code,
there is no tag, so there is no way to reference more examples of this structure

63
Accessing structs
 A struct is much like an array
 The structure stores multiple data
 You can access the individual data, or you can reference the entire structure

 To access a particular member, you use the . operator


 as in student.firstName or p1.x and p1.y

 To access the struct itself, reference it by the variable name


 Legal operations on the struct are assignment, taking its address with &,
copying it, and passing it as a parameter
 p1 = {5, 10}; // same as p1.x = 5; p1.y = 10;
 p1 = p2; // same as p1.x = p2.x; p1.y = p2.y;

64
typedef
 typedef is used to define new types
 The format is
 typedef description name;
 Where description is a current type or a structural description
such as an array declaration or struct declaration
 Examples:

typedef int Length; // Length is now equivalent to the type int

typedef char[10] String; // String is the name of a type for a character array of size 10

typedef struct student { // declares a node structure that contains


int mark [2];
char name [10];
float average;
}aStudent;

aStudent s1; // this allows us to refer to aStudent instead of struct node 65


Functions and Header
Files in C
66
Introduction to Functions
 A complex problem is often easier to solve by dividing it into several
smaller parts (i.e., functions), each of which can be solved by itself.

 main() then uses these functions to solve the original problem.

 Functions separate the concept (what is done) from the


implementation (how it is done).

 Functions make programs easier to understand.

 Functions can be called several times in the same program, allowing


the code to be reused. 67
C Functions
C allows the use of both internal (user-
defined) and external functions.

 External functions (e.g., abs, ceil, floor,


rand, sqrt, etc.) are usually grouped into
specialized headers (e.g., stdlib.h,
math.h, etc.)

68
User-Defined Functions

 C programs usually have the following form:

// include statements
// function prototypes
// main() function
// function definitions

69
Absolute Value
#include <stdio.h>

int absolute (int);// function prototype for absolute()

int main(){
int num, answer;
printf("Enter an integer (0 to stop): “);
scanf(%d, &num);

while (num!=0){
answer = absolute(num);
printf("The absolute value of %d is: %d“, num, answer);
scanf(%d, &num); }
return 0;
}

// Define a function to take absolute value of an integer


int absolute(int x){
if (x >= 0) return x;
70
else return -x;
}
Function Prototype and Definition
 The function prototype
 declares the input and output parameters of the function.
 The function prototype has the following syntax:

<type> <function name>(<type list>);

 Example: A function that returns the absolute value of an integer is:


int absolute(int);

 The function definition


 can be placed anywhere in the program after the function prototypes.
 If a function definition is placed in front of main(), there is no need to
include its function prototype.

71
Absolute Value (alternative)
#include “stdio.h”

// Define a function to take absolute value of an integer


int absolute(int x){
if (x >= 0) return x;
else return -x;
}

int main(){
int num, answer;
printf("Enter an integer (0 to stop): “);
scanf(%d, &num);

while (num!=0){
answer = absolute(num);
printf("The absolute value of %d is: %d“, num, answer);
scanf(%d, &num);
}
return 0;
72
}
Function of three parameters
#include <stdio.h>

double total_second( int hour, double minutes, double second)


{
return hour*3600 + minutes * 60 + second;
}

int main(){
double tot_sec = total_second(1,1.5, 2);
printf(“ %f”,tot_sec);
return 0;
}
73
Arrays as Funtion Parameters
// Program to calculate the average of ages by passing an array to a function

#include <stdio.h>
float average(int age[]);

int main()
{
float avg;
int age[] = {23, 55, 22, 3, 40, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}

float average(int age[])


{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Return Array via Functions
#include <stdio.h>

/* function to generate and return random


/* main function to call above defined function */ numbers */
int main () { int * getRandom( ) {

/* a pointer to an int */ static int r[10];


int *p; int i;
int i;
/* set the seed */
p = getRandom(); srand( (unsigned)time( NULL ) );

for ( i = 0; i < 10; i++ ) { for ( i = 0; i < 10; ++i) {


printf( "*(p + %d) : %d\n", i, *(p + i)); r[i] = rand();
} printf( "r[%d] = %d\n", i, r[i]);
}
return 0;
return r;
}
}
Return Multiple Values via Functions (1)
#include <stdio.h>
#include <math.h> // for sin() and cos()

void getSinCos(double degrees, double &sinOut, double &cosOut)


{
// sin() and cos() take radians, not degrees, so we need to convert
const double pi = 3.14;
double radians = degrees * pi / 180.0;

sinOut = sin(radians);
cosOut = cos(radians);
}

int main()
{
double sin = 0.0;
double cos = 0.0;

getSinCos(30.0, sin, cos);

printf("The sin is %lf\n", sin);


printf("The cos is %lf", cos);

return 0;
}
Return Multiple Values via Functions (2)
#include <stdio.h>

void getAreaCirc(double radius, double &areaOut, double &circumOut)


{
const double pi = 3.14;

areaOut = pi * radius * radius;


circumOut = 2 * pi * radius;
}

int main()
{
double areaOut = 0.0;
double circumOut = 0.0;

getAreaCirc(3.0, areaOut, circumOut);

printf("The area of circle is %f\n", areaOut);


printf("The circum of circle is %f\n", circumOut);

return 0;
}
Structs as Function Parameters and Return Values
 We may pass structs as parameters and functions can return structs
 Passing as a parameter:
 void foo(struct point x, struct point y) {…}
 notice that the parameter type is not just the tag, but
preceded by the reserved word struct

 Returning a struct:
struct point createPoint(int a, int b) Structs differ from arrays as
{ structs are not pointed to!
struct point temp;
temp.x = a;
temp.y = b;
return temp;
}
78
Nested structs
 In order to provide modularity, it is common to use already-defined structs as
members of additional structs
 Recall our point struct, now we want to create a rectangle struct
 the rectangle is defined by its upper left and lower right points

struct point { If we have


int x;
struct rectangle r;
int y;
}
Then we can reference
struct rectangle {
struct point pt1; r.pt1.x, r.pt1.y,
struct point pt2; r.pt2.x and r.pt2.y
}

79
Arrays of structs
 To declare an array of structs (once you have defined the
struct):
 struct rectangle rects[10];
 rects now is a group of 10 structures (that consist each of two points)
 You can initialize the array as normal where each struct is initialized
as a { } list as in {5, 3} for a point or {{5, 3}, {8, 2}} for a rectangle

80
Example
struct point{
int x
int y;
};

struct rectangle {
struct point p1;
struct point p2;
};

void printRect(struct rectangle r)


{
printf("<%d, %d> to <%d, %d>\n", r.p1.x, r.p1.y, r.p2.x, r.p2.y);
}

void main( )
{
int i;
struct rectangle rects[ ] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; // 2 rectangles
for(i=0;i<2;i++) printRect(rects[i]);
81
}
Function Overloading

Criteria for Function


Overloading?

82
Recursive Functions

Recursive Funcs
vs.
Iterations?

83
Header files
 In applications with multiple C programs, function prototypes are typically
provided in header files
 I.e., the ‘.h’ files that programmers include in their code

 Grouped by related functions and features


 To make it easier for developers to understand
 To make it easier for team development
 To make a package that can be used by someone else

 A lot of small C programs, rather than a few large ones


 Each .c file contains closely related functions
 Usually a small number of functions

 Header files to tie them together


84
Example:
Calculate the
permulation and
combination by
using header
files!

85
#include

 #include <foo.h>
 Search the system’s directories in order for a file of the name foo.h
 Directories can be added with ‘-I’ switch to gcc command
 E.g., gcc –I myProject/include foo.c
 Precedes system directories in search order

 #include "foo.h"
 Search the directory where the source program is found first, before -I
and system directories

86
Pointers in C

87
Computer Memory
 Computers store data in memory slots
 Each slot has an unique address
 Variables store their values like this:

Addr Content Addr Content Addr Content Addr Content


1000 i: 37 1001 j: 46 1002 k: 58 1003 m: 74
1004 a[0]: ‘a’ 1005 a[1]: ‘b’ 1006 a[2]: ‘c’ 1007 a[3]: ‘\0’
1008 ptr: 1001 1009 … 1010 1011

88
Addressing Concept

 Pointer stores the address of another entity


 It refers to a memory location

int i = 5;
int *ptr; /* declare a pointer variable */
ptr = &i; /* store address-of i to ptr */
printf(“*ptr = %d\n”, *ptr); /* refer to referee of ptr */

89
What actually ptr is?

 ptr is a variable storing an address


 ptr is NOT storing the actual value of i

int i = 5;
int *ptr;
ptr = &i;
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr);
printf(“ptr = %p\n”, ptr);

90
Twin Operators
 &: Address-of operator
 Get the address of an entity
 e.g. ptr = &j;

Addr Content Addr Content Addr Content Addr Content


1000 i: 40 1001 j: 33 1002 k: 58 1003 m: 74
1004 ptr: 1001 1005 1006 1007

 *: De-reference operator
 Refer to the content of the referee
 e.g. *ptr = 99;

Addr Content Addr Content Addr Content Addr Content


1000 i: 40 1001 j: 99 1002 k: 58 1003 m: 74
1004 ptr: 1001 1005 1006 1007
91
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i;
*ptr = -2;

92
An Illustration
int i = 5, j = 10;
int *ptr; /* declare a pointer-to-integer variable */
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable
*ptr = -2;

93
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr; /* declare a pointer-to-pointer-to-integer variable */
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable
*ptr = -2;
pptr int ** integer pointer pointer variable

Double
Indirection 94
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i; /* store address-of i to ptr */
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable
*ptr int de-reference of ptr 5

95
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr; /* store address-of ptr to pptr */
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*pptr int * de-reference of pptr value of ptr
(address of i)
96
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 3
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr 3

97
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of 7
pptr
98
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of j
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr 10

99
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of j
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of 9
pptr
100
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*pptr int * de-reference of pptr value of ptr
(address of i)
101
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable -2
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr -2

102
Pointer Arithmetic
 What’s ptr + 1?
➔ The next memory location!
 What’s ptr - 1?
➔ The previous memory location!
 What’s ptr * 2 and ptr / 2?
➔ Invalid operations!!!

103
Pass by Value vs. Pass by Reference
 Modify behaviour in argument passing

void f(int j) void f(int *ptr)


{ {
j = 5; *ptr = 5;
} }
void g() void g()
{ {
int i = 3; int i = 3;
f(i); f(&i);
} i = 3? } i = 5?

104
Pointers Example #1
Pointers Example #2
Pointers Example #3

You might also like