0% found this document useful (0 votes)
4 views42 pages

Lec 05

This document provides an introduction to computer programming, focusing on the C programming language and its development environment. It covers basic concepts, types of programming languages, the C standard library, and the structure of C programs, including examples and explanations of key programming principles. Additionally, it discusses debugging, testing, and data types relevant to C programming.

Uploaded by

kin yam Law
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views42 pages

Lec 05

This document provides an introduction to computer programming, focusing on the C programming language and its development environment. It covers basic concepts, types of programming languages, the C standard library, and the structure of C programs, including examples and explanations of key programming principles. Additionally, it discusses debugging, testing, and data types relevant to C programming.

Uploaded by

kin yam Law
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to Computer

programming

Lecture 5
Acknowledgement: Some images of these slides come from the book:
C how to program

CC2005 (10/11) Sem 1 - L5 1


Learning Outcomes
• To understand basic computer concepts.
• To become familiar with different types of
programming languages.
• To become familiar with the history of the C
programming language.
• To become aware of the C standard library.
• To understand the basic elements of a typical C
program development environment.
• Study some C program examples
CC2005 (10/11) Sem 1 - L5 2
Computer Programming and
Programming Languages
• Creating instructions that control the operation of a
computer or computer hardware is called computer
programming

• The instructions themselves are called computer


programs, applications, software, or simply
programs

• The pieces of information that a program needs are


called data

CC2005 (10/11) Sem 1 - L5 3


Different types of computer language (1)

Three types of programming languages


1. Machine languages
• Strings of numbers giving specific machine instructions
• Example:
+1300042774
+1400593419
+1200274027

2. Assembly languages
• Symbolic abbreviations representing elementary computer
operations (translated into machine code via assemblers)
• Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

CC2005 (10/11) Sem 1 - L5 4


Different types of computer language (2)

Three types of programming languages


3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via compilers)
• Example:
grossPay = basePay + overTimePay

CC2005 (10/11) Sem 1 - L5 5


The C Standard Library
• C programs consist of pieces/modules called functions
– A programmer can create his own functions
• Advantage: the programmer knows exactly how it works
• Disadvantage: time consuming
– Programmers will often use the C library functions
• Use these as building blocks
– Avoid re-inventing the wheel
• If a premade function exists, generally best to use it rather than
write your own
• Library functions carefully written, efficient, and portable
– Examples
printf( "Sum is %d\n", integer1 + integer2 );
scanf( "%d", &integer1 );

CC2005 (10/11) Sem 1 - L5 6


Procedural Programming
• One of the most common forms of programming
in high-level languages is called procedural
programming
– Instructions are run sequentially
– Instructions are structured so that they can be tested
and debugged easily
• In procedural programming, computer
instructions are often grouped into logical units
called procedures
• In C programming, procedures are referred to as
functions
CC2005 (10/11) Sem 1 - L5 7
Object Oriented Programming (OOP)

• Object is programming code and data that can be


treated as an individual unit or component
• Reusable software components that model items in the
real world
• Meaningful software units
– Date objects, time objects, paycheck objects, invoice objects,
audio objects, video objects, file objects, record objects, etc.
– Any noun can be represented as an object
• More understandable, better organized, and easier to
maintain than procedural programming
• Favor modularity

CC2005 (10/11) Sem 1 - L5 8


Other High Level Languages
• FORTRAN
– Used for scientific and engineering applications
• COBOL
– Used to manipulate large amounts of data in business
applications
• Pascal
– Intended for academic use
• C++
– Extension of C language
– Use OOP approach
• Java
– Machine independent and run by using an interpreter
– Widely used in the web technology

CC2005 (10/11) Sem 1 - L5 9


Basics of a Typical C Program Development Environment
Program is created in
Editor Disk the editor and stored
on disk.
• Phases of C Programs: Preprocessor program
Preprocessor Disk processes the code.

1. Edit Compiler
Compiler creates
Disk object code and stores
it on disk.
2. Preprocess Linker Disk Linker links the object
code with the libraries
Primary Memory
3. Compile
Loader
Loader puts program
4. Link in memory.
Disk ..
..
..

5. Load Primary Memory


CPU takes each
instruction and
6. Execute CPU
executes it, possibly
storing new data
7. Debug CC2005 (10/11) Sem 1 - L5
..
..
..
values as the program
10
executes.
Program design
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
• While writing a program:
– Know what “building blocks” or functions are
available
– Use good programming principles, e.g. write proper
comments

CC2005 (10/11) Sem 1 - L5 11


Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to be executed

CC2005 (10/11) Sem 1 - L5 12


Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding C program
• Consists only of executable statements ??

CC2005 (10/11) Sem 1 - L5 13


C Compiler
• The C complier is used to compile source code
files into an executable program (object code)
– E.g. Visual C++, Borland C++, GCC, etc.
• GCC is a GNU compiler
– It can compile the program languages of C, C++,
Fortran, Java, etc.
– It can run under MS Windows/Linux/Unix platform
• Compilation example:
– gcc –o hello -g hello.c
• –o option specifies the output program name and –g option
enables the interactive mode by gdb/ddd debugger

CC2005 (10/11) Sem 1 - L5 14


Debugger
• A software tool for debug and test a program
– Break points can be set inside the program in order to
stop the execution of the program
– It can support the data investigation
– It often runs interactively
• GDB/DDD debuggers
– Debuggers in Linux environment
• GDB is running under the console mode while DDD is
running in windows mode

CC2005 (10/11) Sem 1 - L5 15


Debugging and testing a program
• It is inevitable to avoid error in a large program
• Tips for debugging and testing
1. Carefully place comments in the program
2. Create a trace of executing
3. Display the values of input, immediate and output
with interest
4. Investigate the program flow and control
• Tools: debugger program or insert some
diagnostic function calls, e.g. printf

CC2005 (10/11) Sem 1 - L5 16


A Simple C Program: Printing a Line of Text (1)
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
Welcome to C!

Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor directive
• Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations
CC2005 (10/11) Sem 1 - L5 17
A Simple C Program: Printing a
Line of Text (2)
• int main()
– C programs contain one or more functions, exactly
one of which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
• The bodies of all functions must be contained in braces

CC2005 (10/11) Sem 1 - L5 18


A Simple C Program: Printing a
Line of Text (3)
• printf( "Welcome to C!\n" );
– Instructs computer to perform an action
• Specifically, prints the string of characters within quotes (" ")
– Entire line is called a statement
• All statements must end with a semicolon (;)
– Escape character (\)
• Indicates that printf should do something out of the ordinary
• \n is the newline character

CC2005 (10/11) Sem 1 - L5 19


A Simple C Program: Printing a
Line of Text (4)
Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double quote character in a string.
Fig. 2.2 Some common escape sequences.

CC2005 (10/11) Sem 1 - L5 20


A Simple C Program: Printing a
Line of Text (5)
• return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally
• Right brace }
– Indicates end of main has been reached
• Linker
– When a function is called, linker locates it in the library
– Inserts it into object program
– If function name is misspelled, the linker will produce an error
because it will not be able to find function in the library

CC2005 (10/11) Sem 1 - L5 21


1 /* Fig. 2.3: fig02_03.c
2 Printing on one line with two printf statements */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome " ); Example 1
9 printf( "to C!\n" );
10
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */
Welcome to C! output
1 /* Fig. 2.4: fig02_04.c
2 Printing multiple lines with a single printf */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome\nto\nC!\n" ); Example 2
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
Welcome
to CC2005 (10/11) Sem 1 - L5 output 22
C!
1 /* Fig. 2.5: fig02_05.c
2 Addition program */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 int integer1; /* first number to be input by user */
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
11
12 printf( "Enter first integer\n" ); /* prompt */
Example 3
13 scanf( "%d", &integer1 ); /* read an integer */
14
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */

Enter first integer


45
Enter second integer output
72
Sum isCC2005
117 (10/11) Sem 1 - L5 23
Another Simple C Program: Adding
Two Integers (1)
• As before
– Comments, #include <stdio.h> and main
• int integer1, integer2, sum;
– Definition of variables
• Variables: locations in memory where a value can be stored
– int means the variables can hold integers (-1, 3, 0, 47)
– Variable names (identifiers)
• integer1, integer2, sum
• Identifiers: consist of letters, digits (cannot begin with a digit)
and underscores( _ )
– Case sensitive
– Definitions appear before executable statements
• If an executable statement references and undeclared variable
it will produce a syntax (compiler) error
CC2005 (10/11) Sem 1 - L5 24
Another Simple C Program: Adding
Two Integers (2)
• scanf( "%d", &integer1 );
– Obtains a data value from the user
• scanf uses standard input (usually keyboard)
– This scanf statement has two arguments
• %d - indicates data should be a decimal integer
• &integer1 - location in memory to store variable
• & is confusing in beginning – for now, just remember to
include it with the variable name in scanf statements
– When executing the program the user responds to the
scanf statement by typing in a number, then pressing
the enter (return) key

CC2005 (10/11) Sem 1 - L5 25


Another Simple C Program:
Adding Two Integers (3)
• = (assignment operator)
– Assigns a value to a variable
– Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
– Variable on left receiving value
• printf( "Sum is %d\n", sum );
– Similar to scanf
• %d means format of decimal integer will be printed
• sum specifies what data value will be printed
– Calculations can be performed inside printf
statements
printf( "Sum is %d\n", integer1 + integer2 );
CC2005 (10/11) Sem 1 - L5 26
Memory Concepts
• Variables
– Variable names correspond to locations in the
computer's memory
• Can begin with letters and ‘_’ but not the others
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable
(through scanf, for example), it replaces (and destroys)
the previous value
– Reading variables from memory does not change
them
• A visual representation integer1 45

CC2005 (10/11) Sem 1 - L5 27


Data Types (1)
• A data type is the specific category of information that
a variable contains
• It determines how much memory to allocate for the
data, as well as the types of operations that can be
performed on a variable

CC2005 (10/11) Sem 1 - L5 28


Data types (2)
• C data types:
– Integer (int) is a positive or negative number with no
decimal places
• Can be unsigned (unsigned int): always positive
• Can use decimal, octal and hexadecimal number system
• E.g. int a = 123;
– floating-point number (float, double) contains decimal
places or is written using exponential notation
• Can use scientific and exponential notation
• E.g. float a = 1.234;

CC2005 (10/11) Sem 1 - L5 29


Data types (3)
• C data types (cont.):
– Character (char) variable is used to store a single
character
• E.g. char a = ‘a’;
– String (a char array) variable is used to store a
character strings
• E.g. char str[] = “Hello world!”;
– Boolean (bool) variable can store true or false logic
value only
• E.g. bool t = true;

CC2005 (10/11) Sem 1 - L5 30


Type Casting
• Casting, or type casting, copies the value
contained in a variable of one data type into a
variable of another data type
• The C and C++ syntax for casting variables is
variable = (new_type) old_variable;
• Example :
float a = 1000.123;
int b = (int) a; //b = 1000

CC2005 (10/11) Sem 1 - L5 31


Constant
• There are two methods of creating constants in
C: the #define statement or the const keyword
• The #define statement is a preprocessor
directive that defines a constant
• You place a #define statement at the beginning
of a file, just as you do with the #include
statement

CC2005 (10/11) Sem 1 - L5 32


Arithmetic (1)
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication
before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3

CC2005 (10/11) Sem 1 - L5 33


Arithmetic (2)
• Arithmetic operators:
C operation Arithmetic operator Algebraic expression C expression

Addition + f+7 f + 7

Subtraction - p–c p - c

Multiplication * bm b * m

Division / x/y x / y

Modulus % r mod s r % s

• Rules of operator precedence:


Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is
evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not
nested), they are evaluated left to right.

*, /, or % Multiplication,Division, Evaluated second. If there are several, they are


Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

CC2005 (10/11) Sem 1 - L5 34


Decision Making: Equality and Relational Operators (1)
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; (Leftm ost multip lic ation)
2 * 5 is 10

Step 2. y = 10 * 5 + 3 * 5 + 7; (Leftm ost multip lic ation)


10 * 5 is 50

Step 3. y = 50 + 3 * 5 + 7; (Multip lic ation before ad dition)


3 * 5 is 15

Step 4. y = 50 + 15 + 7; (Leftm ost ad dition)


50 + 15 is 65

Step 5. y = 65 + 7; (Last a dd ition)


65 + 7 is 72

Step 6. y = 72; (Last op era tio n—p la c e 72 in y)


CC2005 (10/11) Sem 1 - L5 35
Decision Making: Equality and Relational Operators (2)

• Executable statements
– Perform actions (calculations, input/output of data)
– Perform decisions
• May want to print "pass" or "fail" given the value of a test grade
• if control statement
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement will be
executed
• 0 is false, non-zero is true
– Control always resumes after the if structure
• Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names

CC2005 (10/11) Sem 1 - L5 36


Decision Making: Equality and Relational Operators (3)
Standard algebraic equality C equality or Example of C Meaning of C condition
operator or relational operator relational operator condition
Equality Operators
= == x == y x is equal to y

≠ != x != y x is not equal to y

Relational Operators
> > x > y x is greater than y

< < x < y x is less than y

>= >= x >= y x is greater than or equal to y

<= <= x <= y x is less than or equal to y

CC2005 (10/11) Sem 1 - L5 37


Decision Making: Equality and Relational Operators (4)

Operators Associativity
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
= right to left
Fig. 2.14 Precedence and associativity of the operators discussed so far.

Keywords

auto double int struct

break else long switch


case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Fig. 2.15 C’s reserved keywords.

CC2005 (10/11) Sem 1 - L5 38


1 /* Fig. 2.13: fig02_13.c
2 Using if statements, relational
3 operators, and equality operators */
4 #include <stdio.h>
5
6 /* function main begins program execution */
7 int main()
8 {
9 int num1; /* first number to be read from user */
10 int num2; /* second number to be read from user */
11
12 printf( "Enter two integers, and I will tell you\n" );
13 printf( "the relationships they satisfy: " ); Example 5
14
15 scanf( "%d%d", &num1, &num2 ); /* read two integers */
16
17 if ( num1 == num2 ) {
18 printf( "%d is equal to %d\n", num1, num2 );
19 } /* end if */
20
21 if ( num1 != num2 ) {
22 printf( "%d is not equal to %d\n", num1, num2 );
23 } /* end if */
24

CC2005 (10/11) Sem 1 - L5 39


25 if ( num1 < num2 ) {
26 printf( "%d is less than %d\n", num1, num2 );
27 } /* end if */
28
29 if ( num1 > num2 ) {
30 printf( "%d is greater than %d\n", num1, num2 );
31 } /* end if */
32
33 if ( num1 <= num2 ) {
34 printf( "%d is less than or equal to %d\n", num1, num2 );
35 } /* end if */
36
37 if ( num1 >= num2 ) {
38 printf( "%d is greater than or equal to %d\n", num1, num2 );
39 } /* end if */
40
41 return 0; /* indicate that program ended successfully */
42
43 } /* end function main */

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7 Output
3 is less than or equal to 7

CC2005 (10/11) Sem 1 - L5 40


Adding Comments to a Program
• Comments are nonexecuting
lines that you place in your
code that contain various
types of remarks

– Important in program
development in team and
maintenance

• C supports block comments


(/* */) only but usually also
support line comments (//)

CC2005 (10/11) Sem 1 - L5 41


Summary
• Introduction to computer programming
– Use of different programming languages
– Methods on how to design, test & debug a program
• The basic of C programming
– Variables
– Arithmetic operators
– Decision making
• On-line references
– http://www.cs.cf.ac.uk/Dave/C/CE.html
– http://www.strath.ac.uk/IT/Docs/Ccourse/
END
CC2005 (10/11) Sem 1 - L5 42

You might also like