You are on page 1of 15

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, mouse
2. Output device – a device that allows the computer to communicate information to the user.
Examples: monitor 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
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.
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.

Figure: Main Components of a Computer


Input Output
Device Device

Figure: A Typical Computer Installation

Keyboard (Display

Floppy Disk / Printer
Flash disk Main


Hard Disk Drive

(secondary memory)


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



Input “Data”
Program of Program



Figure: Compiling
Machineand Running a Program:


Output of
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



Algorithm algorithm
design as a program

Desktop Testing


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. syntax error – occurs during compilation, can be detected by the compiler/computer.
2. run-time error – occurs during run-time, can be detected by the compiler/computer.
3. 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
Int z;
main() Note: 1. Global declarations may consist of:
{ - header declaration
local variables , b,h,area, - constant declaration
statement sequence - type declaration
} - variable declaration
f2() - function prototypes declaration
f1() 2. Every C program has a main function and it
{ is where execution of the program starts.
local variables, a,m,h
statement sequence
statement sequence

local variables
statement sequence

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. Global variable – a variable whose scope is the entire program. Any function in the program have
access to it.
Declare outside of any function
2. 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. character, char (8 bits) - 0 to 255 - %c
2. integer, int (16 bits) - -32768 to 32767 - %d or %i
3. floating point, float (32 bits) - 3.4E-38 to 3.4E+38 - %f
4. double floating point, double (64 bits) - 1.7E-308 to 1.7E+308 = %lf
5. 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 Bit width Range
Char 8 -128 to 127
unsigned char 8 0 to 255
signed char 8 -128 to 127
int 16 -32768 to 32767
unsigned int 16 0 to 65535
signed int 16 -32768 to 32767
short int 16 -32768 to 32767
unsigned short int 16 0 to 65535
signed short int 16 -32768 to 32767
long int 32 -2147483648 to
unsigned long int 32 0 to 4294967295
signed long int 32 -2147483648 to
float 32 3.4E-38 to
double 64 1.7E-308 to
long double 64 1.7E-308 to

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 Format (displays…)
c single char
d decimal
i signed decimal integer
e scientific notation, with exponent
f decimal floating point, without exponent
g uses %e or %f, whichever is shorter, trailing zeros, decimal point will not be displayed.
o octal without leading zero
s string
u unsigned decimal integer
x hexadecimal integer, without leading 0x
% % itself
p 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 g-
type conversion)

Prefix Meaning
digits minimum field-width
.digits number of digits printed at the right of the decimal pt. (precision)
h short data item
l long data item (long int, long unsigned int or double)
L long data item (long double)

SCANF Format Specifiers: %char

Char Format (reads…)
c single char
d signed decimal
i decimal integer, hexadecimal, or octal integer.
e floating-point
f floating-point
g floating-point
h short integer
o octal
s string
u unsigned decimal integer
x 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 Meaning
digits maximum field-width
* value assignment is suppressed
H short data item (short int, or short unsigned int)
l long data item (long int, long unsigned int or double)
L 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>
#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

+ 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.


Data type Conversion

- in case of different types, the result is expressed in the highest precision possible, consistent with the data type of the
Example: float op double = double
float/double/long double op int/char =
float/double/long double


Type Conversion
Syntax: (data type) expression
- the type of the expression is changed to data type.


Unary Operators:
1. - negative
2. -- decrement
3. ++ increment
Note: 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.

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: x=y=3.45;

3. 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: (i<0) ? 0:100 if i=5

Example: (f<g) ?f : g if f =2, g=3
Example: 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: if (expr) <stmt/compound stmt>

2. if-else statement
Syntax: if (expr)
<stmt/compound stmt>
<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

Loop - a programming mechanism or a way of executing a set of 0 or more statements finite times.

3 Control Statements (3 types of Loops):

1. while statement / while loop
while (<conditional expr>)
stmt 1;

Execution Flow of do-while loop:

a) check the cond., if true, execute the loop body and check the cond. again or go back
to a). If the cond. is false the while loop terminates.
b) if cond is initially false, the loop body is never executed.

2. do-while statement / do-while loop

stmt 1;
} while (<conditional expr>);

Execution Flow of do-while loop:

a) execute 1st the loop body and then check the cond., if true execute the loop body
again or go to - repeat a) , if the cond. is false the do-while loop terminates.
b) if cond is initially false, the loop body is never executed.

3. for statement / for loop


for (expr1 ; expr2 ; expr3)

stmt 1;

Execution Flow of for Loop:

a) execute the EXPR1
b} check the cond., if true, execute the loop body, otherwise (if cond is false) for loop terminates.
c) execute EXPR3
d) go back to b)

equivalent to:

while (<expr2>)
stmt 1;

1) Expr1 - initialization, 0 or more statements separated by comma
2) Expr2 - 0 or 1 conditional expression
3) Expr3 - update , 0 or more statements
4) 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.

Disadvantage of label & goto statements:

- confuse the normal flow of the program. (Spaghetti style.)

label - a valid identifier followed by a colon.

- must be in the same function as the goto statement.

goto - a statement which causes a jump to a labeled statement.

Function Declaration:
Syntax: <return_type> <function name> (formal parameter list)
local declarations;

Function Call:
Syntax: <function name>(actual parameter list)

Return Statement
- causes an immediate exit from the function.
- used to return a value.

Two(2) ways a function terminates:

1. When the last statement has been executed and the ending } is encountered.
2. 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();
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. provide a very fast means of referencing array elements.
2. 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>


#include <stdio.h>

struct person
char name[10];
int age;
char gender;
float money;
struct person p;

Collection of variables under structure person: (10 bytes)
p.age (2 bytes)
p.gender (1 byte) (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
 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);