Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 3: Introduction to C Programming

Similar presentations


Presentation on theme: "CHAPTER 3: Introduction to C Programming"— Presentation transcript:

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

2 Topics Steps for Creating, Compiling and Executing a C program
Basic Structure of a C Program Formatting Output Writing Comments Errors and Debugging BS (May 2012)

3 Steps for Creating, Compiling and Executing a C program
Topic 1 Steps for Creating, Compiling and Executing a C program BS (May 2012)

4 Major Steps Steps: Prepare Compile Link Execute These steps depend on the computer, the OS, and the C IDE that you will use. BS (May 2012)

5 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)

6 Example: Prepare – Visual Studio
BS (May 2012)

7 2. Compile Once your C program is properly written, direct the compiler to do compilation process. C compiler performs: Preprocessing Preprocessor reads the source code and prepares the code for the translator. 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)

8 Example: Compile – Visual Studio
BS (May 2012)

9 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)

10 Example: Link – Visual Studio
BS (May 2012)

11 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)

12 Example: Execute – Visual Studio
BS (May 2012)

13 Basic Structure of a C Program
Topic 2 Basic Structure of a C Program BS (May 2012)

14 Basic C Structure: Writing a Simple Program
1 pre-processor directives main function heading { statements } //pre-pocessor directives void main(void) { //declarations //executable statements; } 2 3 4 #include <stdio.h> void main(void) { //executable statements printf(“I love programming\n”); printf(“You will love it too once ”); printf(“you know the trick\n”); } Color code: Green – Blue – Red – Black – BS (May 2012)

15 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 : #include #define In our example (#include <stdio.h>) identifies the header file for standard input and output needed by the printf(). BS (May 2012)

16 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 void main(void) { } int main(void) { return 0; } main(void) { } main( ) { } NO semicolon (;) BS (May 2012)

17 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)

18 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: 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 Executable statements Program lines (excluding comments) that are converted to machine language instructions and executed by the computer. int age, total=0.0; BS (May 2012)

19 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: printf(FormatString); Each print a single line to the screen printf(“This is C!”); printf(“C is actually very easy”); printf(“Hope you like it.”); Characters enclosed in “ ” – double quotation marks BS (May 2012)

20 Basic Rules for Writing a C program
C programs consists of functions and the primary function is the main() function - The main() function body is enclosed in braces { } To use printf() function, you must include this pre-processor directive: #include <stdio.h> Each statement (declaration and executable statements) in C needs to be terminated with semicolon (;) C is a case-sensitive language, so in this chapter: void Void VOID main Main MAIN printf Printf PRINTF X X X X X X BS (May 2012)

21 Topic 4 Formatting Output BS (May 2012)

22 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 printf(“Welcome to”); printf(“London!”); Welcome toLondon! Welcome to London! printf(“Welcome to\n”); printf(“London!”); BS (May 2012)

23 Character Escape Sequence
Are used in the printf()function to format the output. Escape Sequence Meaning Result \0 Null character Terminates a character string \a Alert/bell Generates an audible or visible alert \b Backspace Moves the active position back one space on the current line \f Form feed Moves the active position to the initial position at the start of the next logical page (e.g. eject printer page) \n New line Linefeeds to the initial position of the next line \r Carriage return Moves the active position to the initial position of the current line \t Horizontal tab Moves the active position to the next horizontal tabulation position on the current line \v Vertical tab Moves the active position to the initial position of the next vertical tabulation position \\ Backslash Displays a backslash \’ Single quote Displays a single quote \” Double quote Displays a double quote %% Percent Displays a percent character BS (May 2012)

24 Escape Sequence: \n and \t
New line \n: Display: Vertical tab \t: printf(“How do we jump”); printf(“\n\ntwo lines”); How do we jump two lines printf(“I Love\t\tKuala\t\tLumpur.”); I Love Kuala Lumpur. BS (May 2012)

25 Ways to Connect a C String Literal
To connect a string literal that continues on the next line: Use a backslash \ Enclose each unfinished string literal in double quotes Combination of methods 1 & 2 Equivalent to: printf(“From KL with \ Love.\n”); printf(“From “ “KL “ “with” “ love.\n”); printf(“From “ “KL \ with ” “love.\n”); printf(“From KL with love.\n”); BS (May 2012)

26 Exercise Write a program to print to the screen the following menu:
Re-write the above program using only one printf() statement Review Topic 2 – Formatting Output! We have learned: How to write a simple C program How to continue a line How to use \t, beep \t, and carriage return \r How to print special characters %, \, “ BS (May 2012)

27 Topic 4 Writing Comments BS (May 2012)

28 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)

29 Structure of Comments Structure: Example: Incorrect comments:
Single line: // to begin comment lines Multi-line: /* any text, number or character*/ Example: Incorrect comments: /* 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 BS (Feb 2012)

30 Location of Comments Comments can be written:
At the very beginning and end of a C program On lines separate from the code On the same line as other C code In a C statement Example: /* 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 */ BS (May 2012)

31 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: /*************************************************** ** Name: Apples.c * ** Purpose: Learning how to write comments in C * ** Date: Written on 01/04/ * ***************************************************/ BS (May 2012)

32 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)

33 Topic 5 Errors and Debugging BS (May 2012)

34 Basic Debugging The process of looking for and correcting errors or mistakes that cause your programs to behave unexpectedly. 3 types of errors: Syntax errors Run-time errors Logic errors BS (May 2012)

35 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)

36 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)

37 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 output Actual 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)

38 Debugging in a Nutshell
Compile your source code. Correct syntax errors and run-time errors in the region of the first error detected Program executes? N Y Execute program. Look at your output. If it is not correct, look for logic errors. Make sure your program is fully documented and commented. N Output is correct? Y BS (May 2012)

39 Test your skill Find and correct errors in the following 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 ****** BS (May 2012)

40 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)


Download ppt "CHAPTER 3: Introduction to C Programming"

Similar presentations


Ads by Google