chapter 3: introduction to c programming

40
CHAPTER 3: Introduction to C Programming CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1 BS (May 2012)

Upload: noelle

Post on 12-Jan-2016

60 views

Category:

Documents


2 download

DESCRIPTION

CHAPTER 3: Introduction to C Programming. CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon. Topics. Steps for Creating, Compiling and Executing a C program Basic Structure of a C Program Formatting Output Writing Comments Errors and Debugging. Topic 1. - PowerPoint PPT Presentation

TRANSCRIPT

CHAPTER 3: Introduction to C Programming

CSEB113 PRINCIPLES of PROGRAMMING CSEB134

PROGRAMMING I

byBadariah Solemon

1BS (May 2012)

Topics1. Steps for Creating, Compiling and Executing a

C program2. Basic Structure of a C Program3. Formatting Output4. Writing Comments5. Errors and Debugging

2BS (May 2012)

STEPS FOR CREATING, COMPILING AND EXECUTING A C PROGRAM

Topic 1

BS (May 2012) 3

Major Steps

BS (May 2012) 4

Prepare

Compile

Link

Execute

Steps:

These steps depend on the computer, the OS, and the C IDE that you will use.

Step 1: Prepare • Prepare source code (and data files)

– Use a text editor to type your source C program statements.

– Assign a name to your source program file (.c) and save the file into disk storage.

– (optional) Use the text editor to create a data files. Assign names to the data files (.txt or .dat) and save the file

BS (May 2012) 5

Example: Prepare – Visual Studio

BS (May 2012) 6

2. Compile• Once your C program is properly written,

direct the compiler to do compilation process.

• C compiler performs: 1. Preprocessing

• Preprocessor reads the source code and prepares the code for the translator.

2. Translating• Translator translates the code into machine language.• This creates an object code and stores this object code

in another file (i.e. object file)

BS (May 2012) 7

Example: Compile – Visual Studio

BS (May 2012) 8

3. Link (“Build”)• After compilation is completed, call the linker

portion of the C compiler.• As you will see later, a C program is made up

of many functions and will call on functions in the C library to perform certain operations.

• The linker assembles all the functions called by the source code into final executable program (creates .exe file).

BS (May 2012) 9

Example: Link – Visual Studio

BS (May 2012) 10

4. Execute• Also known as running the C program.• If a program is successfully executed with no

more error, it will produce an output.• Otherwise, you must debug (i.e. locate and

fix errors) the program.• This is a compiler dependent task.

BS (May 2012) 11

Example: Execute – Visual Studio

BS (May 2012) 12

BASIC STRUCTURE OF A C PROGRAM

Topic 2

BS (May 2012) 13

Basic C Structure: Writing a Simple Program

BS (May 2012) 14

pre-processor directives main function heading {

statements }

pre-processor directives main function heading {

statements }

#include <stdio.h>

void main(void){

//executable statementsprintf(“I love programming\n”);printf(“You will love it too once ”);printf(“you know the trick\n”);

}

#include <stdio.h>

void main(void){

//executable statementsprintf(“I love programming\n”);printf(“You will love it too once ”);printf(“you know the trick\n”);

}

//pre-pocessor directives

void main(void) { //declarations //executable statements; }

//pre-pocessor directives

void main(void) { //declarations //executable statements; }

1

3

2

4

Color code:Green –Blue –Red –Black –

1. Preprocessor Directives• A C program line begins with # provides an

instruction to the C preprocessor • It is executed before the actual compilation is

done.• Two most common directives :

1. #include

2. #define

• In our example (#include <stdio.h>) identifies the header file for standard input and output needed by the printf().

BS (May 2012) 15

2. The main() Function• Every C program has a function main• The word main is a C reserved word or

keyword. We MUST NOT use it for declaring any other variable or constant.

• 4 common ways of main declaration:

• Is compiler-dependent

BS (May 2012) 16

int main(void){ return 0;}

int main(void){ return 0;}

void main(void){

}

main(void){

}

main(void){

}

main( ){

}

main( ){

}

NO semicolon (;)

3. The Braces {}• Identify a segment / body of a program

– The start and end of a function– The start and end of the selection or repetition

block.• Since the opening brace indicates the start of

a segment with the closing brace indicating the end of a segment, there must be just as many opening braces as closing braces (this is a common mistake of beginners)

BS (May 2012) 17

4. Statements• Specify an action to be taken by the computer

as the program executes.• Each statement in C needs to be terminated

with semicolon (;) • Two types of statements:

1. Declaration*• The part of the program that tells the compiler the names of

memory cells to store values: variables/constant

* Refer chapter 4 for detail

2. Executable statements• Program lines (excluding comments) that are converted to machine

language instructions and executed by the computer.

BS (May 2012) 18

int age, total=0.0;int age, total=0.0;

The printf() Function• Is a library or built-in function• Used to send data to the standard output (usually the

monitor) to be printed according to specific format.• Syntax:

• FormatString is a combination of characters, placeholders and escape sequence.

• Ex:

BS (May 2012) 19

printf(FormatString);

printf(“This is C!”);printf(“C is actually very easy”);printf(“Hope you like it.”);

printf(“This is C!”);printf(“C is actually very easy”);printf(“Hope you like it.”);

Characters enclosed in “ ” – double quotation marks

Each print a single line to the screen

Basic Rules for Writing a C program

1. C programs consists of functions and the primary function is the main() function

- The main() function body is enclosed in braces { }2. To use printf() function, you must include this pre-processor

directive:#include <stdio.h>

3. Each statement (declaration and executable statements) in C needs to be terminated with semicolon (;)

4. C is a case-sensitive language, so in this chapter: void Void VOID main Main MAIN printf Printf PRINTF

BS (May 2012) 20

X

X

X X

X

X

FORMATTING OUTPUT

Topic 4

BS (May 2012) 21

Use of Escape Sequence• These statements:

– print the two strings on a single line to the screen– Means:

• To print the two strings on two lines:

– add the \n escape sequence– Means:

BS (May 2012) 22

printf(“Welcome to”);printf(“London!”);printf(“Welcome to”);printf(“London!”);

Welcome toLondon!Welcome toLondon!

Welcome to London!Welcome to London!

printf(“Welcome to\n”);printf(“London!”);printf(“Welcome to\n”);printf(“London!”);

Character Escape Sequence• Are used in the printf()function to format the output.

BS (May 2012) 23

Escape Sequence: \n and \t• New line \n:

• Display:

• Vertical tab \t:

• Display:

BS (May 2012) 24

printf(“How do we jump”);printf(“\n\ntwo lines”);printf(“How do we jump”);printf(“\n\ntwo lines”);

How do we jump two lines

How do we jump two lines

printf(“I Love\t\tKuala\t\tLumpur.”);printf(“I Love\t\tKuala\t\tLumpur.”);

I Love Kuala Lumpur.I Love Kuala Lumpur.

Ways to Connect a C String Literal

To connect a string literal that continues on the next line:1.Use a backslash \

2.Enclose each unfinished string literal in double quotes

3.Combination of methods 1 & 2

Equivalent to:

BS (May 2012) 25

printf(“From KL with \Love.\n”);printf(“From KL with \Love.\n”);

printf(“From “ “KL ““with” “ love.\n”);

printf(“From “ “KL ““with” “ love.\n”);

printf(“From “ “KL \with ” “love.\n”);printf(“From “ “KL \with ” “love.\n”);

printf(“From KL with love.\n”);printf(“From KL with love.\n”);

Exercise• Write a program to print to the

screen the following menu:

• Re-write the above program using only one printf() statement

BS (May 2012) 26

Review Topic 2 – Formatting Output!

We have learned:1.How to write a simple C program2.How to continue a line3.How to use \t, beep \t, and carriage return \r4.How to print special characters %, \, “

Review Topic 2 – Formatting Output!

We have learned:1.How to write a simple C program2.How to continue a line3.How to use \t, beep \t, and carriage return \r4.How to print special characters %, \, “

WRITING COMMENTS

Topic 4

BS (May 2012) 27

Reasons for Writing Comments

• A better programmer write comments in their programs

• Comments are notes describing what a particular portion of your program does and how it does it (or anything else that you would like to write)

• Usually intended for documentation and clarification purposes

• Have no effect on program execution.

BS (Feb 2012) 28

Structure of Comments• Structure:

Single line: // to begin comment linesMulti-line: /* any text, number or character*/

• Example:

• Incorrect comments:

BS (Feb 2012) 29

/* This is a comment */

// This is known as comment line

/* The comments can span into more than one lines */

printf(“Hello!”); // This comment in on same line of a C statement

printf(“Hello!”); /* This comment in on same line of a C statement */

/* Wrong comment 1: no end asterisks and slash

/* Wrong comment 2: no end slash *

/ *Wrong comment 3: there is a blank between / and * */

X

XX

Location of Comments• Comments can be written:

1. At the very beginning and end of a C program2. On lines separate from the code3. On the same line as other C code4. In a C statement

Example:

BS (May 2012) 30

/* This comment is at the beginning of a C program & separated from the code*/#include <stdio.h>void main (void) // This comment is on the same line as other C code{ printf /*This comment is legal & in a C statement */(“Hello”); printf ( /*This comment is legal & in a C statement */“Hello”);}/* This comment is at the end of the C program */

/* This comment is at the beginning of a C program & separated from the code*/#include <stdio.h>void main (void) // This comment is on the same line as other C code{ printf /*This comment is legal & in a C statement */(“Hello”); printf ( /*This comment is legal & in a C statement */“Hello”);}/* This comment is at the end of the C program */

How to write valuable comments?

• Write comments that can enhance the understandability of your program & are of benefit to you

• Make them pleasing to the eye and clear– Often looks much better if comments are on lines separate from the

code. So, avoid writing comments on the same line as other C code

• Some programmers use a banner at the beginning of their programs– Describes things such as name, identifiers name, author, purpose, and

date of the program– Example:

BS (May 2012) 31

/***************************************************** Name: Apples.c *** Purpose: Learning how to write comments in C * ** Date: Written on 01/04/90 ****************************************************/

/***************************************************** Name: Apples.c *** Purpose: Learning how to write comments in C * ** Date: Written on 01/04/90 ****************************************************/

Test your skill• Write a banner for the program written

to answer the exercise in slide 25. Include the following information:

Name of source code file Purpose Date written Author

BS (May 2012) 32

ERRORS AND DEBUGGING

Topic 5

BS (May 2012) 33

Basic Debugging• The process of looking for and correcting

errors or mistakes that cause your programs to behave unexpectedly.

• 3 types of errors:1. Syntax errors2. Run-time errors3. Logic errors

BS (May 2012) 34

1. Syntax Error• A violation of the C grammar rules, detected during

program translation (compilation).• Effect: statements cannot be translated and program

cannot be executed• Ex:

#include <stdio.h> ;

printf(‘I like programming.”);

BS (May 2012) 35

2. 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 * (depends on IDE – Ms Visual Studio: warning)

BS (May 2012) 36

3. Logic/Design Error• An error caused by following an incorrect 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• Example:

Expected output: This is my outputActual output: This is myoutput

• 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

BS (May 2012) 37

Debugging in a Nutshell

BS (May 2012) 38

Compile your source code. Correct syntax errors and

run-time errors in the region of the first error detected

Make sure your program is fully documented and

commented.

Execute program. Look at your output. If it is not

correct, look for logic errors.

Program executes?

Output is correct?

Y

Y

N

N

Test your skill• Find and correct errors in the

following program.

BS (May 2012) 39

#<include stdio.h>Void main (void);[

printf(‘Debugging example:\n’);printf(“Debug this program \;and look for syntaz errors and logic errors\n”);printf(“Do not run this program\n;printf(“You can do it on you own.”):

]

/******* This is still a simple C program ******

#<include stdio.h>Void main (void);[

printf(‘Debugging example:\n’);printf(“Debug this program \;and look for syntaz errors and logic errors\n”);printf(“Do not run this program\n;printf(“You can do it on you own.”):

]

/******* This is still a simple C program ******

Summary• C compilers operations – prepare, compile, link, execute• C program structure and elements of C language:

– Preprocessor directives, main () function, the {} braces, statements

• Using printf()function and formatting output using character escape sequence

• Writing comments – reason for writing comments, writing valuable comments, structure and location of comments

• Types of programming errors - syntax error, run-time error; logic error, and basic debugging techniques

BS (May 2012) 40