Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C...
-
Upload
aaron-oleary -
Category
Documents
-
view
223 -
download
3
Transcript of Unit 2 Getting Started with C Using an Integrated Development Environment Introduction to C...
Unit 2
Getting Started with CUsing an Integrated Development
Environment
Introduction toC Programming
Review of Unit 1
Unit 1: Review
A Computer System is … Hardware:
Central processing unit (CPU)Main memory (RAM, ROM)Secondary memory (Hard disk, CD, DVD, flash
drive, etc)Input devicesOutput devicesNetwork interfacePower supply
Software:FirmwareOperating systemApplication programs
What is a Software “Program”? A set of instructions Performs a specific task Required to make the hardware “do
something” The hardware “runs” or “executes” it Must be in main memory (RAM or ROM) Is written in machine language (specific to
a CPU) Consists of binary ‘1’s and ‘0’s
What Programs Have in Common Programs process information:
Information is stored in the form of binary dataDifferent types of information use different data
typesPrograms acquire input dataPrograms produce output data
Programs are implementations of algorithms:Algorithms are precise solutions to problems
Programs are written in programming languages:May be compiled (translated) to machine languageMay be compiled to intermediate form and then
interpreted
Embedded Systems Found everywhere as part of electronic devices Examples: Watches, calculators, appliances,
irrigation and lighting systems, copiers, traffic lights, MP3 players
Pre-programmed computer Dedicated to a few functions inside a device Often must be real-time (respond “immediately”
to events) Non-stop computing (continuously functioning) Traditionally viewed as non-reprogrammable Reprogrammability is becoming commonplaceTherefore, programming is essential to
electronics students!
Creating a Program Use problem solving skills Create an algorithm Implement the algorithm in a programming
language Understand the programming model Use specialized tools Use software engineering methodology
Use Problem-Solving Process
Heuristics (strategies) for successful problem solving
Five-step process (from Strategies for Creative Problem Solving, Fogler et al.):1. Define the problem2. Generate possible solutions3. Evaluate and decide on a solution4. Implement the solution5. Evaluate the solution
Develop Problem-Solving Skills
A good programmer is an effective problem solver Has a belief that problems can be solved through
analysis Develops a high level of problem-solving skills:
Active – Makes sketches, draws figures, asks questions
Methodical – Keeps track of progress in solving the problem
Detail-orientedTakes great care to understand facts and
relationshipsChecks and re-checks for accuracy
Create an Algorithm
Develop an algorithm before writing a program
Use precise statementsBased in mathematics and logicClear and concrete language
Define a step-by-step process Goal is solution to a problem
Software Development Method1. Specify the problem requirements2. Analyze the problem3. Design the algorithm to solve the problem4. Implement the algorithm as a program5. Test and verify the completed program6. Maintain and update the program
Analyzing the Problem
Requires identifying the …Inputs – the data available to work withOutputs – the desired results
Including the format of the outputAdditional requirementsConstraints
Producing the Algorithm List of steps from beginning to end Begin at step 1, have a specific step to end Don’t try to get every detail at first Use top-down design:
Break the problem into subproblemsSolve each subproblem individuallySimilar to outlining a written paper
Use pseudo-code combined with flowcharting
Desk-check the algorithm
Begin and End Shapes These shapes are used to begin and end a
flowchart The beginning shape has the algorithm
name as its label The end shape contains the word “End”
Rectangle Shape – Actions Rectangle has one entry and one exit The text in the rectangle is pseudo-code
corresponding to one step in the algorithm
Diamond Shape – Decision Point One entry, two exits (one for “yes”, the
other for “no”) Contains one question, with yes/no answer
Selection Shape Selection is an extension of the decision
point Instead of a question, the diamond contains
a value The value selects which branch to take One “other” branch is used for all other
values that don’t have a branch
Connector Shape – On-page Use for a connection on same page Shape shows connection from one point to
another
Left shape can be used multiple times Right shape, used once, shows the destination
of connection
Connector Shape – Off-page Use for a flowchart larger than one page Shape shows connection from one page to another
Left shape can be used multiple times Right shape, used once, shows the destination of
connection Visio automatically creates a new page when this
shape used
Introducing the C Language
Unit 2: Introduction to the C Programming Language
Origin and History of C
Lineage:BCPL (Martin Richards, Univ of Cambridge, 1966)
B programming language (Ken Thompson et al., Bell Labs, 1969)
Creation:Dennis Ritchie of AT&T Bell Labs1969-1973Supported development of UNIX
Peculiarities:Terse language – author of C didn’t like typingWidespread use led to many variations in 1980sSyntax and idioms can be frustrating to learn
Standardization By mid-to-late 1980s:
Many differing implementations on different computersIncompatible extensionsIncompatibilities in "standard" libraries
American National Standards Institute (ANSI) – 1989:Created a standard, now called C89
International Organization for Standardization (ISO) – 1990:Adopted ANSI standard, now called C90 (same as C89)C99 - Revision published in 1999 (slow adoption, Pelles C is
C99)C1X - New revision underway
Ensures that all standard C implementations are compatible:Defines the meaning and extent of compatibility
C Has Many SuccessorsSubsequent creation of many “C-like” derivative languages:Embedded C (ISO C Standards Committee, 2008)C++ (Object-oriented, Bjarne Stroustrup, Bell Labs)C# for .NET (Object-oriented, Anders Hjelsberg, Microsoft)Java and derivatives (Sun Microsystems)Perl (structurally similar to C)Ruby… and many other less popular languages
C is a Procedural Language C is a high-level procedural language:
In C, a procedure is called a functionProgram divided into a number of functionsEach function consists of steps called statementsStatements may use other functions
Matches top-down design:Sub-problem solved with a functionFunction implements an algorithm
Functions operate on data in the form of:Constants - values that do not change, such as
12, 2.5, and “bacon”Variables - named locations in memory
The “Hello, World!” ProgramFlowchart for the traditional first C program:
Let’s see what it takes to implement this in C.
The “Hello, World!” Program in C
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Structure of a C Program
Unit 2: Introduction to the C Programming Language
Each Program has a main() This program has a function named main() The compiler looks for main() as the starting
point The loader starts the program at main() The function body is inside the { and }
(braces)
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Statements Function body has one or more statements (this
one has 2) Each statement is a step, like a rectangle on a
flowchart All statements must end with a semicolon (shown
in red)(You may, at first, feel frustrated by the semicolons)
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Use of a Library Function This main() uses another function named printf() The printf() function is in the Standard I/O (stdio)
library The standard libraries are supplied with the C
compiler The #include line allows us to use the stdio.h library
header
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
A Function's return Statement
The caller of a function is that program which started it running
Functions can return a value back to the caller The main() function always returns zero (0) to the OS The word int indicates the type of value that main()
will return
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Constant Values A C program can contain various constant values The text inside the double-quote characters is called
a string constant The zero character, 0, is called an integer constant
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Miscellaneous A comment starts with /* and ends with */ The entire comment is ignored by the compiler Comments are included in programs to aid in
human understanding The word void in main() will be explained in a
later class
#include <stdio.h>
/* Our first C program */
int main(void){
printf("Hello world!\n");return (0);
}
Algorithm to Convert miles to km1. Output “Convert miles to kilometers”2. Output “Please enter the distance in miles”3. Input dist_in_miles4. Convert dist_in_miles to kilometers
a)Multiply dist_in_miles by 1.609b)Put the result in dist_in_kms
5. Output “The distance in kilometers is”6. Output dist_in_kms7. End
This algorithm was presented in Unit 1
Program to Convert miles to km
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms;
printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);
dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);
return (0);}
The Statements Match the Algorithm
Each step in the algorithm becomes a statement:
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms;
printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);
dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);
return (0);}
Variables Must be DeclaredVariables used in the function must be declared before use:
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms; /* Declaration */
printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);
dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);
return (0);}
C Syntax Requires Exact Punctuation
Parentheses, brackets, and braces always are in matched pairs
Commas are used to separate items in a list A semicolon must end each statement
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms;printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);return (0);
}
Some Special Words are Reserved
Reserved words have special use and meaning Functions cannot use reserved words as their names Variables cannot use reserved words as their names
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms;printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f", dist_in_kms);return (0);
}
C Reserved WordsThe C language has 32 reserved words:
auto double int structbreak else long switchcase enum registertypedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeofvolatiledo if static while
This list is also in Appendix E of the textbook
The printf() Function The printf() function is in <stdio.h> library It creates formatted output for the console
display Can output a string of characters
printf("Hello World!\n");
Can output numeric data from constants or variables
printf("%f", 12.5);printf("%f", dist_in_kms);
The % character and the character(s) that follow are called conversion specifiers (Hanly book, et al, use term format placeholders).
The scanf() Function The scanf() function is in <stdio.h> library It performs formatted input from the console
keyboard Can input numeric data into variables
scanf("%lf", &dist_in_miles);
The '&' character is required to designate an input variable
The '%' character and the letter(s) that follow are conversion specifiers (or format placeholders).
We will come back to printf() and scanf() later
Variables and Data Types
Unit 2: Introduction to the C Programming Language
Data Resides in Variables Variables must be declared to the compilerdouble dist_in_miles, dist_in_kms;
The compiler manages size and location in main memory
Programmer refers only to the variable's nameName should be descriptive of data in
variable Each variable also has a data type
The word that begins the declaration is the data type, for example, "double" as shown above
Variables Placed in Main Memoryby Compiler
Variable Name Rules ANSI C Rules:
Only letters, digits, and underscores (_ shift-minus)
Cannot begin with a digitUppercase is different than lowercaseCannot be a reserved word
Tips:Don't use a name found in a C standard libraryUse a standard coding style (we'll talk more
about this next unit)
Data Types in C int - An integer, positive or negative (signed)
whole number0 143 -213415
float - A signed number with fraction in scientific notation
24.7063 -0.148 3.0E8 -12.7E-6 double - Like float with twice the precision
24.7063000000 -0.148000000000(Once used sparingly as inefficient, now is the norm)
char - A single ASCII character'.' 'r' 'E' '4' ' ' '?'
Typical Usage of Numeric Data Types double
MoneyMeasurements of physical quantities
(distance, voltage, current)Very large and very small numbers
intCountersIndex (position in a list)Settings, positions of dials and controlsDigital and binary values
Advanced Data Types An int is typically 32 bits signed two's
complement binaryIts range is -2147483648 to 2147483647
signed or unsignedCan combine with int
signed int - same as an intunsigned int - positive numbers only 0 to 4294967295
short or longCan combine with int and unsigned int
short int - 16-bit binary -32768 to 32767unsigned short int - 16-bit binary 0 to 65535long int - on some machines can be a 64-bit integer
String Constants
Unit 2: Introduction to the C Programming Language
String Constants Defined A string constant is zero or more characters
(A string constant can be empty) Each character takes one byte in memory
(An extra zero byte is used in memory at the end of a string)
Each character is encoded using the ASCII code
A string constant must begin and end with a double-quote(The quote characters are not stored in
memory)
String Constants - Examples "Hello World" "Hello" and "Hello " are different "134.5" is not a number, it's a string "!@#$%;" is a string containing punctuation
characters "" is the empty string " " is a string consisting of a space; it's not
empty "AF" and "af" are different - case
sensitive
String Escape Sequences Put special characters in a string or character constant Sequence of characters, starting with backslash \ Put quote or double-quote in a string or character
constant"\"Hi!\", we said." Single string of 15 characters
Put a backslash in a string or character constant"\\" A string with one backslash character
Put special codes in a string or character constant"\n" Makes console output start a new line"\t" Outputs a tab character'\g' Make a "beep" noise from the speaker
More on printf( ) and scanf( )
Unit 2: Introduction to the C Programming Language
The printf( ) Function Function accepts one or more inputs (called
arguments) First argument is a string (called format string) Format string can contain:
TextOne or more format placeholders, mixed in with
textThe official name of a format placeholder is a
conversion specifier Format placeholders begin with a % character Placeholders are only understood by printf, in its
1st argument The formatted text prints on the console screen
Conversion Specifiers for printf( ) Formatting an int:
%d Format as decimal integer 27%b Format as binary integer 11011%x Format as hexadecimal integer
1b%X Format as hex integer using uppercase 1B
Formatting a float or double:%f Format as decimal fraction 0.125%e Format as scientific notation 1.25e-1%E Same as %e but with capital E
1.25E-1 Formatting a character:
%c Format as a single character x Formatting a string:
%s Format as a string xyzzy For a '%' character - must use %%
Examples of printf( ) 1 of 3
Assume the following variables and values:
int pebble_count; /* There are 14 pebbles
*/
Example:printf("There are %d pebbles\n", pebble_count);
Output:There are 14 pebbles
Examples of printf( ) 2 of 3
Assume the following variables and values:
double radius; /* The radius is 1.5 */
Example:printf("The radius is %f\n", radius);
Output:The radius is 1.50000
Examples of printf( ) 3 of 3
Assume the following variables and values:
double gas_cost; /* The value is 54.70 */
double pct_gas; /* The value is 17.5 */
Example:printf("%s cost $ %f, %f %% of your budget.\n,"
"Gas", gas_cost, pct_gas);
Output:
Gas cost $ 54.7000, 17.5000 % of your budget.
The scanf( ) function Function accepts one or more inputs (called
arguments) First argument is a string (called format string) Format string can contain:
TextOne or more format placeholders, mixed in with
textThe official name of a format placeholder is a
conversion specifier Format placeholders begin with a % character Placeholders are only understood by scanf, in its
1st argument Remaining arguments must be variables
Each variable preceded with & character
Conversion Specifiers for scanf( ) For inputting an int:
%d Input as decimal integer%b Input as binary integer%x Input as hexadecimal integer
For inputting a float:%f Input a float
For inputting a double:%lf Input a double (The lf means "long float",
i.e. double) For inputting a char:
%c Input a single character Codes for inputting a string:
%s Input a string These codes must match the data type of the
variable
Examples of scanf( ) 1 of 2
Assume the following variables:double radius;
Example:printf("Enter a radius: "); /* Note no newline */
scanf("%lf", &radius);
Examples of scanf( ) 2 of 2
Assume the following variables:int pebbles;
Example:printf("How many pebbles? "); /* Note no newline */
scanf("%d", &pebbles);
Human Factors Note Technique for asking for short-answer input
at the console:Be clear in what data is requestedProvide information about the type of data
needed Output a prompt (before scanf) explaining
what to enter: printf("Please enter the distance in miles: "); scanf("%lf", &dist_in_miles);
Make sure input position is after prompt, with a separator:There is no newline character at end of the
printf stringThere is a space at end of the printf string