Computer Programming (4800153-3) - PowerPoint PPT Presentation

1 / 220
About This Presentation
Title:

Computer Programming (4800153-3)

Description:

Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year * – PowerPoint PPT presentation

Number of Views:432
Avg rating:3.0/5.0
Slides: 221
Provided by: Mast125
Category:

less

Transcript and Presenter's Notes

Title: Computer Programming (4800153-3)


1
Computer Programming(4800153-3)
  • Department of Computer Science
  • Preparatory Year
  • 1433/1434

2
Number Systems
3
Common Number Systems
System Base Symbols Used by humans? Used in computers?
Decimal 10 0, 1, 9 Yes No
Binary 2 0, 1 No Yes
Octal 8 0, 1, 7 No No
Hexa-decimal 16 0, 1, 9, A, B, F No No
4
Quantities/Counting (1 of 3)
Decimal Binary Octal Hexa-decimal
0 0 0 0
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
5
Quantities/Counting (2 of 3)
Decimal Binary Octal Hexa-decimal
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
6
Quantities/Counting (3 of 3)
Decimal Binary Octal Hexa-decimal
16 10000 20 10
17 10001 21 11
18 10010 22 12
19 10011 23 13
20 10100 24 14
21 10101 25 15
22 10110 26 16
23 10111 27 17
Etc.
7
Conversion Among Bases
  • The possibilities

Decimal
Octal
Binary
Hexadecimal
8
Quick Example
2510 110012 318 1916
Base
9
Decimal System
Weight
12510 gt 5 x 100 5 2 x 101 20 1 x
102 100 125
Base
10
Binary to Decimal
  • Technique
  • Multiply each bit by 2n, where n is the weight
    of the bit
  • The weight is the position of the bit, starting
    from 0 on the right
  • Add the results

11
Example
Bit 0
1010112 gt 1 x 20 1 1 x 21 2 0
x 22 0 1 x 23 8 0 x 24
0 1 x 25 32 4310
12
Octal to Decimal
  • Technique
  • Multiply each bit by 8n, where n is the weight
    of the bit
  • The weight is the position of the bit, starting
    from 0 on the right
  • Add the results

13
Example
7248 gt 4 x 80 4 2 x 81 16 7 x 82
448 46810
14
Hexadecimal to Decimal
  • Technique
  • Multiply each bit by 16n, where n is the weight
    of the bit
  • The weight is the position of the bit, starting
    from 0 on the right
  • Add the results

15
Example
ABC16 gt C x 160 12 x 1 12 B x
161 11 x 16 176 A x 162 10 x 256
2560 274810
16
Decimal to Binary
  • Technique
  • Divide by two, keep track of the remainder
  • First remainder is bit 0 (LSB, least-significant
    bit)
  • Second remainder is bit 1
  • Etc.

17
Example
12510 ?2
12510 11111012
18
Octal to Binary
  • Technique
  • Convert each octal digit to a 3-bit equivalent
    binary representation

19
Example
7058 ?2
7058 1110001012
20
Hexadecimal to Binary
  • Technique
  • Convert each hexadecimal digit to a 4-bit
    equivalent binary representation

21
Example
10AF16 ?2
10AF16 00010000101011112
22
Decimal to Octal
  • Technique
  • Divide by 8
  • Keep track of the remainder

23
Example
123410 ?8
8 1234 154 2
123410 23228
24
Decimal to Hexadecimal
  • Technique
  • Divide by 16
  • Keep track of the remainder

25
Example
123410 ?16
123410 4D216
26
Binary to Octal
  • Technique
  • Group bits in threes, starting on right
  • Convert to octal digits

27
Example
10110101112 ?8
10110101112 13278
28
Binary to Hexadecimal
  • Technique
  • Group bits in fours, starting on right
  • Convert to hexadecimal digits

29
Example
10101110112 ?16
  • 10 1011 1011
  • B B

10101110112 2BB16
30
Octal to Hexadecimal
  • Technique
  • Use binary as an intermediary

31
Example
10768 ?16
10768 23E16
32
Hexadecimal to Octal
  • Technique
  • Use binary as an intermediary

33
Example
1F0C16 ?8
1F0C16 174148
34
Exercise Convert
Decimal Binary Octal Hexa-decimal
33 100001 41 21
117 1110101 165 75
451 111000011 703 1C3
431 110101111 657 1AF
35
Binary Addition (1 of 2)
  • Two 1-bit values

A B A B
0 0 0
0 1 1
1 0 1
1 1 10
two
36
Binary Addition (2 of 2)
  • Two n-bit values
  • Add individual bits
  • Propagate carries
  • E.g.,

1
1
10101 21 11001 25 101110 46
37
Multiplication (1 of 2)
  • Binary, two 1-bit values

A B A ? B
0 0 0
0 1 0
1 0 0
1 1 1
38
Multiplication (2 of 2)
  • Binary, two n-bit values
  • As with decimal values
  • E.g.,

1110 x 1011 1110 1110 0000
111010011010
39
Digital Logic
40
Introduction to Digital Logic Basics
  • Hardware consists of a few simple building blocks
  • These are called logic gates
  • AND, OR, NOT,
  • NAND, NOR, XOR,
  • Logic gates are built using transistors
  • NOT gate can be implemented by a single
    transistor
  • AND gate requires 3 transistors
  • Transistors are the fundamental devices
  • Pentium consists of 3 million transistors
  • Compaq Alpha consists of 9 million transistors
  • Now we can build chips with more than 100 million
    transistors

41
Basic Concepts
  • Simple gates
  • AND
  • OR
  • NOT
  • Functionality can be expressed by a truth table
  • A truth table lists output for each possible
    input combination
  • Precedence
  • NOT gt AND gt OR
  • F A B A B
  • (A (B)) ((A) B)

42
Basic Concepts (cont.)
  • Additional useful gates
  • NAND
  • NOR
  • XOR
  • NAND AND NOT
  • NOR OR NOT
  • XOR implements exclusive-OR function
  • NAND and NOR gates require only 2 transistors
  • AND and OR need 3 transistors!

43
Basic Concepts (cont.)
  • Number of functions
  • With N logical variables, we can define
  • 22N functions
  • Some of them are useful
  • AND, NAND, NOR, XOR,
  • Some are not useful
  • Output is always 1
  • Output is always 0
  • Number of functions definition is useful in
    proving completeness property

44
Basic Concepts (cont.)
  • Complete sets
  • A set of gates is complete
  • If we can implement any logical function using
    only the type of gates in the set
  • You can uses as many gates as you want
  • Some example complete sets
  • AND, OR, NOT Not a minimal
    complete set
  • AND, NOT
  • OR, NOT
  • NAND
  • NOR
  • Minimal complete set
  • A complete set with no redundant elements.

45
Basic Concepts (cont.)
  • Proving NAND gate is universal

46
Basic Concepts (cont.)
  • Proving NOR gate is universal

47
Logic Chips (cont.)
48
Logic Chips (cont.)
  • Integration levels
  • SSI (small scale integration)
  • Introduced in late 1960s
  • 1-10 gates (previous examples)
  • MSI (medium scale integration)
  • Introduced in late 1960s
  • 10-100 gates
  • LSI (large scale integration)
  • Introduced in early 1970s
  • 100-10,000 gates
  • VLSI (very large scale integration)
  • Introduced in late 1970s
  • More than 10,000 gates

49
Logic Functions
  • Logical functions can be expressed in several
    ways
  • Truth table
  • Logical expressions
  • Graphical form
  • Example
  • Majority function
  • Output is one whenever majority of inputs is 1
  • We use 3-input majority function

50
Logic Functions (cont.)
  • 3-input majority function
  • A B C F
  • 0 0 0 0
  • 0 0 1 0
  • 0 1 0 0
  • 0 1 1 1
  • 1 0 0 0
  • 1 0 1 1
  • 1 1 0 1
  • 1 1 1 1
  • Logical expression form
  • F A B B C A C

51
Logical Equivalence
  • All three circuits implement F A B function

52
Logical Equivalence (cont.)
  • Proving logical equivalence of two circuits
  • Derive the logical expression for the output of
    each circuit
  • Show that these two expressions are equivalent
  • Two ways
  • You can use the truth table method
  • For every combination of inputs, if both
    expressions yield the same output, they are
    equivalent
  • Good for logical expressions with small number of
    variables
  • You can also use algebraic manipulation
  • Need Boolean identities

53
Logical Equivalence (cont.)
  • Derivation of logical expression from a circuit
  • Trace from the input to output
  • Write down intermediate logical expressions along
    the path

54
Logical Equivalence (cont.)
  • Proving logical equivalence Truth table method
  • A B F1 A B F3 (A B) (A B) (A B)
  • 0 0 0
    0
  • 0 1 0
    0
  • 1 0 0
    0
  • 1 1 1
    1

55
Boolean Algebra
56
Boolean Algebra (cont.)
57
Boolean Algebra (cont.)
  • Proving logical equivalence Boolean algebra
    method
  • To prove that two logical functions F1 and F2 are
    equivalent
  • Start with one function and apply Boolean laws to
    derive the other function
  • Needs intuition as to which laws should be
    applied and when
  • Practice helps
  • Sometimes it may be convenient to reduce both
    functions to the same expression
  • Example F1 A B and F3 are equivalent

58
Logic Circuit Design Process
  • A simple logic design process involves
  • Problem specification
  • Truth table derivation
  • Derivation of logical expression
  • Simplification of logical expression
  • Implementation

59
Deriving Logical Expressions
  • Derivation of logical expressions from truth
    tables
  • sum-of-products (SOP) form
  • product-of-sums (POS) form
  • SOP form
  • Write an AND term for each input combination that
    produces a 1 output
  • Write the variable if its value is 1 complement
    otherwise
  • OR the AND terms to get the final expression
  • POS form
  • Dual of the SOP form

60
Deriving Logical Expressions (cont.)
  • 3-input majority function
  • A B C F
  • 0 0 0 0
  • 0 0 1 0
  • 0 1 0 0
  • 0 1 1 1
  • 1 0 0 0
  • 1 0 1 1
  • 1 1 0 1
  • 1 1 1 1
  • SOP logical expression
  • Four product terms
  • Because there are 4 rows with a 1 output
  • F A B C A B C
  • A B C A B C

61
Deriving Logical Expressions (cont.)
  • 3-input majority function
  • A B C F
  • 0 0 0 0
  • 0 0 1 0
  • 0 1 0 0
  • 0 1 1 1
  • 1 0 0 0
  • 1 0 1 1
  • 1 1 0 1
  • 1 1 1 1
  • POS logical expression
  • Four sum terms
  • Because there are 4 rows with a 0 output
  • F (A B C) (A B C)
  • (A B C) (A B C)

62
Logical Expression Simplification
  • Two basic methods
  • Algebraic manipulation
  • Use Boolean laws to simplify the expression
  • Difficult to use
  • Dont know if you have the simplified form
  • Karnaugh map (K-map) method
  • Graphical method
  • Easy to use
  • Can be used to simplify logical expressions with
    a few variables

63
Algebraic Manipulation
  • Majority function example
  • A B C A B C A B C A B C
  • A B C A B C A B C A B C A B C A B C
  • We can now simplify this expression as
  • B C A C A B
  • A difficult method to use for complex expressions

Added extra
64
Implementation Using NAND Gates
  • Using NAND gates
  • Get an equivalent expression
  • A B C D A B C D
  • Using de Morgans law
  • A B C D A B . C D
  • Can be generalized
  • Majority function
  • A B B C AC A B . BC . AC

65
Implementation Using NAND Gates (cont.)
  • Majority function

66
Logical Expression Simplification
Prove the following Equivalence
67
Logical Expression Simplification
  • Prove that
  • X.(YZ) X.Y X.Z
  • XXY X
  • X(XY) X

68
Logical Expression Simplification
  • Simplify the next

69
Algorithms and Flowcharts
70
Problem Solving in a Computer System
  • The main purpose of problem solving is to convert
    inputs to outputs with some processes.

71
Main Steps in Problem Solving in Computer System
  • Problem understanding
  • Algorithm developing
  • Program writing
  • Program editing
  • Program compiling
  • Program running
  • Testing and debugging

72
Main Operations for Problem Solving
  • Input operations
  • Like input, read
  • Output operations
  • Like write, print
  • Arithmetic operations
  • Like add, subtract, multiply etc....
  • control transferring operations
  • Like conditional, non-conditional etc....
  • Looping
  • Like repeat, do while, for, etc...

73
What is an Algorithm?
A sequence of precise instructions which leads
to a solution is called an algorithm. or An
algorithm is a set of steps that defines how a
task is to performed. Example Steps
(algorithm) to solve a first degree
equation. Steps (algorithm) to calculate the
area of Triangle Steps (algorithm) to find
maximum digits among a set of input digits
74
Example
What is the algorithm for solving a first degree
equation (AX B)? 1. Read the values A,B 2.
Check if A0 (if yes there is no equation)
therefore no equation to be solved (end
processing). 3. Check if B0 (if yes X0 and
end processing). 4. Calculate the value of X
B/A 5. Print the value of X
75
Algorithm Representation
  • There are many ways in which we may represent an
    algorithm.
  • We use many techniques to represent an algorithm
    in computer programming, such as
  • Flowchart
  • Pseudocde

76
Why Flowcharts
  • The flowchart is graphical representation of the
    steps required for an algorithm or program.
  • The flowchart is characterized by
  • Clarify the program logic
  • Identify alternative processing methods
  • Serve as guide for program coding
  • Serve as documentation

77
Principals of Flowchart
  • 1. Simplicity
  • Easy to put on paper
  • Easy to draw
  • Readable and meaningful
  • 2. Organization
  • - putting ideas together and organizing those
    ideas in logical way.
  • 3. Planning
  • - flowchart helps for looking the program in
    deeper and global way.

78
General Concepts
  • Flowchart must be characterized by the following
  • The major element of the project.
  • Elements are clearly labeled.
  • Sequence of element must be clear.
  • No gap or dead ends.
  • Sequence of elements must be in logical form.
  • Flowchart must be used correctly.

79
Levels of Flowcharts
  1. Simple sequential flowchart.
  2. Branched flowchart.
  3. Simple-loop flowchart.
  4. Multi-loop flowchart.

80
No Name Symbol Usage
1 Ellipse Start/Stop
2 Rectangle Expressions
3 Parallelogram Input (Read) / Output(Print)
4 Rhombus Conditional checking
5 Arrow Flow of solution
6 Circle Connector
7 Elongated Hexagon Continue
8 Rectangle with bars Procedure / Function call
81
First Level of Flowchart
start
It is simplest level which contain the sequence
of steps without loops or branch and the
flowchart comes in straight line from the
beginning to the end.
process 1 . . . Process n
Stop
82
Second Level of Flowchart
start
It is branched flowchart, when there is a
condition statement in the program.
Input
Condition?
Yes
No
Process 1--n
Process 1--m
Stop
83
Third Level of Flowchart
  • It is a flowchart which contain iteration or
    repetitions. It is usually called loop
    flowcharts.
  • In this type we need to repeat some operation
    several times using the same set of operation.
  • The general form for this type is as follow

84
Example 1 Algorithm for reading student name
start
  1. Start
  2. Read student name
  3. End

Read student name
Stop
85
Example 2 Algorithm for calculate the area of
circle
start
  1. Start
  2. Read value of R
  3. Set PI equal to 3.14
  4. Calculate AreaPIRR
  5. Print R, Area
  6. Stop

Read R
PI3.14
AreaPiRR
Print R, Area
Stop
86
Example 3 Write an algorithm and draw the
flowchart to add two numbers.
  • Algorithm
  • Start
  • Read a, b
  • Calculate c a b
  • Print c
  • Stop

87
Example 4 Write an algorithm and draw a
flowchart to find the circumference of circle
  • Algorithm
  • Start
  • Read r
  • Calculate c 23.14 r
  • Print c
  • Stop

88
Example 5 Draw a flowchart to evaluate the
following functions F(X)x if Xgt0, F(X) -X if
Xlt0
start
  1. Start
  2. Read X
  3. If Xgt0 then go to step 4, else step 5
  4. Calculate F(X)X than go to step 6
  5. Calculate F(X)X
  6. Print X, F(X)
  7. Stop

Read X
Xgt0
Yes
No
F(X)X
F(X) -X
A
Print X, F(X)
Stop
89
Example 6 write an algorithm and draw a
flowchart to print 10 integers starting from 1
  • Algorithm
  • Start
  • Set A1
  • Check if Alt10 if yes goto step 4 else got to
    step 7
  • Print A
  • Calculate A A1
  • Goto step 3
  • If no End

90
Exercise
  • Write an algorithm and draw the flowchart that
    read three numbers and print the value of the
    largest number.

91
Exercise
  • Step 1 Input N1, N2, N3
  • Step 2 if (N1gtN2) then
  • if (N1gtN3) then
  • MAX ? N1 N1gtN2, N1gtN3
  • else
  • MAX ? N3 N3gtN1gtN2
  • endif
  • else
  • if (N2gtN3) then
  • MAX ? N2 N2gtN1, N2gtN3
  • else
  • MAX ? N3 N3gtN2gtN1
  • endif
  • endif
  • Step 3 Print The largest number is, MAX

92
Looping
  • When we need to use a loop a special symbol can
    be used?
  • Counter i
  • Any Initial value ? ( Set i 0)
  • Final Value (N)? (Set N 10)
  • Increment or Decrement Value (M)?(Set M1)

93
Exercise
  • Write an algorithm and draw a flowchart to
    calculate and print the sum of numbers from 1 to
    10 .

94
Programming Using C
  • Introduction

95
Programming Language
  • Programming language is an artificial language
    that specifies instruction to be executed on a
    computer.
  • This language consists of a set of commands,
    understandable by computer directly or after
    translating.

96
Computer Languages
  • There are many types of computer languages, which
    can be categorized into the following four
    types-
  • Low-Level Languages (1st 2nd Generation
    Languages)
  • High-Level Languages (3rd Generation Languages)
  • User-Friendly Languages (4th Generation
    Languages)
  • Object-Oriented Languages (5th Generation
    Languages)

97
Computer Languages
  • Low Level Language (Machine)
  • A language that is machine-dependent and/or that
    offers few control instructions and data types.
  • Each statement in a program written in a
    low-level language usually corresponds to one
    machine instruction.
  • To calculate Area Width Length in Low Level
    language
  • 100100 010001 //Load
  • 100110 010010 //Multiply
  • 100010 010011 //Store

98
Computer Languages
  • High-Level Language
  • The languages, which computer cannot understand
    directly and are not machine dependent are called
    High-Level Languages. Some of the high-level
    languages are-
  • BASIC (Beginners All Purpose Symbolic Instruction
    Code)
  • COBOL (Common Business Oriented Language)
  • FORTRAN (Formula Translator)
  • C

99
Computer Languages
  • User-Friendly Languages
  • These languages are very easy to codify and
    simplest to learn. Some of the common
    user-friendly languages are-
  • dBASE
  • FoxPro
  • Oracle
  • Sybase

100
Computer Languages
  • Object-Oriented Languages
  • The languages which are based on object oriented
    programming (OOP) approach are called as
    Object-Oriented languages. For example-
  • Smalltalk
  • C
  • Object COBOL
  • JAVA
  • Simula

101
Language Translators
  • The software, which converts the codes of other
    languages into machine code are called Language
    Translator.
  • Language Translators are categorized into three
    types-
  • Assemblers
  • Interpreters
  • Compilers

102
Language Translators
  • Assembler
  • Assembler translates the assembly language code
    (source program) into machine language code
    (object program).
  • After assembling, a linker program is used to
    convert the object program into an executable
    program.
  • The Microsoft assembler program (MASM)
  • Borland Turbo assembler program (TASM)
  • Assemblers are used mainly in development of
    system software.

103
Language Translators
  • Interpreters
  • Interpreters translate the high-level language
    code into machine language code, command by
    command.
  • They are very slow for executing large programs.

104
Language Translators
  • Compilers
  • As contrast to interpreters, compilers provide
    faster execution speed.
  • Compilers translate the entire program (source
    code) into machine code (Object File). By using
    linker, the object code is converted into
    Executable File.
  • Compilers are widely used in translating codes
    of high level languages.
  • As compared to assemblers or interpreters,
    compilers are preferred in development of
    application software.

105
Debugging
  • Programming errors are called bugs
  • Debugging - the process of tracking them down.
  • Three kinds of errors
  • syntax errors
  • runtime errors
  • semantic errors

106
Syntax errors
  • Occur if syntax is not correct
  • Syntax refers to the structure of a program and
    the rules about that structure.
  • (1 2) is legal
  • 8) is a syntax error

107
Runtime errors
  • Error does not appear until after the program has
    started running
  • Also called exceptions
  • Rare in simple programs

108
Semantic errors
  • Program runs successfully (no error messages
    generated)
  • Will not do the right thing
  • The program result is wrong.
  • Tricky to identify

109
Motivation for Studying C
  • The objective of learning C is to write
    programs using this higher level language to
    solve our day-to-day problems and tomorrow may be
    to write a whole software. It is a most widely
    used language.

110
Origins of C
  • The first language developed was (BCPL) and the
    next upgraded version was (B). the language (B)
    was upgraded to (C) by Dennis Ritche of AT T
    laboratories, USA. C was first used to write
    UNIX OS
  • (C)is a general purpose language.
  • Bjarne Strousstrup added object orientation to
    (C )and developed (C)

111
A Simple C Program
Let us begin with a simple C program that
displays the message Welcome to C! .
include ltiostreamgt using namespace std void
main() // Display Welcome to C cout ltlt
"Welcome to C!" ltlt endl
112
Extending the Simple C Program
Once you understand the program, it is easy to
extend it to display more messages. For example,
you can rewrite the program to display three
messages.
include ltiostreamgt using namespace std void
main() cout ltlt "Programming is Useful!" ltlt
endl cout ltlt "Fundamentals First" ltlt
endl cout ltlt "Problem Driven" ltlt endl
113
Computing with Numbers
Further, you can perform mathematical
computations and displays the result .
include ltiostreamgt using namespace std void
main() cout ltlt (1 2 3) / 3 ltlt endl
114
Basic Concepts for Programming Skills
Programming Using C
115
Phase of C Programs
  • Edit
  • Program is created in the editor and stored on
    the disk
  • Compile
  • Compiler create Object code and stores on disk
  • Link
  • Linker links the Object code with Libraries,
    creates result and stores it on disk
  • Load
  • Loader prints program in memory
  • Execute
  • CPU takes each instruction and executes it.
    Possibly storing new data Values as program
    execute

116
Creating, Compiling, and Running Programs
117
C Character Set
  • Character set includes the basic building blocks
    of a language.
  • C character set consists of
  • Numeric Character Set 0-9
  • Alphabetic Character Set A-Z, a-z
  • Special Character Set , , ,(comma) etc
  • Escape Character Set they are used for
    formatting the output.
  • It always starts with a back slash ( \ ).
  • Some Examples are \n, \t, \b, \a

118
Tokens
  • The smallest individual unit in a program is
    known as token.
  • C has the tokens, like
  • Keywords, Identifiers, Literals, Punctuators,
  • Operators

119
Keywords
  • Reserved words or Keywords are those words which
    are reserved for a specific purpose and part of
    the language.
  • Examples are
  • if, int, char, break, constant, case, do, class,
    else,
  • template, true, structure, void etc

120
Identifiers
  • Words that are not reserved or keywords are
    called user defined words or identifiers.
  • Identifiers must follow the following rules
  • Can be composed of alphabets (A-Z or a-z),
    numbers (0 to 9) and underscore _
  • The first character must be an alphabet or an
    underscore _.
  • Identifier must be unique.
  • Blank Spaces are not allowed.
  • They are case sensitive i.e. Val and val are
    different
  • Examples Roll_number, r_no, Z, A1234_BC etc.
  • Use the name of the identifier that is self
    explanatory
  • e.g. employee_name, student_name etc.

121
Data Types
  • Data types are means to identify the type of data
    and associated operations of handling it.
  • C data types are of two types
  • (i) Fundamental data types
  • (ii) Derived data type

122
Data Types
  • (i) Fundamental Data Types

Name Data type Size in bytes Range of values
char Character 1-Byte -128 to 127
int Integer 2-Bytes -32768 to 32767
short int Short Integer 2-Bytes -32768 to 32767
long int Long Integer 4-Bytes -2147483648 to 2147483647
float Floating Point 4-Bytes -3.4E38 to 3.4E38
double Double Floating Point 8-Bytes -1.7E308 to 1.7E308
123
Data Types
  • (ii) Derived data type
  • From the fundamental types other types can be
    derived by using the declaration operators, e.g.
    Arrays.
  • Expression
  • Expressions are the valid combination of
    operators, constants and or variables.
  • e.g. X X 5

124
Constants and Variables
  • Identifiers can be classified into two categories
    constants and variables.
  • Constants (Literals)
  • Constants are identifiers which do not change
    its stored value during executing the program.
  • Two types are
  • (a) Numeric Constant e.g. const float pi3.14
  • (b) Non Numeric constant e.g. const char
    pi?

125
Constants and Variables
  • Variables
  • a variable is an identifier that has a changeable
    value during the execution of a program.
  • Variable Declaration
  • Declare a variable means to allocate a memory
    location to hold the value of this variable.
  • To define a variable, each variable should have
  • Identifier which is the variable name that you
    will use during the program, and in fact it is
    translated to an address of the memory location.
  • Data Type which shows the type of the value that
    will be stored in this variable. Example
  • Data_Type  Identifier
  • int number1

126
Constants and Variables
  • There are different types of variables such as-
  • (a) Character variable (To store characters)
  • (b) Integer variable (To store whole numbers)
  • (c) Float variable (To store floating point
    numbers)
  • (d) Boolean variable (To store two values
    true/false)
  • e.g. int a,b,c,d10 (you can also initialize
    at the time of declaration)

127
Punctuators
  • The following characters are used as punctuators
    (also known as separators) in C.
  • ( ) ,

128
Operators
  • Operators cause the compilers to take some
    action.
  • Operators work on operands (data).
  • Operators are classified as-
  • I/O operators
  • input operator(gtgt) is used to read value from
    standard input
  • output operator(ltlt) is used to direct a value to
    standard output.
  • Assignment Operator
  • Equal sign () used for assignment operator. It
    is used to assign values to variables e.g. A10
    or ab. In every case the value of the right hand
    variable (constant) are assigned to variable in
    the left hand side.

129
Operators
  • Assignment Operator

Example 1 int x float y12.52 xy coutltltvalue of x ltltx //the output is 12 as x is an integer it is truncated to 12 Example 2 int x11 float yx coutltltvalue of y ltlty //the output is 11.0 as y is a float variable its value becomes 11.0
130
Operators
  • Arithmetic Operators
  • Are used to perform arithmetic operations. For
    Example
  • These used to perform arithmetic operations.
    There are always two operands e.g. in a b OR
    (Operand1 Operand2) a and b are operands.

Addition
Subtraction -
Division /
Multiplication
Used to find out remainder
131
Operators
  • Arithmetic Operators
  • They can be of any data types.

Operand-1 (a) Operand-2 (b) Operations Result
int int , -, , / int
int float , -, , / float
float int , -, , / float
float float , -, , / float
float double , -, , / double
Long double double , -, , / Long double
132
Operators
  • Arithmetic Operators
  • Note that the result always takes the larger
    data type of the operands used.

Example 1 int x10, y3 coutltltvalue of x ltltx/y //the output is 3 not 3.33 as both the operands are integers Example 2 int x10 float y3.5 coutltltvalue of x ltltx/y //the output is 3 not 3.33 as both the operands are integers
133
Operators
  • Unary operators
  • Increment () e.g. a (postfix), a(prefix)
    equivalent to aa1
  • Decrement (--) e.g. b-- (postfix), --b (prefix)
    equivalent to bb-1
  • When these operators (prefix or suffix) are used
    in isolation, their impact is same
  • e.g. if a10, a or a results making a11.
  • But the impacts are different when used along
    with assignment operators or cout statements

134
Operators
  • Unary operators Examples

void main( ) int x10 x cout ltlt x //output is 11 as x is xx1 void main( ) int x10 x cout ltlt x //output is 11 as x is also xx1
void main( ) int x10 cout ltlt x //output is 10 as it outputs then increments void main( ) int x10 cout ltlt x //output is 11 as it increments then outputs
135
Operators
  • Unary operators Find the output for the
    following

void main( ) int x10,y y --xy cout ltlt xltlt\tltlty void main( ) int x10,y y x-- y cout ltlt xltlt\tltlty
void main( ) int x10,y5 y --x y cout ltlt xltlt\tltlty void main( ) int x10,y5 y --x y cout ltlt xltlt\tltlty
136
Operators
  • Relational Operators
  • are used for the comparison of variables. For
    Example

Less than lt
Greater than gt
Less than or equal to lt
Greater than or equal to gt
Equal to
Not equal to !
137
Operators
  • Relational Operators
  • For Example
  • Remaining operators work in the same way.

(XltY) If X is less than Y the condition results to true otherwise results to false
(XltY) If X is less than or equal to Y the condition results to true otherwise results to false
138
Operators
  • Logical Operators
  • are used to for logical combination, disjunction
    or negation of variables.

In general Symbol in program Use Explanation
AND ab True if a is true and b is true else false
OR a b True if either a is true or b is true else false
NOT ! ! a True if a is false and vice versa
139
Operators
  • Logical Operators
  • Examples are
  • (agtb) (bgtc) is true if (agtb) is true and (bgtc)
    is true
  • (agtb) (bgtc) is false if one of them is false
    or both are false
  • (agtb) (bgtc) is true if either (agtb) is true or
    (bgtc) is true or both are true
  • (agtb) (bgtc) is false when both are false

140
Operators
  • Compound operators
  • C allows the assignment to combine with other
    operators.
  • Examples Z5 which is equal to ZZ5
  • xy is equal to xxy
  • x/5 is equal to xx/y

141
Operators
  • Compound operators Find out for the output for
    following

void main( ) int x10,y20 y x xy cout ltlt xltlt\tltlty void main( ) int x10,y30 y/ x xy cout ltlt xltlt\tltlty
void main( ) int x10,y40 y x cout ltlt xltlt\tltlty void main( ) int x10,y40 y x xx cout ltlt xltlt\tltlty
142
The Priority of Operators
Highest
Lowest
143
Programming Using C
  • Input/Output

144
Input/Output in C
  • cout
  • The identifier cout is a predefined object
    that corresponds to standard output stream.
  • cin
  • The identifier cin is a predefined object
    that corresponds to standard input stream.
  • Escape sequence/ Escape character
  • Character combinations consisting of a
    backslash (\) followed by a letter or by a
    combination of digits is called escape
    sequence.

145
Input/Output in C
  • I/O operators
  • The input operator(gtgt) is used to read value
    from standard input, while output operator(ltlt) is
    used to direct a value to standard output. For
    Example
  • includeltiostreamgt
  • Using namespace std
  • void main( )
  • int a,b,c
  • float d
  • coutltltEnter three numbers
  • cingtgtagtgtbgtgtc
  • d(abc)/3
  • coutltltThe averageltltd


146
Input and Output
  • A data stream is a sequence of data. Typically in
    the form of characters or numbers
  • An input stream is data for the program to use
  • Usually originates from
  • the keyboard
  • a file
  • An output stream is the programs output
  • Destination would be usually
  • the monitor
  • a file

147
Output using cout
  • cout is an output stream sending data to the
    monitor
  • The insertion operator "ltlt" inserts data into
    cout
  • Example cout ltlt number_of_bars ltlt "
    candy bars\n"
  • This line sends two items to the monitor
  • The value of number_of_bars
  • The quoted string of characters " candy bars\n"
  • Notice the space before the c in candy
  • The \n causes a new line to be started
    following the s in bars
  • A new insertion operator is used for each item of
    output

148
Examples Using cout
  • This produces the same result as the previous
    sample cout ltlt
    number_of_bars
    cout ltlt " candy bars\n"
  • Here arithmetic is performed in the cout
    statement cout ltlt
    "Total cost is " ltlt (price tax)Quoted
    strings are enclosed in double quotes ("Walter")
  • Dont use two single quotes (')
  • A blank space can also be inserted with
    cout ltlt " " if
    there are no strings in which a space is desired
    as in " candy bars\n"

149
Include Directives
  • Include Directives add library files to our
    programs
  • To make the definitions of the cin and cout
    available to the program
    include ltiostreamgt
  • Using Directives include a collection of defined
    names
  • To make the names cin and cout available to our
    program using
    namespace std

150
Escape Sequences
  • Escape sequences tell the compiler to treat
    characters in a special way
  • '\' is the escape character
  • To create a newline in output use
    \n cout ltlt "\n" or the newer
    alternative cout ltlt
    endl
  • Other escape sequences \t -- a
    tab \\ -- a backslash character
    \" -- a quote character

151
Input Using cin
  • cin is an input stream bringing data from the
    keyboard
  • The extraction operator (gtgt) removes data to be
    used
  • Example cout ltlt "Enter the number of bars in a
    package\n" cout ltlt " and the weight in
    ounces of one bar.\n" cin gtgt
    number_of_bars cin gtgt one_weight
  • This code prompts the user to enter data then
    reads two data items from cin
  • The first value read is stored in number_of_bars
  • The second value read is stored in one_weight
  • Data is separated by spaces when entered

152
Reading Data From cin
  • Multiple data items are separated by spaces
  • Data is not read until the enter key is pressed
  • Allows user to make corrections
  • Example cin gtgt v1 gtgt v2 gtgt v3
  • Requires three space separated values
  • User might type 34 45 12
    ltenter keygt

153
Designing Input and Output
  • Prompt the user for input that is desired
  • cout statements provide instructions cout ltlt
    "Enter your age " cin gtgt age
  • Notice the absence of a new line before using cin
  • Echo the input by displaying what was read
  • Gives the user a chance to verify datacout ltlt
    age ltlt " was entered." ltlt endl

154
Programming Using C
  • Control Structures

155
Conditional Constructs
  • Provide
  • Ability to control whether a list of statements
    is executed
  • A mechanism for deciding whether an action should
    be taken
  • Two types
  • If statement
  • if statement
  • if-else statement
  • Nested if-else structure
  • Switch statement

156
The Basic If Statement
  • Syntax
  • if (Expression)
  • Action
  • If the Expression is true then execute Action
  • Action is either a single
  • statement or a group of statements within
    braces

Expression
false
true
Action
157
Example
  • if (Value lt 0)
  • Value -Value

Is the Value negative ?
Value lt 0
false
If Value is less than zero then we need to update
its value to that of its additive inverse
If Value is not less than zero then our number is
fine as is
true
Value - Value
The number is now definitely nonnegative
158
Sorting Two Numbers
  • void main()
  • cout ltlt "Enter two integers "
  • int Value1
  • int Value2
  • cin gtgt Value1 gtgt Value2
  • if (Value1 gt Value2)
  • int RememberValue1 Value1
  • Value1 Value2
  • Value2 RememberValue1
  • cout ltlt "The input in sorted order "
  • ltlt Value1 ltlt " " ltlt Value2 ltlt endl

159
What is the Output?
  • int m 5
  • int n 10
  • if (m lt n)
  • m
  • n
  • cout ltlt " m " ltlt m ltlt " n ltlt n ltlt endl

160
The If-Else Statement
  • Syntax
  • if (Expression)
  • Action1 else Action2
  • If Expression is true then executeAction1
    otherwise execute Action2
  • if (v 0)
  • cout ltlt "v is 0"
  • else cout ltlt "v is not 0"

Expression
true
false
Action1
Action2
161
Finding the Max
  • void main()
  • cout ltlt "Enter two integers "
  • int Value1
  • int Value2
  • cin gtgt Value1 gtgt Value2
  • int Max
  • if (Value1 lt Value2)
  • Max Value2
  • else
  • Max Value1
  • cout ltlt "Maximum of inputs is " ltlt Max ltlt endl

162
Finding the Max
Yes, it is. So Value2 is larger than Value1. in
this case, Max is set to Value2
Is Value2 larger than Value1 ?
No, its not. So Value1 is at least as large as
Value2. In this Case, Max is set to Value1
Value1 lt Value2
false
true
Max Value1
Max Value2
Either case, Max is set correctly
163
Selection
  • It is often the case that depending upon the
    value of an expression we want to perform a
    particular action
  • Two major ways of accomplishing this choice
  • Nested if structure
  • if-else statements "glued" together
  • Switch statement
  • An advanced construct

164
If-Else Structure
  • if ( nbr lt 0 )
  • cout ltlt nbr ltlt " is negative" ltlt endl
  • else if ( nbr gt 0 )
  • cout ltlt nbr ltlt " is positive" ltlt endl
  • else
  • cout ltlt nbr ltlt " is zero" ltlt endl

165
Switch Statement
  • A nested if-else structure is just as efficient
    as a switch statement.
  • However, a switch statement may be easier to
    read.
  • Also, it is easier to add new cases to a switch
    statement than to a nested if-else structure.

166
Switch Statement
  • switch (expression)
  • case Constant1
  • Action1
  • break
  • case Constant2
  • Action 2
  • break
  • .
  • .
  • default
  • default group of Actions

167
Break
  • The last statement of each case in the switch
    statement should almost always be a break.
  • The break causes program control to jump to the
    closing brace of the switch structure.
  • Without the break, the code flows into the next
    case. This is almost never what you want.
  • A switch statement will compile without a default
    case, but always consider using one.

168
Example1
  • switch (ch)
  • case 'a' case 'A'
  • case 'e' case 'E'
  • case 'i' case 'I'
  • case 'o' case 'O'
  • case 'u' case 'U' cout ltlt ch ltlt " is a vowel"
    ltlt endl
  • break
  • default cout ltlt ch ltlt " is not a vowel" ltlt
    endl

169
Example2
  • void main()
  • cout ltlt "Enter simple expression "
  • int Left
  • int Right
  • char Operator
  • cin gtgt Left gtgt Operator gtgt Right
  • cout ltlt Left ltlt " " ltlt Operator ltlt " " ltlt Right
  • ltlt " "
  • switch (Operator)
  • case '' cout ltlt Left Right ltlt endl break
  • case '-' cout ltlt Left - Right ltlt endl break
  • case '' cout ltlt Left Right ltlt endl break
  • case '/' cout ltlt Left / Right ltlt endl break
  • default cout ltlt "Illegal operation" ltlt endl

170
Programming Using C
  • Repetition Structure
  • (Loop)

171
Definition
  • A Repetition structure certain parts of the code
    will be executed multiple times, or not at all
    based on the current state (condition).
  • A loop is a group of instructions the computer
    executes repeatedly until a terminating condition
    is satisfied.
  • In C, there are 3 forms of implementing
    repetition
  • While Loop
  • Do-while Loop
  • For Loop

172
While Loop
  • The syntax in C is
  •  
  • Initialize
  • while (condition)
  • statement //action
  • increment

173
While Loop
  • The syntax in C is
  •  
  • Initialize
  • while (condition)
  • statement //action
  • increment
  • Initialize initialize the control variable which
    will be used to test the condition, this
    initialization is applied only once.
  • If the condition is true, the statement and the
    increment are executed, then the whole thing is
    done again.
  • The statement and the increment are executed
    repeatedly until the condition becomes false.
  • If the condition starts out false, the while-body
    will never be executed.
  • Increment is the statement that makes change on
    the condition, otherwise, the loop will continue
    running. (Infinite loop).

174
Trace While Loop
Trace the following code Void main() int count
0 while (count lt 2) cout ltlt "Welcome to
C!" count
175
Do-While Loop
  • The syntax in C is
  •  
  • do any number of statements //
    action while (condition)

176
Do-While Loop
  • The syntax in C is
  •  
  • do any number of statements //
    action while (condition)
  • The do-while statement performs the test after
    executing the body.
  • As long as the test is true, the body will
    execute again.
  • In all cases the body will be executed at least
    once, even if the condition was wrong because
    testing happened at the end.
  • The difference between while and do-while
  • The testing happen before executing the body in
    the while structure, so if the condition is false
    from the beginning, the body will not be executed
    at all.

177
Do-While Example
  • Void main()
  • int count 1
  • do
  • cout ltlt "Welcome to C!"
  • count
  • while (count lt 2)
  • --------------------------------------------------
    ------
  • What is the output?
  • What is the output if the condition changed to
    (count gt2)?

178
For Loop
  • The syntax in C is
  • for ( initialize condition increment )
  • statements

179
For Loop
  • The syntax in C is
  • for ( initialize condition increment )
  • statements
  • for structure is composed of 4 parts
  • Initialize initialize the loop control variable,
    and done only once.
  • Condition is the condition that determines
    whether the loop should continue executing or
    not.
  • Statements the body of the loop.
  • The increment is a statement that changes the
    value of the initialization either by adding,
    subtracting, or any math operation. But usually
    it is either adding or subtracting.
  • Notice that there is no semicolon after the
    increment.
  • It is better to use for structure when the number
    of iterations is known.

180
For Loop Example
Try to trace the following code void
main() int i for (i 0 i lt 2 i) cout
ltlt "Welcome to C!"
181
Break and Continue Statements
  • break and continue alter the flow of control
  • break statement
  • The break statement when executed in while, for,
    do-while or switch structure causes immediate
    exit from that structure. The program continues
    with the first statement after the structure.
  • Example What is the output of the following
    code?
  • for (int x 1 xlt 10 x)
  • if ( x 5 )
  • break
  • coutltltxltlt" "
  • coutltlt"\n broke out of the loop when x became
    "ltltxltltendl

182
Break and Continue Statements
  • break and continue alter the flow of control
  • continue statement
  • The continue statement, when executed in a while,
    for, or do-while structure skips the remaining
    statements in the body of that structure and
    proceeds with the next iteration of the loop.
  • Example What is the output of the following
    code?
  •  
  • for (int x 1 xlt 10 x)
  • if ( x 5 )
  • continue
  • coutltltxltlt" "
  • coutltlt"\n used continue to skip printing the
    value 5"ltltendl

183
Programming Using C
  • Arrays and Strings

184
Introducing Arrays
  • Arrays are data structures which hold multiple
    variables of the same data type.
  • Consecutive group of memory locations having same
    name and type (int, char, float, double etc.)
  • To refer to an element, Specify array name and
    position number (index) e.g. myList5 

185
Introducing Arrays
186
Syntax
  • Declaration Datatype arrayname size e.g.
    int A20 means A is an integers array
    with size 20.
  • Each element in the array is accessed with a
    subscript i.e. A0, A1 .. A19
  • Each memory element can hold an integer only.
  • First element at position 0 and the maximum
    position at size -1
  • Memory requirements depend on the size of array.
  • Array declaration is static i.e. the size must
    be specified at the time of declaration.

187
Initializing Arrays 
  • Declaring, creating, initializing in one step
  • int a51,5,7,9,10 ? a01, a15,,a410
  • If not enough initializers, rightmost elements 0, 
    If too many syntax error 
  • int b3 1? b01,b10,b20.
  • int c2 1,2,3,4? //Wrong
  • To set every element to same value, e.g. int d 5
       0 
  • If  array  size  omitted,  initializers 
    determine  size  i.e.  int  e        1,  2, 
    3,  4,  5    this  implies  size of a is 5

188
Initializing Arrays
  • If A is an array and B is an array of same
    dimension (size) we can assign A B i.e. the
    contents of B will be copied to array A.
  • Example 
Write a Comment
User Comments (0)
About PowerShow.com