0% found this document useful (0 votes)
28 views29 pages

Module01 ClassNotes

This course introduces modular programming techniques in C, highlighting programming principles, techniques, and dynamic memory allocation. It covers topics like problem solving, data abstraction, pointers, debugging, and dynamic data structures. Students will complete assignments, self-assessments, and an examination to be assessed for the course. C was designed in 1972 for systems programming and the UNIX operating system. It has gained popularity for applications in many fields due to being close to hardware yet supporting structuring.

Uploaded by

Geay Peter
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
28 views29 pages

Module01 ClassNotes

This course introduces modular programming techniques in C, highlighting programming principles, techniques, and dynamic memory allocation. It covers topics like problem solving, data abstraction, pointers, debugging, and dynamic data structures. Students will complete assignments, self-assessments, and an examination to be assessed for the course. C was designed in 1972 for systems programming and the UNIX operating system. It has gained popularity for applications in many fields due to being close to hardware yet supporting structuring.

Uploaded by

Geay Peter
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 29

RCS 210: PROGRAMMING IN C

Module 1 - - Getting Started


“If it wasn't for C, we'd be using BASI,
PASAL and OBOL”
-- anon.
1-1
Course Introduction
• This course assumes you have studied programming for one or
two semesters previously. The broad course aims are to
introduce modular programming techniques using the ANSI/ISO
C programming language, to highlight a range of programming
principles and techniques, and introduce dynamic memory
allocation in C for the the creation and manipulation of dynamic
data structures.
• Programming well requires both knowledge and experience. You
can not hope nor expect to gain the necessary experience by
merely completing the requirements of this course, in the same
way you would not expect attending weekly art classes would
result in you becoming a great artist. Practice is essential!
1-2
Modules / Topics to be covered
• Getting Started • Portability
• Problem Solving • Program Readability
• Functional Abstraction • Program Usability
• Data Abstraction • Generics
• Pointer Types • Code Reusability
• Debugging Techniques • Memory Management
• Managing C Programs • Dynamic Data Structures
• Module Abstraction • Disk File Processing
 
1-3
Assessment for this course
• Course work will consists of assignments and tests. It will cover
40% of your grade
• Three self-assessment tests to be completed individually and
assessed by peers or by yourself. (0%)
• One formal written examination at the end of the semester/study
period (60%) 
• Normally the programming assignments and the formal written
examination should be considered hurdles that must each be
passed in order to pass the course overall.

1-4
A Brief History of C
• Designed by Dennis Ritchie of Bell Laboratories.
• Implemented on PDP-11 in 1972, as a systems programming language
for the UNIX operating system.
• Evolved from B and BCPL
– BCPL = type-less PL developed by Martin Richards (Camb., ’67).
– B was based on BCPL and was written by Ken Thompson in 1970 for the first
UNIX system on a PDP-7.
• C was formed with low-level programming + structured programming
issues in mind.
• C revised by ANSI (X3J11) to form new standard (1989).
• Internationalised and became ANSI/ISO standard in 1990.
• “C99” standard revision finalised in 1999.
1-5
Characteristics of C

• 3GL permitting machine-oriented and problem-oriented


solutions.
• Close to underlying hardware allowing detailed program
control, yet supports advanced program and data structuring.
• Supports modular programming through use of storage-classes
and functions within separate program files.
• Whilst not providing strong typing (ala Pascal, Ada) and array
bound checking, and permitting difficult-to-read code, these
difficulties can be overcome (ANSI C has improved type
checking).
1-6
Applications of C

• C has gained popularity in wide-ranging application areas since


the days it was used solely for low-level (operating systems)
programming.

– AI/Database/Graphics applications.
– Commercial (Business) applications.
– Embedded/Real-time applications.
– Engineering/Scientific applications.

1-7
Getting Started
• We will use these next few C program examples to begin our
study of C, and to highlight the following:

– Function main()
– Simple #define and #include
– Variable declarations
– Functions printf() and scanf()
– Function return from main -- exit()

1-8
#include <stdio.h>
Pre-processor directives
#include <stdlib.h>

int main(void) Function heading and start of block


{
int ass1, ass2, exam;
Variable declarations
float total;
if (scanf("%d%d%d", &ass1, &ass2, &exam) != 3) Data input
{
printf(“Unable to find 3 integers on standard input\n”);
return EXIT_FAILURE;
}
total = ass1 * 0.2 + ass2 * 0.3 + exam * 0.5; Arithmetic expressions
and assignment
printf("Assignment 1 = %3d\n", ass1);
printf("Assignment 2 = %3d\n", ass2); Output
printf("Exam = %3d\n", exam);
printf("Total = %6.2f\n", total);

return EXIT_SUCCESS; Terminate program


1-9
} End of block/function
symbolic constants
#include <stdio.h> [aka pre-processor symbols]
#include <stdlib.h> [aka pseudo-constants]
[aka defined symbols]
#define ASS1_WORTH 20
#define ASS2_WORTH 30 Variable initialisations
#define EXAM_WORTH 50 at declaration time
int main(void)
{
int ass1, ass2, exam, j;
int ass1Sum=0, ass2Sum=0, examSum=0, studentCount=0;
float total, totalSum = 0.0;
char grade;

printf(“\n Line Assignment Scores Exam Total\n”);


printf(“Number 1 2 Score Score\n”);
printf(“====== ================= ====== =====\n”);

(cont’d …) 1-10
while ( scanf("%d%d%d", &ass1, &ass2, &exam) == 3 )
{
studentCount++;

total = ass1 * ASS1_WORTH / 100.0 +


ass2 * ASS2_WORTH / 100.0 +
exam * EXAM_WORTH / 100.0;

if ( total < 50.0 )


grade = 'N';
“Magic Numbers”
else if ( total < 60.0 )
Avoid Them !
grade = 'P';
Use Symbolic Constants !
else if ( total < 70.0 )
grade = 'C';
else if ( total < 80.0 )
grade = 'D';
else
grade = 'H';

(cont’d …)
1-11
printf(" %d %3d %3d %3d %6.2f %c\n",
studentCount, ass1, ass2, exam, total, grade);
ass1Sum += ass1;
ass2Sum += ass2;
examSum += exam;
totalSum += total;
}/* end of while loop */

if ( studentCount == 0 )
printf("\n Empty input file\n");
else
{
printf(" ================ ======= ======\n");
printf("Averages: %6.2f %6.2f %6.2f %6.2f",
ass1Sum / (float) studentCount,
ass2Sum / (float) studentCount,
examSum / (float) studentCount,
totalSum / studentCount );
printf(" Total no. of students = %d\n", studentCount);
}
return EXIT_SUCCESS;
1-12
}
Data Types, Pointers, and Pitfalls
• Variables, types and values
• Type limits and sizeof()
• Type qualifiers
• Expressions and operators
• The (missing) boolean data type
• The ++ and -- operators
• Beware of Side effects
• Order of evaluation
• The pointer data type
1-13
Variables, Types and Values
• a variable is a named memory location where a value can be
stored

• each variable has a type which defines the range of legal values
for that variable

• the pre-defined data types in C are:


int char float double

1-14
Variables, Types and Values

int integer values


3 -6 077 0x3f 3U

char character (typically ASCII) values


‘A’ ‘z’ ‘\n’ ‘\004’ ‘\0’

float real (floating point) numbers


1.0F 273.33f -1.1F 1.1e-02f

double 1.0 273.33 -1.1 1.1e-02

1-15
Type limits and sizeof()

• C does not specify max/min values or the storage space


allocation for any of its types

• the operator sizeof() is defined which evaluates to the no. of


bytes allocated for a variable or type

• type char is always 1 byte (which is assumed to be 8 bits)

• type wchar_t is provided for Unicode et. al.

1-16
Type limits and sizeof()

• nor does C specify the internal representation for data values


e.g. negative numbers, real numbers etc

• limits and internal representations are machine dependent

• libraries <limits.h> and <float.h> have the details of these

1-17
#include <stdio.h>
#include <stdlib.h> Program: to display size of the data types
int main(void)
{
int x;
char c;
float f;
double d;

printf(“Size of type int = %d bytes\n”, sizeof(x));


/* nb. sizeof(int) is fine too ie. a type name */
printf(“Size of type char = %d bytes\n”, sizeof(c));
printf(“Size of type float = %d bytes\n”, sizeof(f));
printf(“Size of type double = %d bytes\n”, sizeof(d));

return EXIT_SUCCESS;
}

1-18
Type qualifiers
C has the following data type qualifiers:
{unsigned} {long | short} int
{signed | unsigned} char
{long} double

the actual effect of these is compiler dependent


– a long int might be larger (more bits) than an int but this is
not guaranteed (it is guaranteed that it won’t be smaller)

1-19
Expressions and operators
• each type has a set of operators for the legal operations that can
be performed in expressions with those types - e.g.

integer arithmetic: + - * / % ++ --
real arithmetic: + - * /
relational: == > < ! || && !=
assignment: =
bit manipulation: ~ ^ | & << >>

NB: this is not a complete list of all the C operators


1-20
Expressions and operators
• strict precedence (and associativity) rules are defined for all
operators (see table in textbook)

• these determine which operands apply to which operators (not


the order of evaluation - see later)

• C is not a strongly typed language - i.e. you can mix types in


the one expression
e.g. charVar = intVar + 2;
potential pitfall - be careful - if in doubt avoid it!
1-21
Expressions and operators - casts
• use casts to force explicit type conversions
(and to remove compiler warnings!)

float x;
int y = 5, z = 10;
x = y / z; /* problem! */
x = (float) y / (float) z; /* solution */

NB: strictly speaking, only one cast is required, which will “promote” the
expression being evaluated to that type
1-22
The (missing) boolean data type
• C (sadly) has no type “boolean”

• achieved in C by using integer values:


zero is interpreted as boolean FALSE
non-zero is interpreted as boolean TRUE

• so the boolean expression:


( A == B )
will evaluate to zero if A and B are not equal
otherwise to some non-zero value (typically 1)
if they are equal
1-23
The ++ and -- operators
• by itself: x++; /* or ++x */ is
equivalent to: x = x + 1;
• But in expressions with more than one operator:
post-increment pre-increment
m = 10; m = 10;
x = m++; x = ++m;

yields: x == 10 x == 11

( the same applies for the pre- and post- decrement operator -- )

1-24
Beware of Side-Effects
• Unexpected and unwanted side-effects can occur when you have
both:
– multiple assignments in the one statement and
– the same variable used more than once

Consider the following:

x = (y = 6) - (s = 3); /* OK */
x = (y *= y) - (s -= y); /* yikes! */
x = y++ + ++y; /* legal but yikes2 !! */
1-25
Order of evaluation
• C does not specify the order of evaluation of sub-expressions
within a statement - e.g. given:
x = (y *= y) - (s -= y);

the compiler could generate code to:


– first evaluate the sub-expression (y *= y)
– and then evaluate the sub-expression (s -= y)
– or vice versa - which would yield a different result!!!
• implementation dependent, undefined, unpredictable ==>
don’t do it!!

1-26
The pointer data type

• there is one other basic data type in C that - we will see - is very
important and characteristic of C
• a pointer variable is a variable that can store a memory address
• a memory address is not just a simple integer
• there are two components to a pointer declaration
– that the variable is a pointer (indicated by a *)
– the type of what it can point to - i.e. the type for the data at
the address the pointer points to

1-27
The pointer data type
• the legal operators with pointers in C are:
– assigning a memory address to a pointer variable
– dereferencing the pointer - i.e. accessing the value that is
stored at the address that the pointer points to
– pointer arithmetic - addition and subtraction only
– comparison operators - e.g. == != > < etc.
• no other operations are legal - nor make sense!
• the pre-defined constant value of NULL can be assigned to a
pointer to indicate that the pointer doesn’t currently contain a
legal address value
1-28
The pointer data type

int x, y;
int *ptr; pointer declaration ptr
x = 2; 230
(238)
ptr = &x; assigning an address
y = *ptr + 3;

y
dereferencing 5
(234)

x 2
NB: this example assumes that an integer is (230)
32 bits (4 bytes) and we have 32 bit (4 byte)
addresses. 1-29

You might also like