C Programming LECTURE - June2016

advertisement
Computer Fundamentals
Computer - a machine that performs simple tasks according to specific instructions.
Why computers are useful?
Their ability to perform so many simple tasks at such great speed and with such a high degree of accuracy is what
makes computers so useful.
Characteristics of Computers:




Perfect accuracy
Infinite patience
Flawless memory
Unimaginable speed
Program – a set of instructions for a computer to follow(execute).
Software – the collection of programs used by a computer.
Hardware – the physical machines that make up a computer installation.
Main Components of a Computer:
1. Input device - any device that allows a person to communicate information to the computer.
Examples: keyboard, (stdin) mouse
2.
Output device – a device that allows the computer to communicate information to the user.
Examples: monitor (stdout) or CRT (Cathode Ray Tube), printer
3.
Memory - used to store input and to have the equivalent of a scratch paper for performing calculations.
– consists of a long list of numbered locations called words or memory locations. Each memory
location or word contains a string of zeros and ones.
Bit – a digit that assumes only the values zero and one.
Byte – consists of 8 bits.
Word – size of a memory location (varies depending on machine)
Note: The term “32-bit machine” means either the word size is 32 bits or data transfer is 32 bits per machine
cycle
4.
CPU – Central Processing Unit, the brain of the computer.
- the one that follows the instructions in a program and performs the calculations specified by the program.
2 Kinds of Memory in a Computer:
1. Main memory – serves as a temporary memory that is used only while the computer is actually following the
instructions in a program.
- used to store running programs & data of running programs. When power is lost, stored info is lost.
2.
Secondary memory – also called secondary storage or auxiliary storage, used for keeping a permanent record
of information after(and before) the computer is used. (Exs. Floppy disks or diskettes, hard disk.
- used to store program files & data files. When power is lost, stored info is NOT lost.
Figure: Main Components of a Computer
CPU
Output
Device
Input
Device



Figure: A Typical Computer Installation
Monitor
(Display
screen)
Keyboard
Floppy Disk /
Flash disk
CPU
Printer
Main
Memory
Tape
Drive
Hard Disk Drive
(secondary memory)
The Notion of an Algorithm
Algorithm – a set of instructions that leads to a solution, usually written in human (English) language.
Program – an algorithm expressed in a language that the computer can understand.
Programming language – a language that a computer can understand.
Pseudocode – an algorithm written in both human and programming language.
Input – the information that is given to an algorithm/program.
Output – the answers given by an algorithm/program.
Data – input to an algorithm or program.
– any information that is available to an algorithm or to a computer.
Variable – a programming object (container) whose value may change anywhere in a program.
2 Kinds of Algorithms:
1. Partial algorithm – an algorithm that might not end.
Example: Computerized airline reservation/ticketing systems, Automated teller machines (ATMs)
2.
Total algorithm – an algorithm that is guaranteed to end.
2 Kinds of Programming Languages:
1. High level language – resembles a human language
Ex. Pascal, C, Fortran, Lisp, Prolog, etc.
2.
Low level language – the language that a computer can understand.
Ex. Assembly, Machine language
Machine language – the native language of a computer, programs written in this language consists of zeros and ones.
Compiler – a program that translates a high level language to a machine language.
Source program – the input program to a compiler.
Object code or Object program – translated program, output of the compiler.
Operating System – the main systems program on a computer which controls and manages all other programs.
Examples: Windows 95, 98, 2000, NT, Unix, Linux
Figure: Simple View of Running a Program
Program
Data
Computer
Output
Figure: Compiling and Running a Program:
Input “Data”
of Program
Program
Compiler
Computer
Machine language
program
Computer
Output of
Program
2 Phases of Program Design Process:
1. Problem solving phase – its result is an algorithm for solving the problem.
2. Implementation phase – its result is a working program.
Figure: Ideal Program Design Process
Start
Problem
definition
Algorithm
design
Coding
algorithm
as a program
Desktop
testing
Testing
Working
program
Top-down design / Step-wise Refinement / Divide and Conquer
- design an algorithm by breaking down the big task into few subtasks, then decompose each subtasks into smaller
substasks, and so on.
Iterative Enhancement – the process of first designing a simple working (correct) program and then adding features and
refinements later.
Testing & Debugging
Debugging – the process of eliminating bugs from a program.
Bug – a program error.
3 Main Kinds of Programming Errors:
1.
2.
3.
syntax error – occurs during compilation, can be detected by the compiler/computer.
run-time error – occurs during run-time, can be detected by the compiler/computer.
logical error – error in the logic of the program, cannot be detected by the compiler/computer.
Syntax of a programming language – the rules on how to construct a statement/instruction. Refers to the spelling and
grammar of a programming language. Format of programming constructs.
Semantics – refers to the meaning of programming constructs (program statements).
Origin of the C Programming Language
BCPL - older language developed by Martin Richards
B - invented by Ken Thompson
C - invented by Dennis Ritchie in 1970s which was implemented first in Unix operating system at Bells laboratory.
ANSI C - the standard C language created in 1983. ANSI is acronym for American National Standards Institute.
Turbo C - fully implements the ANSI C.
C language - considered as a middle-level language which means that it combines elements of high-level language
with the functionalism of assembly language (low-level language).
- allows the manipulation of bits, bytes, and memory addresses.
- has only 32 keywords (27 original from Ritchie and Kernighan plus 5 from ANSI committee).
- a structured language which means it compartmentalize code and data. Compartmentalization is the
language's ability to section off and hide from the rest of the program all information and instructions
necessary to perform a specific task.
The General Form of a C Program
global declarations
main()
{
local variables
statement sequence
}
f1()
{
local variables
statement sequence
}
f2()
{
local variables
statement sequence
}



fn()
{
local variables
statement sequence
}
Note:
1. Global declarations may consist of:
- header declaration
- constant declaration
- type declaration
- variable declaration
- function prototypes declaration
2. Every C program has a main function and it is
where execution of the program starts.
C Library – a collection of predefined or built-in functions grouped in headers.
- collection of header files.
Note: Each header file contains definitions of predefined or built-in functions belonging to that header file.
Examples of header files:
stdio.h – contains definitions of standard input-output built-in functions such as: printf(), scanf(), getchar(),…
math.h – contains definitions of mathematical built-in functions such as pow(x,y), …
string.h – contains definitions of built-in functions for string manipulations such as strlen(string), …
conio.h – contains definitions of console input output built-in functions
stdlib.h – contains definitions of standard library of built-in functions
2 Types of Variable:
1.
2.
Global variable – a variable whose scope is the entire program. Any function in the program have access to it.
Local variable - a variable whose scope is only the function where it is declared. No other function in the program
have access to it except the function that declares it.
Constant - a programming object whose value is fixed.
Identifiers – the names used to reference variables, constants, functions, labels, and other user-defined objects.

A valid identifier consists of letters, digits, underscore and starts with a letter.
Data Type – a type or category of data. Each variable can hold only one type of data.
5 Atomic Data Types:
1.
2.
3.
4.
5.
character, char (8 bits) - 0 to 255 - %c ‘1’ ‘r’ ‘8’
integer, int (16 bits) - -32768 to 32767 - %d or %i
floating point, float (32 bits) - 3.4E-38 to 3.4E+38 - %f
double floating point, double (64 bits) - 1.7E-308 to 1.7E+308 = %lf
valueless, void (0 bits)
Note: Integers may be of these forms:
decimal, combination of 0..9,
Octal : combination of 0..7 and prefixed by 0.
Hexadecimal : combination of 0..9, A..F, and prefixed by 0x.
character - a single symbol enclosed in single quotes.
ex. 'b' , 'x' , '\0' - null char, marks the end of string.
string - a sequence of characters enclosed in double quotes, terminated by the null char, '\0'.
Example: "hello" , "" - empty string.
Note: ‘a’ is different from “a”
Type Modifiers
(signed, unsigned, long, short)
precede the basic data types

Access Modifiers (const, volatile)
- used to control the ways in which variables may be accessed or modified.
const int a;
const int a = 5;
All Possible Combinations of Turbo C's Basic Types and Modifiers
Type
Char
unsigned char
signed char
int
unsigned int
signed int
short int
unsigned short int
Bit width
8
8
8
16
16
16
16
16
Range
-128 to 127
0 to 255
-128 to 127
-32768 to 32767
0 to 65535
-32768 to 32767
-32768 to 32767
0 to 65535
signed short int
long int
16
32
unsigned long int
signed long int
32
32
float
32
double
64
long double
64
-32768 to 32767
-2147483648 to
2147483647
0 to 4294967295
-2147483648 to
2147483647
3.4E-38 to
3.4E+38
1.7E-308 to
1.7E+308
1.7E-308 to
1.7E+308
Sample Variable Declarations:
short int x;
short x;
long int y;
long y;
float z;
double a;
unsigned int x;
unsigned x;
Conversion Specifications:
%d - print as decimal integer
%6d - print as decimal integer, 6 char wide
%f - print as floating point
%6f - print as floating point, 6 chars wide
%.2f - print as floating point, 2 chars after decimal pt.
%6.2f - print as floating point, 6 chars wide & 2 chars after decimal pt.
Escape Sequences:
\a -alert (bell) character
\b - backspace
\n - newline
\r - carriage return
\t - horizontal tab
\\ - backslash
\? - question mark
\' - single quote
\" - double quote
\000 - octal number
\xhh - hexadecimal number
Data Input/Output: Library Functions
1) printf - writes output to stdout(screen).
Syntax: int printf(char *format, arg1, arg2,..,argn)
Note: Each arg is an output data item which has a corresponding conversion specification in the format string.
2) putchar - writes a character output to stdout.
Syntax: int putchar(int c)
3) putc - writes a character output to stream.
Syntax: int putc(int c, FILE *stream)
4) puts - writes the string s and a newline to stdout.
Syntax: int puts(char *s)
5) scanf - reads input from stdin(keyboard).
Syntax: int scanf(char *format, arg1, arg2,..,argn)
Note: Each arg is an address where the input data item is placed which has a corresponding conversion specification in
the format string.
6) getchar - reads a characrter input from the keyboard.
Syntax: int getchar(void)
7) getch – reads a character without echo
Syntax: int getch(void)
8) getche – reads a character with echo
Syntax: int getche(void)
9) gets - reads a string input from the keyboard.
Syntax: int *gets(char *s)
PRINTF Format Specifiers: %char
Char
c
d
i
e
f
g
o
s
u
x
%
p
Format (displays…)
single char
decimal
signed decimal integer
scientific notation, with exponent
decimal floating point, without exponent
uses %e or %f, whichever is shorter, trailing zeros, decimal point will not be displayed.
octal without leading zero
string
unsigned decimal integer
hexadecimal integer, without leading 0x
% itself
pointer
Flag
Meaning
data item is left-justified
+
sign for signed numerical data item
0
causes leading zeros to appear instead of leading blanks
blank space
blank space will precede each positive signed numerical data item
#
causes octal and hexadecimal data items to be preceded by 0 or 0x respectively(with o- or x-type conversion)
#
causes a decimal point to be present in all floating-pt numbers, even if data item is a whole no. (with e-, f-, or gtype conversion)
Prefix
digits
.digits
h
l
L
Meaning
minimum field-width
number of digits printed at the right of the decimal pt. (precision)
short data item
long data item (long int, long unsigned int or double)
long data item (long double)
SCANF Format Specifiers: %char
Char
c
d
i
e
f
g
h
o
s
u
x
[…]
[^…]
Format (reads…)
single char
signed decimal
decimal integer, hexadecimal, or octal integer.
floating-point
floating-point
floating-point
short integer
octal
string
unsigned decimal integer
hexadecimal integer
data item is a string which include only the characters in the list.
data item is a string which does not include the characters in the list.
Prefix
digits
*
H
l
L
Meaning
maximum field-width
value assignment is suppressed
short data item (short int, or short unsigned int)
long data item (long int, long unsigned int or double)
long data item (long double)
Array - an identifier that refers to a collection of data items whose subscript starts with zero.
ex. char A[10];
/* array of 10 elements A[0] ..A[9] each of which is of char data type. */
3 Classes of Statements in C:
1. expression statement - an expression followed by a semicolon.
2. compound statement - consists of statement enclosed in { }.
3. control statement - used to create special features such as logical tests, loops, and branches.
Constant Declaration
Syntax: #define <identifier> <value>
ex.
#define Max 20
#define True 1
#define False 0
#define ans 'y'
#define str "jack"
Note: It doesn't end in semicolon since constant declaration is not part of C, a separate C preprocessor translate these lines
to machine language.
Arithmetic Operators & Expressions
Operator:
+
*
/
%
Addition
Subtraction
Multiplication
Division , if the operands are integers, it performs integer division, if one (or both) operand/s is/are float then
the result if float.
Modulus/Remainder. The sign of the 1st operand is the sign of the result.
Note: There is no exponentiation operator available but a predefined or built-in function pow is available.
<Exercises>
Data type Conversion
- in case of different types, the result is expressed in the highest precision possible, consistent with the data type of the
operand.
Example:
float op double = double
float/double/long double op int/char =
float/double/long double
<Exercises>
Type Conversion
Syntax: (data type) expression
- the type of the expression is changed to data type.
<Exercises>
Unary Operators:
1. 2. -3. ++
Note:
negative
decrement
increment
decrement/increment - if the operator precedes the operand then the value is altered first before it's used,
otherwise, the value is used first before it's altered.
4. sizeof
returns the size of its operand in bytes,
operand may be a cast or an expression.
<Exercises>
Relational Operators
< , <= , > , >= , == , !=
Logical Operators
&& , || , !
Assignment Operators
1.
Single Assignment:
Syntax: <identifier> = <expression>
2.
Multiple Assignment: assignment is right to left.
Syntax: <identifier 1> = <identifier 2>=…=<identifier n>= <expression>
Example:
3.
x=y=3.45;
a=b=c=d=1;
Syntax: <expression 1> <operator>= <expression2>
Example:
x += 2 equiv. x=x+2
i += 1 equiv. i=i+1
x *= -2 * (y+z)/3
Conditional Operators
Syntax: <expression1> ? <expression2> : <expression3>
Example:
Example:
Example:
(i<0) ? 0:100
if i=5
(f<g) ?f : g
if f =2, g=3
c+= (a > 0 && a <=10) ? ++a : a/b
Bitwise Operators:
Operator
&
|
^
~
&=
|=
^=
<<
>>
<<=
>>=
Meaning
Bitwise AND
Bitwise Inclusive OR
Bitwise Exclusive OR
Bitwise 1's complement
Compound bitwise AND assignment
Compound bitwise Inclusive OR assignment
Compound bitwise Exclusive OR assignment
Bitwise left shift
Bitwise right shift
Compound bitwise left shift assignment
Compound bitwise right shift assignment
Conditional Expressions:
1.
if statement
Syntax:
2.
if (expr) <stmt/compound stmt>
if-else statement
Syntax:
if (expr)
<stmt/compound stmt>
else
<stmt/compound stmt>
3.
ladderized if-else statement / multi-way decision
Syntax:
if (expr1)
<stmt/compound stmt>
else if (expr 2)
<stmt/compound stmt>
else if (expr 3)
<stmt/compound stmt>
...
else if (expr n)
<stmt/compound stmt>
Switch Statement:
- equivalent to case statement in Pascal language.
Syntax: switch (expr) {
case const-expr : statements
case const-expr : statements
default : statements
}
Control Statements:
1.
while statement / while loop
Syntax:
2.
do-while statement / do-while loop
Syntax:
3.
while (<expr>) <stmt / compound stmt>;
do <stmt / compound stmt> while (<expr>);
for statement / for loop
Syntax:
for (expr1;expr2;expr3) <stmt / compound stmt>
equivalent to:
expr1;
while (<expr2>)
{
<stmt/compound stmt>;
expr3;
}
Note:
1) expr1 and expr3 are assignment statements
2) expr2 is a relational(boolean) expression.
3) if expr2 is omitted, the condition is always TRUE, and so resulting to infinite loop.
break - causes the innermost enclosing loop or switch to be terminated immediately.
 applies to FOR, WHILE, DO loops and switch.
continue - causes the next iteration of the enclosing FOR, WHILE, or DO loops to begin.
- not applicable for SWITCH.
Comma Operator - causes a sequence of operations to be performed. When it is used on the right side of an
assignment statement, the value assigned is the value of the last expression of the comma.
Function Declaration:
<return_type> <function name> (formal parameter list)
{
local declarations;
statements;
}
Syntax:
Function Call:
<function name>(actual parameter list)
Syntax:
Return Statement

causes an immediate exit from the function.
used to return a value.

Two(2) ways a function terminates:
1.
2.
When the last statement has been executed and the ending } is encountered.
When a return statement is encountered.
exit() – a predefined function using the stdlib.h header file which causes immediate termination of the entire program.
Syntax: exit(status) , where status=0 if termination is normal.
Example:
#include <stdlib.h>
main() {
if (!color_card()) exit();
play();
return 0;
}
Pointer Operators: & (ampersand), *(asterisk)
Pointer - the memory address of a variable.
Pointer variable - a variable that is specifically declared to hold a pointer to a value of its specified type.
2 advantages of using Pointers in C:
1.
2.
provide a very fast means of referencing array elements.
allow C functions to modify their calling parameters.
&-
returns the "address of".
- a unary operator that returns the memory address of its operand.
*-
a unary operator that returns "the value of the variable located at the address that follows".
Structure – a collection of variables of any data type that are referenced under one name, providing a convenient means
of keeping related information together.
- also called a conglomerate (heterogeneous) data type.
Syntax: Structure type declaration
struct <tag/type name - optional>
{
<Data type 1> <variable 1>;
<Data type 2> <variable 2>;
} <structure variable list - optional>;
Syntax: Structure variable declaration
struct <tag/type name> <variable list>;
Syntax: To refer to a structure element using the structure variable
<structure variable>  <field/element>
Syntax: To refer to a structure element using the structure pointer
<structure pointer>  <field/element>
Example:
#include <stdio.h>
struct person
{
char name[10];
int age;
char gender;
float money;
};
struct person p;
Collection of variables under structure person:
p.name (10 bytes)
p.age
(2 bytes)
p.gender (1 byte)
p.money (4 bytes)
Total no. of bytes allocated for structure person if 17 bytes.
Array of structure - an array whose elements are structures.
Structure of array – a structure with at least one field/element an array.
Structure of structure (nested structure) – a structure with at least one field/element a structure.
Union – a memory location that is shared by several variables that are of different types.
Syntax: Union type declaration
union <tag/type name - optional>
{
<Data type 1> <variable 1>;
<Data type 2> <variable 2>;
} <structure variable list - optional>;
Syntax: Union variable declaration
union <tag/type name> <variable list>;
Syntax: To refer to a union element using the union variable
<union variable>  <field/element>
Syntax: To refer to a union element using the union pointer
<union pointer>  <field/element>
Typedef – use to define a new data type name for an existing type.
Syntax:
typedef <existing data type> <new name>;
Example: #include <stdio.h>
typedef int wholenum;
wholenum x = 3;
Example: #include <stdio.h>
#define numClients 10
typedef struct
{ float due;
int over_due;
char name[10];
} client; // client is a structure type name, not a structure variable
client clist[numClients];
Enumeration – a set of named integer constants that specifies all the legal values that a variable of its type can have.
Syntax:
enum <tag/type name> { namelist } <variable list – optional>;
enum <tag/type name> <variable list>;
Example: #include <stdio.h>
enum shapes {Circle,Rectangle,Square,Triangle}; //Circle = 0, Rectangle=1,Square=2,Triangle=3
enum shapes s;
Text file – a stream of characters saved permanently as a file.
File pointer

position.


a pointer to information that defines various things about the file, including its name, status, and current
identifies a specific disk file and is used by the stream.
Pointer variable of type FILE.
File System Function Prototypes:
FILE *fopen(char *name, char *mode);
int fclose(FILE *fp);
int putc(int c, FILE * fp);
int getc(FILE *fp);
int fseek(FILE *fp, long num_bytes, int origin);
int fprintf(FILE *fp, char *format_string);
int fscanf(FILE *fp, char *format_string);
int feof(FILE *fp);
int ferror(FILE *fp);
void rewind(FILE *fp);
int remove (char *filename)
char *fgets(char *line, int maxline, FILE *fp);
int fputs(char *line, FILE *fp);
int getw(FILE *fp);
int putw (int n, FILE *fp);
Size_t fread(void *buffer, size_t numbytes, size_t count, FILE *fp);
Size_t fwrite(void *buffer, size_t numbytes, size_t count, FILE *fp);
Download