20
1 Programming in C Concept Outlines Contents Programming Overview ...................................................................................................... 2 C Programming Components .............................................................................................. 3 Selection Structures (if and switch structures).................................................................... 5 Iteration Structures (for loops) ............................................................................................ 6 Iteration Structures (while loops)........................................................................................ 7 Functions ............................................................................................................................. 8 Recursion ............................................................................................................................ 9 Recursion (Recurrence relations and Linear Homogeneity) ............................................. 10 Preprocessor and macros................................................................................................... 11 Arrays and Matrices .......................................................................................................... 12 Pointer Basics.................................................................................................................... 14 Dynamic Memory Allocation ........................................................................................... 15 Files ................................................................................................................................... 17 Basic Structures ................................................................................................................ 19 Structures and Pointers ..................................................................................................... 20

Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

  • Upload
    others

  • View
    21

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

1

Programming in C – Concept Outlines

Contents

Programming Overview ...................................................................................................... 2

C Programming Components .............................................................................................. 3

Selection Structures (if and switch structures) .................................................................... 5

Iteration Structures (for loops) ............................................................................................ 6

Iteration Structures (while loops) ........................................................................................ 7

Functions ............................................................................................................................. 8

Recursion ............................................................................................................................ 9

Recursion (Recurrence relations and Linear Homogeneity) ............................................. 10

Preprocessor and macros................................................................................................... 11

Arrays and Matrices .......................................................................................................... 12

Pointer Basics.................................................................................................................... 14

Dynamic Memory Allocation ........................................................................................... 15

Files ................................................................................................................................... 17

Basic Structures ................................................................................................................ 19

Structures and Pointers ..................................................................................................... 20

Page 2: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

2

Programming in C – Concept Outlines

Programming Overview

Generic Concepts

Application software vs. System software

Language generations

Other languages

Problem solving technique (define, devise, implement, test)

Programming Language

Words and symbols

Rules of the language

Syntax and semantics

Necessary Information

Is computer program required?

Inputs/Outputs

Formulas

Algorithm

C

History

o Bell Telephone Laboratories (1972)

o Dennis Richie (also created Unix)

o A – B – C

ANSI standard

Advantages

o Powerful, flexible, stable

o Popular

o Portable

Program cycle

o Develop algorithm

o Write source code (.c and .h files)

o Link and compile (.exe file)

o Errors (compile, run-time, logic)

Page 3: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

3

Programming in C – Concept Outlines

C Programming Components

main function

drives program flow

first and last statements executed are in main

#include

preprocessor directive

includes additional files in program

program statements

I/O

execute functions

perform calculations

other

functions

block of code that perform specific tasks

discussed in detail later

comments

documentative

stripped out by preprocessor

variables

declaration

o reserve memory

o supply name and type

naming rules

types

o integer

char, short, int, long

o floating-point

float, double

sample program 2_1

constants

#define preprocessor directive

const reserved word

Page 4: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

4

Programming in C – Concept Outlines

basic I/O

printf

o C’s basic output function

scanf

o C’s basic input function

conversion specifiers

o %c, %d, %f, %lf, %s

escape sequences

o \a, \n, \t, \\, \”

sample program 2_2

operators

assignment

mathematical

o unary

pre and post increment and decrement

o binary

+, –, *, /, %

precedence follows standard mathematical order of operations

o compound assignment (operator equals)

sample program 2_3

conditional

o only C ternary operator

o sample program 2_4

Page 5: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

5

Programming in C – Concept Outlines

Selection Structures (if and switch structures)

Structure theorem – any algorithm can be written using some combination of the

following three control structures:

1. Sequence

2. Selection

3. Iteration

More operators

Relational operators and Boolean values

o ==, !, >, >=, <, <=

Evaluation of relational expressions (0 or 1)

Evaluation of integers

Logical

o !, &&, ||

Selection structures

family of ‘if’ statements

o if

o if…else

o nested if

linear

non-linear

o relationship to conditional operator

o sample program 3_1

switch

o sample program 3_2

Page 6: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

6

Programming in C – Concept Outlines

Iteration Structures (for loops)

Structure theorem

Iteration structures – repeated execution of a block of code

for loop basics

o used when the number of iterations is known PRIOR TO loop execution

o syntax

loop control variable

initialization

condition

incrementation

code blocks

arrays

o Declaration

o Initialization

o Referencing elements

sample program 4_1

sample program 4_2

additional for loop concepts

o variable scope

o additional functionality

break

continue

omission of initialization

omission of incrementation (intentional or otherwise…)

o logical operators in a for loop

o commas in a for loop

o nested for loops

sample program 4_3

Page 7: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

7

Programming in C – Concept Outlines

Iteration Structures (while loops)

Structure theorem

Iteration structures – repeated execution of a block of code

while loop basics

o syntax

conditional

code blocks

o used when the number of iterations is unknown PRIOR TO loop execution

sentinel

sample program 5_1

data validation

sample program 5_2

other

do...while

o syntax

conditional

code blocks (required for do…while)

comparing loops

o syntax

o uses

o top checking vs. bottom checking

nested loops

o sample program 5_3

Page 8: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

8

Programming in C – Concept Outlines

Functions

function

uniquely named

independent

may receive or send information

function anatomy

prototype

definition

o header

o body

return type

parameter list

sample program 7_1

functionality

only used if called

o information may be sent in via the parameter list

may have local variables

after code is executed, control returned to calling function

o information may be sent back via a return statement

variable scope

global variables

o generally considered poor structure

local variables – reinitialized with each call

o sample program 7_2

static variables

o maintain value

o default initialization of 0

function calls

resolve to the returned value

can be used wherever the returned datatype is allowed

o printf

o in calculation

o part of a condition

o as parameter to another function

other

Page 9: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

9

Programming in C – Concept Outlines

Recursion

Review of mathematical sequences:

Explicitly defined

Example: ( 1)

32

n

n na

Recursively defined

Example: 1 1 where 4n nb b n b

Recursion in computer science

definition

calls itself

must have at least one base case

4 questions for recursion

what is the base case(s)?

how can problem be defined in terms of a smaller case?

will the base case be reached?

how are the smaller-case solutions used to find the original solution?

Recursive sequence

sample program 9_1 (recursively written)

sample program 9_2 (explicitly written)

Implementation

run-time stack

o duplicate variables

Page 10: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

10

Programming in C – Concept Outlines

Recursion (Recurrence relations and Linear Homogeneity)

Examples

1 1

( 1)3

2

where b 4

n

n n

n na

b b n

Recurrence relation

definition

solving

Linear Homogeneity

identifying linearly homogenous sequence

characteristic function

theorem to solve

Theorem to find an explicit formula which generates the same sequence as a recursive

formula which is linearly homogenous of degree 2:

If the characteristic equation 2

1 2 0x r x r of the recurrence relation

1 1 2 2n n na r a r a has 2 distinct roots 1s and 2s , then 1 2

n n

na us vs (where u and

v depend on initial conditions) is the explicit formula for the sequence.

If the characteristic equation 2

1 2 0x r x r of the recurrence relation

1 1 2 2n n na r a r a has a single root s, then n n

na us vns

(where u and v depend on initial conditions) is the explicit formula for the

sequence.

Example:

Use linear homogeneity to find an explicit sequence that is equivalent to:

1 2 1 22 15 where 3 and 8n n na a a a a

Page 11: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

11

Programming in C – Concept Outlines

Preprocessor and macros

Preprocessor

part of all C compilers

produces modified code based on directives

Directives

#include

o <> for built-in libraries

o “” for user-defined libraries

additional directives used

#ifndef

#endif

see directions linked from CSCI 171 Links and Downloads page

#define

o substitution macro

#define PI 3.14159

o function macro

example: #define HALFOF(value) ((value)/2)

sample program 10_1

common errors

forgetting parenthesis

o example: #define AREA(x, y) (x*y)

placing space after function name

o becomes a substitution macro

o example: #define AREA (x, y) ((x)*(y))

compared to regular functions

no overhead to ‘find’ the function

disadvantages

limited functionality

expanded in code for every call

o Sometimes used to simply indicate something has been defined:

#define _USE_MATH_DEFINES

#include <math.h>

#undef

o opposite effect of #define

Page 12: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

12

Programming in C – Concept Outlines

Arrays and Matrices

matrices

addition

multiplication

multiplication by scalar

transposition

Boolean matrices

o join

o meet

o Boolean product

arrays

declaration and initialization

memory usage

o sizeof function

arrays as arguments to functions

function prototype/definition/call

o sample program 11_1

passing by value

o sample program 11_2

passing by reference

o sample program 11_3

multi–dimensional arrays

number of dimensions = number of subscripts

o no set limit

o increased complexity / decreased performance

declaration and initialization

geometric objects

o numbers stored adjacently

multi–dimensional arrays as parameters to functions

function prototype/definition/call

o sample program 11_4

all dimensions other than the first MUST be provided in prototype and header

o Why?

in an array declared as: int x[5][7]

which element is: x[3][4]?

Page 13: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

13

Programming in C – Concept Outlines

strings

arrays of characters

output

o printf(%s conversion specifier)

o puts

input

o scanf (no & is used)

%s conversion specifier

leave a space before the %s to clear buffer

dangerous because user can enter a string larger than the array

reads up to whitespace

example: scanf(“ %s”, name);

o gets will read a string, but has no length safeguard either

reads up to carriage return

example: gets(name);

o see sample program 11.5 for a solution – use this function anytime a string

is needed from input

Page 14: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

14

Programming in C – Concept Outlines

Pointer Basics

variables

have a data type

have specific location in RAM

o address

& is address operator

&x is read as ‘the address of x’

o can be printed with %p

segment and offset

o can be printed with %d

easier to read

pointers

variables that hold an address

declared using the indirection operator

default initialization should be NULL

using pointers

contents accessed the same way as any other variable

if indirection operator precedes the pointer, it refers to the contents of the

‘pointed to’variable

o indirect access

sample program 12_1

arrays (sometimes called ‘pointer constants’)

array name refers to address of first byte of first element

o location cannot be changed

pointer can reference an array

o array can be traversed via pointer

o pointer arithmetic

adding 1 to a pointer adds the size of the data type in bytes

only adding or subtracting integers is valid

no other arithmetic operations allowed

no floating–point data types

o sample Program 12_2

pointers and functions

like arrays, pointers can be parameters to functions

o sample program 12_3

unlike arrays, pointers can be returned from functions

o more complicated than returning simple data types and many pitfalls

Page 15: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

15

Programming in C – Concept Outlines

Dynamic Memory Allocation

static memory allocation

memory allocation can be determined at compile time

memory is allocated immediately upon program execution

o does not change

o example: int x = 3;

dynamic memory allocation

memory allocated during program execution

o cannot be determined at runtime

functions in stdlib.h library that implement this

o malloc

o calloc

o realloc

o free – deallocation function

malloc function

prototype: void * malloc(int);

o return: address of allocated space (NULL if unable to allocate)

o parameter

number of bytes to allocate

issues with allocation functions

returned values must always be cast to appropriate data type

returned value must always be checked for NULL

sizeof function must be used for portability

o sample program 12_4

memory leaks

o memory that is not de-allocated is lost until program termination

sample program 12_5

free function

prototype: void free(void *);

o parameter

pointer to de-allocate

o function DOES NOT set pointer to NULL (you have to do this manually)

calloc function

prototype: void * calloc(int, int);

o return: address of allocated space (NULL if unable to allocate)

o parameters

number of objects to allocate space for

size of each object

o calloc clears the allocated memory to 0

o sample program 12_6

Page 16: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

16

Programming in C – Concept Outlines

realloc function

prototype: void * realloc (void *, int);

o return: address of allocated space (NULL if unable to allocate)

o parameters

pointer which is to be changed

current values associated with pointer are maintained

any de-allocation will be handled

if pointer is NULL, function behaves like malloc

new size in bytes

if int is 0, function behaves like free

can capture the returned NULL value in the pointer to

avoid having to set it to NULL manually

o sample program 12_7

Page 17: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

17

Programming in C – Concept Outlines

Files

Files and File Streams

types

o text

0 – 255 characters ending in carriage return

can be viewed in text editor

o binary

machine readable (cannot be displayed)

data ‘dumped’ in unchanged format from RAM

rules

o naming conventions dictated by operating system

o file path and name stored in a string

char * file_name = “c:\\temp\\myfile.txt”;

char * file_name = “c:/temp/myfile.txt”;

functions associated with files reside within stdio.h

functions to open and close files

o fopen

parameters

pointer to the file pointer

file name (String)

file mode (String)

o “r” – open for reading (“rb” for binary file)

returns NULL if file cannot be opened

o “w” – open for writing (“wb” for binary file)

creates file if it does not exist

data is erased if file does exist

o “a” – open for appending (“ab” for binary file)

creates file if it does not exist

data is not erased if file does exist

return

NULL if not successful

always check to see if return is NULL, and handle this

appropriately

o fclose

closes a file

parameter – FILE pointer

Page 18: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

18

Programming in C – Concept Outlines

functions associated with output and input to and from text files

o fprintf

text file output

same as printf_s, except first parameter is the FILE pointer

sample program 13_1

o fputs

text file output

same as puts, except second parameter is the FILE pointer

o fscanf

text file input

same as scanf_s, except first parameter is the FILE pointer

sample program 13_2

o fgets

text file input

same as gets, except second parameter is max number of characters

and third parameter is the FILE pointer

detecting end-of-file

o feof

determines if the end-of-file has been reached

parameter

the file in question

sample program 13_5

functions associated with output and input to and from binary files

o fwrite

binary file output

parameters

pointer to data to be written

size of each object to be written

number of objects to be written

FILE pointer

returns the number of objects written

sample program 13_3

o fread

binary file input

parameters

pointer to store the read data

size of each object to be read

number of objects to be read

FILE pointer

returns the number of objects read

sample program 13_4

Page 19: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

19

Programming in C – Concept Outlines

Basic Structures

structure

collection of one or more variables grouped under a single name

o each variable is called a ‘member’

structure members may be:

o simple data type (int, double, etc.)

o array

o pointer

o another structure

when an actual structure has been declared, it is called an ‘instance’

defining a structure

3 ways

o instances immediately declared

no more declaration possible

sample program 14_01

o structure defined and given a name

declarations can be done at anytime

‘struct’ reserved word must be used with declaration

sample program 14_02

o ‘typedef’ compiler token used

most structured approach

declarations done in the same way as other data types

‘struct’ reserved word is not necessary

sample program 14_03

accessing structure members

the dot member operator is used between the instance and member

sample program 14_04

other concepts

array members – sample program 14_05

structure members – sample program 14_06

arrays of structures – sample program 14_07

functions that use structures

o as parameters – sample program 14_08

o as return type – sample program 14_09

Page 20: Programming in C – Concept OutlinesProgramming in C – Concept Outlines Programming Overview Generic Concepts Application software vs. System software Language generations Other

20

Programming in C – Concept Outlines

Structures and Pointers

pointers to structures

declared like any other pointer

accessing members

o dereferencing the pointer and using the dot–member operator

the dot – member operator has precedence over dereferencing

o indirect membership operator (–>)

o sample program 14_10

like all pointers, memory can be allocated to point to multiple structures

o sample program 14_11

structures with pointer members

members declared within the structure definition like any other pointer

o memory for pointer members will be dynamically allocated:

after structure is instantiated

before structure is used

sample program 14_12

pointers to structures with pointer members

assimilation of the ideas above

o memory allocation for structure must occur prior to memory allocation for

members

sample program 14_13

dynamic data structures

linked lists

stacks

queues

trees