C Language

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 77

Programming in C

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) {

%s,A,100,200,10.25,10.25,50,76,string); printf(%10c%10.4d%10.4i%10.2f%10.3e%10o%10x %s,A,100,200,10.25,10.25,50,76,string);

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) {

%s,A,100,200,10.25,10.25,50,76,string); printf(%10c%10.4d%10.4i%10.2f%10.3e%10o%10x %s,A,100,200,10.25,10.25,50,76,string);

printf(%10c%10d%10i%10f%10e%10o%10x

getch(); return 0;

Output: A A

100 200 0100 0200

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

%s,A,100,200,10.25,10.25,50,76,string); printf(%10c%10.4d%10.4i%10.2f%10.3e%10o%10x %s,A,100,200,10.25,10.25,50,76,string);

getch(); return 0;

Output: A A

100 200 0100 0200

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

The getchar() and putchar() function


Sample program to illustrate how to use the getchar() and putchar() in a program.
#inlcude<stdio.h> #include<conio.h> int main(void) { char c; while((c=getchar())!=x) putchar(c); getch(); return 0; }

12

The getchar() and putchar() function


Sample program to illustrate how to use the getchar() and putchar() in a program.
Note: #inlcude<stdio.h> #include<conio.h> int main(void) { char c; while((c=getchar())!=x) putchar(c); getch(); return 0; } a followed by carriage return input a - output x followed by carriage return - input Function getchar() is executed this presumably returns a character from the keyboard which is assigned to variable c. the value of subexpression (c = getchar()) is the value which is assigned to c and this value is compared with the character x. If they are not equal then a true value (non zero value) is the final value of the expression ((c = getchar()) != x) Otherwise, its value is false (or a value of 0)

13

The gets() and puts() function


Sample program illustrating gets() and puts() function:
#inlcude<stdio.h> #include<conio.h> int main(void) { char s1[20], *s2; while(strcmp(s2 = gets(s1),\0)) { puts(s1); puts(s2); } getch(); return 0; }
14

The gets() and puts() function


Sample program illustrating gets() and puts() function:
#inlcude<stdio.h> #include<conio.h> int main(void) { char s1[20], *s2; while(strcmp(s2 = gets(s1),\0)) { puts(s1); puts(s2); } getch(); return 0; } Note: a string. followed by carriage return input a string - output hello world! flw by carriage return - input hello world! - output Carriage return
- input

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

Relational and Logical Operators


Expression may also assume boolean (true or false) values. In this case, the operators involve in the expressions are relational and logical operators. Relational Operators define in C: > >= < <= greater than greater than or equal less than less than or equal

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

Relational and Logical Operators


5 +3*2>26/2 5+6>23 11 > -1 True Logical Operators in C: && || and not is evaluated as?

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

Relational and Logical Operators


4 + 2 > 7 3 && 3 + 3 > 4 + 4 || 8 + 7 == 13 6 > 4 && 3 + 3 > 4 + 4 && 8 + 7 == 13 True && 3 + 3 > 4 + 4 && 8 + 7 == 13 True && 6 > 8 && 8 + 7 == 13 True && False && 8 + 7 == 13 False && 8 + 7 == 13 False Notice that the rightmost relational expression is not evaluated anymore because the falsehood of the expression is already established. Finally, there is the unary negation operator ! Which converts a true to false and false to true. For example: !(4 + 2 > 3 + 8) is evaluated as?
30

Relational and Logical Operators


!(4 + 2 > 3 + 8) !(6 > 11) !(False) True If the value of an expression is non-zero this is automatically interpreted as true while a value of 0 is interpreted as false. Hence, the expression !number Is equal to number == 0

31

Relational and Logical Operators


Sample program: What will be the output of this program? #include <stdio.h> #include <conio.h> int main(void) { printf(%d\n, 7 + 2 != 5 + 2 && 4 > 2 + 3); getch(); return 0; }

32

Bitwise Logical Operators


Bitwise Logical Operators in C: & | ^ << << ~ bitwise and bitwise inclusive or bitwise exclusive or shift left shift right ones complement (unary)

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

Bitwise Logical Operators


Examples how this work: Consider a variable integer n with value 143. The binary representation of n is 0000000010001111. The value of n & 0177 = 0000000010001111 & 00000000001111111 = 0000000000001111 = 15 = 0000000010001111 | 000000000001111111 = 0000000011111111 = 255 = 0000000010001111 ^ 000000000001111111 = 0000000011110000 = 240 = 0000000010001111 << 2 = 0000001000111100 = 572
34

n | 0177

n ^ 1077

n << 2

Bitwise Logical Operators


Examples how this work: n >> 2 = 0000000010001111 >> 2 = 0000000000100011 = 35 = ~0000000010001111 = 1111111101110000 = 65392

~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

Increment and Decrement Operators


The idea of this operator is it adds one to the value of the operand. The format in using this operator is:

++operand or operand++ --operand or operand--

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

Increment and Decrement Operators


The same rules apply to the decrement operator --. The only difference is that the value of the operand is decrease by 1. the same format as for increment is used for decrement. Sample Program: #include <stdio.h> #include <conio.h> int main(void) { int i = 10; printf(%d\n, ++i + i++); printf(%d\n,i); getch(); return 0; }
37

The Output: 22 12

Increment and Decrement Operators


The same rules apply to the decrement operator --. The only difference is that the value of the operand is decrease by 1. the same format as for increment is used for decrement. Sample Program: #include <stdio.h> #include <conio.h> int main(void) { int i = 10; printf(%d\n, ++i + i++); printf(%d\n,i); getch(); return 0; } The Output: 22 12 This is because the first ++i will set i = 11. Then, the second term in ++i + i++ will use the value i = 11 which is added to the first term which is 11 to give 22. After i++ i will already be 12.

38

More on Increment and Decrement Operators


1.The Increment Operator (++)
The increment operator (++) is a unary operator that increments the contents of a variable by 1. For example, the statement ++ age; increments the contents of the variable age by 1. If age = 5, then ++age will make age = 6. In other words, ++age is the same as age = age + 1. The ++ operator can also be in the postfix notation. This means that age ++ will also have the same effect as ++age.
39

More on Increment and Decrement Operators


2.The Decrement Operator (--) The decrement operator (--) is a unary operator that decrements the contents of a variable by 1. In other words, --age or age-- is the same age = age - 1. NOTE: Both the increment and decrement operators are not applicable to constants or ordinary expressions. For example, --8 and ++(a + b) are not allowed.

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

Increment and Decrement Operators


Sample Program: #include <stdio.h> #include <conio.h> main() { int a, b, c, d; c = 1; d = 1; a = ++c; b = d++; printf (The value of a is %d and the value of c is %d.\n, a, c); printf (The value of b is %d and the value of d is %d.\n, b, d); getch(); return 0; } The output of the program is: The value of a is 2 and the value of c is 2. The value of b is 1 and the value of d is 2.
42

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


As in algebra, the arithmetic operators (+, -, *, /, and %) in C follow rules in precedence and associativity. These rules determine how evaluation of expressions should take place. The following summarizes the rules of precedence and associativity:
Operators ( ) ++ (postfix) -- (postfix) + (unary) - (unary) ++ (prefix) -- (prefix) * / % = + += -= *= /= etc. Associativity left to right right to left left to right left to right right to left
43

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


In the table, all operators in the same line have equal precedence with respect to each other, but have higher precedence than all operators that occur on the lines below them. The associativity rule for all operators evaluates from left to right or right to left.

OPERATORS FROM HIGH PRIORITY TO LOW PRIORITY ORDER:

() [] -> ! ~ -* & sizeof cast ++* / % + < <= >= > == !=

& ^ && || ?: = += -= then , (comma)


44

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


THE ASSOCIATIVITY OF OPERATORS

() [] ++ -(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

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


THE ASSOCIATIVITY OF OPERATORS Continuation

! * / % + >> << >

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

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


THE ASSOCIATIVITY OF OPERATORS Continuation Greater than or equal to Left to right >=

<= < == != & ^ | &&

Less than or equal to

Less than Is equal to Is not equal to Bitwise AND


Bitwise exclusive OR Bitwise inclusive OR

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

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


THE ASSOCIATIVITY OF OPERATORS Continuation

|| = += -= *= /= %= >>= <<=

Logical OR Assign Add assign Subtract assign Multiply assign Divide assign
Remainder assign Right shift assign

Left 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

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


THE ASSOCIATIVITY OF OPERATORS Continuation

&= ^= |=

AND assign Exclusive OR assign Inclusive OR assign

Right to left Right to left Right to left

Therefore, the expression

a > b && c * d < e is evaluated in as ( a > b ) && ( ( c * d ) < e a=b=c/d+e a = ( b = ( ( c / d ) + e)


is evaluated as
49

EXAMPLES ON EXPRESSION EVALUATION


BOARDWORK: 1. a += b += c + d + e * f 2. - 8 * 5 / 4 * 2 3. x * y - z / 2++ where x = 5, y = 4 and z = 12 4. 7 - -a * ++b where a = 2 and b = 4 5. ++u * v - w -- where u = 1, v = 2, and w = 3

50

EXAMPLES ON EXPRESSION EVALUATION


5. ++u * v - w -= = = = = ++u * v - 3 2*v-3 2*2-3 4-3 1 where u = 1, v = 2, and w = 3

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

PERFORMING ARITHMETIC OPERATIONS ON DIFFERENT DATA TYPES


Any variable whose value is computed from at least one floating-point operand should generally be a floating-point variable. Example: x = 3.5 + 2 Variable x should be of type float or double. y = 2.7 * z Variable y should be of type float or double regardless on the type of variable z. Any variable whose value is computed from at least one division operation should be a floating-point variable. Example: x = y/z Variable x should be of type float.
53

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

You might also like