Introducing C

36
S Lecture 2 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 Presentation

Transcript of Introducing C

Page 1: Introducing C

S

Lecture 2Introducing C

Page 2: Introducing 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

Page 3: Introducing C

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

Page 4: Introducing C

Binary code generation

Source file

PreprocessedSource

FileObject

FileExecutable

File

Preprocessing Compile LinkPreprocessor Compiler Linker

Header File Library

.exe (Windows)

.lib (Windows).h

.c

Page 5: Introducing 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.

Page 6: Introducing C

A Simple Example of C

I am a simple computer. My favorite number is 1 because it is first.

Page 7: Introducing C

#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.

Page 8: Introducing C

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.

Page 9: Introducing C

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

Page 10: Introducing C

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

Page 11: Introducing C

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

Page 12: Introducing C

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 (;)

Page 13: Introducing C

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.

Page 14: Introducing C

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

Page 15: Introducing C

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.

Page 16: Introducing C

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

Page 17: Introducing C

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

Page 18: Introducing C

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.

Page 19: Introducing C

The Structure of a Simple Program

preprocessor instructions

declaration statementfunction name with argumentsassignment statement

function statements

Page 20: Introducing C

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:

Page 21: Introducing C

Multiple functions

I will summon the butler function. You rang, sir? Yes. Bring me some tea and writeable CD-ROMS.

Page 22: Introducing C

C Tokens In a passage of text, individual words and

punctuation marks are called tokens. C has six types of tokens.

Page 23: Introducing C

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

Page 24: Introducing C

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.

Page 25: Introducing C

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

Page 26: Introducing C

Constants Constants in C refer to fixed values that do not change

during the execution of a program.

Page 27: Introducing C

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

Page 28: Introducing C

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

Page 29: Introducing C

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

Page 30: Introducing C

Introducing DebuggingFind errors!

Page 31: Introducing C

Missing closing */

Should be {

Should be }

Missing ;

Introducing Debugging

Page 32: Introducing C

Is the program syntactically correct?

What about semantics? Will program operate as you

expect?

Introducing Debugging

Page 33: Introducing C

Is the program syntactically correct?

What about semantics? Will program operate as you

expect?

Introducing Debugging

n = 5, n squared = 25, n cubed = 625

Page 34: Introducing C

Introducing Debugging

Output

Page 35: Introducing C

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

Page 36: Introducing C

Find errors

QUIZ