Professional Documents
Culture Documents
C Language
C Language
C Language
THE FIRST PROGRAM IN C #include<stdio.h> #include<conio.h> //The first program in C int main(void) { printf(Hello World!\n); getch(); return 0; } stdio.h is the header file used to define the standard function printf(). If not used the undefined function printf() will be issued by the compiler. The int before main() means that the function main() will return a value of int type to the OS a standard for ANSI C requires that main() returns an integer value. The character \n is appended at the end of the string to force the printing of a newline character. \n is a special character.
Programming in C
SPECIAL CHARACTERS IN C \n - new line \b baskspace \f form feed \t horizontal tab \r carriage return \ single quote \ double quote \0 null \\ - backslash \ddd character whose ASCII code is in octal \xddd character whose ASCII code is hexadecimal HEADER FILES alloc.h dynamic memory allocation conio.h direct console input/output functions Dos.h dos interface functions graphics.h graphics related functions math.h mathematical functions stdio.h standard i/o functions stdlib.h miscellaneous functions string.h string related functions time.h time and date related functions
Programming in C
C Basic Types for Variables: 1. 2. 3. 4. char character type int can contain integer values float stands for floating point or numbers with fractional part double double precision floating point
Sizes for Values or Variables: Type char int float double Value char integer real real Bit Width 8 16 32 64 Range 0 to 255 -32768 to 32768 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308
Programming in C
PRINTING OF VALUE FORMATS/ INPUT SIZE MODIFIERS %c - character %d decimal integer %f floating point %o octal %x hexadecimal %s character string %% - the % itself %e float in scientific notation %i signed integer INPUT/OUTPUT IN C getchar() reads a character from the keyboard; waits for carriage return. putchar() writes a character onto the screen. gets() - reads a string from the keyboard. puts() writes a string to the screen. printf() writes input data on the screen; printing formatted output. scanf() input data to a program; reading formatted input.
Programming in C
Program to Illustrate input size modifiers: #include<stdio.h> #include<conio.h> int main(void) { printf(%c %d %i %f %e %o %x %s,A,100,200,10.25,10.25,50,76,string); getch(); return 0; }
Programming in C
Program to Illustrate input size modifiers: #include<stdio.h> #include<conio.h> int main(void) { printf(%c %d %i %f %e %o %x %s,A,100,200,10.25,10.25,50,76,string); getch(); return 0; } Output: A 100 200 10.250000 1.025000e+01 62 4c string Note: By default the number of decimal places used in format %f and %e is 6.
Programming in C
Next, suppose the width and precision specifiers are included in the format. Illustrated by the program below. #include<stdio.h> #include<conio.h> int main(void) {
printf(%10c%10d%10i%10f%10e%10o%10x
getch(); return 0;
Programming in C
Next, suppose the width and precision specifiers are included in the format. Illustrated by the program below. #include<stdio.h> #include<conio.h> int main(void) {
printf(%10c%10d%10i%10f%10e%10o%10x
getch(); return 0;
Output: A A
10.250000 10.25
1.025000e+01 1.025e+01
62 62
4c 4c
string string
8
Programming in C
Next, suppose the width and precision specifiers are included in the format. Illustrated by the program below. #include<stdio.h> #include<conio.h> int main(void) { Command format %10 means to print the values with a maximum of 10 spaces. Command format %10.2f means to print floating point value with 10 spaces with 2 decimal places
printf(%10c%10d%10i%10f%10e%10o%10x
getch(); return 0;
Output: A A
10.250000 10.25
1.025000e+01 1.025e+01
62 62
4c 4c
string string
9
Programming in C
Sample Program that uses some of the Input/Output procedures: #include<stdio.h> #include<conio.h> int main(void) { int sum,a,b,c; float ave; char name[10]; char initial[3]; printf(Good day!); printf(What is your name?); scanf(%s,&name); printf(\nHow about your middle initial?); scanf(%s,&initial); printf(\nGive three integers and Ill compute the average :); scanf(%d %d %d,&a,&b,&c);
10
Programming in C
sum = a=b=c; ave = sum/2.0; printf(\nThe average of %d %d and %d is %0.2f,a,b,c,ave); printf(Goodbye %s,name); getch(); return 0;
Output: Good day! What is your name? Pinoy How about your middle initial? Give three integers and Ill compute the average : 5 6 5 The average of 5 6 and 5 is 5.33 Goodbye Pinoy
11
12
13
The function gets() reads a string from the keyboard and store this string in the string parameter. It also returns a pointer to the string parameter.
15
Constants
Constants - purpose is to enhance the readability of the programs, C allows the definition of constant values. Usually the definition of constant is placed on top of the program file after the header file. The general form of this directive is: #define identifier value Example: #define PI 3.1416 #define MAXINT 32767 #define FORMFEED \014 #define Message Hello World! #define Octal30 036 #define Hex30 0x1e
16
Constants
Constants - purpose is to enhance the readability of the programs, C allows the definition of constant values. Usually the definition of constant is placed on top of the program file after the header file. The general form of this directive is: #define identifier value Example:
\014 constant enclosed in single quote stands for the character whose decimal value is 12 or in octal 014.
#define PI 3.1416 #define MAXINT 32767 The constant enclosed in double quotes are interpreted as #define FORMFEED \014 array of characters. #define Message Hello World! #define Octal30 036 #define Hex30 0x1e The constant that start with 0 are in octal while those that start with 0x are in hexadecimal notation.
17
Constants
Once defined, the value can be used instead of the value in the body of the program. For example; #include <stdio.h> #include <conio.h> #define Radius 10.34 #define PI 3.1416 int main(void) { float area; area = PI * Radius * Radius; printf (The area of the circle with radius %.2f is %.2f, Radius,area); getch(); return 0; }
18
Constants
Once defined, the value can be used instead of the value in the body of the program. For example; #include <stdio.h> #include <conio.h> #define Radius 10.34 #define PI 3.1416
int main(void) { float area; area = PI * Radius * Radius; printf (The area of the circle with radius %.2f is %.2f, Radius,area); getch(); return 0; }
Note: If the radius of a circle is changed to another value, you only need to change the definition of radius once. Unlike the hard coded wherein you need to change every occurrence of the value of the radius in the code.
19
Constants
To illustrate, the program above can be written without the constant definition as follows; #include <stdio.h> #include <conio.h> int main(void) { float area; area = 3.1416 * 10.34 * 10.34; printf (The area of the circle with radius 10.34 is %.2f,area); getch(); return 0; }
20
Constants
To illustrate, the program above can be written without the constant definition as follows; #include <stdio.h> #include <conio.h> int main(void) { float area; area = 3.1416 * 10.34 * 10.34; printf (The area of the circle with radius 10.34 is %.2f,area); getch(); return 0; } Note: that you need to edit the three occurrences of 10.34 in the code instead of just once. Imagine if this value occurs 100 times in the code, then you need to edit the 100 occurrences of the value unlike only once if it is defined as a constant.
21
Constants
Alternative constant. ANSI C allows the use of the keyword const for defining constants. For example; #include <stdio.h> #include <conio.h> int main(void) { float area; const float Radius = 10.34; const float PI = 3.1416; area = PI * Radius * Radius; printf (The area of the circle with radius %.2f is %.2f,Radius,area); getch(); return 0; }
22
Constants
Alternative constant. ANSI C allows the use of the keyword const for defining constants. For example; #include <stdio.h> #include <conio.h> int main(void) { float area; const float Radius = 10.34; const float PI = 3.1416; area = PI * Radius * Radius; printf (The area of the circle with radius %.2f is %.2f,Radius,area); getch(); return 0; }
23
Note: Those identifiers declared as const will be disallowed to modify the initial value of the identifiers.
Constants
THE ADVANTAGE of const over #define is its applicability to pointers. For example, the declaration; const int *p = 100; Which has an alternative syntax int const *p = 100; Declares p as a variable pointer to a constant integer. Thus, int a; *p = 200; illegal p = &a; - legal Another possible syntax int *const p; Which declares p as constant pointer to variable integer. Thus, int a; p = &a; - illegal *p = 200; - legal
24
Arithmetic Operators
An expression is a code of fragment in C, that when evaluated will result to a value. Some expressions can be formed by combining variables and constant values using operators. For expressions that results to integer, floating point or character values, the operators used are ARITHMETIC OPERATORS. Basic Binary Operators: + addition - subtraction * multiplication / division % modulo Unary Operator: - additive inverse The % operator produces the remainder, for example; a%b will result to 2 if a has a value of 6 and b has a value of 4. This operator cannot be applied to float or double type of values.
25
Arithmetic Operators
The / operator when presented with operand whose values are integers will result to integer division which truncates any fractional part. For example: a/b will result to 1 if a has a value 6 and b has a value 4. But the operator will produce floating point result if at least one of the operands is floating point.
The + and have the same precedence, which is lower than *, / and % which in turn is lower than unary -. The usual evaluation order for operators of the same precedence is from left to right. For example: 3+2*46/2 will be evaluated as?
26
Arithmetic Operators
3+2*46/2 3+86/2 3+83 11 3 8 Sample: What will be the output of this program. #include <stdio.h> #include <conio.h> int main(void) { printf(%d %d %f %d\n, 7 % 3, 12 / 5, 12.0 / 5, 2 + 3 * 4 / 5 - 1); getch(); return 0; } What can you say about the evaluation of operators with the same precedence? will be evaluated as?
27
These operators have equal precedence and just below them in precedence are relational operators: == != equal not equal
These operators have lower precedence than arithmetic operators. Therefore, the expression: 5 +3*2>26/2 is evaluated as?
28
The evaluation of these logical operators is consistent with the mathematical meanings of and and or. Expressions using && and || are evaluated left to right and the evaluation continues until the truth or falsehood of the expression is determined. For example: 4 + 2 > 7 3 && 3 + 3 > 4 + 4 || 8 + 7 == 13 will be evaluated as?
29
31
32
The shift operators << and >> shift the bits of the left operand by a number equal to its right operand. Thus n << 2 shift the bits of n two places to the left. The unary operator ~ yields the ones complement of an integer. That is, it reverses the bits of the integer thus making 1 to a 0 and a 0 to a 1.
33
n | 0177
n ^ 1077
n << 2
~n
Sample program: #include <stdio.h> #include <conio.h> int main(void) { int n = 64; printf(%d\n,n&011111); print(%d\n,n|011111); printf(%d\n,n^011111); printf(%d\n,n>>3); printf(%d\n,n<<3); getch(); return 0; }
35
Note: Since the ++ is found as a prefix, this means increment i before using the value of i.
Example: ++i; - adds one to the value of i. i++; - increment i after using the value i. Examples to see the difference between these two increment operators: j = ++i; and j = ++i; j = i++; j = i++; suppose i has a current value of 10. After j will have a value 11 while that of j will have a value of 10. The next time i is used only then will it have a value 11.
36
The Output: 22 12
38
40
DIFFERENCE BETWEEN POSTFIX AND PREFIX NOTATIONS OF THE INCREMENT AND DECREMENT OPERATORS
The postfix and prefix notations of the increment and decrement operators differ when used in expressions. Examples: a = ++age; Assume age = 5. After execution of this statement, a = 6 and age = 6. In other words, the value of age is incremented first and then its value is assigned to variable a. a = age++; Assume age = 5. After execution of this statement, a = 5 and age = 6. In other words, the value of age is assigned first to variable a and then its value is incremented.
41
() [] ++ -(type) * & ~
Parenthesis Square brackets Increment Decrement Cast operator The contents of The address of Unary minus Ones complement
Left to right Left to right Right to left Right to left Right to left Right to left Right to left Right to left Right to left
45
Logical NOT Multiply Divide Remainder (MOD) Add Subtract Shift right Shift left Is greater than
Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right
46
Logical AND
Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right
47
|| = += -= *= /= %= >>= <<=
Logical OR Assign Add assign Subtract assign Multiply assign Divide assign
Remainder assign Right shift assign
Left to right Right to left Right to left Right to left Right to left Right to left Right to left Right to left Right to left
48
&= ^= |=
50
NOTE: In the case of w--, the value of w will be used in the evaluation of the expression first before it is decremented. But in the case of ++u, the value of u was incremented first before being used in the expression.
51
PARENTHESES
Parentheses change the rules of precedence and associativity. Expressions in parentheses have the highest precedence. Examples: 1. 5+3*4+2 = 5 + 12 + 2 = 2. = 3. = 5 + 3 * (4 + 2) 5+3*6 = (5 + 3) * (4 + 2) 8 * (4 + 2) =
17 + 2 5 + 18 8*6
= = =
19 23 48
52
CONTROL FLOWS
The concept of a block is actually a group of declarations and statements. For example, in the program:
#include<stdio.h> int main(void) { float area; area = 3.1416 * 10.34 * 10.34; printf(The area of the circle with radius %.2f is %.2f, radius, area); return 0; }
54
CONTROL FLOWS
In the program we have one block enclosed by { } the main block, inside this block it is possible to define new blocks by simply enclosing it in { }. A block is synthetically equivalent to one statement. Hence, we also call a single statement not enclosed in { } a block. Therefore, we can view a block as composed of several blocks. To illustrate this consider this example
55
#include <stdio.h> #define small Small #define medium Medium #define large Large int main(void) { float area; char size; area = 3.1416 * 10.34 * 10.34; printf ("The Value area of circle with radius 10.34 is %.2f,area); if (area < 100) { size = S; printf(%c or %s, size, small); } else if (area >= 100 && area < 200) { size = M; printf(%c or %s, size, medium); } else if (area > 200) { printf(L or %s,large); return 0; }
56
#include <stdio.h> #define small Small #define medium Medium #define large Large int main(void) In this program, we have three blocks. { A, B and C inside the main block float area; defining the main program. char size; area = 3.1416 * 10.34 * 10.34; printf ("The Value area of circle with radius 10.34 is %.2f,area); if (area < 100) { size = S; A printf(%c or %s, size, small); } else if (area >= 100 && area < 200) { size = M; B printf(%c or %s, size, medium); } else if (area > 200) { printf(L or %s,large); C return 0; 57
C LANGUAGE STATEMENTS
If-Else Statement - is the basic decision statement in C. It allows one to execute a block of statement based on the truthfulness of a condition. Format / syntax: if (expression) block1 else block2
58
C LANGUAGE STATEMENTS
If-Else Statement - is the basic decision statement in C. It allows one to execute a block of statement based on the truthfulness of a condition. Format / syntax: Note: if (expression) block1 else block2
The else part in this format is optional. The first expression is evaluated. If it evaluates to true, then block1 is executed skipping block2. The statement following block2 is executed next after executing block1. However, if the expression evaluates to false, then it is block1 that is skipped and block2 is the one executed. Execution continues to the statement following block2 after the if statement is executed.
59
C LANGUAGE STATEMENTS
Else-If Statement - is one way of writing a multi-way decision in C is the use of else-if statement. Format / syntax: if (expression1) block1 else if (expression2) block2 else if (expression3) block3 else block4
Note: The last else handles the case where expressions 1 to 3 are all false. An example was given earlier.
60
C LANGUAGE STATEMENTS
Switch Statement - an alternative to else-if statement for multi-way decision making. Format / syntax: switch (expression) { case constant1: block1 case constant2: block2 . case constantn: blockn default: blockn+1 }
61
C LANGUAGE STATEMENTS
Switch Statement
In this statement, each case is labeled by a constant expression which should be different in value from other cases. The execution starts by evaluating the expression, then it matches with the values in the cases. If a match is found, the block in that case is executed. The execution continues falling to other cases below until everything is executed or a break or exit statement is encountered. The default case is optional and it catches the execution if the expression does not match any of the cases. The break statement if present will bring the execution outside of the switch statement.
62
C LANGUAGE STATEMENTS
While Statement - the first statement that allows one to loop through a block. Format / syntax: while (expression) block
63
C LANGUAGE STATEMENTS
While Statement - the first statement that allows one to loop through a block. Note: Format / syntax: The execution starts by evaluating the expression. If the expression is true while (expression) (for no-zero), then the block is executed, otherwise, the execution block goes outside of the while
statement. After executing the block, it then reevaluates the expression and the process is repeated.
64
C LANGUAGE STATEMENTS
For Statement - another looping statement that allows one to loop through a block. Format / syntax: for (statement1; condition; statement2) { block }
This is equivalent to the following while statement: statement1; while (condition) { block; statement2; }
65
C LANGUAGE STATEMENTS
For Statement More general format / syntax: for (statements1; condition; statements2) { block }
Note: The statements in statements1 and statements2 are separated by commas. The execution starts by executing statements1, then the condition is evaluated. If the condition evaluates to true the statements in the block is executed. After the statements in the block is executed, statements2 is executed. Then, the condition is again evaluated, if true continue to statements in the block followed by statements2. This continues until the condition becomes false where the execution goes out of the for loop.
66
C LANGUAGE STATEMENTS
For Statement
#include<stdio.h>
int main(void) { int c, i, j; j = 0; for (i = 1; i <= 10; i++) { c = getchar(); if (c == E) j++; } printf(In 10 tries you entered the letter E %d times.,j); getch(); retrun 0; }
Note: Obviously, the statement1 is an assignment statement setting some control variable to an initial value. Statement2 modifies the value of the control variable and condition must involve the control variable.
67
C LANGUAGE STATEMENTS
For Statement
In some cases, we may want the for loop to loop infinitely. In this case we use and simply write the syntax;
for(;;) { ... }
We can get out of the infinite loop using the break statement.
68
C LANGUAGE STATEMENTS
For Statement
#include<stdio.h>
In some cases, we may want the for loop to loop infinitely. In this case we use and simply write the syntax;
for(;;) { int main(void) ... { } int c, i, j; j = 0; We can get out of the infinite loop using the break statement. for (;;) { c = getchar(); if (c == E) break; else j++; } printf(In 10 tries you entered the letter E %d times.,j); getch(); retrun 0; 69 }
C LANGUAGE STATEMENTS
Do-While Statement - in this loop statement, the expression is evaluated before the block is executed. Hence, it is possible for the block not to be executed at all. To force the execution of the block at least once, this statement was introduced. Format / syntax: do { block } while (expression)
70
C LANGUAGE STATEMENTS
Do-While Statement - in this loop statement, the expression is evaluated before the block is executed. Hence, it is possible for the block not to be executed at all. To force the execution of the block at least once, this statement was introduced. Format / syntax: Note: do { block } while (expression)
In the statement, the block is executed first then the expression is evaluated. If the expression is true then it goes back and executes block again, otherwise it simply gets out of the do-while statement.
71
C LANGUAGE STATEMENTS
Do-While Statement
#include<stdio.h> int main(void) { int x, y; y = 0; do { x = getchar(); y++; } while (x != E); printf(You tried %d times before entering E, y-1); getch(); return 0; }
72
C LANGUAGE STATEMENTS
Do-While Statement
#include<stdio.h> This program accepts a character from the int main(void) user and counting the number of characters entered until the character { E is entered. int x, y; But in this case, the variable y keeps track of the number of times a character is y = 0; entered including the E character. do { x = getchar(); y++; } while (x != E); printf(You tried %d times before entering E, y-1); getch(); return 0; }
73
C LANGUAGE STATEMENTS
Break Statement We have seen earlier the use of this statement. For completeness, we say that break statement - is used to get out of the execution of the following: 1. for statement 2. while statement 3. do-while statement 4. switch statement
74
C LANGUAGE STATEMENTS
Continue Statement
If a break statement forces the execution to get out of a loop, the continue statement forces the evaluation of the expression in a loop statement. The evaluation of the expression is immediately done regardless of where in the loop the current execution is. For example,
int main(void) { int x, sum; sum = 0; for(x = 1; x <= 100; x++){ if (x <= 50) continue; sum = sum + x; getch(); return 0; }
This program use to illustrate the continue statement. This adds the numbers 51 to 100.
75
C LANGUAGE STATEMENTS
Continue Statement
Note that the program can be better coded in this way.
int main(void) { int x, sum; sum = 0; for (x = 1; x <= 100; x++) { if (x <= 50) continue; sum = sum + x; getch(); return 0; } int main(void) { int x, sum; sum = 0; for (x = 51; x <= 100; x++) { sum = sum + x; getch(); return 0; }
76
C LANGUAGE STATEMENTS
Goto Statement
Since the advent of structured programming, many authors advised against using the goto statements. However, one can still find situations where a goto is the cleanest way of solving the problem. One of these problems is going out of a deeply nested loop statements. For example
int main(void) { for (;;) for (;;) for (;;) . goto label; } label: . }
77