introducing c
DESCRIPTION
Introducing C. Lecture 2. Lecture overview. Operator := Functions: main (), printf () Putting together a simple C program Creating integer-valued variables, assigning them values, and displaying those values onscreen The newline character ‘\n’ - PowerPoint PPT PresentationTRANSCRIPT
S
Lecture 2Introducing C
Lecture overview Operator: = Functions: main(), printf() Putting together a simple C program Creating integer-valued variables, assigning them values, and
displaying those values onscreen The newline character ‘\n’ How to include comments in your programs, create programs
containing more than one function, and find program errors. Debugging
C Development Environment
Disk Phase 2 :Preprocessorprogramprocesses the code.
DiskCompilerPhase 3 :Compiler creates objectcode and stores it on Disk.
Preprocessor
Disk Linker Phase 4 :
Editor (Source)
Phase 1 :Program iscreated using theEditor and stored on Disk.
Disk
Linker links objectcode with libraries,creates a.out andstores it on Disk
Binary code generation
Source file
PreprocessedSource
FileObject
FileExecutable
File
Preprocessing Compile LinkPreprocessor Compiler Linker
Header File Library
.exe (Windows)
.lib (Windows).h
.c
Execution processes
Loader Phase 5 :
:.
Primary Memory
Loader putsProgram inMemory
C P U (execute) Phase 6 :
:.
Primary Memory
CPU takes eachinstruction and executes it, storingnew data values asthe program executes.
A Simple Example of C
I am a simple computer. My favorite number is 1 because it is first.
#include Directives and Header Files
The effect of #include <stdio.h> is the same as if you had typed the entire contents of the stdio.h file into your file at the point where the #include line appears.
The main() Function
A C program begins execution with the function called main().The int is the main() function's return type. That means that the kind of value main() can return is an integer.
The main() Function
Example of main function declaration
int main(void)
{
return 0;}
void main(void)
{
}
main(void)
{
}
main( )
{
}
'main' is a C keyword. We must not use it for any other variable
Comments
The parts of the program enclosed in the /* */ symbols are comments. Using comments makes it easier for someone (including yourself) to understand your program.
// Here is a comment confined to one line. int rigue; // Such comments can go here, too.
comment
Braces, Bodies, and Blocks
In general, all C functions use braces to mark the beginning as well as the end of the body of a function.
Their presence is mandatory! Only braces ({ }) work for this purpose, not parentheses (( )) and not brackets ([ ]).
there must be just as many opening braces as closing braces
Declarations
This line declares two things. Somewhere in the function, you
have a variable called doors. The int proclaims doors as an
integer—that is, a number without a decimal point or fractional part.
The word int is a C keyword identifying one of the basic C data types
The word doors in this example is an identifier—that is, a name you select for a variable, a function, or some other entity.
Each statement in C needs to be terminated with semicolon (;)
Data types C deals with several kinds (or types) of data:
integers, characters, and floating point, etc. Declaring a variable to be an integer or a character type makes it possible for the computer to store, fetch, and interpret the data properly.
Four Good Reasons to Declare Variables
Putting all the variables in one place makes it easier for a reader to grasp what the program is about.
Thinking about which variables to declare encourages you to do some planning before plunging into writing a program. What information does the program need to get started? What exactly do I want the program to produce as output? What is the best way to represent the data?
Declaring variables helps prevent one of programming's more subtle and hard-to-find bugs—that of the misspelled variable name.
RADIUS1 = 20.4;
CIRCUM = 6.28 * RADIUSl;
One
letter l
Assignment Assign the value 1 to the variable num:
num = 1; Earlier int num; line set aside space in computer
memory for the variable num, and the assignment line stores a value in that location.
The printf() Function printf("I am a simple ");
printf("computer.\n");
printf("My favorite number is %d because it is first.\n", num);
The parentheses () signify that printf is a function name. The material enclosed in the parentheses is information
passed from the main() function to the printf() function.
Arguments
The printf() Function printf("computer.\n"); The \n symbol means to start a new
line the same function as pressing the Enter key of a typical keyboard.
Escape Sequence Effect \a Beep sound \b Backspace \f Formfeed (for printing) \n New line \r Carriage return \t Tab \v Vertical tab \\ Backslash \” “ sign \o Octal decimal \x Hexadecimal \O NULL
Return Statement
return 0; This return statement is the final statement of the
program. The int in int main(void) means that the main() function is supposed to return an integer.
The Structure of a Simple Program
preprocessor instructions
declaration statementfunction name with argumentsassignment statement
function statements
Tips on Making Your Programs Readable
A readable program is much easier to understand, and that makes it easier to correct or modify. 1. Choose meaningful variable names;2. Use comments;3. Use blank lines to separate one conceptual section of a function from another.
The following is correct, but ugly, code:
Good code:
Multiple functions
I will summon the butler function. You rang, sir? Yes. Bring me some tea and writeable CD-ROMS.
C Tokens In a passage of text, individual words and
punctuation marks are called tokens. C has six types of tokens.
Keywords
Keywordsauto do goto signed unsignedbreak double if sizeof voidcase else int static volatilechar enum long struct whileconst extern register switchcontinue float return typedefdefault for short union
Every C word is classified as either a keyword or an identifier.
All keywords have fixed meanings
Rules of identifiers Identifiers refer to the names of variables,
functions and arrays. These are user-defined names. First character must be an alphabet (or underscore) Must consist of only letters, digits or underscore. Only first 31 characters are significant. Cannot use a keyword. Must not contain white space.
You should use meaningful names for variables (such as car_count instead of x3 if your program counts sheep.).
The characters at your disposal are lowercase letters, uppercase letters, digits, and the underscore (_). The first character must be a letter or an underscore.
Rules ExampleCan contain a mix of characters and numbers. However it cannot start with a number
H2o
First character must be a letter or underscore Number1; _area
Can be of mixed cases including underscore character
XsquAremy_num
Cannot contain any arithmetic operators R*S+T
… or any other punctuation marks… #@x%!!
Cannot be a C keyword/reserved word struct; printf;
Cannot contain a space My height
… identifiers are case sensitive Tax != tax
Rules of identifiers
Constants Constants in C refer to fixed values that do not change
during the execution of a program.
Three types of errors: Syntax
Syntax Errors - a violation of the C grammar rules, detected during program translation (compilation). You make a syntax error when you don’t follow C’s rules. It
is similar to a grammatical error in English. Example: Sing to likes he He likes to sing
Three types of errors: Run-time
Run-time error - an attempt to perform an invalid operation, detected during program execution. Occurs when the program directs the computer to perform an
illegal operation, such as dividing a number by zero. The computer will stop executing the program, and displays a
diagnostic message indicates the line where the error was detected
Semantic Errors and Logic errors are errors in meaning and design Consider “The flying box thinks greenly.” The syntax is fine,
but sentence does not mean anything. In C the program following syntactically correct but wrong
algorithm. Very difficult to detect - it does not cause run-time error and
does not display message errors. The only sign of logic error – incorrect program output. Can be detected by testing the program thoroughly,
comparing its output to calculated results To prevent – carefully desk checking the algorithm and
written program before you actually type it
Three types of errors: Semantic
Introducing DebuggingFind errors!
Missing closing */
Should be {
Should be }
Missing ;
Introducing Debugging
Is the program syntactically correct?
What about semantics? Will program operate as you
expect?
Introducing Debugging
Is the program syntactically correct?
What about semantics? Will program operate as you
expect?
Introducing Debugging
n = 5, n squared = 25, n cubed = 625
Introducing Debugging
Output
By tracing the program step-by-step manually (on the paper), keeping track of variable you monitor the program state.
Add extra printf() statements throughout to monitor the values of selected variables at key points in the program.
Use debugger, that is a program that runs another program step-by-step and examine the value of the program’s variable.
Introducing Debugging
Find errors
QUIZ