C Language Notes
C Language Notes
Structured Problem
Solving
Using the Computer
by
Lynne Koenecke
In tro d u c t i o n t o M i c ro c om p ute r s
Components of a Computer
Hardware components of a Computer
Central
Processing
Unit
Input Output
Main Memory
(Primary Storage)
RAM
Secondary
Storage
Input -
Keyboard, Scanner, Mouse, Light Pen, Digitizing Tablet
Output -
Monitor, Laser Printer, Dot-matrix Printer, Ink Jet Printer, Plotter,
Sound
Secondary Storage -
Floppy Disk, CD-ROM, Hard Disk, Magnetic Tape
Main Memory
Random Access Memory - volatile memory that holds instructions to
be processed by the CPU and data ready to be used. All types of
information are stored in main memory.
• Data and instructions are stored sequentially.
• Each memory cell has a unique address associated with it.
• The information stored in a memory location is called its
contents.
• Every memory cell always contains some information.
Address Contents
0 -27.2
1 354
2 0.005
3 -785
4 H
. .
. .
98 OH
99 65.78
Lynne Koenecke 3
Illinois State University, ACS
Software
Application software is also custom written for the user. In this class
you will be writing customized software application programs in C.
Software includes both source code written by humans and executable
machine code produced by assemblers or compilers.
Lynne Koenecke 4
Illinois State University, ACS
P ro g r amm in g L a n g u a g e s
Machine Language
The "native tongue" of a particular kind of computer. Written in binary
numbers (0s and 1s).
0010 0000 0000 0100
0100 0000 0000 0101
0011 0000 0000 0110
Assembly Language
Uses descriptive names to reference data.
LOAD value
ADD delta
STORE value
The result of assembly instructions is Machine Language.
High-Level Language
• Easier to understand
• Portable - can be used on many different types of computers
with few modifications.
• Allow programmers to write instructions with statements that
resemble English.
Lynne Koenecke 5
Illinois State University, ACS
P ro c e s s in g a H i g h -L e v e l L a n g u a g e P ro g r am
Programmer enters high-level
programming statements into and
editor and saves it as a source file.
Compiler attempts to
translate the program Programmer corrects syntax errors
Failure
Success List of errors
New
Object
File Other
Object
Files
Load
file
Executable program
in memory
Lynne Koenecke 6
Illinois State University, ACS
Source Preprocessed Object Executable
Code Source Code Code Code
External
Items
E r ro r s i n P ro g r amm in g
Programs rarely run correctly the first time they are compiled.
Programming errors are known as “bugs”. The process of correcting
errors in programs is called debugging a program.
Types of Errors
Syntax Errors
They are also called compilation errors. Syntax errors are detected by
the compiler as it tries to translate the program statement. Syntax
errors are the result of incorrect usage of the programming language's
rules of syntax.
Run-time Errors
Run-time errors are detected by the computer as a program is
executing. These errors stop the execution of the program and an error
message is displayed.
Logic Errors
Logic errors become evident in programs that are syntactically correct
and do not have run-time errors, yet the program produces an incorrect
answer. It is very important that you test your program with hand
calculated answers to be sure that your program works as intended.
Lynne Koenecke 7
Illinois State University, ACS
H o w P ro g r am s R e c e i v e In p u t
D a t a vs . In f o rm a t i o n
Data - raw facts given to a computer during the input operation
which is used to process information.
Information - Data that has been processed into a form that has
meaning and is useful.
Lynne Koenecke 8
Illinois State University, ACS
Wh a t C omp ute r s C a n D o
Computers can:
1. Receive data
from an input device (keyboard,
mouse, etc.)
from a file
2. Display/write information
to the display device (monitor)
to a printer
3. Perform arithmetic
addition, subtraction, multiplication, division
Lynne Koenecke 9
Illinois State University, ACS
P ro b l em S o lv i n g a n d S o ft w a re D ev e l o pm e nt
Top-Down Design
Most programming problems are too complex to solve all at once.
Turning a problem into a program requires a programmer to create
smaller problems that fit together to solve the large, complex problem.
This is referred to as top-down design, because the design process
starts at the top, with the main ideas, and works down to the details.
Characteristics of Algorithms
Algorithms must . . .
1. be precise and unambiguous
2. be the correct solution in all cases
3. eventually end
Pseudocode
Programmers typically write algorithms in a form called pseudocode.
Pseudocode is a cross between a computer language and plain English.
The pseudocode is translated into a computer language after the
algorithm has been tested for correctness.
Characteristics of Pseudocode
• Statements written in simple English
• Each instruction written on a separate line
• Keywords and indentation are used to signify control
Lynne Koenecke 10
Illinois State University, ACS
St e p s t o S o lv i n g a P ro b l em
Design
1. Defining the problem
2. Outline the solution
3. Develop the outline into an algorithm
4. Test the algorithm for correctness
Implementation
5. Code the algorithm into a specific programming language
6. Run the program on the computer
7. Document and maintain the program
art
sk ithm Ch
n t &
De or re
7. De de
tai en
Do bug
k
4. Alg ctu
Co
2. IPO
ain m
ec
M cu
3. Stru
Ch
5.
1.
6.
Design Implementation
Lynne Koenecke 11
Illinois State University, ACS
1. Defining the Problem:
Divide the problem into three components: inputs, processing, and
outputs.
We use an IPO chart to illustrate this step.
I P O
Lynne Koenecke 12
Illinois State University, ACS
Example 1
Outline a solution for a program that will read 3 numbers and print the
average.
I P O
number1 get numbers average
number2 add numbers
number3 calculate average
print average
Example 2
Outline a solution for a program that will read 3 numbers and print the
numbers and the average.
I P O
number1 get numbers number1
number2 add numbers number2
number3 calculate average number3
print average average
Lynne Koenecke 13
Illinois State University, ACS
3. Converting the IPO into an Algorithm
Example 1
Average 3 numbers
get number1
get number2
get number3
total = number1 + number2 + number3
average = number1 + number2 + number3/3
print “Average: “ average
End Average 3 numbers
Lynne Koenecke 14
Illinois State University, ACS
P ro g r am C o n t ro l S tr u c tu re s
Sequence
Selection
Repetition
Sequence
Execution of one processing step after another in order.
Task A
Task B
Task C
True False
Is 1>2?
Lynne Koenecke 15
Illinois State University, ACS
Repetition (looping)
Repeating a group of
instructions as long as a False
condition is true or until a
condition is false. ?
True
Pre-test loop
DO WHILE condition
statement
statement
statement
END WHILE
Lynne Koenecke 16
Illinois State University, ACS
A c t i o n D i a g r am s
Action Diagrams add an additional visual element to algorithms to indicate
sequence, selection, and repetition. (Refer to the Action Diagrams section
in the Appendix of your Lab Manual).
Sequence
Indicates start of algorithm Algorithm Name
statement
statement
statement
statement
Indicates end of algorithm End Algorithm Name
Statements are followed in order from the start of the algorithm to the end
of the algorithm.
Lynne Koenecke 17
Illinois State University, ACS
Selection (CASE structure)
Indicates start of algorithm Algorithm Name
statement
CASE of final_grade
90 - 100: letter_grade = ‘A’
80 - 89: letter_grade = ‘B’
70 - 79: letter_grade = ‘C’
60 - 69: letter_grade = ‘D’
other: letter_grade = ‘F’
END CASE
Indicates end of algorithm End Algorithm Name
As the statements in the algorithm are executed, a choice is made by
evaluating the value of final_grade and using a CASE control structure.
Only one assignment is made based on the evaluation of final_grade..
Repetition
Indicates start of algorithm Algorithm Name
statement
DO WHILE condition
statement
statement
statement
END WHILE
End Algorithm Name
Indicates end of algorithm
As the statements in the algorithm are executed, a group of statements are
repeated withing the DO WHILE control structure until the condition is
evaluated to FALSE. The double line indicates repetition.
Lynne Koenecke 18
Illinois State University, ACS
Va r i a b l e s
As mentioned earlier, computers use main memory (RAM) to hold
instructions and data for processing. High-level programs allow programmers
to assign a name to a memory cell. When program statements are written, the
memory cell is referred to as the name the programmer gave it.
Assignment Statement:
value1 = number + variable1
Lynne Koenecke 19
Illinois State University, ACS
C on t ro l St r u c tu re E x amp l e s
Predict what the output would be for each of the following Selection Control
Structures:
Example 1:
num1 = 10 Output
num2 = 20
IF num1 < num2 THEN
Print “num1 is less than num2”
ELSE
Print “num2 is less than num1”
ENDIF
Example 2:
variable1 = 100 Output
variable2 = 101
IF variable1 > variable2 THEN
Print “variable1 is greater than variable2”
ELSE
Print “variable 2 is greater than variable1”
ENDIF
Lynne Koenecke 20
Illinois State University, ACS
Predict the output of the following Repetition Control Structures:
value = 1 Output
DO WHILE value < 3
Print value
value = value + 1
END WHILE
Print “The last number is” value
value = 4 Output
DO WHILE value < 6
Print value
value = value + 1
END WHILE
Print “The Last number is” value
value = 4 Output
DO WHILE value > 0
Print value
value = value - 1
END WHILE
Lynne Koenecke 21
Illinois State University, ACS
Jessica
A g e n t l e r In t ro d u c t i o n to P ro g r amm in g
Jessica’s World
• Jessica lives on Santong Island
• Jessica’s home position is in the extreme Northwest corner
• Jessica cannot swim
• She knows direction: North, South, East, and West
• She moves by hopping one space at a time
• She picks flowers (*)
• She gets killed by nets (#)
• She can detect nets one space ahead, on her left, and on her
right
• She can disable a net by tossing a flower on it
Lynne Koenecke 22
Illinois State University, ACS
Jessica’s Island
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .#. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .*. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . # . . . . . . . . . ##### . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .#. . . . . . . . . . . . . . * . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lynne Koenecke 23
Illinois State University, ACS
C o n d it i o n s
Jessica can make decisions that affect selection and repetition control
structures. These decisions are based on simple conditions and NOT simple
conditions.
(see p. 6 of the Jessica section of your lab manual for an explanation of each of these conditions)
Lynne Koenecke 24
Illinois State University, ACS
S e l e c t i o n C o n tro l S tr u c tu re s
IF (condition) THEN
instruction block
END IF;
IF (condition) THEN
instruction block
ELSE
instruction block
END IF;
R e p e t it i o n C o n tro l S tr u c tu re s
WHILE (condition)
instruction block
END WHILE;
Do (number) TIMES
instruction block
END DO;
*Notice that there are no semicolons after the IF line, ELSE line, and WHILE line.
There would be appropriate semicolons after each instruction block line.
Lynne Koenecke 25
Illinois State University, ACS
IP O C h a r t fo r J e s s i c a
Jessica does not have any variables. Therefore, there are no inputs and no
outputs.
I P O
turn to face north
hop to north beach
turn left
hop to west beach
go to home position
Lynne Koenecke 26
Illinois State University, ACS
P re - c on d i t i o n s a n d P o st-c o n d it i o n s
By looking at individual statements or a group of statements in a control
structure, a program can be tested for accuracy. Test data must be selected
carefully to determine if the statements (or group of statements) work in all
cases. (Refer to the section “Program Verification-Using Preconditions
and Postconditions” in the Appendix of your lab manual.)
Pre-condition:
-what is true or known before the statement (or group of statements) is
executed
Post-condition:
-what is true or known after the statement (or group of statements) is
executed
Example
number = 100
Pre-condition: number has no assigned value
Post-condition: number has been assigned the value 100
Example
read balance
IF balance > 200
balance = balance * 1.05
ELSE
balance = balance - 5
Pre-condition: balance has a value
(We don’t know the specific value. It is dependent on what is read in.)
Post-condition: Either balance has been increased by 5% or $5 has been
subtracted from balance
Lynne Koenecke 27
Illinois State University, ACS
Example
LEFT;
Pre-condition: Jessica is in her home position at the NW corner of the island
facing east.
Post-condition: Jessica is facing North.
Example
Jessica is in her home position and there is no net immediately in front of her.
WHILE (NOT NET_AHEAD)
HOP;
END WHILE;
Pre-condition: Jessica is in her home position at the NW corner of the island
facing east and there is no net immediately in front of her.
Post-condition: Jessica is facing East. Jessica has hopped at least one space
to the East. She may have hopped more than one space. There is a net in the
next space to the east.
Exercises:
Indicate whether the following statements are true or false given the
preconditions and postconditions as stated. If it is false, indicate why it is
false.
Lynne Koenecke 28
Illinois State University, ACS
Statement: DOWHILE (number is positive)
number = number - 1
ENDDO
Statement: IF X = Y THEN
X=X-Y
ELSE
Y=Y+X
ENDIF
Postcondition: X>Y
Lynne Koenecke 29
Illinois State University, ACS
Members of Big R Video’s VIP Rental Club receive a 20% discount on
rentals. Regular rental rates are $2 per night.
Test Cases:
Lynne Koenecke 30
Illinois State University, ACS
N e ste d I F C o n t ro l St r u c tu re s
Example
Determine a student’s final grade based on a 90,80,70,60 scale.
Lynne Koenecke 31
Illinois State University, ACS
Trace the following algorithm and answer the question below.
num = 0
DO index = 1 to 4
num = num + index + 3
Print index, number
ENDDO
num = 0
DO index = 1 to 4
num = num + index + 3
ENDDO
Print index, number
Lynne Koenecke 32
Illinois State University, ACS
Modularization
art
sk ithm Ch
n t&
De or re
7. De de
tai en
M ocu ug
k
4. Alg ctu
6. Co
2. IPO
ain m
ec
D b
3. Stru
Ch
5.
1.
Design Implementation
Level 0
Example
Level 1
The main program is the driver program. It controls the program flow of the
entire program. The main program asks a module to perform its task. When
this occurs, control is temporarily given to that module. When the module
finishes its task, control is given back to the main program.
Lynne Koenecke 33
Illinois State University, ACS
Steeplechase
Run to Jump
Steeple Steeple
Run to Steeple
Jump Steeple
Pick Flower
Run to Steeple and Jump Steeple will each have their own
algorithms. The algorithms would be written based on their pre
conditions, post conditions and the task they are asked to
perform.
Lynne Koenecke 34
Illinois State University, ACS
In tro d u c t i o n t o C P ro g r amm in g
C is portable
• portability is the ability to transfer a written program from one
computer to another with few or no changes
C is fast and efficient
C is flexible
• high-level language, but allows manipulation of the inner
workings of the computer
Ex am p l e C C o d e
Line
No.
1 /* Program to prompt for and print two numbers.*/
2 #include <stdio.h>
3 int num_1, num_2;
4 int main (void)
5 {
6 /*Input the first number*/
7 printf ("Enter a number between 1 and 100: ");
8 scanf ("%d", &num_1);
9 /*Input the second number*/
10 printf ("\nEnter another number between 1 and 100: ");
11 scanf ("%d", &num_2);
12 /*Print both numbers */
13 printf ("\n\nYou entered %d and %d.", num_1, num_2);
14 return(0);
15 }
(Line numbers are not entered in the C editor as part of the code. They are used here for reference
only.)
Lynne Koenecke 35
Illinois State University, ACS
S am p le o u tp u t:
Enter a number between 1 and 100: 25
Enter another number between 1 and 100: 50
T h e P ro g r am C omp o n e n ts
a n d D e f i n it i o n s
main ( ) function - (lines 5 - 15) The main is the only component that is
required in every C program. Usually program execution starts at the first
statement in the main and ends at the last statement in the main.
#include Directive -(line 2) instructs the C compiler to add the included file
to your program during compilation. Also called header files. Header files
define operations, symbols, values. Most C programs require the use of one
or more include files. The sample program includes stdio.h, the header file
which contains the standard input/output functions used in C.
Lynne Koenecke 36
Illinois State University, ACS
Variable Definition (line 3) a variable is a name that is assigned to a storage
location in memory. In C, you must define a variable before you can use it.
The definition tells the compiler the name of the storage location and the type
of data that will be stored there. You must follow specific C rules for naming
variables.
scanf() - library function that reads data from the keyboard and assigns
it to one or more program variables.
Lynne Koenecke 37
Illinois State University, ACS
Va r i a b l e s
A variable is a named storage location in the computer's random access memory (RAM).
Variable Names - you must follow the rules of C for naming variables.
• The name can contain letters, digits, and underscores ( _ ).
• The first character of a variable must be a letter. (the underscore is
legal, but shouldn't be used as a first letter)
• C is case sensitive (uppercase and lowercase letters are different to
the C compiler) Num1 is not the same as num1. C looks at these
two variable names as referring to two different storage locations.
• C keywords cannot be used as variable names.
• Variables can be 1 - 31 characters in length.
Reserved words in C
asm auto break case char
const continue default do double
else enum extern float for
goto if int long register
return short signed sizeof static
struct switch typedef union unsigned
void volatile while
Suggestions:
• Make variable names meaningful
• Don't make them too long (leaves more room for typing errors)
• Don't use single character variables except for counters
• Use lowercase letters with underscores to separate words
Lynne Koenecke 38
Illinois State University, ACS
Va r i a b l e D e c l a r a t i o n
Before a variable can be used in C, it must be declared. Declaring a variable
lets the compiler know that it needs to set aside a portion of main memory for
use during the execution of your program. It tells the compiler the name that
you are going to refer to the memory location as and the type of data that will
be stored there.
typename varname;
int score_1;
int count, number, start; /* declares three integer variables on one line */
float total_amount, percent; /*declares two float variables */
If you do not initialize a variable by either of the above methods, you variable
could contain "garbage".
Lynne Koenecke 39
Illinois State University, ACS
Numeric Variable Types - C has several different types of variables
for numeric data because different numeric values require different storage
requirements in main memory. Using the correct data types ensures that your
program runs as efficiently as possible.
Integer variables
• whole numbers (have no fractional parts)
• -1, 0, 10, -12, 354
Floating-point variables
• real numbers (have a fractional part)
• -5.64, 0.564, 6.445, 7.2, -12.01
Within each of the two categories are more specific data types that deal with
different memory requirements based on the size of the values.
Variable Type Keyword Bytes Range
Required
character char 1 -128 to 127
integer int 2 -32768 to 32767
short integer short 2 -32768 to 32767
long integer long 4 -2,147,483,648 to
2,147,438,647
unsigned character unsigned char 1 0 to 255
unsigned integer unsigned int 2 0 to 65535
unsigned short integer unsigned short 2 0 to 65535
unsigned long integer unsigned long 4 0 to 4,294,967,295
single-precision floating- float 4 1.2E-38 to 3.4E38
point
double-precision floating double 8 2.2E-308 to 1.8E308
point
Table showing amount of bytes required to store different types of numeric variables on a 16-bit
architecture PC.
Lynne Koenecke 40
Illinois State University, ACS
C o n st a n ts
Another method of assignment is defining a constant value with the #define
directive which is one of C's preprocessor directives.
The statement above defines PI as 3.14159 for the entire execution of the
program. Anywhere in the program where PI is used, it is substituted for the
value of 3.14159.
Lynne Koenecke 41
Illinois State University, ACS
Up p e rc a s e a n d L o w e rc a s e L e tte r s
Great care must be taken when using case in letters. Num1, num1, and
NUM1 are viewed as different identifiers by the C compiler.
All reserved words in C are lowercase.
#define preprocessor directives are all uppercase.
P ro g r am S ty l e
Guidelines from improving readability of programs
Use meaningful variable names.
Use an underscore to separate words in a variable name
lbls_per-sq_inch is much easier to read than
lblspersqinch
Ex e c u t a b l e S t a tem e n ts
Operations of a program are specified by executable statements that appear in
the body of a program, following variable declarations.
Lynne Koenecke 42
Illinois State University, ACS
O r d e r o f C P ro g r am C omp o n e n ts
/************************************************************* main
comment block SEE the Comment Specifics in the back
* of your Lab Manual!!!!!
************************************************************/
Preprocessor Directives (#include, #define)
Function Prototypes
int main (void)
{ /* open brace which starts the function block*/
/*variable declarations*/
/*executable statements*/
return (0);
/************************************************************
* user - defined function comment block
************************************************************/
function definition
{
/*variable declarations -if needed*/
/*executable statements*/
Lynne Koenecke 43
Illinois State University, ACS
D e ve l o p in g a C p ro g r am
1. Use an editor to type in and save your C source code. We will be using
the editor in Turbo C++. The source code will be saved as filename.c.
2. Compile the program using a C compiler. If no errors occur then an object
file is produced by the C compiler - filename.obj. If errors occur, they
are displayed for you. Correct them, and try to compile again.
3. Link the program. If no errors are detected, then an executable file is
created - filename.exe.
4. Execute the program. Here you should test to make sure that your
program is free of logic errors and works exactly as how you intended it
to. If there are errors, go back to step 1, revise the code and proceed
through steps 2-4 again.
External
Items
Lynne Koenecke 44
Illinois State University, ACS
Ass i g nm en t St a t em en ts
The = sign is used in C to place values into variables. The form is as follows:
variable = constant; or variable = expression;
Ex:
counter = 0; /* puts a value of 0 into the variable named counter */
Visually, in memory, the space allocated for counter now has a value of zero.
counter
0
The value 0 is a constant.
Expressions:
When an expression is on the right side of the equal sign (=), the expression
is first evaluated and then the value of that expression is assigned to the
variable which is named on the left side of the equal sign (=).
Ex: The variables number_1 and number_2 have been declared and
assigned values of 5 and 6 respectively.
number_1 number_2 sum
5 6
Lynne Koenecke 45
Illinois State University, ACS
S om e A r i thm et i c Op e r a t o r s
Arithmetic Meaning
Operator
+ addition
- subtraction or negation
* multiplication
/ division
In p ut / Ou tp u t Op e r a t i o n s
To get values into your program, the scanf function is used. The scanf
function has two arguments. The first is the format control string and the
second is the variable name preceded by an ampersand (&) which is the
address of operator in C.
Ex:
scanf ("%d", &number_1);
When this statement is executed, the cursor waits until the user enters a
number and the enter key to proceed. After the enter key is pressed, the
statement is completed. This example statement gets a decimal integer from
the keyboard and assigns it to the address of number_1.
Lynne Koenecke 46
Illinois State University, ACS
Prompting for scanf
You should prompt the user to let them know what they are to enter before
using the scanf function.
printf ("Enter the first and second scores separated by a space: ");
scanf ("%d%d", &score_1, &score_2);
C onv e r s i o n s Sp e c s f o r sc a n f ( );
The format strings should match the data type for scanf.
Data type scanf ( ) placeholder
char %c
int %d
float %f
double %lf
C Output: printf ( );
The printf function is used for C output to the screen. The following
statement prints a line of text to the screen:
printf ("This is my first C program.");
Lynne Koenecke 47
Illinois State University, ACS
You can add a backslash (\), called an escape character, plus another
character to indicate that printf should do something besides print the line of
text.
C on ve r s i o n s S p e c s f o r p r i n t f ( );
The format strings should match the data type for printf.
Data type printf ( ) placeholder
char %c
int %d
float %f
double %lf
Lynne Koenecke 48
Illinois State University, ACS
P r in t i n g Va r i a b l e s
/* Addition program */
#include <stdio.h>
int main(void)
{
int integer1, integer2, sum; /* variable declarations */
Program output
Lynne Koenecke 49
Illinois State University, ACS
Algorithm:
calculate_double
get value to num_to_double
double = num_to_double * 2
Print message with num_to_double and double
End of calculate_double
C Program: (Use the comments to be sure you include all necessary components.)
/* include statement(s) */
#include <stdio.h>
int main (void)
{
/* variable declarations */
int num_to_double;
int double;
Lynne Koenecke 50
Illinois State University, ACS
S im p le C o n t ro l S tr u c tu re s
The if structure and if - else structure
if (expression) if (expression)
statement if true; statement if true;
else
statement if false;
if (expression) if (expression)
{ {
statement; statement;
....... .......
statement; statement;
} }
else
{
statement;
.......
statement;
}
Lynne Koenecke 51
Illinois State University, ACS
Nested If
if (expression) if (expression)
statement if true; statement;
else else if (expression)
if (expression) statement;
statement if true; else
else statement;
statement if false;
R e p e t it i o n C o n t ro l St r u c tu re
or
for (initial; condition; increment)
{
statement;
statement;
......
statement;
}
Lynne Koenecke 52
Illinois State University, ACS
Graphics
See the back of your ACS 168 lab manual for the graphics functions and
explanations.
Check your lab manual for code to include in every graphics program as well
as how to change the Turbo C++ settings and change to the bgi directory.
Lynne Koenecke 53
Illinois State University, ACS
M a th in C
Integer Division
C evaluates the expression 8 / 3 to have the value of 2. Both 8 and 3 are
integers and the result will also be an integer. C divides and drops the
fractional part of the answer.
Modulus
Gives the remainder after integer division.
5%2=1
How did we get that answer? 5/2 = 2 R 1 1 is the modulus
12 % 2 = 14 % 2 = 16 % 3 25 % 6 =
Lynne Koenecke 54
Illinois State University, ACS
O r d e r o f Op e r a t i o n s
When C evaluates expressions, it follows rules of operator precedence.
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses 1st to be evaluated. If there are parentheses
inside parentheses (nested parentheses), the
inner most parentheses are evaluated first, then
continue out to the outermost parentheses.
+, -, ! (not) unary 2nd to be evaluated.
*, /, or % Multiplication 3rd to be evaluated. If there is more than one
Division of these operators, C evaluates from left to
right.
Modulus
+ or - Addition Last. If there is more than one of these
Subtraction operators, C evaluates from left to right.
x = q - 8 * y / 4 + 16
Order of operation 3 1 2 4
x = 4 - 8 * 2 / 4 + 16
4 - 16 / 4 + 16
4 - 4 + 16
0 + 16
16
Lynne Koenecke 55
Illinois State University, ACS
Ty p e C o n v e r s i o n s
All of C's data objects have a specific type. The logic of programs sometimes
requires that different types be combined in expressions and statements.
Sometimes C automatically handles these different types. At other times, the
conversion must be made by the programmer.
When the above is evaluated the result has the same type as its most
comprehensive component.
Lynne Koenecke 56
Illinois State University, ACS
Explicit type conversions - occurs when the programmer instructs the
computer to convert a value from one type to another.
Using typecasts -
A typecast uses the cast operator explicitly to control type conversions in a
program. A typecast consists of a type name, in parentheses, placed before
an expression.
Example:
int integer;/*integer is declared*/
Lynne Koenecke 57
Illinois State University, ACS
Problems- evaluate as the C compiler would.
2. total = a2 + b2
Answer Data type of total
Lynne Koenecke 58
Illinois State University, ACS
S w i t c h (M u lt ip l e -S e l e c t i o n S tr u c tu re )
default:
any number of statements;
}
Lynne Koenecke 59
Illinois State University, ACS
/* Demonstrates the switch statement */
#include <stdio.h>
void main ()
{
int reply;
printf ("Enter a number between 1 and 5: ");
scanf ("%d", &reply);
switch (reply)
{
case 1:
printf ("You entered 1.");
break;
case 2:
printf ("You entered 2.");
break;
case 3:
printf ("You entered 3.");
break;
case 4:
printf ("You entered 4.");
break;
case 5:
printf ("You entered 5.");
break;
default:
printf ("Out of range, try again.");
}
}
Lynne Koenecke 60
Illinois State University, ACS
Switch is used quite often to process menu choices that a user makes.
80 columns (x value)
24 rows
(y value)
/**************************************************
* Function to print a menu using gotoxy
**************************************************/
void print_menu (void)
{
gotoxy (38,7); printf ("Menu Choices");
gotoxy (32,9); printf ("1. Enter Data");
gotoxy (32,10); printf ("2. Process Information");
gotoxy (32,11); printf ("3. Exit");
gotoxy (32, 15); printf ("Enter your choice: ");
}
Lynne Koenecke 61
Illinois State University, ACS
Ch a r a c t e r D a t a
Another standard data type in C is type char. Variables of type Char can be
used to store any single character value.
Variable declaration
char letter_1, letter_2, letter_3;
We have previously used getch() to hold the screen for viewing output . If
you assign getch(); to a character variable, the key that was hit by the user is
stored.
The enter key is stored as ‘/n’
Screen Design
Be sure to read the guidelines for screen design for Lab 10. Materials are on
reserve in the Library under your instructor’s name.
Lynne Koenecke 62
Illinois State University, ACS
Functions
Parts of a function:
• Function prototype
• Function call
• Function definition
Lynne Koenecke 63
Illinois State University, ACS
Function prototype tells the compiler:
• type of data returned by the function
• number of arguments the function expects to receive
• data types of the arguments
• order in which the arguments are expected
y=half_of(x);
/*function call with argument of x, 1 value is returned and placed in y*/
print_half (y);
/*function call with argument of y, nothing is returned*/
print_header ( );
/*function call with no argument(s), nothing is returned*/
Lynne Koenecke 64
Illinois State University, ACS
Function definition tells the compiler:
• type of data to be received by the function
• number of parameters the function expects to receive
• name of parameter(s) the function receives
• data types of the parameters
• order in which the parameters are expected
Also, notice that there is no semi-colon at the end of the line just as in the main.
statements
}
Lynne Koenecke 65
Illinois State University, ACS
/* A programmer-defined square function */
#include <stdio.h>
/* Function definition */
int square (int y)
{
return y * y;
}
Lynne Koenecke 66
Illinois State University, ACS
P a ss i n g A r gum en ts
You can pass arguments two ways. 1. By Value or 2. By Address
Passing by Value
• The value of the variable is passed through the argument list to the
receiving function.
• Passing a variable by value protects it's content.
return (0);
} /*end main */
Lynne Koenecke 67
Illinois State University, ACS
Passing by Address
• The memory address of the variable is passed to the receiving function
from the calling function.
• If the value of the variable is changed in the receiving function, it is also
changed in the calling function.
To pass a variable by address, you must:
• put an & operator in from of the variable name in the argument list
of the calling function
• put an * (dereferencing) operator in front of the variable everywhere
it is referenced in the receiving function
Lynne Koenecke 68
Illinois State University, ACS
E x amp l e s o f P os s ib l e F o rm s F u n c ti o n s C a n Take
Returns No Result
void print_header (); /* function prototype */
/******************************
*This function displays a header
******************************/
void print_header(void) print_header
{
printf ("Report title");
}
With Arguments
void print_summary (int, int); /* function prototype */
/****************************** count
*This function displays a summary total
******************************/
void print_summary (int count, int total)
{
double average; print_summary
average = (float) count/total;
printf ("The count is: %d\n", count);
printf ("The total is: %d\n", total);
printf ("The average is: %d\n, average);
}
Lynne Koenecke 69
Illinois State University, ACS
Returns a Single Result
int sum (int, int); /* function prototype */
/****************************** number1
answer
*This function adds 2 numbers number2
******************************/
int sum (int num1, int num2)
{
sum
int total;
total = num1 + num2;
return (total);
}
/***************************************
*This function calculates subtotal, tax, and total
***************************************/
subtotal
void calculate_total (double item1, double item2, item1 tax
double *subtotal, double *tax,
item2 total
double *total )
{
*subtotal = item1 + item2; calculate_total
*tax = *subtotal * .07
*total = *subtotal + *tax;
}
Lynne Koenecke 70
Illinois State University, ACS
C omp ou n d Ex p re ss i o n s & N e ste d I f s
Logical Operators
Sometimes, you must ask more than one question to evaluate an expression.
For example, "If it is 7:00 a.m. and a weekday and not a vacation day, ring
the alarm."
Expression Evaluates As
(exp1 && exp2) True (1) only if both exp1 and exp2 are
true; false (0) otherwise.
(exp1 | | exp2) True (1) if either exp1 or exp2 is true;
false (0) only if both are false.
(!expr1) False (0) if exp1 is true; true (1) if exp1 is
false
Lynne Koenecke 71
Illinois State University, ACS
Expression Evaluates As
(5 = = 5 ) && (6 != 2) True (1) because both operands are true
(5 > 1) | | (6 < 1) True (1) because one operand is true
(2 = = 1) && ( 5 = = 5) False (0) because one operand is false
!(5 = = 4) True (1) because the operand is false
() highest
! - (unary)
* / %
+ - (binary)
< <= > >=
= = !=
&&
||
= lowest
Lynne Koenecke 72
Illinois State University, ACS
Truth Tables (T = true, F = false)
x y x && y
F F F
F T F
T F F
T T T
x y x||y
F F F
F T T
T F T
T T T
x !x
F T
T F
Lynne Koenecke 73
Illinois State University, ACS
F o rm a tti n g Num e r i c a l Ou tp u t
int
• %d prints the value exactly as it is
• the field width, placed between the % and the d indicates the number of
columns to be displayed.
• default is right justified
• use a - to left justify
• a negative sign is counted in the field width
• the field expands as needed
Examples:
printf("%d%d\n",254,842);
printf("%1d%2d\n",254,842);
printf("%3d%4d\n",254,842);
printf("%4d%5d\n",254,842);
printf("%-4d%-5d\n",254,842);
printf("%-6d%-7d%d\n",254,842, 324);
254842
254842
254b842
b254bb842
254b842bb
254bbb842bbbb324
Lynne Koenecke 74
Illinois State University, ACS
float, double
• %f always prints with 6 decimal place
• format: %n.mf
• n is the total field width
• m is the number of decimal places
n=6
• the decimal point and negative sign are counted in the total width
• if there is no whole number, a 0 always prints
• fractional parts are rounded if the field is smaller than the assigned number
• if the format %.mf is used, it will print with no leading blanks
• a number is right-justified unless a minus sign is placed immediately after the %
Examples:
printf("%f%f\n",254.0,842.0);
printf("%6.4f%8.4f\n",254.0,842.0);
printf("%.2f%.4f\n",254.0,842.0);
printf("%3.2f%6.2f\n",254.0,842.0);
printf("%-15.4f%-9.4f\n",254.0,842.0);
printf("%-8.0f%-9.0f\n",254.0,842.0);
Lynne Koenecke 75
Illinois State University, ACS
Arrays
Array - data structure used for storage of a group of related items that are of
the same data type.
score [0]
score [1]
score [2]
score [3]
score [4]
Lynne Koenecke 76
Illinois State University, ACS
Getting Values into Array Elements
There are 3 ways to assign values to the elements of an array
1. Initializing arrays in the variable declaration statement.
2. Reading input values into the array from the keyboard or file.
3. Assignment statements.
Initialization
float score [SIZE] = {90, 84, 76, 100, 64};
score [0] 90
score [1] 84
score [2] 76
score [3] 100
score [4] 64
Assignment Statements
difference [1] = score [1] - average;
/*The average has been found by adding up all of the array elements and
dividing by the number of elements.*/
Lynne Koenecke 77
Illinois State University, ACS
Advantages of Using Arrays
❏ You can reference many items by one name. This reduces the number of
different variable names that you need for your program.
❏ You can use the same code to reference different memory locations by
changing the array subscript by using a variable name for the subscript.
❏ You can store multiple data items for use later in the program.
float score [SIZE] = {90, 84, 76, 100, 64}; score [4] 64
Lynne Koenecke 78
Illinois State University, ACS
Passing Arrays
❏ Arrays cannot be used in the return of the function.
❏ Arrays are passed by address by default.
❏ To override this, use the word const in front of the declaration in the
parameter list.
Function prototype
void function_a (int [ ]);
Function call
fuction_a (score);
Function definition
void function_a (int score [ ])
{
.
.
}
Lynne Koenecke 79
Illinois State University, ACS
S o r t i n g A r r a y E l em en ts
There are times when the elements of an array need to be sorted. Numbers or
names may need to be put in ascending or descending order so that they can
be searched or printed in order. There are several sorting methods. We will
discuss the bubble sort and selection sort.
Bubble Sort
1. Decide if the array should be sorted in ascending or descending order.
2. Compare adjacent elements in an array and exchange the values when they
are out of order.
3. One complete time through all array elements is referred to as a pass
through the array. At the end of the first pass, the largest value is in the
last element of the array (if you are sorting in ascending order).
4. The maximum number of passes through an array to sort the elements is
the number of elements minus 1. The minimum number of passes is 1.
Selection Sort
1. Find the smallest element in the array. Exchange that element with the one
in the first position (this is for ascending order).
2. Starting from the second element, find the smallest element in the array
and exchange that element with the element in the second position.
Lynne Koenecke 80
Illinois State University, ACS
Bubble Sort Example
Original unsorted array score:
score [0] 80
score [1] 70
score [2] 50
score [3] 90
score [4] 60
Lynne Koenecke 81
Illinois State University, ACS
Selection Sort
Algorithm
target not found
start with initial array element
while (target is not found and there are more elements)
if (current element matches target)
set flag to indicate target found
else
advance to the next element
if target found
return target index as the result
else
return -1 as the search result (target not found)
/***************************************************************
*Search for the target item of an array
*Returns the index of the target or not_found
*Pre-conditions: target and first n elements are devined & n>0
* array is the array, target is the value to search for, n = num_elements
***************************************************************/
int search (const int array [ ], int target, int n)
{
int k;
int found = 0; /* flag to indicate whether the target has been found */
int where; /*index where target found or not found*/
Algorithm array[ ]
bottom = subscript of the initial array element
element
0 5
top = subscript of the last array element
1 8
found = false
2 12
3 20
while (target not found)
4 32
calculate middle position
5 35
if (the element at middle is the target
then) 6 36
found = true 7 40
record position 8 60
else 9 65
if (element at middle > target) 10 68
top = middle - 1 11 70
else 12 75
bottom = middle + 1
Looking for 36
int binary_search (int array [ ], int size, int item)
{
int middle, where, botom, top, found;
bottom = 0;
top = size;
found = 0;
char
• variable that stores a single character of information
• placed between two apostrophes 'c' or 'C' or 'm' or 'M', etc.
• use %c for printf or scanf
• getchar - reads a character from keyboard
• putchar - displays a character to the screen
Buffers
• buffers stores characters in s special location in main memory to be sent to secondary
storage or they can be brought in from secondary storage
• there is a stdin buffer and a stdout buffer
• when the buffer fills, the computer flushes to a peripheral device
• you can force the buffer to flush by fflush (include conio.h) fflush(stdin); flushes the
stdin buffer
This code flushes the input buffer and allows you to grab the next character.
C d e f in e d c h a r a c t e r f u n c t i o n s
(uses #include <ctype.h>)
strings
• series of characters dealt with as a single unit
• can include letters, digits, and +, -, *, /, $, and other special characters
• enclosed in double quotes
• treated as an array of characters (char) is the ASCII value 0 (null or '\0')
follows the last meaningful character
The end of all strings are marked with null zero '\0' by C
You must account for this in your delcaration.
'x' - takes one byte of memory x
"x" - takes two bytes of memoryx\0
char month[10];
If the month "September" were stored in memory and the address of month it
would look like the following
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
S e p t e m b e r \0
1. Initialization
char month[10] = "January";
void main()
{
char mystring[20];
clrscr();
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
printf ("%s",mystring);
printf ("\n");
printf ("%c",mystring[5]);
getch( );
}
Output
Hello
A r r a y s o f S tr in g s
If you want to store several strings under the same name, you must use an
array of strings. The are declared as follows:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
Memory would look like this after the values have been assigned.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0] J a n u a r y \0
[1] F e b r u a r y \0
[2] M a r c h \0
[3] A p r I l \0
[4] M a y \0
[5] J u n e \0
[6] J u l y \0
[7] A u g u s t \0
[8] S e p t e m b e r \0
[9] O c t o b e r \0
[10] N o v e m b e r \0
[11] D e c e m b e r \0
I/O of strings
#include <stdio.h>
void main()
{
/*Demostrates that the control string is just a string*/
char format [] = "%s\n";
char message [] = "hello";
clrscr();
printf (format, message);
getch();
}
Output
hello
F i l e s in C
Files defined
C performs input and output by streams. The standard input and output are
the keyboard and monitor respectively. Disk file streams work basically the
same way.
Text Files
• A text (stream) file is a collection of characters stored under the same
name in secondary memory (i.e. on a disk).
• Each line has 0-255 characters.
• The line is ended by a special character called an end of line character or
'\n'. A line is not a string because it is not terminated with '\0'.
• The CR-LF is translated into \n as it is being read from a file in a C
program.
• The \n is translated into CR-LF as it is being written to a file in a C
program.
• Data is sent one character at a time.
File Names
You must name files when dealing with disk files. The DOS naming
convention must be used in Turbo C++. You will be working with files on
your floppy disk. Files should be named a:\filename.txt. (The file name must
be 8 characters or less and the extension must be 1 to 3 characters.)
Declaring Files
Before a file can be used for input or output, you must declare a file pointer
variable and give it a value. The stidio library function fopen prepares the file
for input or output before permitting access. A file pointer's data type is FILE
*. A declaration statement for a file to be used in C would look like one of
the following:
FILE * infile_ptr;
FILE * in_ptr;
FILE * out_ptr;
FILE * fp;
Opening a File stream
The file must be opened before a program can read from it or write to it. The
declarations above only declare space in memory. No value has been
assigned. The library function fopen() points to the file pointer and checks to
see if the filename is valid.
fopen requires 2 arguments. Both arguments are strings and can be displayed
in the function as literals or variables.
fp = fopen (filename, mode);/* both filename and mode have been declared and have values*/
infile_ptr = fopen ("a:students.txt","r");
out_ptr = fopen ("a:payroll.dat","w");
Errors
There are several possibilities for file error. A few of those are:
• The program is trying to write to a write-protected disk.
• The program is trying to read a file that is not on the disk.
• The pathname is incorrect.
If a file does not successfully open the value assigned is NULL. Code should
always be written after an fopen to verify that the file was opened correctly.
if (infile_ptr == NULL)
{
printf("students.txt does not exist.\n");
exit (1); /* terminates the program*/
}
Modes
Values of Mode
Mode Meaning
r Open the file for reading only. If the file doesn't exist, fopen()
returns NULL.
w Open the file for writing. If a file of the specified name does not
exist, it is created. If the file already exists, existing data will be
erased.
a Open the file for appending. If a file of the specified name doesn't
exist, it is created. If the file already exists, new data is appended
(added) to the end of the file.
r+ Open the file for reading and writing. If a file of the specified name
does not exist, it is created. If the file already exists, new data is
added at the beginning of the file, overwriting existing data.
w+ Open the file for reading and writing. If a file of the specified name
does not exist, it is created. If the file already exists, it is
overwritten.
a+ Open the file for reading and appending. If a file of the specified
name does not exist, it is created. If the file already exists, new data
is appended to the end of the file.
wb Open a binary file for writing.
rb Open a binary file for reading.
Closing a File
The function fclose() is used to close a file when the program no longer needs
the use of the file.
fclose (infile_ptr);
fclose (out_ptr);
The file argument must be an opent file.
Skip Stop
White reading
Function Call Read from Space Read Error
with return
before?
scanf ("%s", string); stdin yes word white space EOF
gets (string); stdin no line '\n' (discard) NULL
fscanf (infile_ptr, "%s", string); input file yes word white space EOF
fgets (str, n, infile_ptr); input file no line '\n' (keep), NULL
EOF, or n-1
characters
fgets - functions similar to gets. Output goes to a file, rather than the monitor.
fgets (str, 20, infile_fp);
/* fgets puts characters in the array str until it encounters and EOR or ‘\n’ or after reading
19 characters */
feof - file end of file detects the end of a file. If there is more data in the file a
value of zero (false) is returned.
if (feof (infile_ptr)) . . /* the body of the if statement executes if there is data in the file*/
-evaluates to true or false
File I/O Binary Files
feof - file end of file detects the end of a file. If there is more data in the file a
value of zero (false) is returned.
if (feof (infile_ptr)) . . /* the body of the if statement executes if there is data in the file*/
-evaluates to true or false
Recursion
A function that calls itself is said to be recursive. The ability to invoke itself
enables a recursive function to be repeated with different parameter values.
You can use recursion as an alternative to iteration (looping).
/*
* Compute n! using a recursive definition
* Pre: n>=0
*/
if (n == 0)
ans = 1;
else
ans = n * factorial (n-1);
return (ans);
}
Trace of: fact = factorial (3);
n is 3
n is 2
n is 1
n is 0
ans is 1
return (ans)
Iterative factorial Function
/*
* Compute n! using an iteration
* Pre: n>=0
*/