Computer Programming I UP ITTC AY 2009-2010
Computer Programming I Introduction: Computer Programming Lesson 1: Overview of Programming Languages Lesson 2: Introduction to C Programming Lesson 3: C Fundamentals Lesson 4: Control Structures
Computer Programming I Lesson Lesson Lesson Lesson Lesson Lesson
5: Subprograms 6: Arrays, Strings and Pointers 7: Command-Line Arguments 8: Structures 9: Dynamic Memory Allocation 10: File Handling
Preface
Prerequisites Computer
Systems 1 Knowledge of algorithms
Related Publications The
C
C Programming Language 2nd Edition
Brian W. Kernighan, Dennis M. Ritchie
by Dissection 4th Edition
Al Kelly, Ira Pohl
Overview
This course introduces computer programming using the language C.
Objectives At the end of this course, you should be able to: Understand the methodology for implementing a program. Understand the programming elements involved in implementing a program in C. Understand the creation and reuse of parts of a program.
Duration
Lecture: 24 hours (4 days) Workshop: 36 hours (6 days)
Schedule Day 1 Lesson 1: Overview of Programming Languages Lesson 2: Introduction to C Programming Lesson 3: C Fundamentals
Schedule Day 2
Lesson 5: Control Structures Lesson 6: Subprograms
Schedule Day 3
Lesson 8: Array, Strings and Pointers Lesson 9: Command-Line Arguments Lesson 10: Structures
Schedule Day 4
Lesson 10: Dynamic Memory Allocation Lesson 11: File Handling
Schedule Days 5 - 7: Workshop:
Machine Problem Part 1
Days 8 – 10: Workshop:
Machine Problem Part 2 Departmental Exam
Course Requirements
Machine Exercises Machine Problem Part 1 Machine Problem Part 2 Long Exam (Departmental Exam)
20% 20% 30% 30%
Overview of Programming Languages Lesson 1
Introduction
Definition of Programming Languages Levels of Programming Languages Machine
Language Assembly Languages High-level Languages Very High-level Languages Natural Languages
What is a Programming Language?
A programming language is a set of rules for instructing the computer what operations to perform.
Levels of Languages
Machine Language Assembly Languages High-level Languages Very High-level Languages Natural Languages
Machine Language
Machine language is the only language understood by a computer
Consists of binary numbers (1s and 0s)
Assembly Languages
Assembly language is a low level message which uses mnemonic codes and abbreviations that are easy to remember We use an assembler in order to convert it from assembly language to machine language
High-level Languages
High-level languages are programming languages that are written in English-like manner. Examples: C, C++, Java, Pascal We use a compiler in order to convert it to machine language.
Very High-level Languages
Very high-level languages are essentially shorthand programming languages.
Also called fourth-generation languages or 4GLs.
Lesson Review
A programming language is a set of rules for instructing the computer what operations to perform. There are five generations/levels of languages: Machine Language, Assembly Languages, Highlevel Languages, Very High-level Languages and Natural Languages. An assembler is used to convert assembly language to machine language. A compiler is used to convert a high-level language to machine language.
Introduction to C Programming Lesson 2
Introduction
Introduction to C Characteristics of C Elements of a C Program Our First C Program: Hello World Compiling & Running our first C Program Phases of a C Program
The “C” Programming Language
A high-level general-purpose programming language
Developed by Brian Kernighan and Dennis Ritchie of AT&T Bell Labs in 1972
Characteristics of C
C is a small language. C is the standard development language for personal computers. C is portable. C is modular. C is the basis for C++ and java.
Elements of a C Program
Identifiers a
name in a C program a string of letters, digits and underscores, provided that the string doesn’t start with a digit. Case-sensitive Examples of VALID identifiers _hello IamAnIden1234 _1234 Example of INVALID identifiers 123hello dDAT.1 file-name
Elements of a C Program
Reserved Words/Keywords words that have predefined meanings and cannot be used as names for anything else. C has 32 keywords, these are:
Our First C Program /** * Hello.c * This is my very first C program and I'm * excited about it :-) **/ #include <stdio.h> int main( void ) { /*print text to screen*/ printf("Hello world!"); }
This is a Comment. Comments are used for documentation purposes and does not affect the program flow.
Our First C Program
/** * Hello.c * This is my very first C program and I'm * excited about it :-) **/ #include <stdio.h> int main( void ) { /*print text to screen*/ printf("Hello world!"); }
Our First C Program
This is a Preprocessor or Precompiler directive. A Preprocessor or Precompiler directive are lines in C that are processed before compiling the code.
/** * Hello.c * This is my very first C program and I'm * excited about it :-) **/ #include <stdio.h> int main( void ) { /*print text to screen*/ printf("Hello world!"); }
Our First C Program Define a block of commands called main. main is a special block – it is where the program starts Crunning. program and I'm Every C program must have a single main block.
/** * Hello.c * This is my very first * excited about it :-) **/ #include <stdio.h>
int main( void ) { /*print text to screen*/ printf("Hello world!"); }
Our First C Program /** * Hello.c * This is my very first C program and I'm * excited about it :-) **/ #include <stdio.h> int main( void ) { /*print text to screen*/ printf("Hello world!"); }
This is also a comment.
Our First C Program The printf function is a standard output function which takes in a string as its function argument, and it to theand screen.I'm Coutputs program This is an example of a statement, it ends with a semicolon.
/** * Hello.c * This is my very first * excited about it :-) **/ #include <stdio.h>
int main( void ) { /*print text to screen*/ printf("Hello world!"); }
Compiling our first C Program
Compiler Used to convert a high-level language to machine language gcc – name of the compiler we will use to compile our C programs
Phases of C Programs:
Edit (C program file names should end with the .c extension) Preprocess Compile Link Load Execute
Phases of C Program
Phase 1: Create your program with an editor program Phase 2: A preprocessor find some preprocessor directives (#include <stdio.h>) to include other files and perform various text replacements Phase 3: Compiler compiles the program into machine languages (object code != object-oriented programming). Phase 4: A linker links the object code with the code in library or other places to produce an executable image. Phase 5: A loader loads the executable image into memory (RAM). Phase 6: CPU executes the program one instruction at a time.
Lesson Review
C is a high-level general-purpose programming language developed by Brian Kernighan and Dennis Ritchie of AT&T Bell Labs in 1972. Identifiers are names in a C program. It consists of a string of letters, digits and underscores, provided that the string doesn’t start with a digit. It is case-sensitive. Reserved words or keywords in C, are words that have predefined meanings and cannot be used as names for anything else. C has 32 keywords.
Lesson Review
To compile: gcc
-o
To run: ./
6 phases that a C program undergoes: Edit, Preprocess, Compile, Link, Load and Execute
Exercise 1
Write a short but complete C program that outputs to screen what you feel about your instructor.
C Fundamentals Lesson 3
Introduction C
Program Structure
Preprocessor/Precompiler directives Libraries Declarations
Type declarations Variable/constant declarations Function/procedure declarations Main function declarations
Introduction
Statements and Blocks Basic Data Types Constants Variables Basic I/O: scanf, printf Operators Arithmetic, Increment/Decrement, Relational, Logical, Modulo, Assignment, Shortcut Precedence
C Program Structure Program structure for C programs: [<preprocessor/precompiler directives>] [<declarations>] <main-function-definition> []
Preprocessor / Precompiler Directives
Precompiler directives or preprocessors are statements in C that are processed before compilation. Usually begins with the # symbol perhaps preceded by white spaces. They may appear anywhere. Examples: #include.. #define...
Libraries a
collection of useful functions and symbols that may be accessed by a program has a standard header file whose name ends with the symbols .h Example: #include <stdio.h> definitions*/
/*printf, scanf
Declarations The following are different types of declarations in C: | |
Variable/Constant Declarations The
syntax of a variable/constant declaration is: [const] [= ];
Variable/Constant Declarations Declarations
that begin with const are constant declarations while those that do not are variable declarations. Examples: const age_type age = 22; const float salary = 54321.20; char* name, address; char gender = 'M';
Function/Procedure Declarations The
syntax of a function/procedure declaration is: (<parameters>) { }
Function/Procedure Declarations Declarations
whose return type is void are procedure declarations. Otherwise, they are function declarations. Examples: void greet(void){ printf("Hello there.\n");
} int add(int x, int y){ return x+y;
}
Main Function Declaration The
syntax of the main function declaration is: main (<parameters>){ <main_body> }
Sample Program
C Statements & Blocks C
Statements are lines of code ending with a semicolon (;).
Blocks
are groups of statements enclosed in curly braces {}.
Basic Data Types C
has at least 3 basic data types:
Character (char) Integer (int) Floating point numbers (float/double)
Character Data Type A
character in C is in the form: '<single character>'
Examples: 'a' (letter a) ':' (colon) '*' (asterisk) 'T' (capital T)
'1' (number one) ' ' (space) '?' (question mark)
Character Data Type C
has special kinds of characters called escape sequences. Here are some of the escape sequences in C: '\f' (formfeed) '\\' (backslash) '\n' (newline) '\'' (single quote) '\r' (carriage return) '\"' (double quote) '\t' (horizontal tab) '\ooo' (octal number) '\xhh' (hexadecimal number)
Character Data Type Are
really just integers.
Character encoding is platform specific. ASCII, Unicode, ISO 8859
char
At least 8 bits (“byte”)
wchar_t
“Wide character” Usually the same as unsigned int (Unicode)
The ASCII Table
Integer Data Type
Integers have values that are whole numbers. They can be positive or negative. The type name for integer data type in C is:
int
Can be written as: Decimal -1234 Hexadecimal -0x1234 Octal -01234
230 0x0E6 0346
+250 +0xFA +0372
Floating Point Data Type A
floating point in C is the data type whose values are numbers, that, when written in the usual decimal notation, have digits after the decimal point. The type name for floating point data type in C is: float Examples of floating points are: 1.0
0.31416 1E6
4.3E5
typedef In
C, you can define your own data types based on existing data types. (alias) Type declaration using basic data types has the following syntax: typedef ;
typedef Examples:
typedef char gender_type; typedef int age_type; typedef float grade_type;
Constants Constants
in C are values that never change throughout the entire program. Types of Constants in C:
Integer Character Floating-point String Enumeration
Constants To
declare your own constants:
const = ; Examples:
const char middle_initial = 'C'; const int num_colors = 7; const float pi = 3.1416;
Constants You
can also use the #define preprocessor to declare constants in your program. The syntax is: #define [value] Examples:
#define Kg_Per_Lbs #define Pi
0.454545 3.1416
Variables Variables,
in C, are objects whose value may change during the course of a program’s execution.
A
variable in C is declared using the following syntax: [= ];
Variables
Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They contain the data your program works with
Variables Declaration
Before using a variable, one must declare it. Variables declaration may only appear at the beginning of a block. The declaration first introduces the variable type, then its name. When a variable is declared, its value is undefined.
Type
int float double char
integer; small_real; big_real; c1, c2;
Identifier
Variables Declaration Naming
Letters, digits, underscores
i CSE_5a a_very_long_name_that_isnt_very_useful fahrenheit
First character cannot be a digit
rules:
5a_CSE
is not valid!
Case sensitive
CSE_5a is different from cse_5a
Example: Variable Declarations int i, j; char ch; float num1 = 5.20, num2 = 7.0; double d;
Primitive Data Types
char – character (1 byte) ‘a’, ‘b’, ‘c’ ..., ‘A’, ‘B’, ‘C’, ... ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘0’ ‘_’ ‘,’ ‘#’ ‘$’ ‘^’ ‘*’ ‘@’ ‘!’ .... int – integer number (4 bytes). 0, -1, 1, -2, 2, .... float – real number (4 bytes) 0.5, 3.2, 4.0, -5.122323, ... double – double precision real number (8 bytes) char
float
int
double
Basic output: printf printf
Allows you to print on the screen To print some string using printf, we type: printf("");
To print a value of a variable using printf, we use format specifiers:
printf("[format specifier]", variable);
printf Conversion Codes
%c – a character %d – an integer, %u – an unsigned integer. %f – a float %e – a float in scientific representation %g – whichever is better between %e and %f %lf – a double %% - the ‘%’ character
Basic output: printf Example:
char letter = 'a'; int number = 100; float fnum = 13.09 printf("This is the letter %c", letter); printf("The number = %d", number); printf("This is a floating point number %f", fnum); printf("%c %d %f", letter, number, fnum);
Basic input: scanf scanf
Allows you to get input from the keyboard
Format: scanf( "", &variableName )
Basic input: scanf Examples:
int number; char letter; printf("Enter a number:"); scanf("%d", &number); printf("Enter a character:"); scanf("%c", &letter);
scanf Conversion Codes
%c – a character %d – an integer, %u – an unsigned integer. %f – a float %e – a float in different representation %lf – a double
Exercise 2
Write a program that asks the user to input his/her name, age, address, telephone number and desired grade. Afterwards print all the information provided by the user.
Signed vs. Unsigned
integer types can be signed or unsigned unsigned int ui; unsigned char uc;
char
signed: -128 to +127 unsigned: 0 to +255
int
signed: −2,147,483,648 to +2,147,483,647 unsigned: 0 to +4,294,967,295
The unsigned qualifier
Normally, the last bit of a variable serves as a sign bit. value sign (+/-)
We can use all the bits to represent the value by declaring a variable as unsigned. To declare a variable as unsigned we add the ‘unsigned’ keyword before its type. unsigned int; unsigned char;
Unsigned Range
char (256 different values) signed unsigned
-127..+128 0..+255
int (4294967296 different values) signed unsigned
-2147483648.. +2147483647 0.. +4294967295
Unsigned - output
When using printf We use %d for signed variables and %u for unsigned ones void main() { unsigned char u = 200; char s; printf("%d\n", u); printf("%u\n", u);
200
s = u;
-56 printf("%d\n", s); printf("%u\n", s); }
4294967240
Overflow
Happens when a variable gets assigned a value that is outside of its range This is equivalent to saying that the number of bits required to encode the value exceeds the number of bits in the variable The value of the variable will usually be corrupted
Overflow Example #include <stdio.h> void main() { int iA = 1000, iB = 1000000, iC = 3000000, iD = 5000000; printf ("%d * %d = printf ("%d * %d = printf ("%d * %d = printf ("%d * %d = }
%d\n", %d\n", %u\n", %u\n",
iA, iA, iA, iA,
iB, iC, iC, iD,
iA*iB); iA*iC); iA*iC); iA*iD);
1000000000 -1294967296 3000000000 705032704
Casting
Sometimes it is desirable for a variable of one type to be considered as belonging to another in an operation We say the variable is cast to the new type. The casting operator is of the form: (type) For example, (float)i casts the variable i to a float.
IO functions from <stdio.h> printf
- prints formatted output to stdout scanf - reads formatted input from stdin puts - prints a string to stdout gets - reads a string from stdin putc - prints a character to stdout getc, getchar - reads a character from stdin
Operators Types
of operators in C:
Arithmetic Operators Increment and Decrement Operators Relational Operators Logical Operators Modulo Operator Assignment Operator Shortcut Operators
Arithmetic Operators Arithmetic Function Operator + Used for Addition
-
Used for Subtraction
*
Used for Multiplication
/
Used for Division
Examples 5 + 2 is 7 (int) 5.0 + 2.0 is 7.0 (float) 5 – 2 is 3 5.0 – 2.0 is 3.0 5 * 2 is 10 5.0 * 2.0 is 10.0 5.0 / 2.0 is 2.5 (float) 5 / 2 is 2 (int)
Increment and Decrement Operators Operator
Function
Examples
++
Increment operator adds 1 to its operand
int x = 10; x++; /*equal to 11*/
--
Decrement operator subtracts 1 to its operand
int x = 10; x--; /*equal to 9*/
Increment and Decrement Operators ++
and -- may be used either as prefix operators (before the variable) or as postfix operators (after the variable).
Increment and Decrement Operators Example:
int num1 = 5; int num2 = 0; num1++; --num2; num2 = num1++; num2 = ++num1;
/*num1 == 6*/ /*num2 == -1*/ /*num2 is assigned value 6 *and num1 incremented*/ /*num1 incremented and *num2 is assigned value of ? */
Exercise 3 Write a program in C that asks the user to input the radius of a circle in centimeters (or portions of centimeters), and then output the area and the circumference of the circle to the screen. The formula for the area is A = πr² and the formula for the circumference is C = 2πr, where r is the radius and π can be approximated to be 3.1416.
Exercise 4 Write a program in C that asks the user to input two integers, one at a time, and then outputs the sum and product to the screen.
Relational Operators
The result of a statement using relational operators could either be 0 (false) and nonzero values (true). Relational Operator < > <= >= == !=
Function
less than greater than less than or equal to greater than or equal to equal to not equal to
Relational Operators Examples: char ch1 = 'c';
int number1 = 10; int number2 = 3; ch1 == 'f' 7 != number1 number2 > number1 number2 < number1
/*false*/ /*true*/ /*false*/ /*true*/
Logical Operators The
result of a statement using logical operators could either be 0 (false) and non-zero values (true). Logical operators
Logical Logical Logical Logical
AND OR NOT XOR
&& || ! ^
Logical Operators
Logical AND Form: op1 && op2 op1
op2
result
nonzero nonzero 0 0
nonzero 0 nonzero 0
nonzero 0 0 0
Logical Operators
Logical OR Form: op1 || op2 op1
op2
result
nonzero nonzero
nonzero
nonzero 0
nonzero
0
nonzero
nonzero
0
0
0
Logical Operators
Logical NOT Form: !op1 op1 result nonzero 0 0 nonzero
Logical Operators
Logical XOR Form: op1 ^ op2 op1
op2
result
nonzero nonzero
0
nonzero 0
nonzero
0
nonzero
nonzero
0
0
0
Logical Operators Examples:
int B1 = 1; int B2 = 0;
/*true*/ /*false*/
B1 && B2; B1 || B2; !B1; B1 ^ B2 ;
/*false*/ /*true*/ /*true*/ /*true*/
Modulo Operator (%)
C allows us to perform modulo operations using the % symbol. This means that if, for example, x and y are two integer variables, the operation x % y will return the remainder of the operation (dividing the first operand by the second). Examples: 10% 3 2 % 3
(this is equal to 1) (this is equal to 2)
Assignment Operator An
assignment Operator stores a value or a computational result in a variable. It is used to perform most arithmetic operations in a program.
The
syntax is:
= <expression>;
Shortcut Operators Any
statement of the form:
= <expression>;
where operator is one of the binary operators + - * / % can be written in the form: =<expression>;
Shortcut Operators Examples:
a c d e f
= = = = =
a c d e f
+ – * / %
b 4 5 3 2
can can can can can
be be be be be
written written written written written
as as as as as
a c d e f
+= -= *= /= %=
b 4 5 3 2
Operator Precedence ! * / % + < <= > >= == != ^ && || = += -= *=
/= %=
(right-associative) (left-associative) (left-associative) (left-associative) (left-associative) (left-associative) (left-associative) (left-associative) (right-associative)
Lesson Review Precompiler directives or preprocessors are statements in C that are processed before compilation. A library is a collection of useful functions and symbols that may be accessed by a program Declarations:Type declarations, Variable/constant declarations, Function/procedure declarations and Main function declarations
Lesson Review
C Statements are lines of code ending with a semicolon (;). Blocks are groups of statements enclosed in curly braces {}. C has at least 3 basic data types: Character (char), Integer (int) and Floating point (float). You can define your own data types by using typedef. Type declaration using basic data types has the following syntax: typedef ;
Lesson Review
You can declare your own constants in C by using const or #define. The syntax for const is: const = ; The syntax for #define is: #define [value] A variable in C is declared using the following syntax: [= ];
Lesson Review We use printf function to print to the screen and scanf to get input from the keyboard. The types of operators in C are: Arithmetic Operators, Increment and Decrement Operators, Relational Operators, Logical Operators, Modulo Operator, Assignment Operator and Shortcut Operators. They follow a certain precedence.
Exercise 5 Write
a program that receives three integers as input and outputs the numbers in increasing order.
Control Structures Lesson 4
Control Structures Kinds
Sequence Control Structures Selection Control Structures
of Control Structures
if if-else switch
Repetition Control Structures
while do-while for
Sequential Program int main() { statement1; statement2; …. statementN; }
statement1
statement2
statementN
if Statement
used to conditionally execute a statement or block of statement.
if (expression) statement;
True or False
In C, every expression has a numeric value An expression is ‘true’ when its value is nonzero it is false it evaluates to zero. Therefore, in the following – if (expression) statement statement is executed if expression evaluates to non-zero.
if-else Statement if (expression) statement1; else statement2;
if expression is false, statement2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”) The else portion is optional.
Multiple if-else constructs
Multiple if-else constructs can also be used to choose between three of more options. TRUE
if (expression1) statement1; else if (expression2) statement2; else statement3;
expression1
statement1
FALSE expression2 FALSE statement3
rest of program
TRUE
statement2
The conditional or ternary operator: ‘?: ‘
The ?: operator is a more efficient form for expressing simple if statements.
It has the following form: <expression1>? <expression2>: <expression3>
It simply states: if (<expression1>) <expression2>; else <expression3>;
The conditional or ternary operator: ‘?: ‘
Example:
Suppose we want to assign the maximum of a and b to z. Using the ? operator, we have the following statement: z = (a > b) ? a : b;
which is the same as: if (a > b)
z = a; else
z = b;
switch Statement
A multi-way conditional statement similar to the if … else if … else … allows the selection of an arbitrary number of choices based on an integer value switch (<expression>) { case : <statements> case : <statements> …. …. case : <statements> default : <statements> }
switch Statement
expression must have an integer value (char, int)
when the switch statement is executed: the expression is evaluated if a case matches the value of the expression, the program jumps to the first statement after that case label otherwise, the default case is selected the default is optional
while loop The while loop has the following while ()
syntax:
<statement>
where,
The boolean_expression in the syntax can be any expression that evaluates to TRUE or FALSE only. The statement can be either a simple statement or a compound statement.
while loop FALSE expression
The statement is executed as long as condition is true. The loop terminates when the condition is no longer true.
TRUE statement/s
rest of program
while loop Here
is a simple example of the use of the while loop: i=1 while (i<=5) { printf("%d",i); i++; }
while loop There
are some things you have to remember when using the while loop. First
and foremost is that the while loop must terminate eventually. This means that you have to make sure that the boolean expression must evaluate to FALSE at some foreseeable point. Loops that do not terminate are called infinite loops.
do-while loop statement/s TRUE
do { statement(s); } while ( condition );
condition FALSE rest of program
Similar to while loops Except the condition is evaluated after the loop body The loop body is always executed at least once, even if the expression is never true
do-while loop Example:
i=1; do { printf("%d", i); i++; } while (i<=5);
for loop initialization
for ( ; ; ) { statement(s); }
condition
statement(s)
increment
rest of program
break and continue C
provides two commands to control how we loop:
break – to exit from a loop or a switch continue – skip an iteration of the loop
End