CProgramming Part 1
CProgramming Part 1
1/12/2007
instructions to the computer telling it to carry out the tasks that you want it to do to produce the results you want.
1/12/2007
What is Programming?
Programming consists of two distinct steps: algorithmic design (the problem solving stage, analogous to the work of an architect designing a building) coding (the construction phase)
1/12/2007 School of Computer Science [email protected] 3
1/12/2007
Machine Language
Actual binary code that gives basic instructions to the computer. These are usually simple commands like adding two numbers or moving data from one memory location to another. Different for each computer processor
1/12/2007 School of Computer Science [email protected] 5
Assembly Language
A way for humans to program computers directly without memorizing strings of binary numbers. There is a one-to-one correspondence with machine code.
For example ADD and MOV are mnemonics for addition and move operations that can be specified in single machine language instructions.
1/12/2007
High-level language
Permits humans to write complex programs without going step-by step. High-level languages include Pascal, FORTRAN, Java, Visual Basic, and many more. One command in a high-level language may translate to tens of machine language instructions.
1/12/2007 School of Computer Science [email protected] 7
Translation
Computers can only run machine language programs directly. Assembly language programs are assembled, or translated into machine language. Likewise, programs written in high-level languages, like Java, must also be translated into machine language before they can be run. To do this translation compile a program.
1/12/2007
Translation
#include <stdio.h> int main() { printf(Hello World); return 0; }
10100110 01110110 00100110 00000000 11111010 11111010 01001110 10100110 11100110 10010110 11001110 00101110 10100110 01001110 11111010 01100110 01001110 10000110 etc...
Source code
Executable code
Compilers and linkers translate a high level program into executable machine code 1/12/2007 School of Computer Science [email protected]
Structured Programming
STRUCTURED PROGRAMMING A technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure withOUT UNconditional branches to higher levels of the structure. Three types of control flow are used: (1) sequential, (2) selection, and (3) iteration.
1/12/2007
10
Programming language C
C is a general purpose programming language. C is a middle level language. C is a structured language.
1/12/2007
11
Programming language C
Why C is called a middle level language? C contains the features of high level language portability it is easy to adapt software written for one type of computer to another type. the functionality low level language. - operators such as &, |,>,< etc. simulate to low level instruction codes. - Direct manipulation of bits, bytes and addresses.
1/12/2007
12
Writing C Programs
A programmer uses a text editor to create or modify files containing C code. Code is also known as source code. A file containing source code is called a source file. After a C source file has been created, the programmer must invoke the C compiler before the program can be executed (run).
1/12/2007
13
3 Stages of Compilation
Stage 1: Preprocessing
Performed by a program called the preprocessor Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code
Strips comments and white space from the code The source code as stored on disk is not modified.
1/12/2007
16
Program Development
Editor
Source File pgm.c
Preprocessor
Modified Source Code in RAM
Compiler
Program Object Code File pgm.obj Other Object Code Files (if any)
Linker
Executable File pgm.exe
1/12/2007 School of Computer Science [email protected] 19
A Simple C Program
/* Filename: Author: Date written: Description: */ #include <stdio.h> int main ( void ) { printf ( Hello, World!\n ) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 20
hello.c Brian Kernighan & Dennis Ritchie ?/?/1978 This program prints the greeting Hello, World!
Anatomy of a C Program
program header comment preprocessor directives (if any) int main ( ) { statement(s) return 0 ; }
1/12/2007 School of Computer Science [email protected] 21
1/12/2007
22
Preprocessor Directives
Lines that begin with a # in column 1 are called preprocessor directives (commands). Example: the #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code. This header file was included because it contains information about the printf ( ) function that is used in this program.
1/12/2007 School of Computer Science [email protected] 23
stdio.h
When we write our programs, there are libraries of functions to help us so that we do not have to write the same code over and over again. Some of the functions are very complex and long. Not having to write them ourselves make it easier and faster to write programs. Using the functions will also make it easier to learn to program!
1/12/2007 School of Computer Science [email protected] 24
1/12/2007
26
return 0 ;
Because function main() returns an integer value, there must be a statement that indicates what this value is. The statement return 0 ; indicates that main() returns a value of zero to the operating system. A value of 0 indicates that the program successfully terminated execution. Do not worry about this concept now. Just remember to use the statement.
1/12/2007 School of Computer Science [email protected] 28
Another C Program
/***************************************** ** File: proj1.c ** Author: ___________ ** Date: 9/15/01 ** E-mail: _________________ ** ** This program prompts the user for two integer values then displays ** their product. ** ***********************************************/
1/12/2007
29
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.
1/12/2007
31
Tokens are:
Tokens can be:
Numeric constants Character constants String constants Keywords Names (identifiers) Punctuation Operators
1/12/2007
32
Numeric Constants
Numeric constants are an uninterrupted sequence of digits (and may contain a period). They never contain a comma. Examples:
123 98.6 1000000
1/12/2007
33
Character Constants
One character from a defined character set. Surrounded on the single quotation mark. Examples:
A a $ 4
1/12/2007 School of Computer Science [email protected] 34
String Constants
A sequence characters surrounded by double quotation marks. Considered a single item. Examples:
DAVV I like ice cream. 123 DHOOM-2 car
1/12/2007 School of Computer Science [email protected] 35
Keywords
Sometimes called reserved words. Are defined as a part of the C language. Can not be used for anything else! Examples:
int while for
1/12/2007
36
Names
Sometimes called identifiers. Can be of anything length, but on the first 31 are significant (too long is as bad as too short). Are case sensitive:
abc is different from ABC
Must begin with a letter and the rest can be letters, digits, and underscores. There can be one exception to beginning letter that variable name can start with underscore( _ ) but it is used by C library.
1/12/2007 School of Computer Science [email protected] 37
Punctuation
Semicolons, colons, commas, apostrophes, quotation marks, braces, brackets, and parentheses. ; : , [ ] { } ( )
1/12/2007
38
Operators
There are operators for:
1/12/2007
assignments mathematical operations relational operations Boolean operations bitwise operations shifting values calling functions subscripting obtaining the size of an object obtaining the address of an object referencing an object through its address
School of Computer Science [email protected] 39
Naming Variables
Variables in C may be given representations containing multiple characters. But there are rules for these representations. Variable names (identifiers) in C
May only consist of letters, digits, and underscores May be as long as you like, but only the first 31 characters are significant May not begin with a digit May not be a C reserved word (keyword)
1/12/2007 School of Computer Science [email protected] 41
Naming Conventions
C programmers generally agree on the following conventions for naming variables.
Begin variable names with lowercase letters Use meaningful identifiers Separate words within identifiers with underscores or mixed upper and lower case. Examples: surfaceArea surface_Area surface_area Be consistent!
1/12/2007 School of Computer Science [email protected] 43
1/12/2007
44
Case Sensitivity
C is case sensitive
It matters whether an identifier, such as a variable name, is uppercase or lowercase. Example: area Area AREA ArEa are all seen as different variables by the compiler.
1/12/2007 School of Computer Science [email protected] 45
1/12/2007
46
Declaring Variables
Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it. The declaration statement includes the data type of the variable. They must be declared just after the start of block (i.e. start of a function) and before any other executable statement. Examples of variable declarations: int meatballs ; float area ;
1/12/2007 School of Computer Science [email protected] 47
int
[email protected] 48
1/12/2007
49
7
diameter
5.9
initial
1/12/2007
51
Functions
It is necessary for us to use some functions to write our first programs. Functions are parts of programs that perform a certain task and we have to give them some information so the function can do the task. We will show you how to use the functions as we go through the course and later on will show you how to create your own.
1/12/2007
53
Displaying Variables
Variables hold values that we occasionally want to show the person using the program. We have a function called printf( ) that will allow us to do that. The function printf needs two pieces of information to display things.
How to display it What to display
Backslash Codes
Code
\b \f \n \r \t \" \' \\ \v \a \? \N \xN
1/12/2007
Meaning
Backspace Form feed New line Carriage return Horizontal tab Double quote Single quote Backslash Vertical tab Alert Question mark Octal constant (where N is an octal constant) Hexadecimal constant (where N is a hexadecimal constant)
School of Computer Science [email protected] 57
We also can call a scanf m=scanf(%d%f,&i,&f) What will be the value of n & m if every thing goes fine.
1/12/2007 School of Computer Science [email protected] 59
garbage
feet
garbage
fathoms
garbage
fathoms 7 feet 42 inches 504
1/12/2007
60
printf (Its depth at sea: \n) ; printf ( %d fathoms \n, fathoms) ; printf ( %d feet \n, feet) ; printf ( %d inches \n, inches) ; return 0 ; }
1/12/2007
61
Enhanced Program
#include <stdio.h> int main ( void ) { float inches, feet, fathoms ; printf (Enter the depth in fathoms : ) ; scanf (%f, &fathoms) ; feet = 6 * fathoms ; inches = 12 * feet ; printf (Its depth at sea: \n) ; printf ( %f fathoms \n, fathoms) ; printf ( %f feet \n, feet) ; printf ( %f inches \n, inches) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 63
Notice the & in front of the variable name. It says to use the address of the variable to hold the information that the user enters.
1/12/2007 School of Computer Science [email protected] 64
/* Get the depth in fathoms from the user */ printf (Enter the depth in fathoms : ) ; scanf (%f, &fathoms) ;
1/12/2007 School of Computer Science [email protected] 65
Arithmetic Operators in C
Name Operator Example num1 + num2 initial - spent fathoms * 6 sum / count m%n
1/12/2007
70
Division
If both operands of a division expression are integers, you will get an integer answer. The fractional portion is thrown away. Examples : 17 / 5 = 3 4 / 3 = 1 35 / 9 = 3
1/12/2007
71
Division (cont)
Division where at least one operand is a floating point number will produce a floating point answer. Examples : 17.0 / 5 = 3.4 4 / 3.2 = 1.25 35.2 / 9.1 = 3.86813 What happens? The integer operand is temporarily converted to a floating point, then the division is performed.
1/12/2007 School of Computer Science [email protected] 72
Division By Zero
Division by zero is mathematically undefined. If you allow division by zero in a program, it will cause a fatal error. Your program will terminate execution and give an error message. Non-fatal errors do not cause program termination, just produce incorrect results.
1/12/2007 School of Computer Science [email protected] 73
Modulus
The expression m % n yields the integer remainder after m is divided by n. Modulus is an integer operation -- both operands MUST be integers. Examples : 17 % 5 = 2 6%3 = 0 9%2 = 1 5%8 = 5
1/12/2007 School of Computer Science [email protected] 74
1/12/2007
75
* / % + =
1/12/2007
76
Using Parentheses
Use parentheses to change the order in which an expression is evaluated. a+b*c Would multiply b * c first, then add a to the result. If you really want the sum of a and b to be multiplied by c, use parentheses to force the evaluation to be done in the order you want. (a + b) * c Also use parentheses to clarify a complex expression.
1/12/2007 School of Computer Science [email protected] 77
Relational Operators
< > <= >= == != less than greater than less than or equal to greater than or equal to is equal to is not equal to
Relational expressions evaluate to the integer values 1 (true) or 0 (false). All of these operators are called binary operators because they take two expressions as operands.
1/12/2007 School of Computer Science [email protected] 79
Expression a + b >= c a + b == c a != b a + b != c
Value
80
1/12/2007
81
True/False
82
Increment Operator
If we want to add one to a variable, we can say: count = count + 1 ; Programs often contain statements that increment variables, so to save on typing, C provides these shortcuts: count++ ; OR ++count ; Both do the same thing. They change the value of count by adding one to it.
1/12/2007 School of Computer Science [email protected] 84
Postincrement Operator
The position of the ++ determines when the value is incremented. If the ++ is after the variable, then the incrementing is done last (a postincrement). int amount, count ; count = 3 ; amount = 2 * count++ ; amount gets the value of 2 * 3, which is 6, and then 1 gets added to count. So, after executing the last line, amount is 6 and count is 4.
1/12/2007 School of Computer Science [email protected] 85
Preincrement Operator
If the ++ is before the variable, then the incrementing is done first (a preincrement). int amount, count ; count = 3 ; amount = 2 * ++count ; 1 gets added to count first, then amount gets the value of 2 * 4, which is 8. So, after executing the last line, amount is 8 and count is 4.
1/12/2007 School of Computer Science [email protected] 86
Decrement Operator
If we want to subtract one from a variable, we can say: count = count - 1 ; Programs often contain statements that decrement variables, so to save on typing, C provides these shortcuts: count-- ; OR --count ; Both do the same thing. They change the value of count by subtracting one from it.
1/12/2007 School of Computer Science [email protected] 88
Postdecrement Operator
The position of the -- determines when the value is decremented. If the -- is after the variable, then the decrementing is done last (a postdecrement). int amount, count ; count = 3 ; amount = 2 * count-- ; amount gets the value of 2 * 3, which is 6, and then 1 gets subtracted from count. So, after executing the last line, amount is 6 and count is 2.
1/12/2007 School of Computer Science [email protected] 89
Predecrement Operator
If the -- is before the variable, then the decrementing is done first (a predecrement). int amount, count ; count = 3 ; amount = 2 * --count ; 1 gets subtracted from count first, then amount gets the value of 2 * 2, which is 4. So, after executing the last line, amount is 4 and count is 2.
1/12/2007 School of Computer Science [email protected] 90
Value
4
Answer
garbage
Lvalue Required
answer++ = value-- / 3 ;
In C any value that is having an address is called an Lvalue.
1/12/2007
92
Practice
Given int a = 1, b = 2, c = 3 ; What is the value of this expression? ++a * b - c-What are the new values of a, b, and c?
1/12/2007
93
More Practice
Given int a = 1, b = 2, c = 3, d = 4 ; What is the value of this expression? ++b / c + a * d++ What are the new values of a, b, c, and d?
1/12/2007
94
Assignment Operators
= += -= Statement a=a+2; a=a-3; a=a*2; a=a/4; a=a%2; b=b+(c+2); d=d*(e-5);
1/12/2007
*= /= %= Equivalent Statement a += 2 ; a -= 3 ; a *= 2 ; a /= 4 ; a %= 2 ; b += c + 2 ; d *= e - 5 ;
[email protected] 95
Value
The braces are not required if the body contains only a single statement. However, they are a good idea and are required by the 104 C Coding Standards.
1/12/2007 School of Computer Science [email protected] 100
Examples
if ( age >= 18 ) { printf(Vote!\n) ; } if ( value == 0 ) { printf (The value you entered was zero.\n) ; printf (Please try again.\n) ; }
1/12/2007 School of Computer Science [email protected] 101
/* the if clause */
103
Example
if ( age >= 18 ) { printf(Vote!\n) ; } else { printf(Maybe next time!\n) ; }
1/12/2007 School of Computer Science [email protected] 104
Example
if ( value == 0 ) { printf (The value you entered was zero.\n) ; printf(Please try again.\n) ; } else { printf (Value = %d.\n, value) ; }
1/12/2007 School of Computer Science [email protected] 105
1/12/2007
107
Example
if ( value == 0 ) { printf (The value you entered was zero.\n) ; } else if ( value < 0 ) { printf (%d is negative.\n, value) ; } else { printf (%d is positive.\n, value) ; }
1/12/2007 School of Computer Science [email protected] 109
Gotcha! = versus ==
int a = 2 ; if ( a = 1 ) /* semantic (logic) error! */ { printf (a is one\n) ; } else if ( a == 2 ) { printf (a is two\n) ; } else { printf (a is %d\n, a) ; }
1/12/2007 School of Computer Science [email protected] 110
Gotcha (cont)
The statement if (a = 1) is syntactically correct, so no error message will be produced. (Some compilers will produce a warning.) However, a semantic (logic) error will occur. An assignment expression has a value -- the value being assigned. In this case the value being assigned is 1, which is true. If the value being assigned was 0, then the expression would evaluate to 0, which is false.
1/12/2007 School of Computer Science [email protected] 111
Logical Operators
So far we have seen only simple conditions. if ( count > 10 ) . . . Sometimes we need to test multiple conditions in order to make a decision. Logical operators are used for combining simple conditions to make complex conditions. && || !
1/12/2007
is AND is OR is NOT
1/12/2007
113
Exp1 && Exp2 && && Expn will evaluate to 1 (true) only if ALL subconditions are true.
1/12/2007 School of Computer Science [email protected] 114
Example Use of ||
if (grade == D || grade == F) { printf (See with your Juniors !\n) ; }
1/12/2007
115
Exp1 && Exp2 && && Expn will evaluate to 1 (true) if only ONE subcondition is true.
1/12/2007 School of Computer Science [email protected] 116
Example Use of !
if ( ! (x == 2) ) /* same as (x != 2) */ { printf(x is not equal to 2.\n) ; }
1/12/2007
117
1/12/2007
118
Gotcha! && or ||
int a = 0 ; int b=1; if ( (a++ == 1) && (b++==1 ) ) /* semantic (logic) error! */ { printf (First Gotcha\n) ; } else if ( (a++ == 0) || (b++==1 ) ) { printf (Second Gotcha\n) ; } else { printf (a is %d\n, a) ; }
1/12/2007 School of Computer Science [email protected] 119
Gotcha (cont)
While evaluating a condition if first subpart of a Complex condition having && operator is false than the remaining subpart will not be evaluated.
Similarly While evaluating a condition if first subpart of a Complex condition having || operator is true than the remaining subpart will not be evaluated.
1/12/2007 School of Computer Science [email protected] 120
Numeric Value
True/False
121
More Practice
Given int a = 5, b = 7, c = 17 ; evaluate each expression as True or False. 1. c / b == 2 2. c % b <= a % b 3. b + c / a != c - a 4. (b < c) && (c == 7) 5. (c + 1 - b == 0) || (b = 5)
1/12/2007 School of Computer Science [email protected] 122
1/12/2007
123
1/12/2007
124
125
126
Example
while ( children > 0 ) { children = children - 1 ; cookies = cookies * 2 ; }
1/12/2007
127
1/12/2007
129
The Pseudocode
<total> = 0 <grade_counter> = 1 While (<grade_counter> <= 10) Display Enter a grade: Read <grade> <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 End_while <average> = <total> / 10 Display Class average is: , <average>
1/12/2007
130
The C Code
#include <stdio.h> int main ( ) { int counter, grade, total, average ; total = 0 ; counter = 1 ; while ( counter <= 10 ) { printf (Enter a grade : ) ; scanf (%d, &grade) ; total = total + grade ; counter = counter + 1 ; } average = total / 10 ; printf (Class average is: %d\n, average) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 131
Versatile?
How versatile is this program? It only works with class sizes of 10. We would like it to work with any class size. A better way :
Ask the user how many students are in the class. Use that number in the condition of the while loop and when computing the average.
1/12/2007
132
New Pseudocode
<total> = 0 <grade_counter> = 1 Display Enter the number of students: Read <num_students> While (<grade_counter> <= <num_students>) Display Enter a grade: Read <grade> <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 End_while <average> = <total> / <num_students> Display Class average is: , <average>
1/12/2007
133
New C Code
#include <stdio.h> int main ( ) { int numStudents, counter, grade, total, average ; total = 0 ; counter = 1 ; printf (Enter the number of students: ) ; scanf (%d, &numStudents) ; while ( counter <= numStudents) { printf (Enter a grade : ) ; scanf (%d, &grade) ; total = total + grade ; counter = counter + 1 ; } average = total / numStudents ; printf (Class average is: %d\n, average) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 134
The more versatile the program, the more difficult it is to write. BUT it is more useable. The more complex the task, the more difficult it is to write. But that is often what a user needs. Always consider the user first.
1/12/2007
135
New Pseudocode
<total> = 0 <grade_counter> = 1 Display Enter a grade: Read <grade> While ( <grade> != -1 ) <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 Display Enter another grade: Read <grade> End_while <average> = <total> / <grade_counter> Display Class average is: , <average>
1/12/2007
138
New C Code
#include <stdio.h> int main ( ) { int counter, grade, total, average ; total = 0 ; counter = 1 ; printf(Enter a grade: ) ; scanf(%d, &grade) ; while (grade != -1) { total = total + grade ; counter = counter + 1 ; printf(Enter another grade: ) ; scanf(%d, &grade) ; } average = total / counter ; printf (Class average is: %d\n, average) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 139
1/12/2007
140
loop?
while ( x != y ) { printf(x = %d, x) ; x=x+2; }
1/12/2007 School of Computer Science [email protected] 144
1/12/2007
146
1/12/2007
147
1/12/2007
148
The for loop is easier to write and read for counter-controlled loops.
1/12/2007 School of Computer Science [email protected] 149
1/12/2007
150
1/12/2007
151
1/12/2007
152
Example
do { printf (Enter a positive number: ) ; scanf (%d, &num) ; if ( num <= 0 ) { printf (\nThat is not positive. Try again\n) ; } } while ( num <= 0 ) ;
1/12/2007
154
Notice that using a while loop in this case requires a priming read.
1/12/2007 School of Computer Science [email protected] 155
A for loop is a very awkward choice here because the loop is event-controlled.
1/12/2007 School of Computer Science [email protected] 156
1/12/2007
157
Infinite Loop
Infinite Loop: A loop that never ends.
Generally, you want to avoid these! There are special cases, however, when you do want to create infinite loops on purpose.
[forever]
1/12/2007
159
1 2 3 4 5
[forever] ?
160
Nested Loops
Loops may be nested (embedded) inside of each other. Actually, any control structure (sequence, selection, or repetition) may be nested inside of any other control structure. It is common to see nested for loops.
1/12/2007
161
162
1/12/2007
163
1/12/2007
165
166
Debugging Tips
Trace your code by hand (a hand trace), keeping track of the value of each variable. Insert temporary printf() statements so you can see what your program is doing.
Confirm that the correct value(s) has been read in. Check the results of arithmetic computations immediately after they are performed.
1/12/2007 School of Computer Science [email protected] 167
Multiple Selection
So far, we have only seen binary selection. if ( age >= 18 )
if ( age >= 18 ) { printf(Vote!\n) ; } } else { printf(Maybe next time!\n) ; } { printf(Vote!\n) ;
1/12/2007
168
1/12/2007
169
1/12/2007
170
This if-else structure is more efficient than the corresponding if structure. Why?
1/12/2007
171
...
default: statement(s) break ; }
1/12/2007 School of Computer Science [email protected] 172
1/12/2007
173
1/12/2007
174
switch Example
switch ( day ) { case 0: printf (Sunday\n) ; break ; case 1: printf (Monday\n) ; break ; case 2: printf (Tuesday\n) ; break ; case 3: printf (Wednesday\n) ; break ; case 4: printf (Thursday\n) ; break ; case 5: printf (Friday\n) ; break ; case 6: printf (Saturday\n) ; break ; default: printf (Error -- invalid day.\n) ; break ; }
Is this structure more efficient than the equivalent nested if-else structure?
1/12/2007
175
1/12/2007
176
1/12/2007
178
char Example
#include <stdio.h> int main ( ) { char ch ; printf (Enter a character: ) ; scanf (%c, &ch) ; printf (The value of %c is %d.\n, ch, ch) ; return 0 ; }
If the user entered an A, the output would be: The value of A is 65.
1/12/2007 School of Computer Science [email protected] 179
1/12/2007
180
getchar ( ) Example
#include <stdio.h> int main ( ) { char ch ; /* int ch would also work! */ printf (Enter a character: ) ; ch = getchar( ) ; printf (The value of %c is %d.\n, ch, ch) ; return 0 ; }
If the user entered an A, the output would be: The value of A is 65.
1/12/2007 School of Computer Science [email protected] 181
If the user entered an A, the output would be: The value of A is 65.
1/12/2007 School of Computer Science [email protected] 183
1/12/2007
187
Problem: Write an interactive program that allows the user to calculate the interest accrued on a savings account. The interest is compounded annually. The user must supply the principal amount, the interest rate, and the number of years over which to compute the interest.
1/12/2007
189
Rough Algorithm
Print explanation of the program Get <principal> from user Get <interest rate> from user Get <number of years> from user <amount> = <principal> While (<number of years> > 0 )
amount = amount + (amount X <interest rate>) <number of years> = <number of year> + 1
Report Design
Interest rate : 7.0000 % Period : 20 years Principal at start of period : 1000.00 Interest accrued : 2869.68 Total amount at end of period : 3869.68
1/12/2007
191
Version #1
/* Filename: interest.c * Author: Hemant Mehta * Date written: 11/14//06 * Description: This program computes the interest accrued in an account * that compounds interest annually. */ #include <stdio.h> int main ( ) { /* Print Instructions */ printf (This program computes the interest accrued in an account that\n); printf (compounds interest annually. You will need to enter the amount\n); printf (of the principal, the interest rate and the number of years.\n\n); return 0; }
1/12/2007 School of Computer Science [email protected] 192
Output #1
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years.
1/12/2007
193
Version #2
/* Filename: interest.c * Author: ___________ * Date written: 11/14//99 * Description: This program computes the interest accrued in an account * that compounds interest annually. */ #include <stdio.h> int main ( ) { float principal, rate ; int years ; /* Print Instructions */ printf (This program computes the interest accrued in an account that\n) ; printf (compounds interest annually. You will need to enter the amount\n) ; printf (of the principal, the interest rate and the number of years.\n\n) ; /* Get input from user */ printf (Enter the principal amount : ) ; scanf (%f, &principal) ; printf (Enter the interest rate as a decimal (for 7%% enter .07) : ) ; scanf (%f, &rate) ; printf (Enter the number of years : ) ; scanf (%d, &years) ; printf (\nprincipal = %f, rate = %f, years = %d\n, principal, rate, years ) ; return 0 ; }
1/12/2007 School of Computer Science [email protected] 194
Output #2
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years. Enter the principal amount : 1000.00 Enter the interest rate as a decimal (for 7% enter .07) : .07 Enter the number of years : 20 principal = 1000.000000, rate = 0.070000, years = 20
1/12/2007
195
Version #3
/* Filename: interest.c * Author: ____________ * Date written: 11/14//99 * Description: This program computes the interest accrued in an account * that compounds interest annually. #include <stdio.h> int main ( ) { float principal, rate, amount, interest ; int years, i ; */
/* Print Instructions */ printf (This program computes the interest accrued in an account that\n); printf (compounds interest annually. You will need to enter the amount\n); printf (of the principal, the interest rate and the number of years.\n\n); /* Get input from user */ printf (Enter the principal amount : ); scanf (%f, &principal); printf (Enter the interest rate as a decimal (for 7%% enter .07) : ) ; scanf (%f, &rate); printf (Enter the number of years : ); scanf (%d, &years);
1/12/2007
196
Version #3 (cont)
/* Save the original principal amount by varying another variable, amount */ amount = principal; /* Calculate total amount in the account after the specified number of years */ for ( i = 0 ; i < 1 ; i++ ) { amount += amount * rate ; } /* Calculate accrued interest */ interest = amount - principal ; printf (\nprincipal = %f, rate = %f, years = %d\n, principal, rate, years ) ; printf (amount = %f, interest = %f\n); return 0 ; }
1/12/2007
197
Output #3
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years. Enter the principal amount : 1000.00 Enter the interest rate as a decimal (for 7% enter .07) : .07 Enter the number of years : 20 principal = 1000.000000, rate = 0.070000, years = 20 amount = 1070.000000, interest = 70.000000
1/12/2007
198
Version #4
/* Filename: interest.c * Author: ____________ * Date written: 11/14//99 * Description: This program computes the interest accrued in an account * that compounds interest annually. #include <stdio.h> int main ( ) { float principal, rate, amount, interest ; int years, i ; */
/* Print Instructions */ printf (This program computes the interest accrued in an account that\n); printf (compounds interest annually. You will need to enter the amount\n); printf (of the principal, the interest rate and the number of years.\n\n); /* Get input from user */ printf (Enter the principal amount : ); scanf (%f, &principal); printf (Enter the interest rate as a decimal (for 7%% enter .07) : ) ; scanf (%f, &rate); printf (Enter the number of years : ); scanf (%d, &years);
1/12/2007
199
Version #4 (cont)
/* Save the original principal amount by varying another variable, amount */ amount = principal; /* Calculate total amount in the account after the specified number of years */ for ( i = 0 ; i < 2 ; i++ ) { amount += amount * rate ; } /* Calculate accrued interest */ interest = amount - principal ; printf (\nprincipal = %f, rate = %f, years = %d\n, principal, rate, years ) ; printf (amount = %f, interest = %f\n); return 0 ; }
1/12/2007
200
Output #4
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years. Enter the principal amount : 1000.00 Enter the interest rate as a decimal (for 7% enter .07) : .07 Enter the number of years : 20 principal = 1000.000000, rate = 0.070000, years = 20 amount = 1144.900000, interest = 144.900000
1/12/2007
201
Version #5
/* Filename: interest.c * Author: ____________ * Date written: 11/14//99 * Description: This program computes the interest accrued in an account * that compounds interest annually. #include <stdio.h> int main ( ) { float principal, rate, amount, interest ; int years, i ; */
/* Print Instructions */ printf (This program computes the interest accrued in an account that\n); printf (compounds interest annually. You will need to enter the amount\n); printf (of the principal, the interest rate and the number of years.\n\n); /* Get input from user */ printf (Enter the principal amount : ); scanf (%f, &principal); printf (Enter the interest rate as a decimal (for 7%% enter .07) : ) ; scanf (%f, &rate); printf (Enter the number of years : ); scanf (%d, &years);
1/12/2007
202
Version #5 (cont)
/* Save the original principal amount by varying another variable, amount */ amount = principal; /* Calculate total amount in the account after the specified number of years */ for ( i = 0 ; i < years ; i++ ) { amount += amount * rate ; } /* Calculate accrued interest */ interest = amount - principal ; printf (\nprincipal = %f, rate = %f, years = %d\n, principal, rate, years ) ; printf (amount = %f, interest = %f\n); return 0 ; }
1/12/2007
203
Output #5
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years. Enter the principal amount : 1000.00 Enter the interest rate as a decimal (for 7% enter .07) : .07 Enter the number of years : 20 principal = 1000.000000, rate = 0.070000, years = 20 amount = 3869.680000, interest = 2869.680000
1/12/2007
204
Final Version
/* Filename: interest.c * Author: ____________ * Date written: 11/14//99 * Description: This program computes the interest accrued in an account * that compounds interest annually. #include <stdio.h> int main ( ) { float principal, rate, amount, interest ; int years, i ; */
/* Print Instructions */ printf (This program computes the interest accrued in an account that\n); printf (compounds interest annually. You will need to enter the amount\n); printf (of the principal, the interest rate and the number of years.\n\n); /* Get input from user */ printf (Enter the principal amount : ); scanf (%f, &principal); printf (Enter the interest rate as a decimal (for 7%% enter .07) : ) ; scanf (%f, &rate); printf (Enter the number of years : ); scanf (%d, &years);
1/12/2007
205
1/12/2007
206
Final Output
This program computes the interest accrued in an account that compounds interest annually. You will need to enter the amount of the principal, the interest rate and the number of years. Enter the principal amount : 1000.00 Enter the interest rate as a decimal (for 7% enter .07) : .07 Enter the number of years : 20 Interest rate : 7.0000 % Period : 20 years Principal at start of period : 1000.00 Interest accrued : 2869.68 Total amount at end of period : 3869.68
1/12/2007
207
Top-Down Design
If we look at a problem as a whole, it may seem impossible to solve because it is so complex. Examples: writing a tax computation program writing a word processor Complex problems can be solved using topdown design, also known as stepwise refinement, where We break the problem into parts Then break the parts into parts Soon, each of the parts will be easy to do
1/12/2007 School of Computer Science [email protected] 208
1/12/2007
209
1/12/2007
210
Read
1/12/2007
Sort
Select
Print
[email protected] 211
Another Level?
Should any of these steps be broken down further? Possibly. How do I know? Ask yourself whether or not you could easily write the algorithm for the step. If not, break it down again. When you are comfortable with the breakdown, write the pseudocode for each of the steps (modules) in the hierarchy. Typically, each module will be coded as a separate function.
1/12/2007 School of Computer Science [email protected] 212
Structured Programs
We will use top-down design for all remaining programming projects. This is the standard way of writing programs. Programs produced using this method and using only the three kinds of control structures, sequential, selection and repetition, are called structured programs. Structured programs are easier to test, modify, and are also easier for other programmers to understand.
1/12/2007 School of Computer Science [email protected] 213
Another Example
Problem: Write a program that draws this picture of a house.
1/12/2007
214
1/12/2007
215
1/12/2007
216
Observation
The door has both a frame and knob. We could break this into two steps.
Main Draw Outline Draw Chimney Draw Door Frame Draw Door Draw Knob Draw Windows
1/12/2007
217
1/12/2007
218
Another Observation
There are three windows to be drawn.
Main Draw Outline Draw Windows
. . .
Draw Window 1
Draw Window 2
Draw Window 3
1/12/2007
219
. . .
1/12/2007
221
1/12/2007
222
1/12/2007
223
Functions
A C program is made up of one or more functions, one of which is main( ). Execution always begins with main( ), no matter where it is placed in the program. By convention, main( ) is located before all other functions. When program control encounters a function name, the function is called (invoked). Program control passes to the function. The function is executed. Control is passed back to the calling function.
1/12/2007 School of Computer Science [email protected] 225
Functions (cont)
We have used few predefined functions such as: printf scanf getchar Programmers can write their own functions. Typically, each module in a programs design hierarchy chart is implemented as a function. C function names follow the same naming rules as C variables.
1/12/2007 School of Computer Science [email protected] 227
Examining printMessage
#include <stdio.h> void printMessage ( void ) ; int main ( ) { printMessage ( ) ; return 0 ; } void printMessage ( void ) { printf (A message for you:\n\n) ; printf (Have a nice day!\n) ; } function definition
1/12/2007 School of Computer Science [email protected] 229
function prototype
function call
Needed because the function call is made before the definition -- the compiler uses it to see if the call is made properly
1/12/2007 School of Computer Science [email protected] 230
After the statements in the function have completed, control is passed back to the calling function, in this case main( ) . Note that the calling function does not have to be main( ) .
1/12/2007 School of Computer Science [email protected] 232
OR
return( ) ;
[email protected] 233
1/12/2007
236
1/12/2007
237
1/12/2007
238
Using averageTwo
#include <stdio.h> float averageTwo (int num1, int num2) ; int main ( ) { float ave ; int value1 = 5, value2 = 8 ; ave = averageTwo (value1, value2) ; printf (The average of %d and %d is %f\n, value1, value2, ave) ; return 0 ; } float averageTwo (int num1, int num2) { float average ; average = (num1 + num2) / 2.0 ; return average ; }
1/12/2007 School of Computer Science [email protected] 239
Parameter Passing
Actual parameters are the parameters that appear in the function call.
average = averageTwo (value1, value2) ;
Formal parameters are the parameters that appear in the function header.
float averageTwo (int num1, int num2)
Actual and formal parameters are matched by position. Each formal parameter receives the value of its corresponding actual parameter.
1/12/2007 School of Computer Science [email protected] 240
1/12/2007
241
Local Variables
Functions only see (have access to) their own local variables. This includes main( ) . Formal parameters are declarations of local variables. The values passed are assigned to those variables. Other local variables can be declared within the function body.
1/12/2007
242
5
int
1/12/2007
8
int float int int float
243
5
int
1/12/2007
8
int float int int float
244 School of Computer Science [email protected]
Changes to Local Variables Do NOT Change Other Variables with the Same Name #include <stdio.h>
void addOne (int number) ; int main ( ) { int num1 = 5 ; addOne (num1) ; printf (In main: ) ; printf (num1 = %d\n, num1) ; return 0 ; } num1 5 int
1/12/2007
void addOne (int num1) { num1++ ; printf (In addOne: ) ; printf (num1 = %d\n, num1) ; } num1 int OUTPUT In addOne: num1 = 6 In main: num1 = 5
[email protected] 245
1/12/2007
246
Header Files
Header files contain function prototypes for all of the functions found in the specified library. They also contain definitions of constants and data types used in that library.
1/12/2007
247
1/12/2007
248
1/12/2007
250
Local variables, function arguments, return value are stored on a stack Each function call generates a new "stack frame" After function returns, stack frame disappears along with all local variables and function arguments for that invocation
1/12/2007
251
void contrived_example(int i, float f) { int j = 10; double d = 3.14; int arr[10]; /* do some stuff, then return */ return (j + i); }
1/12/2007 School of Computer Science [email protected] 252
/* somewhere in code */ int k = contrived_example(42, 3.3); What does this look like on the stack?
1/12/2007
253
(more frames)
stack frame
1/12/2007
Another example:
int factorial(int i) { if (i == 0) { return 1; } else { return i * factorial (i - 1); } }
1/12/2007 School of Computer Science [email protected] 255
Pop quiz: what goes on the stack for factorial(3)? For each stack frame, have...
no local variables one argument (i) one return value
1/12/2007
256
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
stack frame
[email protected] 257
return value
?
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
factorial(1)
return value
?
i = 1
?
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
?
i = 0
factorial(0)
return value
factorial(1)
return value
?
i = 1
?
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
factorial(0)
return value
1
i = 0
factorial(1)
return value
?
i = 1
?
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
factorial(1)
return value
1
i = 1
?
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
2
i = 2
factorial(2)
return value
?
i = 3
factorial(3)
1/12/2007 School of Computer Science
return value
6
i = 3
factorial(3)
1/12/2007 School of Computer Science
stack frame
[email protected] 264
factorial(3)
result:
1/12/2007
265
foo
local variables
1/12/2007
arr[10] = <whatever>
stack frame
[email protected] 267
memory leak!
[email protected] 268
void foo2() { int *arr; /* allocate memory on the heap: */ arr = (int *)calloc(10, sizeof(int)); /* do something with arr */ } /* arr is NOT deallocated */
1/12/2007
269
void foo3() { int *arr; /* allocate memory on the heap: */ arr = (int *)calloc(10, sizeof(int)); /* do something with arr */ free(arr); }
1/12/2007
270
local variables
stack frame
heap
memory leak
1/12/2007
274