Upcoming SlideShare
Loading in...5
×

# 02 1 Introduction To C

3,292
-1

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

No Downloads
Views
Total Views
3,292
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
330
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

### 02 1 Introduction To C

1. 1. Introduction To C Language Lecture 2
2. 2. What you have learnt so far …. <ul><li>Design: </li></ul><ul><ul><ul><li>How to develop solutions (Algorithm) </li></ul></ul></ul><ul><ul><ul><li>How flowchart works </li></ul></ul></ul><ul><ul><ul><li>How to construct flowcharts </li></ul></ul></ul><ul><li>Analysis: </li></ul><ul><ul><ul><li>Understand the problem </li></ul></ul></ul><ul><li>Perlu kemaskini: </li></ul><ul><li>Concept of variable. It has name, address and </li></ul><ul><ul><li>Contents </li></ul></ul><ul><li>Pointer => variable contains another variable </li></ul>
3. 3. The next step is coding Coding is a process of converting flowchart to program code (source code) But, before you can start doing this, you should learn some basics including the language itself.
4. 4. Writing a C Program is a systematic task Problem Flowchart Intermediate code -prepare a rough code- Complete code - add details -
5. 5. The conversion is almost straight forward Example: multiplying two numbers void main (void) { scanf(&A); scanf(&B); C = A * B; printf(C); } Intermediate C Code But!, the program still cannot be executed. It is not completed yet. This code is called an intermediate code.
6. 6. You will get some errors Error 1: Call to undefined function ‘scanf’ The compiler doesn’t recognize ‘scanf’ Error 2: Undefined symbol ‘A’ The program is trying to use a variable A but has never been registered . Compiler doesn’t recognize the variable
7. 7. Fixing the errors and completing the program This line will help the compiler to recognize words ‘ scanf ’ and ‘ printf ’. File stdio.h contains the information of those functions and some others. This tells to register (declare) variables. Compiler only recognizes registered variables. You may notice some extra things. These are called prompts . They used to let the user knows what is going on while the program is running
8. 8. Example Problem: Finding the average of three numbers Flowcharts:
9. 9. void main () { scanf(&n1,&n2,&n3); Average( &avrg , n1, n2, n3); printf(avrg); } Intermediate code of the main flowchart Preparing the rough code The ampersand (&) indicates that avrg is the output or result of the function-call .
10. 10. void Average (*result , a, b, c) { sum = a + b + c; *result = sum / 3.0; return; } Intermediate code of the function flowchart Preparing the rough code The asterisk (*) indicates that result is an output parameter .
11. 11. #include <stdio.h> void Average( float *result , float a, float b, float c) { float sum; sum = a + b + c; *result = sum/3.0; return; } void main () { float n1; float n2; float n3; float avrg; printf (&quot;Enter three numbers: “); scanf (“%f%f%f”, &n1, &n2, &n3); Average( &avrg ,n1,n2,n3); prinf (&quot;The average is %f“, avrg); } Complete source code Adding details to the rough code. The details are shown by bold texts
12. 12. Example: This example is the same as the previous one but this time the result is “return” Problem: Finding the average of three numbers Flowcharts:
13. 13. void main () { scanf(&n1,&n2,&n3); avrg = Average(n1, n2, n3); printf(avrg); } Intermediate code of the main flowchart Preparing the rough code
14. 14. Average(a, b, c) { sum = a + b + c; result = sum / 3.0; return result ; } Intermediate code of the function flowchart Preparing the rough code <ul><li>Notice that, </li></ul><ul><li>result is removed </li></ul><ul><li>from parameter list </li></ul><ul><li>“ void” is also removed </li></ul>
15. 15. #include <stdio.h> float Average( float a, float b, float c) { float sum; float result; sum = a + b + c; result = sum/3.0; return result; } void main () { float n1; float n2; float n3; float avrg; printf (&quot;Enter three numbers: “); scanf (“%f%f%f”, &n1, &n2, &n3); avrg = Average(n1,n2,n3); prinf (&quot;The average is %f“, avrg); } Complete source code Adding details to the rough code. The details are shown by bold texts
16. 16. Today’s Topics <ul><li>Background of C </li></ul><ul><li>Structure of a C Program </li></ul><ul><li>Comments </li></ul><ul><li>Identifiers </li></ul><ul><li>Types </li></ul><ul><li>Variables and Constants </li></ul><ul><li>Formatted Input/Output </li></ul>
17. 17. Figure 2-1: Taxonomy of the C language
18. 18. Figure 2-2: Structure of a C program Statement = Command or instruction
19. 19. Figure 2-3: The greeting program Statement 1. Print output “Hello World” Statement 2. Terminate the program The execution of the program begins at function ‘main’ void means it has no parameter
20. 20. Comment <ul><li>Comment is a statement that will not be executed. </li></ul><ul><li>Compiler will ignore all comments in your program </li></ul><ul><li>It is used to describe part of your program; makes your program more readable. </li></ul><ul><li>This helps people and also yourself to understand your codes. </li></ul>
21. 21. Figure 2-4: Examples of comments // This is single line comment
22. 22. Identifiers <ul><li>A symbolic name of data, functions or other objects </li></ul><ul><li>E.g: </li></ul><ul><ul><li>main => symbolic name of main function </li></ul></ul><ul><ul><li>printf => symbolic name of a function that prints output onto the screen </li></ul></ul><ul><li>Rules for identifiers: </li></ul><ul><ul><li>First character must be alphabetic character or underscore </li></ul></ul><ul><ul><li>Must consist only alphabetic characters, digits, or underscores </li></ul></ul><ul><ul><li>First 31 characters of an identifier are significant </li></ul></ul><ul><ul><li>Cannot duplicate a reserved word </li></ul></ul>
23. 23. <ul><li>Example: </li></ul><ul><li>Valid Names: </li></ul><ul><ul><li>a </li></ul></ul><ul><ul><li>student8 </li></ul></ul><ul><ul><li>student_name </li></ul></ul><ul><ul><li>_person_name </li></ul></ul><ul><ul><li>TRUE </li></ul></ul><ul><ul><li>FALSE </li></ul></ul><ul><li>Invalid Names: </li></ul><ul><ul><li>\$ a </li></ul></ul><ul><ul><li>3 name </li></ul></ul><ul><ul><li>person name </li></ul></ul><ul><ul><li>int </li></ul></ul><ul><ul><li>what ? </li></ul></ul>
24. 24. In C language, identifiers are case-sensitive . Example: a is different from A .
25. 25. Variables <ul><li>A variable is a reserved location in memory that </li></ul><ul><ul><li>has a name </li></ul></ul><ul><ul><li>has an associated type (for example, integer) </li></ul></ul><ul><ul><li>holds data which can be modified </li></ul></ul>
26. 26. Figure 2-9: Variables in memory
27. 27. Variables <ul><li>A variable must be declared before it can be used. </li></ul><ul><li>HOW? </li></ul><ul><ul><li>A declaration statement has this format: </li></ul></ul><ul><ul><ul><li>type variable_name; </li></ul></ul></ul><ul><ul><li>type : what kind of data will be stored in that location (integer? character? floating point?) </li></ul></ul><ul><ul><li>variable_name : what is the name of the variable? </li></ul></ul>
28. 28. Variable types <ul><li>There are four basic data types in C </li></ul>Type Integer Floating point Character C keyword to use: int float double char
29. 29. Variable types <ul><li>int </li></ul><ul><ul><li>Integer variables hold signed whole numbers (i.e. with no fractional part ), such as 10, – 4353, etc. </li></ul></ul><ul><ul><li>Integers typically take up 4 bytes ( = 32 bits, 1 for the sign, 31 for the number). </li></ul></ul><ul><ul><li>The range of integers is typically </li></ul></ul><ul><ul><ul><li>from – 2 31 (approx –10 9 ) to + 2 31 (approx. 10 9 ) </li></ul></ul></ul>
30. 30. Figure 2-7: Integer types
31. 31. Variable types <ul><li>float and double </li></ul><ul><ul><li>floating point variables hold signed floating point numbers (i.e. with a fractional part), such as 10.432, – 33.335, etc. </li></ul></ul><ul><ul><li>double provides twice the precision of float. </li></ul></ul><ul><ul><li>floats typically take up 4 bytes </li></ul></ul><ul><ul><li>doubles take up 8 bytes </li></ul></ul><ul><ul><li>The range of floats is approximately ±2 127 (±10 38 ) </li></ul></ul><ul><ul><li>The range of doubles is approximately ±2 1023 (±10 308 ) </li></ul></ul>
32. 32. Figure 2-8: Floating-point types
33. 33. Variable types <ul><li>char </li></ul><ul><ul><li>character variables hold single characters , such as 'a', ' ', ' ', etc. </li></ul></ul><ul><ul><li>characters usually take 1 byte (8 bits). </li></ul></ul><ul><ul><li>IMPORTANT : Note that the value of a character is enclosed in single quotes . </li></ul></ul><ul><ul><li>Each character is essentially &quot;encoded&quot; as an integer. </li></ul></ul><ul><ul><ul><li>A computer normally stores characters using the ASCII code (American Standard Code for Information Exchange) </li></ul></ul></ul>
34. 34. Variable types <ul><li>char (continued) </li></ul><ul><ul><li>ASCII is used to represent </li></ul></ul><ul><ul><ul><li>the characters A to Z (both upper and lower case) </li></ul></ul></ul><ul><ul><ul><li>the digits 0 to 9 </li></ul></ul></ul><ul><ul><ul><li>special characters (e.g. @, <, etc) </li></ul></ul></ul><ul><ul><ul><li>special control codes </li></ul></ul></ul><ul><ul><li>For example, </li></ul></ul><ul><ul><ul><li>the character 'A' is represented by the code 65 </li></ul></ul></ul><ul><ul><ul><li>the character '1' is represented by the code 49 </li></ul></ul></ul><ul><ul><ul><ul><li>IMPORTANT: the integer 1, the character '1' and the ASCII code 1 represent three different things! </li></ul></ul></ul></ul>
35. 35. Figure 2-10: Some strings
36. 36. Figure 2-11: Null characters and null strings
37. 37. Variable values <ul><li>After a variable has been declared, its memory location contains randomly set bits. In other words, it does not contain valid data . </li></ul><ul><li>The value stored in a variable must be initialized before we can use it in any computations. </li></ul><ul><li>There are two ways to initialize a variable: </li></ul><ul><ul><li>by assigning a value using an assignment statement </li></ul></ul><ul><ul><li>by reading its value from the keyboard </li></ul></ul>
38. 38. Variable values <ul><li>The basic syntax of an assignment statement is </li></ul><ul><li>variable = value; </li></ul><ul><li>Example </li></ul>assign the value on the right hand side to the variable on the left hand side int num_students; // declare num_students = 22; // initialize
39. 39. Literals <ul><li>Literals are fixed values written into a program. </li></ul><ul><li>Example: </li></ul><ul><ul><li>char keypressed; </li></ul></ul><ul><ul><li>keypressed = ‘y’; /* ‘y’ is a character literal */ </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>double pi; </li></ul></ul><ul><ul><li>pi = 3.14; /* 3.14 is a floating-point literal. */ </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>int index; </li></ul></ul><ul><ul><li>index = 17; /* 17 is an integer literal */ </li></ul></ul>
40. 40. Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { int num_students; num_students = 22; return 0; }
41. 41. Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { double rate, amount; /* declare two double variables */ amount = 12.50; rate = 0.05; return 0; }
42. 42. Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char grade = ‘A’; return 0; }
43. 43. Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char pass_grade = ‘A’, fail_grade = ‘F’; return 0; }
44. 44. Input and output
45. 45. <ul><li>printf() will print formatted output to the screen. </li></ul><ul><li>To print a message: printf(&quot;This is a message &quot;); </li></ul><ul><li>How do we print the value of a variable? </li></ul><ul><li>Answer: Use special format specifiers depending on the type of the variable </li></ul>Printing Output : printf() this is a string literal
46. 46. Format of printf statement
47. 47. <ul><li>To print an integer: </li></ul>int degreesF = 68; printf(&quot;The temperature is %d degrees.&quot;, degreesF); > The temperature is 68 degrees. Output: Specifier for “ print an integer value” “ and the value of that number is read from this variable ”
48. 48. <ul><li>If more data </li></ul><ul><li>Data are displayed according to their order </li></ul>int a = 1; int b = 2; int c = 3; printf(“ %d plus %d is equal to %d &quot;, a , b , c ); 1 plus 2 is equal to 3 Output:
49. 49. <ul><li>Format specifiers: </li></ul><ul><ul><li>%c for single characters </li></ul></ul><ul><ul><li>%d for integers </li></ul></ul><ul><ul><li>%f for float/double (fractions): 1234.56 </li></ul></ul><ul><ul><li>%g for float/double (scientific): 1.23456E+3 </li></ul></ul><ul><ul><li>%s for phrases or ‘strings’ </li></ul></ul>
50. 52. <ul><li>Example : </li></ul><ul><li>Statement Output </li></ul>printf(&quot;|%d|&quot;, 987); |987| printf(&quot;|%2d|&quot;, 987); |987| printf(&quot;|%8d|&quot;, 987); | 987| printf(&quot;|%-8d|&quot;, 987); |987 | printf(&quot;|%0.2f|&quot;, 9876.54); |9876.54| printf(&quot;|%4.2f|&quot;, 9876.54); |9876.54| printf(&quot;|%3.1f|&quot;, 9876.54); |9876.5| printf(&quot;|%10.3f|&quot;, 9876.54); | 9876.540|
51. 53. <ul><li>Control Characters (Escape Sequences) </li></ul><ul><li>They are not data, but “commands” to the output device </li></ul>printf(“Hello World!&quot;); Hello World! Output: ‘ ’ is not a data to be printed. Instead, it is a command that tells the monitor to move the cursor to the next line
52. 55. Figure 2-15: Output specification for inventory report printf (“Part Number Qty On Hand Qty On Order Price ”);
53. 56. Keyboard input: scanf() <ul><li>scanf() will scan f ormatted input from the keyboard. </li></ul><ul><li>It uses the same format specifiers as printf() </li></ul><ul><li>To read an integer: </li></ul><ul><li>int num_students; scanf(&quot;%d&quot;, &num_students); </li></ul>Specifier for “ reading an integer value” VERY IMPORTANT special symbol “ Place value into this variable ”
54. 57. Figure 2-14: Format of scanf statement
55. 58. format specifiers for scanf() <ul><li>Format specifiers: </li></ul><ul><ul><li>%c for single characters </li></ul></ul><ul><ul><ul><li>scanf(&quot; %c&quot;, &some_character); </li></ul></ul></ul><ul><ul><li>%d for integers </li></ul></ul><ul><ul><ul><li>scanf (&quot;%d&quot;, &some_integer); </li></ul></ul></ul><ul><ul><li>%f for float </li></ul></ul><ul><ul><ul><li>scanf (&quot;%f&quot;, &some_float); </li></ul></ul></ul><ul><ul><li>%lf for double </li></ul></ul><ul><ul><ul><li>scanf (&quot;%lf&quot;, &some_double); </li></ul></ul></ul>always put a space between &quot; and % when reading characters
56. 59. Literals <ul><li>Literal = fixed value written into a program </li></ul><ul><ul><li>Not declared, no memory location assigned </li></ul></ul><ul><ul><li>Not re-usable; just written directly into each statement </li></ul></ul><ul><ul><ul><li>This makes it easy to make a mistake </li></ul></ul></ul><ul><ul><ul><li>Solution: use #define directive. </li></ul></ul></ul>#define PI 3.14 int main () { double area, radius; radius = 12.1 ; area = PI * radius * radius; return 0; } NOTE : no semicolon after preprocessor directives! directs preprocessor to replace all occurrences of PI with 3.14 12.1 is a literal
57. 60. #define <ul><li>Syntax: </li></ul>#define NAME value the name is usually capitalized preprocessor directives are not statements. There must be no semicolon at the end.
58. 61. #define <ul><li>Advantage : if you need to change the value, you only have to do it once </li></ul>#define PI 3.14 int main () { double area, radius; double circumference radius = 12.6; area = PI * radius * radius; circumference = 2 * PI * radius; return 0; } if you want to change the value of PI to 3.14159, you only have to do it here and the preprocessor will take care of the rest.
59. 62. Constants <ul><li>Constant = named memory location that holds a non-changeable value </li></ul><ul><ul><li>Must be declared </li></ul></ul><ul><ul><li>Re-usable </li></ul></ul><ul><ul><li>MUST be initialized </li></ul></ul><ul><ul><li>Can not be modified after initialization </li></ul></ul>int main () { const double pi = 3.14; double area, radius; radius = 12; area = pi * radius * radius; pi = 3.14159; /* but, this is wrong */ return 0; }
60. 63. String <ul><ul><li>A string is a sequence of zero or more characters enclosed in double quotes (“ “). </li></ul></ul><ul><ul><li>Example: </li></ul></ul>
61. 64. <ul><ul><li>Use single quotes (‘’) for character data. </li></ul></ul><ul><ul><li>Use double quotes (“”) for string data </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>‘ Hello World’ (This is wrong. Single quotes only </li></ul></ul></ul><ul><ul><ul><li>for single character) </li></ul></ul></ul><ul><ul><ul><li>How about this? </li></ul></ul></ul><ul><ul><ul><li>“ H” (is it true? If true, is it a character data or string data) </li></ul></ul></ul>
62. 65. <ul><ul><li>How about these? Are they the same? </li></ul></ul><ul><ul><li>1 </li></ul></ul><ul><ul><li>‘ 1’ </li></ul></ul><ul><ul><li>“ 1” </li></ul></ul>Number 1 Character 1 String 1
63. 66. <ul><ul><li>How about these? </li></ul></ul><ul><ul><li>10 </li></ul></ul><ul><ul><li>‘ 10’ </li></ul></ul><ul><ul><li>“ 10” </li></ul></ul>Invalid. A character can only hold single character
64. 67. <ul><li>A string variable is declared using the following syntax: </li></ul><ul><ul><li>char string_var [ size ]; </li></ul></ul><ul><ul><li>Or </li></ul></ul><ul><ul><li>char string_var [ size]=“Initialized Value”; </li></ul></ul><ul><ul><li>Or </li></ul></ul><ul><ul><li>char string_var [] =“Initialized Value”; </li></ul></ul><ul><ul><li>Examples: </li></ul></ul><ul><ul><li>char stra [50]; </li></ul></ul><ul><ul><li>char strb [50] =“Hello World”; // declare and initialize </li></ul></ul><ul><ul><li>char strc [] = “Hello World”; // the size is optional </li></ul></ul>
65. 68. <ul><li>Example program using string: </li></ul>#include <stdio.h> int main() { char nama[50]; char negeri[15]; printf(&quot;Masukkan nama pelajar: &quot;); scanf(&quot;%s&quot;,&nama); printf(&quot;Masukkan negeri asal: &quot;); scanf(&quot;%s&quot;,&negeri); printf(&quot; %s merupakan seorang pelajar yang berasal dari %s &quot;, nama , negeri ); return 0; } Output
66. 73. <ul><li>Contoh : </li></ul><ul><li>Arahan Output </li></ul><ul><li>printf(&quot;|%d|&quot;, 987); |987| </li></ul><ul><li>printf(&quot;|%2d|&quot;, 987); |987| </li></ul><ul><li>printf(&quot;|%8d|&quot;, 987); | 987| </li></ul><ul><li>printf(&quot;|%-8d|&quot;, 987); |987 | </li></ul><ul><li>printf(&quot;|%0.2f|&quot;, 9876.54); |9876.54| </li></ul><ul><li>printf(&quot;|%4.2f|&quot;, 9876.54); |9876.54| </li></ul><ul><li>printf(&quot;|%3.1f|&quot;, 9876.54); |9876.5| </li></ul><ul><li>printf(&quot;|%10.3f|&quot;, 9876.54); | 9876.540| </li></ul>
67. 83. <ul><li>Masalah dengan aturcara sebelum ini: </li></ul>#include <stdio.h> int main() { char nama[50]; char negeri[15]; printf(&quot;Masukkan nama pelajar: &quot;); scanf(&quot;%s&quot;,&nama); printf(&quot;Masukkan negeri asal: &quot;); scanf(&quot;%s&quot;,&negeri); printf(&quot; %s merupakan seorang pelajar yang berasal dari %s &quot;, nama , negeri ); return 0; } Output Kenapa masalah ini berlaku?
68. 84. <ul><li>Penyelesaian: Gunakan gets menggantikan scanf </li></ul>#include <stdio.h> int main() { char nama[50]; char negeri[15]; printf(&quot;Masukkan nama pelajar: &quot;); gets(nama); // tidak perlu ada simbol & printf(&quot;Masukkan negeri asal: &quot;); gets(negeri); printf(&quot; %s merupakan seorang pelajar yang berasal dari %s &quot;, nama , negeri ); return 0; } Output
69. 85. <ul><li>Latihan Ulangkaji: </li></ul>
70. 86. <ul><li>2. Cari kesilapan ( errors) dalam aturcara berikut: </li></ul><ul><li>include (stdio.h) </li></ul><ul><li>int main() </li></ul><ul><li>{ </li></ul><ul><li>int nom1, nom2; </li></ul><ul><li>unsigned int jum1; </li></ul><ul><li>char warna; </li></ul><ul><li>jum1=-1; </li></ul><ul><li>scanf(&quot;%d %d&quot;, nom1, num2); </li></ul><ul><li>printf(&quot;%u&quot;,jum1); </li></ul><ul><li>&warna=getchar(); </li></ul><ul><li>printf(&quot;%d %c %u&quot;, warna,warna,warna); </li></ul><ul><li>return 0; </li></ul><ul><li>} </li></ul>
1. #### A particular slide catching your eye?

Clipping is a handy way to collect important slides you want to go back to later.