Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)

Similar presentations


Presentation on theme: "Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)"— Presentation transcript:

1 Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)
CHAPTER 3: OVERVIEW OF C By the end of this chapter, students should be able to: Deal with C programming language and its history Explore the C program environment and know why it is appropriate to learn C. Create, compile and run C Programs Format values of data type in program output. Continue .. Reference... Hanly, Koffman, C Problem Solving and Program Design in C, Fifth Edition, Pearson International Edition. Refer chapter 2 (Page 34 – 88) Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012) Prepared by: Pn. Nik Maria Nik Mahamood

2 Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)
By the end of this chapter, students should be able to: Use the specifications to format input and output in program. Apply and practice interactive mode program execution. Code a simple C application. Manage syntax errors, runtime errors and logic errors. Hanly, Koffman, C Program Design for Engineers, Second Edition, Addison Wesley, Refer Chapter 2, at Page 34 Reference... Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012) Prepared by: Pn. Nik Maria Nik Mahamood

3 This chapter introduces to:
C Language Elements Variable Declarations Executable Statements General Form of a C Program Formatting Numbers in Program Output Interactive Mode Common Programming Errors

4 INTRODUCTION To write a program for a computer, you must use a computer language Earliest days of computer – machines language Machine language: made of stream of 0s and 1s. Then assembly language. Symbolic language Because of computer does not understand this language, it must be translated to the machine language. For more info.. - The only language understood by a computer is machine language.

5 Desire to improve programmer efficiency and to change the focus from computer to the problem being solve - High-level language Must be converted to machine language This process called compilation Examples: FORTRAN, COBOL, C For more info.. - Today, one of the most popular high languages for system software and new application code is C

6 History of the C language C – structured language
considered a high level language case sensitive language Developed by Dennis Rithcie 1972 ANSI define a standard on C(1983), which was followed by ISO(1990) ANSI/ISO C is derived from ALGOL. For more info.. - ALGOL (ALGOrithmic Language)- the first language to use a block structure.

7 Taxonomy of the C Language

8 The history of ANSI/ISO C is summarized in Table below:
1960 – a block-structured language emerged, called ALGOL 1967 – Martin Richards invented BCPL. 1970 – Ken Thompson invented language B 1972 – Dennis Ritchie designed C, a combination of BCPL and B 1978 – Brian Kernighan and Dennis Ritchie published the ad hoc standard for traditional C 1989 – American National Standard Institute approved ANSI/ISO C 1990 – the ISO standard for C was approved. For more Info.. Always use ANSI/ISO C. Avoid nonstandard C BCPL (Basic Combined Programming Language)

9 Basic of the C environment All C systems generally consist of 3 parts:
The environment The language The C Standard library The C environment describes about method to write and implement C program The C language emphasizes on rules of syntax in C language

10 C programs typically go through six phases to be executed:
The C Standard library provides collection of existing functions to perform operations such as input/output mathematical calculations. C programs typically go through six phases to be executed: Edit Preprocess Compile

11 Link Load Execute Phase 1 Program is created in the editor, makes corrections if necessary and store on disk Phase 2 Preprocessor program processes the code Phase 3 Compiler creates object code and store it on disk

12 Phase 4 Linker links the object code with the libraries and stores it on disk Phase 5 Loader puts program in memory Phase 6 CPU takes each instruction and executes it, possibly storing new data values as the program executes.

13 Most programs in C input and/or output data.
Certain C functions take their input from stdin (the standard input device) Normally assigned to the keyboard However, stdin can be connected to another device. Data is output to stdout (the standard output device) Normally computer screen However, stout can be connected to another device.

14 There is also a standard error device referred as stderr.
The stderr device (normally connected to screen) is used for displaying error messages. Syntax errors is caught by the compiler A logic error has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing but to produce incorrect results.

15 C LANGUAGE ELEMENTS An advantage of C language is allow programmers to write program - similar to English. The General format of C program is Directive Preprocessor Main function prototype { variables declaration; Body of function; }

16 For more Info.. Figure 2.1 C Language Elements in Miles to Kilometers Conversion Program Source: This figure is taken from Pearson Addison-Wesley, 2007

17 Directive Preprocessor Two types of directive preprocessors #include
To define standard identifiers from standard library. Syntax for #include #include <standard header file> Examples #include <stdio.h>, #include <math.h> #include <string.h>, #include <conio.h> This directive tells preprocessor about file that contains standard identifiers are used in program. For more info: - Refer Page 36: #include Directive for Defining Identifiers From Standard Libraries.

18 #define To create constant micro. Syntax for #define
#define CONSTANT_Name value Examples #define PI #define MAX 100 This directive will tell preprocessor to replace the use of CONSTANT_NAME with the value. CONSTANT_NAME also known as a constant micro –means it’s value is constant after we defined using directive #define. For more info: - Refer Page 37: #include Directive for Creating Constant Micros.

19 Main function Prototype Main function syntax as follows:
To indicate the beginning of a program execution.Main() function has 2 parts: Variables declaration Program body void main() { function body; } void main(void) { function body; } OR int main() { function body; return 0; } int main(void) { function body; return 0; } OR For more info: - Refer Page : main function definition.

20 Example of main function as follows:
Line int indicates that the main function returns an integer value (0) to the operating system. The symbol void indicates that the main function receives no data from the operating system before it begin execution. int main(void) { printf(“Hello world\n”); return 0; }

21 A word that has special meaning in C.
Reserved Words A word that has special meaning in C. All the reserved words appear in lowercase. Reserved word also known as keywords, that are contained in the language it self. Reserved words cannot be used for other purposes such as an identifier’s name. Examples of the reserved words : auto, break, case, char, const, continue, default, do, double, else etc For more info.. Refer textbook book to get a complete list of ANSI C reserved words is found in Appendix E.

22 Example a standard identifier:
Standard Identifiers Like reserved word, standard identifier also has a special meaning in C. Unlike reserved words, standard identifiers can be redefined and used by programmer for other purpose. (However, we don’t recommend this practice) Example a standard identifier: printf and scanf are names of operations defined in stdio.h library. For more info.. Refer Table 2.1: Reserved Words at page 38.

23 User-Defined Identifiers
Our own identifiers. It also called as user-defined identifiers. We use to name memory cells that hold data, program results and to name operations. Example: KMS_PER_MILE The syntax rules and valid identifers: Must consists only of letters, digits and underscores. Cannot be begin with a digit For more info.. Refer Table 2.2: Invalid Identifiers at page 39.

24 Valid Identifiers C reserved words cannot be used as an identifier.
An identifier in a C standard library should not be redefined. Valid Identifiers Example: letter_1, inches, hello, let100_pel The syntax rules for identifiers do not place a limit on length However some ANSI compilers do not considers two names to be different unless there is a variation within 31 characters. Example: per_capita_meat_consumption_in_1980 per_capita_meat_consumption_in_1995 For more info.. Refer Table 2.3: Example of reserved words, standard identifiers and user-defined identifiers at page 40

25 Uppercase and lowercase letters
C is sensitive The names Rate, rate and RATE are viewed by the compiler as different identifiers. Program style Choosing identifier names: pick a meaningful name, so it easy to understand. Example salary : to store person’s salary. Avoid excessively long names

26 VARIABLE DECLARATION AND DATA TYPES
Variable Declarations Variable is a name associated with a memory cell whose value can change. Variable declarations are statements that communicate to the C compiler that names of all variables in a program. It used to store input data, output or logic manipulation. Value stored by variable can be change during the execution of a program. General form of a variable declaration type variable_name; For more info.. Refer page 42: Syntax Display for Declarations

27 Each variable in your program must be declared and defined.
In C, declaration is used to named an object, such as a variable. Definition is used to create an object. A variable can be declared and defined at the same time. When we create variables, the declaration gives them a symbolic name The definition reserves memory for them. For more info.. - once defined, variables are used to hold the data that are required by the program for its operation.

28 The concept of variables in memory is illustrated as below:
For more info.. a variable’s type can be any of data types: char, int and float. However, a variable cannot be type void

29 Example of variable declaration
int maxItem; int a, b; double tax; float pay_rate; char code; char grade_stud, gender; C allows multiple variables of the same type to be defined in one statement.

30 A standard data type in C is a data type that is predefined, such as
Data Types Data type – is a set of values and operations that can be performed on those values. A standard data type in C is a data type that is predefined, such as int Example: double Example: char Example: ‘A’ ‘Z’ ‘*’ ‘9’ ‘”’ For more info.. Data types will be elaborated in chapter 4.

31 EXECUTABLE STATEMENTS
The executable statements follow the declarations in a program. The C compiler translates the executable statements into machine language Program in Memory Let’s see example of program at figure 2.1. Figure 2.2(a) shows the program loaded into memory and the program memory area before the program executes. Figure 2.2(b) shows after the program executes.

32 For more Info.. Figure 2.2: Memory (a) Before and (b) After Execution of a Program. Source: This figure is taken from Pearson Addison-Wesley, 2007

33 Assignment Statements
Store a value or a computational result in a variable. Syntax: variable = expression; Example: kms = KMS_PER_MILE * miles; x = y + z + 2.0; sum = sum + item; For more info .. See figure 2.3: Effect of kms = KMS_PER_MILE * miles; See figure 2.4: Effect of sum = sum + item;

34 For more Info.. Figure 2.3: Effect of kms = KMS_PER_MILE * miles Source: This figure is taken from Pearson Addison-Wesley, 2007

35 For more Info.. Figure 2.3: Effect of sum = sum + item Source: This figure is taken from Pearson Addison-Wesley, 2007

36 Input/Output Operations and Functions
C uses two function for formatted input and output. The first reads formatted data from the keyboard The second writes formatted data to the monitor. In c, data must be input to and output from a program through a file. The keyboard is considered the standard input file.

37 The monitor is considered the standard output file.
For more info .. - printf() function and scanf() function contained in header file stdio.h

38 The printf() function The standard formatted output function in c is printf (print formatted). This function sends data to output device (usually monitor)based on format given. It is called a formatted output because it can convert binary and text data in memory into data formatted for people to read. To see the results of a program execution, we must have a way to specify what variable values should be displayed.

39 printf(“That equals %f kilometers.\n”, kms)
Example: printf(“That equals %f kilometers.\n”, kms) Function printf used to display a line of a program output. Consists of 2 parts: function name and function arguments. Function Arguments Function Name Format String Print list

40 Consist of: format string and print list. A placeholder
Function arguments Consist of: format string and print list. A placeholder Begins with the symbol % The placeholder %f marks the display position for a type double variable. Print list Consists of variables, constants, expressions or combination of them. For more info .. - refer Table 2.5: Placeholder in format string at page 49

41 Newline escape sequence The symbol \n
Used in a format string to terminate an output line (go to the newline). Besides \n character: ASCII character Symbolic name Null character ‘\0’ Alert ‘\a’ Backspace ‘\b’ Newline ‘\n’ Vertical tab ‘\t’ Double quotes ‘\”’ For more info .. Refer example 2.3 (at page 49) for the using of multiple placeholder in a format string. Refer page 50: Syntax display for printf Function Call

42 For more info ..

43 Example of a complete program
For more info .. Example of a complete program /* to print address */ #include <stdio.h> Void main() { printf(“Jabatan Sains Komputer, \n”); printf(“Program Pengajian Diploma, \n”); printf(“Universiti Teknologi Malaysia, \n”); printf(“54100 Jalan Semarak,\n Kuala Lumpur.”); } Output Jabatan sains Komputer, Program Pengajian Diploma, Universiti Teknologi Malaysia, 54100 Jalan semarak, Kuala Lumpur.

44 Equivalent with statement below
For more info .. Placeholder %s To print a string value. Example: printf(“%s”, “Print a string\n”); Equivalent with statement below printf(“Print a string\n”); Output Print a string

45 Equivalent with statement below
For more info .. Another Example: /* to print a name */ #include <stdio.h> void main() { char name[] = “Nadiah”; printf(“%s”, name); } Equivalent with statement below Output Nadiah

46 To print a character value. Example:
For more info .. Placeholder %c To print a character value. Example: printf(“%c %c %c”, ‘U’, ‘T’, ‘M’); or char1 = ‘U’; char2 = ‘T’; char3 = ‘M’; printf(“%c %c %c”, char1, char2, char3); Output U T M

47 %d ~ To print an integer number.
For more info .. Placeholder %d and %f %d ~ To print an integer number. %f ~ To print a floating-point number. Example: /* to print an integer value and a floating-point value */ #include <stdio.h> Void main() { int num1 = 5; float num2 = 33.77; printf(“The first value = %d\n”,nom1); printf(“The second value = %d\n”, nom2); } Output The first value = 5 The second value =

48 The standard formatted input function in c is scanf (scan formatted).
The scanf() function The standard formatted input function in c is scanf (scan formatted). This function reads data from input device (usually keyboard) based on format given. General form of scanf() function as follows: scanf(format string, input list);

49 Format string a format string that contains any text data to be printed for formatting data of input list. Format string is enclosed in a set of quotation marks (“…”). Input list Consists of variables’ address.

50 For more Info.. Figure 2.5: Effect of scanf(“lf”, &miles) Source: This figure is taken from Pearson Addison-Wesley, 2007

51 For more Info.. Figure 2.6: Scanning data Line Bob Source: This figure is taken from Pearson Addison-Wesley, 2007

52 For more Info..

53 Input variable Example: For more Info..
/* A program to format a date */ #include <stdio.h> Void main() { int day, month, year; scanf(“%d %d %d”,day, month, year); printf(“Day: %d, Month: %d, Year: %d”, day, month, year); } Output ????

54 The last line in the main function (Figure 2.1) return(0);
The return statement The last line in the main function (Figure 2.1) return(0); Transfers control from your program to the operating system. The value 0, is considered the result of function main’s execution It indicates that the program executed without error. For more info .. - Refer page 54: Syntax Display for return Statement

55 GENERAL FORM OF A PROGRAM
The General format of C program is Figure 2.7: General form of a C Program Source: This figure is taken from Pearson Addison-Wesley, 2007

56 A simple C program: Printing a line of text.
This program illustrates several important features of the C language. /* A first program in C Written by XYZ */ #include <stdio.h> void main(void) { printf(“ Welcome to UTM !! \n”); }

57 Output: Welcome to UTM !! The line /* A first program in C Written by XYZ */ begins with /* and ends with */ indicating the line is a comment Programmers insert comments to document programs and improve program readability. Comments do not cause the computer to perform any action when the program is run. Comments are ignore by a compiler Comments helps other people read and understand your program.

58 The line is a directive to the C preprocessor.
#include <stdio.h> is a directive to the C preprocessor. Lines beginning with # are processed by the preprocessor before the program is compiled. The specific line tells the preprocessor to include contents of the standard input/output header file (stdio.h) in the program. This header file contains functions such as printf, scanf. The header file also contains information that helps the compiler determine if calls to library functions have been written correctly.

59 The line is a part of every C program.
void main(void) is a part of every C program. The parenthesis after main indicate that main is a program building block called a function. C programs contain one or more functions, one of which must be main. Every program in C begins executing at the function main. Reserved word void before main indicates that main function would not return any value. void after main indicates that main function does not receive any value from OS. For more info - OS is an operating System

60 The left brace, {, must begin the body of every function.
A corresponding right brace } must end each function. The right brace }, indicates that the end of main has been reached. The pair of braces and the portion of the program between the braces called a block. The block is an important program unit in C.

61 The line instructs the computer to perform an action.
printf(“Welcome to UTM !!\n”); instructs the computer to perform an action. printf functions namely to print on the screen the string of characters mark by the quotation marks. The entire line, including printf, its argument within the parentheses, and the semicolon(;), is called a statement. When the preceding printf statement is executed, it prints the message Welcome to UTM !! On the screen.

62 The characters normally print exactly as they appear between the double quotes in the printf statement. Character \n was not printed on the screen. It means new line – causes the cursor to position to the beginning of the next line on the screen. The backslash \, called escape character. Each statement in C program must end with the semicolon. Omit this semicolon would cause syntax error.

63 FORMATTING NUMBERS IN PROGRAM OUTPUT
C displays all numbers in its default notation unless you instruct it to do otherwise. Formatting values of type int Field width: the numbers of columns used to display a values. Example: If meters is 21, feet is 68 and inches is 11, the program output will be: Results: 21 meters = 68ft. 11in. Printf(“Results: %3d meters = %4d ft. %2d in.\n”, meters, feet, inches); For more info .. - Refer this subtopic at page

64 For more info .. Some examples of width specifications and precisions are shown in the following tables: Statements Output Meaning printf(“%d”, 1234); 1234 printf(“%2d”, 1234); printf(“%3d”, 1234); printf(“%4d”, 1234); printf(“%5d”, 1234); ~1234 Note: ~ white space Continue.. For more info .. - Also refer table 2.11: Displaying 234 and –234 using different placeholder. (at page 73)

65 For more info .. Statements Output Meaning printf(“%6d”, 1234); ~~1234 printf(“%6.1f”, ); ~~12.1 printf(“%6.2f”, ); ~12.12 printf(“%6.3f”, ); 12.123 printf(“%6.3f”, ); 12.346 printf(“%6.4f”, ); printf(“%.1f”, ); 12.3 printf(“%.2f”, ); 12.35 printf(“%.3f”, ); Note: ~ white space

66 Formatting values of type double
We must indicates total field width needed and the number of decimal places desired.Example Displaying x using format string placeholder %6.2f: Value of x Displayed output -99.42 .123 ~~0.12 -9.536 ~-9.54 -25.55 999.4 999.40 99.999 100.00 For more info .. - Refer table 2.12 (at page 74) and table 2.13 (at page 75)

67 Example of a Program For more info ..
/* A program to show the combination of output specifications */ #include <stdio.h> int main(void) { int age = 21; float height = 1.73; printf(“Age : %d years old\n Height: %f m\n”, age, height); } Output Age: 21 years old Height: m

68 INTERACTIVE MODE Interactive mode is a mode of program execution in which the user responds to prompts by entering data. Unlike Batch mode ~ a mode of program execution in which the program scans its data from a data file. Example of interactive mode: printf(“Enter first number:”); scanf(“%d”, &num1); printf(“Enter second number:”); scanf(“%d”, &num2); total = num1 + num2 printf(“The sum is: %d”, total); For more info .. - Refer Figure 2.13: Example of program (at page 77)

69 Common programming Errors
Debugging: removing errors from a program. Syntax Error: a violation of the C grammar rules, detected during program translation (compilation). See figure 2.15: Compiler listing of a program with syntax-error (at page 82). Run-time Error: an attempt to perform an invalid operation, detected during program execution. See figure 2.16: A program with a run-time error (at page 84). See figure 2.17: Revised start of main function for coin evaluation (at page 84). Logic Error: an error caused by following an incorrect algorithm. See figure 2.18: A program that produces incorrect results due to & omission (at page 86).

70 Figure 2.15: Compiler Listing of a Program With Syntax Errors.
For more info .. Figure 2.15: Compiler Listing of a Program With Syntax Errors. Source: This figure is taken from Pearson Addison-Wesley, 2007

71 Figure 2.16: A Program with a Run – Time Error
For more info .. Figure 2.16: A Program with a Run – Time Error Source: This figure is taken from Pearson Addison-Wesley, 2007

72 Source: This figure is taken from Pearson Addison-Wesley, 2007
For more info .. Figure 2.18: A Program that produces Incorrect Result Due to & Omission Source: This figure is taken from Pearson Addison-Wesley, 2007


Download ppt "Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)"

Similar presentations


Ads by Google