Date post: | 24-Oct-2014 |
Category: |
Documents |
Upload: | lorelie-vanguardia-mondragon |
View: | 50 times |
Download: | 5 times |
1
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.
2
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
Programming in C
HEADER FILES
alloc.h – dynamic memory allocation
conio.h – direct console input/output functions
Dos.h – dos interface functionsgraphics.h– graphics related
functionsmath.h – mathematical functionsstdio.h – standard i/o functionsstdlib.h – miscellaneous functionsstring.h – string related functionstime.h – time and date related
functions
3
C Basic Types for Variables:
1. char – character type2. int – can contain integer values3. float – stands for floating point or numbers with fractional
part4. double – double precision floating point
Sizes for Values or Variables:
Type Value Bit Width Range
char char 8 0 to 255 int integer 16 -32768 to
32768 float real 32 3.4E-38 to
3.4E+38 double real 64 1.7E-308 to 1.7E+308
Programming in C
4
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
Programming in C
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.
5
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
6
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
7
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%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;}
Programming in C
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){ 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 100 200 10.250000 1.025000e+01 62 4c string A 0100 0200 10.25 1.025e+01 62 4c string
9
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%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 100 200 10.250000 1.025000e+01 62 4c string A 0100 0200 10.25 1.025e+01 62 4c string
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…
10
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 I’ll compute the average :”); scanf(“%d %d %d”,&a,&b,&c);
Programming in C
11
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? PinoyHow about your middle initial?Give three integers and I’ll compute the average : 5 6 5
The average of 5 6 and 5 is 5.33Goodbye Pinoy
Programming in C
12
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;}
The getchar() and putchar() function
13
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;}
Note:
a followed by carriage return – inputa - outputx 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)
The getchar() and putchar() function
14
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;}
The gets() and puts() function
15
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.
16
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
Constants
17
‘\014’ – constant enclosed in single quote stands for the character whose decimal value is 12 or in octal 014.
The constant enclosed in double quotes are interpreted as array of characters.
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
The constant that start with 0 are in octal while those that start with 0x are in hexadecimal notation.
Constants
18
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#definePI 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;}
Constants
19
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#definePI 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.
20
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;}
Constants
21
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.
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
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;}
Note: Those identifiers declared as const will be disallowed to modify the initial value of the identifiers.
24
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; – illegalp = &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
25
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: Unary Operator:
+ addition - additive inverse- subtraction The % operator produces the
remainder,* multiplication for example;/ division a % b% modulo will result to 2 if a has a value of 6
and bhas a value of 4. This operator cannot be applied to
float or double type of values.
26
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 * 4 – 6 / 2 will be evaluated as?
27
Arithmetic Operators
3 + 2 * 4 – 6 / 2 will be evaluated as?
3 + 8 – 6 / 23 + 8 – 311 – 38
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?
28
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 > 2 – 6 / 2 is evaluated as?
29
5 + 3 * 2 > 2 – 6 / 2 is evaluated as?
5 + 6 > 2 – 311 > -1True
Logical Operators in C:
&& and|| not
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?
Relational and Logical Operators
30
Relational and Logical Operators
4 + 2 > 7 – 3 && 3 + 3 > 4 + 4 || 8 + 7 == 13
6 > 4 && 3 + 3 > 4 + 4 && 8 + 7 == 13True && 3 + 3 > 4 + 4 && 8 + 7 == 13True && 6 > 8 && 8 + 7 == 13True && False && 8 + 7 == 13False && 8 + 7 == 13False
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?
31
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
32
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;}
33
Bitwise Logical Operators
Bitwise Logical Operators in C:
& bitwise and| bitwise inclusive or^ bitwise exclusive or<< shift left<< shift right~ one’s 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 one’s 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.
34
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
n | 0177 = 0000000010001111 | 000000000001111111 = 0000000011111111 = 255
n ^ 1077 = 0000000010001111 ^ 000000000001111111 = 0000000011110000 = 240
n << 2 = 0000000010001111 << 2 = 0000001000111100 = 572
35
Bitwise Logical Operators
Examples how this work:
n >> 2 = 0000000010001111 >> 2 = 0000000000100011 = 35
~n = ~0000000010001111 = 1111111101110000 = 65392
Sample program:
#include <stdio.h>#include <conio.h> printf(“%d\n”,n>>3);
int main(void) printf(“%d\n”,n<<3);{ getch(); int n = 64; return 0; printf(“%d\n”,n&011111); } print(“%d\n”,n|011111); printf(”%d\n”,n^011111);
36
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--
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++; suppose i has a current value of 10. After
j = ++i; j will have a value 11 while that of j = i++; j will have a value of 10. The next time i is used only then
will it have a value 11.
Increment and Decrement Operators
Note: Since the ++ is found as a prefix, this means increment i before using the value of i.
37
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: The Output:
#include <stdio.h> 22#include <conio.h> 12
int main(void){ int i = 10; printf(“%d\n”, ++i + i++); printf(“%d\n”,i); getch(); return 0;}
Increment and Decrement Operators
38
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: The Output:
#include <stdio.h> 22#include <conio.h> 12
int main(void){ int i = 10; printf(“%d\n”, ++i + i++); printf(“%d\n”,i); getch(); return 0;}
Increment and Decrement Operators
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.
39
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.
More on Increment and Decrement Operators
40
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.
More on Increment and Decrement Operators
41
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.
42
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.
Increment and Decrement Operators
43
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 Associativity
( ) ++ (postfix) -- (postfix) left to right + (unary) - (unary) ++ (prefix) -- (prefix) right to left
* / % left to right + - left to right = += -= *= /= etc. right to left
44
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:
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
() [] -> &
! ~ -* & sizeof cast ++-
^
* / % &&
+ - ||
< <= >= > ? :
== != = += -= then , (comma)
45
THE ASSOCIATIVITY OF OPERATORS
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
( ) Parenthesis Left to right
[ ] Square brackets Left to right
++ Increment Right to left
-- Decrement Right to left
(type) Cast operator Right to left
* The contents of Right to left
& The address of Right to left
- Unary minus Right to left
~ One’s complement
Right to left
46
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
THE ASSOCIATIVITY OF OPERATORSContinuation…
! Logical NOT Right to left
* Multiply Left to right
/ Divide Left to right
% Remainder (MOD) Left to right
+ Add Left to right
- Subtract Left to right
>> Shift right Left to right
<< Shift left Left to right
> Is greater than Left to right
47
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
THE ASSOCIATIVITY OF OPERATORSContinuation…
>= Greater than or equal to
Left to right
<= Less than or equal to Left to right
< Less than Left to right
== Is equal to Left to right
!= Is not equal to Left to right
& Bitwise AND Left to right
^ Bitwise exclusive OR
Left to right
| Bitwise inclusive OR
Left to right
&& Logical AND Left to right
48
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
THE ASSOCIATIVITY OF OPERATORSContinuation…
|| Logical OR Left to right
= Assign Right to left
+= Add assign Right to left
-= Subtract assign Right to left
*= Multiply assign Right to left
/= Divide assign Right to left
%= Remainder assign Right to left
>>= Right shift assign Right to left
<<= Left shift assign Right to left
49
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
THE ASSOCIATIVITY OF OPERATORSContinuation…
&= AND assign Right to left
^= Exclusive OR assign
Right to left
|= Inclusive OR assign
Right to leftTherefore, the expression
a > b && c * d < e is evaluated in as
( a > b ) && ( ( c * d ) < e
a = b = c / d + e is evaluated as
a = ( b = ( ( c / d ) + e)
50
BOARDWORK:
1. a += b += c + d + e * f2. - 8 * 5 / 4 * 23. x * y - z / 2++ where x = 5, y = 4 and z = 124. 7 - -a * ++b where a = 2 and b = 45. ++u * v - w -- where u = 1, v = 2, and w = 3
EXAMPLES ON EXPRESSION EVALUATION
51
5. ++u * v - w -- where u = 1, v = 2, and w = 3
= ++u * v - 3= 2 * v - 3= 2 * 2 - 3= 4 - 3= 1
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.
EXAMPLES ON EXPRESSION EVALUATION
52
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 = 17 + 2 = 19
2. 5 + 3 * (4 + 2)= 5 + 3 * 6 = 5 + 18 = 23
3. (5 + 3) * (4 + 2)= 8 * (4 + 2) = 8 * 6 = 48
53
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.
54
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;
}
CONTROL FLOWS
55
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…
56
#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;}
57
#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’; 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;}
In this program, we have three blocks. A, B and C inside the main block defining the main program.
58
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
elseblock2
C LANGUAGE STATEMENTS
59
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
elseblock2
Note: 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.
60
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
elseblock4
Note: The last else handles the case
where expressions 1 to 3 are all false. An example was given earlier.
61
C LANGUAGE STATEMENTS
Switch Statement- an alternative to else-if statement for multi-way decision making.
Format / syntax:
switch (expression) {case constant1: block1case constant2: block2….case constantn: blockndefault: blockn+1
}
62
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.
63
C LANGUAGE STATEMENTS
While Statement- the first statement that allows one to loop through a block.
Format / syntax:
while (expression) block
64
C LANGUAGE STATEMENTS
While Statement- the first statement that allows one to loop through a block.
Format / syntax:
while (expression) block
Note: The execution starts by evaluating
the expression. If the expression is true (for no-zero), then the block is executed, otherwise, the execution goes outside of the while statement.
After executing the block, it then re-evaluates the expression and the process is repeated.
65
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;
}
66
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.
67
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.
68
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.
69
C LANGUAGE STATEMENTS
For Statement
#include<stdio.h>
int main(void){ int c, i, j; j = 0; for (;;) { c = getchar(); if (c == ‘E’) break;
else j++; } printf(“In 10 tries you entered the letter E %d times.”,j); getch(); retrun 0;}
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.
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:
do { block} while (expression)
71
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)
Note: 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.
72
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;}
73
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;}
This program accepts a character from the user and counting the number of characters entered until the character ‘E’ is entered.
But in this case, the variable y keeps track of the number of times a character is entered including the ‘E’ character.
74
C LANGUAGE STATEMENTS
Break StatementWe 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 statement2. while statement3. do-while statement4. switch statement
75
C LANGUAGE STATEMENTS
Continue StatementIf 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.
76
C LANGUAGE STATEMENTS
Continue Statement
int main(void) int main(void){ {
int x, sum; int x, sum; sum = 0; sum = 0; for (x = 1; x <= 100; x++) { for (x = 51; x
<= 100; x++) { if (x <= 50) continue; sum = sum
+ x; sum = sum + x; getch(); getch(); return 0; return 0; }
}
Note that the program can be better coded in this way.
77
C LANGUAGE STATEMENTS
Goto StatementSince 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: ….}