1 / 66

CHAPTER 4: The Basic of C

CHAPTER 4: The Basic of C. CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon. Topics. C Tokens Reserved words, identifiers, string literals, operators, punctuators Basic Data Types int , float, double, char Variables Constants Reading Data from the Keyboard

dahlia
Download Presentation

CHAPTER 4: The Basic of C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by BadariahSolemon BS (May 2013)

  2. Topics • C Tokens • Reserved words, identifiers, string literals, operators, punctuators • Basic Data Types • int, float, double, char • Variables • Constants • Reading Data from the Keyboard • Using scanf() function, placeholders, address operator & • Arithmetic Operators and Expressions • Types of operators, operator precedence, associativity rules • Single Character Data • getchar(), putchar(), fflush(stdin) functions BS (May 2013)

  3. Topic 1 C TOKENS BS (May 2013)

  4. Tokens & Types of Tokens • Token – the basic element on a C program recognized by the compiler /* Example Case: Apples Author: MdmBadariahSolemon */ #include <stdio.h> int main() { int Qty; double Cost=0.0, Total=0.0; printf ("Enter quantity of apples purchased (in Kg):"); scanf("%d", &Qty); printf ("Enter the cost per Kg of apples (in RM per Kg):"); scanf("%lf",&Cost); Total = Cost * Qty; printf("\nTotal cost of apples = %.2f\n",Total); return 0; } identifiers string literals reserved words operator punctuation BS (May 2013)

  5. 1. Reserved Words • Keywords that identify language entities such as statements, data types, language attributes, etc. • Have special meaning to the compiler - MUST NOT be used as identifiers in our program. • Must be typed in lowercase. • Ex: auto, double, else, void, int BS (May 2013)

  6. Task: Identify the Keywords BS (May 2013) *Complete this table

  7. 2. Identifiers • Words used to represent and reference certain program entities (variables, constant, functionnames, etc). • Also known as programmer-defined words. • Example: intmyName; • myNameis program variable. #define TAXRATE 26 • TAXRATEis a constant. void calculateTotal(int value); • calculateTotal is a function name. BS (May 2013)

  8. Identifiers: Rules BS (May 2013)

  9. Identifiers: Naming Styles • Avoid excessively short and cryptic names such as x, or wt. • Use reasonably descriptive name such as student_nameand StudentID. • Use userscores or capital letters to separate words in identifiers that consist of two or more words. • Example: StudentName, student_name, or studentName BS (May 2013)

  10. 3. String Literal • A sequence of any number of characters surrounded by double quotation marks “ ”. • Example: • Example of usage in C program: Produces output: “This is a string constant.” “Hello \”John”\.” printf(“My name is David Beckham.\n”); My name is David Beckham. BS (May 2013)

  11. 4. Operators • Tokens that result in some kind of computation or action when applied to variables or other elements in an expression. • Example of operators: * + = - / < > • Usage example: result = total1 + total2; BS (May 2013)

  12. 5. Punctuators • Symbols used to separate different parts of the C program. • These punctuators include: [ ] ( ) { } , ; “: * # • Usage example: • To be discussed when we come to the proper language feature in the coming chapters. main() { printf(“Testing.”); } BS (May 2013)

  13. Test Your Skill • Valid/invalid – variables or constant BS (May 2013)

  14. Topic 2 Basic data types BS (May 2013)

  15. Data Types • Are used to define a variable before its use. • The definition of a variable will assign storage for the variable and define the type of data that will be held in memory location. • Basic data types in C: • int • float • double • char BS (May 2013)

  16. Basic Data Types int number = 12; int sum = -3678; float short = 0.000983; float income = 1234567890.12; double bigvalue = 12E-3; //equals to 12x10-3 char initial = ‘B’; BS (May 2013)

  17. Topic 3 variables BS (May 2013)

  18. What are Variables? • Are memory locations within the computer which allows pieces of data to be stored. • The word variable comes from the word vary, which means that whatever you place within a variable can be changed. • A variable can be viewed as a container used to store things (numbers, character, string etc ) • Types of operations: • Declaring variables names • Assigning variable values • Manipulating variable values – ex: display on the screen BS (May 2013)

  19. Is where anything that the computer is working with is kept. • Memory may be conceptually viewed as an ordered sequence of storage location called memory cells. • Information is stored in memory in bits • A memory cell is a group of bits called a byte • Each memory cell has a unique address Hardware Computer – Main Memory 00010110 11010000 10110010 10010111 10001100 10010110 11010110 10010101 01110111 10110111 11011100 10010000 00001010 10010001 10101110 01110110 10000110 01111110 A6 A1 B1 A7 A3 A5 B9 A2 B8 B5 B6 A8 B4 A9 B3 B2 A4 B7 Ref: Tan and D’Orazio, C Programming for Engineering & Computer Science, New York: McGraw-Hill BS (May 2013)

  20. Hardware Computer – CPU • Does most of the work in executing a program • The CPU inside a PC is usually the microprocessor • Three main parts: • Control Unit • Fetch instructions from main memory and put them in the instruction register • ALU (Arithmetic Logic Unit) • Execute arithmetic operations • Registers • Temporarily store instructions or data fetched from memory BS (May 2013)

  21. Declaring Variables • A variable is declared by specifying the DATA TYPE of the variable name • Ex: • Several variables of the same data type may be declared in the same statement. • Ex: Data Type Variable Name int Age; Variable Names Data Type int Age, Weight; Comma to separate variables BS (May 2013)

  22. Assigning Values to Variable • A variable is assigned with a value using an assignment operator =. • Ex: • During program execution, may be conceptually viewed as: 17 is assigned to Age 60 is assigned to Weight Age = 17; Weight = 60; BS (May 2013)

  23. Assigning Values to Variables During Declaration • Variables may be assigned with values even during the variables declaration. • Ex: Variable Name int Age = 17; Data Type int Age = 17, Weight = 60; Comma to separate variables BS (May 2013)

  24. Printing Variable Values • Use the printf() function to display the value of a variable on the computer screen. • Syntax: • FormatString is a combination of characters, placeholdersand escape sequence. • PrintList is any constants, variables, expressions, and functions calls separated by commas. • Example: printf(FormatString, PrintList); placeholder int age = 80; float cgpa = 4.00; printf(“Your age: %d\n”, age); printf(“CGPA: %f\n”, cgpa); printf(“My CGPA: %.2f\n”, cgpa); Your age: 80 CGPA: 4.000000 My CGPA: 4.00 BS (May 2013)

  25. Placeholders in printf() Function • Placeholders (or also known as format specifiers) always begin with the symbol % • Are used to format and display the variable/constant values on the screen • Common placeholders: Refer Table 12.2, pg 647 (Hanly & Koffman) BS (May 2013)

  26. More About Printing Variable Values • Recall this syntax: • FormatString can have multiple placeholders if the Printlist in printf() function has several variables. • Example: printf(FormatString, PrintList); • #include <stdio.h> • main() • { int age = 80; float cgpa = 3.512, weight = 60.4778; printf(“Age: %d and CGPA: %.2f\n”, age, cgpa); printf(“CGPA: %.2f and Age: %d\n”, cgpa, age); printf(“CGPA: %.1f\tWeight2: %.2f\n”, cgpa, weight); printf(“Weight3: %.3f\t”, weight); printf(“Weight4: %.4f\n”, weight); • } BS (May 2013)

  27. Test Your Skill • Do hand-out exercise – declare & assign variables • What happen if you try to print an int with %f or a float with %d? • What is the output for the following program? • #include <stdio.h> • main() • { intyearS = 4; float cgpa = 3.88, gpa = 4.00; double printf(“How long it takes to complete ur study?\n%d\n”,yearS); printf(“GPA\t\tCGPA\n”); printf(“%.2f\t\t%.2f”,gpa, cgpa); printf(“Excellent!\n”); printf(“Now, test your skill\n”); printf(“CGPA in 1 decimal point = %.1f\n”, cgpa); printf(“CGPA = %f\n”, cgpa) } BS (May 2013)

  28. Topic 4 Constants BS (May 2013)

  29. Constants • Entities that appear in the program code as fixed values. • Types of operations: • Declaring and assigning constant values • Operating constant values • Almost similar treatment like variables but CANNOT change the values after declaration! BS (May 2013)

  30. Declaring Constants • As constant macro – created using a preprocessor directives using define keyword • Ex: • Within a function using the const keyword. • Ex: #include <stdio.h> #define PI 3.14159 #define DAYS_IN_YEARS 365 main() { … DATA TYPE? #include <stdio.h> main() { const double KMS_PER_MILES = 1.609 … } BS (May 2013)

  31. Types of Constants #define PI 3.412 const float PI = 3.412; #define VAL 0.5877e2 const double VAL = 0.5877e2; //stands for 0.5877 x 102 #define MAX 10 const int MIN = -90; enum Language { English Arabic Mandarin } #define LETTER ‘n’ const char NUMBER = ‘1’; BS (May 2013)

  32. Printing Constant Values • Similar to printing variable values • What is the output of the program? #include <stdio.h> #define DAYS 365 #define VAL 0.5877 void main(void) { const double PI = 3.412; printf(“pi = %.3f\n”, PI); printf(“In a year, there are %d days\n”, DAYS); printf(“Value = %.4f\n”, VAL); } BS (May 2013)

  33. Topic 6 Reading data from the keyboard BS (May 2013)

  34. Using scanf() Function • To read data from the standard input device (usually keyboard) and store it in a variable. • The general format is pretty much the same as printf() function. • Syntax: • InputListone or more variables addresses, each corresponding to a placeholder in the FormatString • One placeholder for each variable in InputList. • The two or more variables in InputList must be separated by commas. • Each element of InputList must be an address of a memory cell(using prefix & address operator) scanf(FormatString, InputList); BS (May 2013)

  35. Placeholders in scanf() Function • Are used to format and display the variable/constant values keyed-in by the user • Common placeholders in scanf() function are very similar to placeholders in printf() function: Refer Table 12.2, pg 647 (Hanly & Koffman) BS (May 2013)

  36. Example int Age; float income; printf(“Enter your age: “); scanf(“%d”, &Age); printf(“Enter income: “); scanf(“%f”, &income); printf(“Your age is: %d\nIncome: %.2f”, Age, income); Address operator int Age; double income; printf(“Enter your age and income“); scanf(“%d %lf”, &Age, &income); printf(“Your age: %d\n”, Age); printf(“Your income: %f\n”, income); If you want the user to enter more than one value, you serialise the inputs. BS (May 2013)

  37. Test Your Skill • Write a simple C program that reads two integer values and print them on the screen in one line separated by one vertical tab. Follow this sample output: • Write a simple C program that reads 3 real numbers and print them on the screen in reverse order. Follow this sample output: Enter first integer: 80 Enter second integer: 99 80 99 Enter three real numbers: 5.6 7.8 9.3 In reverse order: 9.3 7.8 5.6 BS (May 2013)

  38. Topic 5 Arithmetic operators and expressions BS (May 2013)

  39. Arithmetic Expressions • A syntactically correct and meaningful combination of operators and operands is known as anExpression. • ‘=’ is the basic assignment operator • Syntax: • Example: Variable = ArithmeticExpression; 12 is assigned to variable month operands month = 12; Expression: cityTax=CITYTAXRATE*grossIncome; arithmetic operator assignment operator BS (May 2013)

  40. Arithmetic Operators • There are 2 types of arithmetic operators in C: • Unary operators are operators that require only one operand. • Example: • Binary operators are operators that require two operands. • Example: • Note that we CANNOT write arithmetic expressions like the following: operand   second = -first; prs = -34; operands   third = first / second; sum = 30 + 76; first / second = third; 30 + 76 = sum; X X BS (May 2013)

  41. 1. Unary Operators • Initial value of a is 10 and b is 5 postfix (after a variable) prefix (before a variable) BS (May 2013)

  42. Prefix/Postfix Increment • a++ or ++a is equals to a = a + 1 but they work differently BS (May 2013)

  43. Prefix/Postfix Decrement • Similarly, --a or a-- is equals to a = a - 1 but they work differently BS (May 2013)

  44. 2. Binary Operators • If all operands in an arithmetic expression are of type double/float, the result is also of type double/float except for modulus operator. • If all operands in an arithmetic expression are of type int, the result is also of type int. • Value of a is 9 BS (May 2013)

  45. Modulus Operator (%) • You could only use modulus (%) operation on integer variables/integer division • Modulus will result in the remainder of an operation • Example: • 7 % 2 is 1 • But 2 % 7 is 2. Any idea why? 7/2 3 integral 2 7 6 - 1 7%2 remainder BS (May 2013)

  46. Example • A simple C program that find an average of two real numbers. #include <stdio.h> void main(void) { float no1, no2, sum, avg; printf(“Enter three real numbers: “); scanf(“%f %f”, &no1, &no2); sum = no1 + no2; avg = sum / 2; printf(“Average: %.2f”, avg); } BS (May 2013)

  47. Test Your Skill • Write a program that sum up 4 integer numbers and display the computed sum. • Design pseudocode/flowcharts to solve the following problems and convert them into complete C programs: • Compute and display the average of three numbers. • Read the value of the height, width and length of a box from the user and print its volume. BS (May 2013)

  48. Compound Assignment Operator • Are combinations of operators with the basic assignment operator = • Initial value of a is 8: BS (May 2013)

  49. Test Your Skill • What is the output of the following program? #include <stdio.h> void main(void) { int first; printf("Enter a value: "); scanf("%d", &first); printf("\nNew value is: %d\n\n", first+=4); printf("\nNew value is: %d\n\n", first*=4); printf("\nNew value is: %d\n\n", first-=4); printf("\nNew value is: %d\n\n", first%=4); } BS (May 2013)

  50. Operations of Mixed or Same Types1 • Examples: • 5 + 3 is 8 • 5/3 is 1 int int WHY? int float • 5.2 + 3.1 is 8.3 • 5.0/3.0 is 1.6 float float float • 5.2 + 3 is 8.2 • 5.0/3 is 1.6 • 5/3.0 is 1.6 float int BS (May 2013)

More Related