Chapter 1 Introduction to Basic C .pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
BASIC C PROGRAMMING DBV10063 TOPIC 1 INTRODUCTION TO BASIC C LANGUAGE MAPPING OF THE COURSE LEARNING OUTCOMES (CLO) TO THE PROGRAM EDUCATIONAL OBJECTIVES (PEO) AND PROGRAM LEARNING OUTCOMES (PLO) Graduates with...
BASIC C PROGRAMMING DBV10063 TOPIC 1 INTRODUCTION TO BASIC C LANGUAGE MAPPING OF THE COURSE LEARNING OUTCOMES (CLO) TO THE PROGRAM EDUCATIONAL OBJECTIVES (PEO) AND PROGRAM LEARNING OUTCOMES (PLO) Graduates with Graduates with leadership adequate qualities, effective knowledge & communication skill, ethical technical skills to values & social responsibilities perform their job to fulfil their duties towards the tasks in the related working culture & community fields Problem Analysis Problem Analysis Modern Tool Usage Modern Tool Usage Communicati on Communi cation WHY do you need to learn programming? TYPE OF PROGRAMMING Strings of numbers giving machine +1200032456 1.Machine specific instructions languages Example: +1300222417 Type of Programming English-like +1400452345 abbreviations representing elementary computer Language 2.Assembly operations (translated languages via assemblers) LOAD BASEPAY Example: ADD OVERPAY Codes similar to STORE GROSSPAY everyday English Use mathematical High-level notations (translated languages via compilers) grossPay = basePay Example: + overTimePay Introduction to C Language C is a powerful procedural-based programming language developed in 1972 by Dennis Ritchie within the halls of Bell Telephone Laboratories. The C programming language was originally developed for use with the UNIX platform and has since spread to many other systems and applications. C has influenced a number of other programming languages, including C++ and Java. Beginning programmers, especially those enrolled in computer science and engineering majors, need to build a solid foundation of operating systems, hardware, and application development concepts. Numerous learning institutions accomplish this by teaching their students how to program in C so that they may progress to advanced concepts and other languages built upon C. Introduction to C Language THE C STANDARD LIBRARY ❖ C programs consist of pieces/modules called functions ❖ A programmer can create his own functions ❖ Advantage: the programmer knows exactly how it works ❖ Disadvantage: time consuming ❖ Programmers will often use the C library functions ❖ Use these as building blocks ❖ Avoid re-inventing the wheel ❖ If a premade function exists, generally best to use it rather than write your own ❖ Library functions carefully written, efficient, and portable CRITERIA OF C ❖ Structured programming ❖ Disciplined approach to writing programs ❖ Clear, easy to test and debug and easy to modify ❖ Multitasking ❖ Specifying that many activities run in parallel ❖ C is a portable language ❖ Programs can run on many different computers ❖ However, portability is an elusive goal Introduction to C Language MEMORY CONCEPTS A computer’s memory is somewhat like a human’s, in that a computer has both short-term and long-term memory. A computer’s long-term memory is called nonvolatile memory and is generally associated with mass storage devices, such as hard drives, large disk arrays, optical storage (CD/DVD), and of course portable storage devices such as USB flash or key drives. RAM is comprised of fixed-size cells with each cell number referenced through an address. Programmers commonly reference memory cells through the use of variables. There are many types of variables, depending on the programming language, but all variables share similar characteristics, as described in Table 2.1. BASICS OF A TYPICAL C PROGRAM DEVELOPMENT ENVIRONMENT Introduction to C Language ERROR TYPES AND SOLUTIONS 1. Syntax Error an error in the syntax of a sequence of characters or tokens that is intended to be written in C language. Taking the following line of programming as an example: for (start expression ; test expression; count expression) { block of one or more C statements; } The above program shows forms that described the syntax of C. Every opening of brackets ( { ) must be followed by its closure ( } ) where in between we will have a block of one or more C statements. If the C program doesn’t detect the closure, during the compilation process, the error will be detected by the compiler. When the error has removed, then we can proceed to the execution of the resulting object program, which is in machine-readable form. ERROR TYPES AND SOLUTIONS 2. Semantic Errors These errors occurred during the execution phase. For example, if you attempt division by zero, an appropriate message will be displayed. Such errors are usually called run-time errors. This means the source program must be edited and recompiled, and the object program executed again. The process of identifying and correcting or removing the bugs is called debugging. 3. Logic Error Even if the program has no compile errors or run-time errors, the program may not be correct. For example, the output result could be incorrect. The source of this error may be the original algorithm design. If this is the case, we must return to the algorithm design phase and modify it, change the source program and compile and execute once more. In order to test the correctness of the program, the program should be executed many times with various inputs. However, this is still not a guarantee that the program is correct, since it may fail on other input data. BASIC STRUCTURE OF C PROGRAM C programming applies top down design. This kind of design will have standard structure which has three phases: Initialization: initializes the program variables Processing: inputs data values and adjusts program variables accordingly Termination: calculates and prints the final results // A first....... It is a comment. # include It is a preprocessor directives contains information used by compiler when compiling calls to standard i/o library function SIMPLE C PROGRAM main() Example: function that is first function called when you program executed // A first C program {} #include Braces mark the start and end of the list of instructions that make up the program within opening and closing main() braces { printf( “Welcome to C!\n”); printf printf( “Thank you for Also called console output, instruct the computer to print using me!\n”); on the screen the string of characters contained between the quotation marks. return 0; } \ This is called escape character. \n means newline. return 0 This statements terminates the function containing it and return the specified value to that function caller. C Keywords ⮚ Keywords are words in C language whose meaning has already been explained to the C compiler. ⮚ Keywords cannot be used as variables names. ⮚ All keywords must be written in lowercase. ⮚ Keywords are already reserved words which carry specific meaning and serve as basic building block for programming statements. %c Single character %s String %d Signed decimal %f Floating point (decimal notation) %e Floating point (exponential notation) %u Unsigned decimal integer %x Unsigned hexadecimal integer (use "abcdef") %o Unsigned octal integer l or L ( %ld, %lu, Long integer or long double floating point %lx, %lo ) Format specifier Console Output(printf) The function to send data to the screen (display the data) Syntax: printf(“controlString”, other arguments); Console Input(scanf) The scanf function is a way to get input from user through the keyboard. When a program reaches a line with a scanf(), the user at the keyboard can enter values directly into variables. Syntax: scanf(“controlString”, other arguments); Header File This file allows the program to access the C built-in features. These files also provide information to the C compiler about the inputs and results produce by each function in the libraries Preprocessor Directive Preprocessing refer to the first step in translating. All preprocesssor directives begin with # and not C statements, so they do not end in (;) #define #include directive define macros that Directive to insert the contents enable you to replace one string of a file into your program with another With this, you can place common You can use it to give meaningful declarations in one location and names to numeric constants, use them in all source file thus improving constants, thus through file inclusion improving the readability of your source files Ex: #include Ex: #define X1 b+c Preprocessor Directive (continue..) With directives such as #if, #ifdef, #else and #endif, you can compile only selected portion of your program. You can use this feature to write source files with code for two nor more systems, but compile only those parts that apply to the computer system on which you compile the program. With this strategy, you can maintain multiple versions of a program using a single set of source files. X1 = b+c = 2+3 = 5 X2 = X1+X1 = b+c+b+c = 2+3+2+3 = 10 X3 = X2*c+X1-d = b+c+b+c*c+b+c-d = 2+3+2+3*3+2+3-4 = 2+3+2+9+2+3-4 = 17 X4 = 2*X1+3*X2+4*X3 = 2*b+c+3*b+c+b+c+4*b+c+b+c*c+b+c-d = 2*2+3+3*2+3+2+3+4*2+3+2+3*3+2+3-4 = 4+3+6+3+2+3+8+3+2+9+2+3-4 = 44 Escape Sequence An escape sequences always begins with the backslash \ and is followed by one or more special characters Escape Sequence Description \n Newline \t Horizontal tab \a Alert. Sound the system bell \\ Backslash. Used to print backslash character. \” Double quote. Used to print double quote character. 1st method COMMENTS C programs can include comments that provide information to a person reading the program 2nd method PSEUDO CODE Pseudo code consists of short, English phrases used to explain specific tasks within a program's algorithm Pseudo code should not include keywords in any specific computer languages and written as a list of consecutive phrases. You must first understand the program specifications, then organize your thoughts and create the program. You must break the main tasks that must be accomplished into smaller ones in order to be able to eventually write fully developed code. Writing pseudo code WILL save you time later during the construction & testing phase of a program's development. In writing pseudo code, make a list of the main tasks that must be accomplished on a piece of scratch paper. Then, focus on each of those tasks; try to break each main task down into very small tasks that can each be explained with a short phrase. FLOWCHART NOTATION Oval symbol: Indicates the beginning or end of a program or a section of code Data [scanf, printf] VDU symbol: Indicates prints on screen Parallelogram symbol: Indicates read/write action Diamond symbol: Indicates options or multi choices Rectangle symbol (action symbol): Indicates any type of action Small circle symbol: Indicates within page connector Example: Write a program that obtains two integer numbers from the user. It will print out the sum of those numbers. Flowchart: Pseudocode: Start 1. Prompt the user to enter the first integer Prompt user “Enter first integer” 2. Obtain user's first integer input Read first integer 3. Prompt the user to enter a second integer 4. Obtain user's second Prompt user “Enter second integer” integer input 5. Add first integer and second integer Read second integer 6. Store the result in another variable Result = 7. Display an output First Integer + Second Integer prompt that explains the answer as the sum Display result of addition 8. Display the result End Example: Write a FLOWCHART and program which will calculate the total grade of 5 students. At the end, get the average of the grades. Variables ❖ Storage element to hold changeable data ❖ Always have an identifying Name, Type and Value Naming Variables ❖can be short as a single letter or as long as 31 characters. ❖ The name must begin with a letter of the alphabet but after the first letter they can contain a letters, numbers and underscore (_) character ❖ example: ❖ letters ‘a’ - ‘z’ & ‘A’ - ‘Z’ and numerals ‘0’ -‘9’ plus ‘_’ but not spaces or other chars. ❖ ‘C’ is CASE SENSITIVE! - ‘My_Name’ is not the same as ‘my_name’! ❖ Must start with an alphabetic char. not numeral so ‘5my_name’ is illegal! ❖ up to 31 chars long. ❖ Avoid reserved (key) words! Define A Variable ⮚ There are two places where you can define a variable: ⮚ after the brace of a block of code (usually at the top of a function) call as Local Variable ⮚ before a function name ( such as before main() in the program) call as Global Variable ⮚ Example: main() { int i,j; char c; float k; } Explanations: int i,j; char c; float k; Data type C keyword Bits Range DATA TYPE Integer Int => %d 16 -32768 to 32767 Long integer Long 32 -4294967296 to 4294967295 Variables can hold Short integer Short 8 -128 to 127 different types of unsigned Unsigned 16 0 to 65535 data. C supports integer seven built-in data Character Char => 8 0 to 255 types and it %c / %s identifiers them by Floating point Float => %f 32 approximately 6 digits of keywords double Double 64 precision floating point approximately 12 digits of precision Assignment Statement The operator used for simple assignment of values to variables using the format: variable = expression; Example: age=29; salary=40000.00; dependents=5; a=b=c=d=100; 🡪 multiple assignment statements Value=5+(r=9-c) 🡪 compound assignment statements Any statement of the form variable = variable operator expression, can be written in the form variable operator = expression; See the table below: Operator Example Equivalent += bonus+=500; bonus=bonus+500; -= budget - = 50; budget=budget - 50; *= salary *=1.2; salary=salary *1.2; /= factor/=.5; factor=factor/.5; %= daynum %=7 daynum=daynum%7; Arithmetic Operator C uses the following notation for arithmetic operations: Name of Syntax Result Operator Addition x+y Adds x and y Subtraction x-y Subtracts y form x Multiplication x*y Multiplies x and y Division x/y Divide x by y Remainder x%y Computes the remainder that results from dividing x by y Preincrement ++x Increments x before use Postincrement x++ Increments x after use Predecrement --x Decrements x before use Postdecrement x-- Decrements x after use ORDER OF PRECEDENCE C applies operators in arithmetic expression a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra. Order Table below display the rulesOperators of operator precedence. First () Second *, /, % Third +, - INCREMENT AND DECREMENT OPERATOR ❖ In the increment (++) and decrement(--) operators are very useful. ❖ The ++ operator add one to the operator and the -- operator subtracts one from the operator. ❖ The following illustrate the operations: X++ is the same as X=X+1 X-- is the same as X=X-1 Symbol Descriptions Preincrement ++X Increment X by 1 then use the new value of X in the expression in which X resides. Postincrement X++ Use the current value of X in the expression in which X resides then increment by 1. Predecrement --X Decrement X by 1 then use the new value of X in the expression in which X resides. Postdecrement X-- Use the current value of X in the expression in which X resides then decrement by 1. RELATIONAL OPERATOR ❖Relational operator are used to ask questions about the variables. ❖These expressions state a relationship between the real and integer expression. If the relationship holds, the expression is true; otherwise the expression is false. ❖Thus the expression is true, if value of the variable ‘Result’ is greater than 10. ❖All expressions that use relational operators will return a 0 for false and a 1 for true. ❖The following is a summary of relational operator are: Operator Meaning > Greater than >= Greater than or equal to < Less than