computer fundamentals & intro to c programming module i
TRANSCRIPT
Computer Fundamentals &
C Programming
Ajit K Nayak, Ph.D.S„O‟A University, Odisha
Module I
Contents
• Introduction to Computers
• Evolution of Computers
• Computer Generations
• Basic Computer
Organization
• Memory Hierarchy
• I/O devices
• Computer Software
• Planning Computer Program
• Computer Languages
• Introduction to C
programming
• Structure of C Programming
• Datatype
• Constant
• Variable
• Expression
• Conditional Expression
• Precedence & order of
evaluation
Introduction• Computer is a fast computing device
• Today‟s Computing refers to computer
supported commercial & scientific
applications.
• Example of computing
– Web services, Control system (missile, vehicular,
household device, Industry) . . .
• Is it comparable to human brain?
– It is fast but not smart!!!
Definitions• A computer is an electronic device that
performs arithmetic & logic operation at a
very high speed
• It is also called a data processor that can
store, process and retrieve data as and
when desired.
Input
(Data)
Process /
Manipulate
Output
(Information)
Evolution (1)• 1642: Blaise Pascal invented “Mechanical
Adding Machine”
• 1671: Baron Gottfried invented “Calculator”
for multiplication
• 1880: “Keyboard machines” designed in
USA
• 1880: Herman Hollerith invented “punched
cards” for input media & is used till late 70s
Evolution (2)• Charles Babbage is considered to be the
father of modern digital computers
– Designed difference engine in 1822
– Designed a fully automatic analytical engine in 1842
for performing basic arithmetic operations
– Established a number of principles that are
fundamental to the design of any digital computer
Well known Early Computers• MARK I computer (1937 - 1944)
– Electro-mechanical calculating device, 50 ft-long x 8 ft-high
– Add: 0.3 sec, mul:4.5 sec
• Atanasoff-Berry Computer (1939-1942)– Electronic machine to solve some mathematical functions
• ENIAC (1943-1946)– All electronic computer 20x40 sqft, add: 200 us, mul: 2000us
• EDVAC (1946-52)– Used stored program concept, instructions & data stored in
binary form
• UNIVAC I (1951)– First digital computer
Generation (I,II)
Generation (III)
Generation (IV)
Generation (V)
Basic Operations• Input
– The process of entering instructions and data to the computer system
• Store– Saving instruction & data to make them available as and when required
for processing
• Process– Performing arithmetic & logic operations on data using corresponding
instructions to produce information
• Output– To produce the information/result of the processing as a printed report or
visual display
• Control– Directing the manner and sequence in which all above operation are
performed
Basic Organization
Input
UnitOutput
Unit
Secondary Storage
Primary Storage
Control Unit
Arithmetic
Logic Unit
Program & DataStorage Unit
Information (Results)
Centarl Processing Unit
(CPU)
Data
Storage (Memory)• Primary Storage
– Used to hold data, ongoing job’s instructions, intermediate results
– Fast in operation
– Small capacity, expensive, volatile
– Ex: RAM, ROM, PROM, EPROM
• Secondary Storage
– Used to store stored program & data
– Slower, large capacity, cheaper, persistent
– Ex: Hard Disk, Magnetic Tape, Floppy, CD, Flash
Memory Hierarchy
Cache
Memory
MainMemory
On-line, Direct-access,
and sequential access secondary
storage such as hard disk
Off-line, Direct-access, and sequential
access secondary storage such as magnetic tape,
floppy disk, zip disk, worm etc
Mass storage device such as tape library, CD etc
CPU• Arithmetic & Logic Unit (ALU)
– Actual execution of the instruction takes place
– Arithmetic Operations like: add, subtract, etc
– Logic Operation: <, >, and, or, etc
• Control Unit (CU)
– Manages & coordinates all other components of a
computer system.
– It acts like a central nervous system of computer
– Ex: It decides when to execute which instruction
Input Devices• Keyboard
• Point & Draw devices
– Mouse, Trackball, Joystick
• Data Scanning Devices
– Image Scanner, OCR, Barcode reader, MICR
• Digitizer
– Used to pictures, maps etc to digital form
• Electronic Card
• Speech Recognition system
Output Device• Monitors
• Printers
• Plotters
• Screen Image Projector
CFCP / Module I / AKN / 19
Basic Terminologies• Hardware
– Physical devices of a computer system
• Software
– A Set of programs
• Program
– Sequence of instructions written using a computer
language to solve a small problem.
• Software Package
– A group of program that solve a specific type of job
CFCP / Module I / AKN / 20
H/W vs. S/W• S/W makes H/W usable
• They are complementary to each other
• Same H/W may perform different jobs using
different S/W
CFCP / Module I / AKN / 21
Types of S/W• System Software
– Are designed to control/manage and extend the
processing capabilities of a computer system.
• Application Software
– Designed to solve a specific problem or to do a
specific task.
CFCP / Module I / AKN / 22
Logical System Architecture
USERS
(Normally interact with the system via the user
interface provided by the application S/W)
APPLICATION SOFTWARE
(Software that do a specific task to solve a
specific problem)
SYSTEM SOFTWARE
(Constitute the operating and
programming environment)
HARDWARE
(Physical
devices/components of a
computer system)
CFCP / Module I / AKN / 23
Program Planning• To write a correct program, a programmer
must write each and every instruction in the
correct sequence
• i.e. it should be ensured that the
instructions are
– Appropriate for the program &
– In the correct sequence
CFCP / Module I / AKN / 24
Algorithm• Also called the ‘program logic’ is a step-by-
step description of how to arrive at solution
of a given problem.
• Algorithm has following characteristics
– Each and every instructions should be precise &
unambiguous
– Each instruction should be executed in finite time.
– After execution of all the instructions, it should
produce the desired result.
CFCP / Module I / AKN / 25
Example 1• Problem
– Mark-sheets of 50 students are available
– Calculate & produce the total number of student passed in ‘first division’
• Solution1. Initialize totalFirstDivision, and totalMarksheetsChecked to
zero.
2. Take the marksheet of next student and check the division.
3. If it is not first division go to step 5
4. Add 1 to totalFirstDivision
5. Add 1 to totalMarksheetsChecked
6. Check if totalMarksheetsChecked = 50 ? If no go to step 2
7. Print totalFirstDivision
8. Stop
CFCP / Module I / AKN / 26
Representation of Algo.• As flowcharts
– Pictorial representation of an algorithm
• As Pseudo code
– Is an imitation of actual computer instruction. i.e. it
written in English language, but looks like a
program.
• As Program
– Represented in the form of a programming language
CFCP / Module I / AKN / 27
Flowcharts
• Terminal– Start or stop
• Processing– Operations like add subtract etc.
• Flow ines– Flow / sequence of operation.
• Connectors– Required if the chart spreads over multiple pages
Terminal Input /
Output
Decision
Processing
Flow Lines
Connectors
CFCP / Module I / AKN / 28
Example Decision
Is I=10?No
Yes
Compare
A & BA>B
A=B
A<B
I = ?
= 0 = 1 = 2 = 3 = 4 = 5 . . .
Two – way
Branching Three – way
Branching
Multi – way
Branching
CFCP / Module I / AKN / 29
Example (1)• Find the % mark secured by a student, given all marks
Start
Read mark
details
Add marks of all
subjects giving total
Percentage =
total / totalSubject
percentage
Stop
CFCP / Module I / AKN / 30
Example (2)• Find the % mark secured by 50 students, given all marks
Start
Read mark details
of one student
Add marks of all
subjects giving total
Counter = 1
Percentage =
total / totalSubject
percentage
Add 1 to
Counter
Is Counter > 50NO
Stopyes
CFCP / Module I / AKN / 31
Flowchart Guidelines• Chart the main logic, then incorporate detail
• Do not chart everything in the chart. A
consistent level of detail to be maintained
• Names used should be prob. Specific
• Crossing of flow lines may be avoided
• Connectors may be leveled
• Construction should be left->right & top-
>bottom
CFCP / Module I / AKN / 32
Flowchart advantages• Better communication
• Proper program documentation
• Efficient coding
• Systematic debugging
• Systematic testing
CFCP / Module I / AKN / 33
Flowchart disadvantages• Very time consuming and laborious to draw
• Difficult to incorporate changes
• No standards available determining the
amount of detail to be produced
CFCP / Module I / AKN / 34
Pseudocode• Program logic is written in an ordinary
natural language
• Also called “Program Design Language” (PDL)
• Basic Logic (control) Structure
– Sequence
• Sequence of execution
– Selection
• Decision (branching)
– Iteration
• Repetition (loop)
CFCP / Module I / AKN / 35
Pseudocode example• Counter = 0
• Read first student record
• DO WHILE counter < 50
– Calculate totalMark
– percentage = totalMark / totalSubject
– Print percentage
– Counter = counter + 1
– IF counter < 49
• Read next student record
– END IF
• ENDDO
CFCP / Module I / AKN / 36
Classification of Languages• Low-level
– Machine Language
– Assembly Language
• High-level Language
CFCP / Module I / AKN / 37
Machine Language• Only language the machine understands directly
• Normally written as a string of binary numbers
• Example
– 000000 00001 00010 00110 00000 100000
– add the registers 1 and 2 and place the result in register 6
• Advantage & Limitation
– Fast execution
– Machine dependent
– Difficult to program or modify the program
– Error prone
CFCP / Module I / AKN / 38
Assembly Language• Uses alphanumeric mnemonic codes for the instructions in
the instruction set
• Needs an assembler (translator) to translate Assembly
language program into equivalent machine language
program.
• Example
– MOV AL, 61h
– Load AL with 97 decimal
• Adv & Limitation
– Easier to understand, code & modify
– Error tracing is easier
– Efficiency of ML
– Machine dependant
– Knowledge of H/W required
CFCP / Module I / AKN / 39
High level Language• Written in English like language with mathematical
symbols & expression.– Ex: FORTRAN, COBOL, PASCAL, BASIC, C, C++,
JAVA, . . .
• Machine independent
• Knowledge of hardware is not needed
• Another software (compiler, interpreter) is needed to translate the code to equivalent machine code.
• For different programs different translator software is required.
• Lower efficiency
• Less flexible to control Hardware resources.
CFCP / Module I / AKN / 40
Translators• Interpreter
– takes one statement of high level language, checks
for syntax error, translates to machine language
instruction and executes it.
– Then it considers the next statement & repeats above
process till the last statement.
• Compiler
– Checks and translates entire source program into
object program and not involved in execution.
CFCP / Module I / AKN / 41
C Programming Language• A General purpose programming language
with low level programming support. (“High-level assembly”)
• Currently, the most commonly-used language for embedded systems
• Very portable: compilers exist for virtually every processor
• Produces efficient code
• Fairly concise
• Structured, strictly-typed, case-sensitive
CFCP / Module I / AKN / 42
History• Developed between 1969 and 1973
along with Unix at AT & T Bell Labs,
USA
• Due mostly to Dennis Ritchie & Brian
Kernighan
• Designed for systems programming
– Operating systems
– Utility programs
– Compilers
– Evolved from B, which evolved from BCPLBrian Kernighan
Denis Ritchi
CFCP / Module I / AKN / 43
Character set• The set of characters which can be used to write a valid
token in C language
– Alphabates (a-z, A-Z)
– Digits (0-9)
– White Spaces (New line, Horizontal Tab, Blank Space)
– Special Characters
~ ! # % ^ & * ( ) _ - + = { } [ ] | \ : ; “ ‘ < > , . / ?
• Tokens
– The smallest element in the C language is the token.
– It may be a single character or a sequence of characters to form a single item.
• Tokens can be:
– Numeric constants, Character constants, String constants
Keywords, Names (identifiers), Operators ,
Punctuation Ex ; : , ‘ “ [ ] { } ( ) ,
CFCP / Module I / AKN / 44
C Keywords (I)• Certain words have a special meaning to
the C compiler.
• They are called reserved words or
keywords.
• We should not try to use these words as
names of variables or function names in a
program.
• The keyword list for C contains 32 words and all small-case letters.
CFCP / Module I / AKN / 45
C Keywords (II)User defined Data types
struct
union
enum
typedef
void
sizeof
Type Qualifier
short
long
signed
unsigned
const
volatile
Control Statements
if
else
do
for
while
break
continue
goto
return
switch
case
default
Datatypes
char
int
float
double
Storage Class
auto
static
extern
register
CFCP / Module I / AKN / 46
First Program in C1./* Filename: hello.c
2. Author: Brian Kernighan & Dennis Ritchie
3. Date written: ?/?/1978
4. Description: This program prints the greeting
5. “Hello, World!”
6. */
7.#include <stdio.h>8.9.void main()10.{11. printf(“Hello, world!\n”);12.}
Preprocessor Directive
Header file
“main” function special:
the entry point
I/O performed by a library function:
Comments
exit point
CFCP / Module I / AKN / 47
Comments (Line 1-6)• A comment is descriptive text used to help a
reader of the program understand its content
• Formal Comments (multiline):
/* Comment ….. */– Used for detailed description of functions or operations (for
our benefit, not compiler’s).
– Can take multiple lines in source file.
• Informal Comments (single line):
// Comment ….. Ends at the end of line– Used for quick comments like:
int temp; // temporary variable for storing // the input value
CFCP / Module I / AKN / 48
Preprocessor (Line 7)• Lines that begin with a # in column 1 are
called preprocessor directives (commands).
# include <stdio.h>
#include directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code.
#define -- define constants and macrosExamples:
#define e 2.7182818
#define pi 3.14159265359
CFCP / Module I / AKN / 49
C Program Structure (I)• Is a function oriented structured
programming language.
– Is a collection of functions.
– It should contain one & only one ‘main’ function and may contain any number of other functions.
– Beginning of main function is the entry point for program execution & end of main function is the exit point of program execution.
CFCP / Module I / AKN / 50
C Program Structure (II)/* Program Detail Comment */
<any global variable & function declarations >
main( )
{
<variable & function declarations & initializations>
<Input Section>
<Program Logic>
<Output Section>
} //end of the program
CFCP / Module I / AKN / 51
C Data Types and Variables• Data types are divided into 3 Category
– Basic data type (primitive data type)
– Derived data type
– User defined data types
• Basic data types: char, int, float, and double
• Variable (or Identifier) declaration syntax
– Data type <variable name>;
• Variable name can be of anything length. sensitive: abc is different from ABC
• Must begin with a letter and the rest can be letters, digits, and underscores.
CFCP / Module I / AKN / 52
Variable & Constants (I)• Integer variables: int a, b ;
• Integer constants: 1, 2, 3, . . .
• Integer variables, like a or b, store only whole
numbers like 3 or 7, not 3.33 or 7.65, and only up
to certain maximum values.
• Floating point variables: float c, d ;
• Floating point constants: 23.178, 0.34, . . .
• Floating point variables, like c or d, store rational
numbers, like 3.14159, but only a limited number
of digits of precision.
CFCP / Module I / AKN / 53
Variable & Constants(II)• double variables: double a, b ;
– Same as float but higher precession
• character variables: char a, b ;
• character constants: „a‟, „b‟, „\n‟,. . . ;
– Stored as an integer. (0-255). i.e. each character
const. is mapped to one integer of the above range
CFCP / Module I / AKN / 54
Basic Definitions• The type of an variable (object) determines the
set of values it can have and what operations can
be performed on it. Where
– set of values is finite
– When declaring a new variable and assigning a type for it,
you have to keep in mind the values and operations you'll be
needing.
• An operator computes new values out of old ones.
• An expression consists of variables, constants,
and operators combined to perform some useful
computation.
CFCP / Module I / AKN / 55
Datatypes• Normally Data types are divided into
following Categories
– Basic data type (primitive data type)• char, int, float, double
– Derived data type• array, pointer
– User defined data types• structure, union, enum
– A Special type• void
CFCP / Module I / AKN / 56
Basic Datatypes• Only 4 basic data types in C.
• char: a character, a single byte storage.
– how the computer stores characters?
– uses a character set, which is simply a mapping
between some set of characters and some set of
integers called ASCII character set,
– letter ‘A’ is represented by the code 65, ‘1’ is
represented by the code 49 etc.
– Number of characters possible?
CFCP / Module I / AKN / 57
Basic Types• int: an integer, reflects the natural size of integers
in the host machine– Find the size of storage & hence the range of vaules in your
machine
• float: a single precision floating-point number.– Find the storage size.
• double: a double-precision floating-point number– with more precision and perhaps greater range than float
– Find the storage size
• Qualifiers: may be used with basic types to increase/decrease the normal storage size. – long, short (int, double), signed, unsigned (char, int).
CFCP / Module I / AKN / 58
Constants (Integer)• A constant is just an immediate, absolute value
found in an expression.
• Decimal integer constants: 0, 1, 2, 123 .
• Octal integer:(0 used as prefix) 0144
• Hexadecimal integer const: (0x prefix)
• the constants 100, 0144, and 0x64 all represent
the same number.
• However, The compiler doesn't care; it always
converts everything into binary internally, anyway.
• A constant can be forced to be of type long int by
suffixing it with the letter L (upper or lower case)
CFCP / Module I / AKN / 59
Constants (Floating Point)• Floating point constant:
– 3.14, 10., .01, 123e4, 123.456e7 .
– The e indicates multiplication by a power of 10;
123.456e7 is 123.456 times 10 to the 7th, or
1,234,560,000.
– Floating-point constants are of type double by
default.
CFCP / Module I / AKN / 60
Constants (char & String)• Character constants: represented in single quote
– ‘A’, ‘f’, ‘t’
– May contain multiple symbols with escape char: ‘\n’, ‘\t’ etc.
• String constants. a string is a set of zero or more
characters;
– enclosed in double quotes: "apple", "hello, world", "this is a
test"
– a string containing one character is distinct from a lone
character?.
– A string is represented in C as a sequence or array of
characters.
CFCP / Module I / AKN / 61
Variable (I)• A variable is a place you can store a value. So
that you can refer to it unambiguously, a variable
needs a name.
• A declaration tells the compiler, the name and
type of a variable you'll be using in your program.
• In its simplest form, a declaration consists of
– the type, the name of the variable, and a terminating
semicolon (;)
– char c; int i; float f;
• Several variables of the same type may be
declared with separating coma in one declaration
– int age, rollNumber;
CFCP / Module I / AKN / 62
Variable (II)• A declaration for a variable can also contain an
initial value.
– This initializer consists of an equal sign and an expression,
which is usually a single constant:
– int i = 1; int a = i*3, i2 = func(20);
• Declarations may also contain qualifiers, storage
classes, and that we can declare arrays,
functions, pointers, and other kinds of data
structures.
CFCP / Module I / AKN / 63
Variable (III)• You can't place variable declarations just
anywhere! They must either be placed
– at the beginning of a function, or
– at the beginning of a brace-enclosed block of statements or
– outside of any function.
• Within limits, you can give your variables and
functions any names (identifiers) you want but
first 32 characters are significant.
– Names may contain alphabets, numbers, and underscores
– The names abc & ABC are different
– keywords can not be used as the names of variables or
functions (or as identifiers of any kind).
CFCP / Module I / AKN / 64
Operators• Used to operate upon operand (s)
• Arithmetic
– Binary: +, -, *, /, % Unary: -
• When applied to integers, the division operator /
discards any remainder,
– so 1 / 2 is 0 and 7 / 4 is 1.
– And 1 / 2.0 is 0.5, and 7.0 / 4.0 is 1.75.
• The modulus operator % gives you the remainder
when two integers are divided: 1 % 2 is 1; 7 % 4
is 3.
– 2.5 % 5.0 ?
CFCP / Module I / AKN / 65
Assignment Operators• The assignment operator „=„ assigns a
value to a variable. For example,
x = 1 sets x to 1, and a = b sets a to whatever b's
value is.
• Groups from right to left
c = a = b is equivalent to c = (a = b)
• Other Assignment Operators
+=, i.e. a += b; is equivalent to a = a + b;
Similarly, -=, *=, /+, %=, . . .
CFCP / Module I / AKN / 66
Increment/decrement Operators
• ++: increments the value of operand by one
• -- : decrements the value of operand by one
• Use
Postfix: i++; j-- is equivalent to i = i+1; & j = j-1;
Prefix: ++i; --j
++5 ?
• Difference
t = 5; x = t++;
k =3; y = -- k
CFCP / Module I / AKN / 67
Operators (IV)• Relational Operators
< , >, <=, >=, ==, !=
• Logical Operators
&&, ||, !
• Numeric value of a relational or logical
expression is 1 for true and 0 for false.
• Bit wise operators
&, |, ^ (ex-or), << (left-shift), >> (right shift), ~
(one’s complement)
CFCP / Module I / AKN / 68
Operators (V)• sizeof: size of variables/data types
– Use: sizeof(int)
• & -> address of
• * -> pointer
• ?: -> conditional expression (ternary operator)
– Use: y = (x = = 1) ? 10 : 20;
• , -> series opeartor
CFCP / Module I / AKN / 69
Precedence & Associativity• Precedence
– Which operator executes first
– i.e. 3 + 4 * 5 ?
• Their associativity indicates in what order
operators of equal precedence in an
expression are applied
CFCP / Module I / AKN / 70
Control Statements• The statement which controls the flow of
execution of a program is called control statement
Control Statement
Branching Statement Looping Statement
One Way Branching (if)
Two Way Branching (if else)
Multi Way Branching
If .. else .. if, switch .. case
Entry Control (while, for)
Exit Control (do … while)
CFCP / Module I / AKN / 71
if Statement (I)• Simple Syntax of an if statement is:
if ( expression )
statement ;
• If you have a series of statements, then enclose
them in braces:
if( expression )
{
statement1
statement2
statement3
}
Example:
if (x > max)
max = x;
CFCP / Module I / AKN / 72
if Statement (II)• Syntax of an if statement
is:
if ( expression )
{statement (s);}
elseif ( expression )
{statement (s);}
else
{statement (s);}
Example: if ( a < b )
printf ("a is less than\n") ;else if ( a == b )
printf (" a is equal to b\n") ;else
printf ("a is larger than b\n") ;
CFCP / Module I / AKN / 73
Assignments• Write a program to print the size of all
datatypes discussed
• Write a program to find largest of 3 integers,
using if statement
• Write the outputs for the following & explain
a=10;
if (a)
b=25
else
b=12
CFCP / Module I / AKN / 74
Readings• Pradeep K Sinha, Priti Sinha, Computer
Fundamentals
• Computer Fundamentals & C Programming
by Balagurusamy