Program Control Statemsnts in C by abrarbaig

VIEWS: 91 PAGES: 23

									MODULE 4 LW 5: C PROGRAM CONTROL 5.1 A C PROGRAM CONTROL
  Program is comprises of several lines of instructions. Instructions are organized into three kind of control structures to control the flow of execution, which are: o Sequence structures o selection structures o repetition structures Sequence structures comprises of several statements: o Declaration statements o Input/output statements o Assignment, Arithmetic and Boolean expression A minimum structure of a complete and free-error of a C program should have one(1) pre-processor directives, single main() function , open curly braces({) and a close curly braces(}). Observe a piece of program given below.







#include <stdio.h> > void main() { …. Declaration statements …. Main program }

pre-processor directives

Figure 5.1 – A basic structure of a C program A group of a statements bracketed by { and } is known as compound statement.

______________________________________________________________ 2/23
Here are some terminologies and their definitions which have been used in programming environment.  Pre-processor directives – set of instruction that causes several program files or symbolic constant or macros to be compiled together. E.g #include, #define. Standard C library header – a collection of function prototypes and definition and declaration of various data types and constant in different separate files. There are two forms of #include directive. E.g stdio.h, math.h, stdlib.h, stringh.h Variable and constant – a memory concept which refers using a name and has data type. Variable is a memory which the value can be changed during the program execution. Constant is a fixed pre-assigned memory. Identifier – any user-defined series of combined characters to refers variable, constant, functions or data structures. To create an identifier, one must follow these rules: o o o o o Must starts with characters Cannot contain symbols except _ Cannot have space bar It is not a reserved word Maximum length of each identifier is 31 characters







Hint: A good identifier is one that resembled its duties.  Reserved word – set of words that have special meaning to C compiler and cannot be used as identifiers. RESERVED WORDS IN C       auto break case char const do       double else enum extern float if       int long register return short static       struct switch typedef union unsigned while

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 3/23
5.2 SEQUENCE STRUCTURE  Sequence structure is statement which is executed one after the other in order in which they are written.

a) Declaration statement  Declaration is process allocating memory spaces based on defined type. o Syntax: <data type> < valid identifier>; // declaration <data type> < valid identifier> = <value>; // initialization o Actual code:

int

marks; /*allocate a memory slot that accept
round numbers value */

float temp; /*allocate a memory slot ready
to accept floating point numbers*/ char code; /*allocate a memory slot ready to accept single character value*/ const pi=3.142; /* allocate a memory to accept a fixed value*/ o Example used in a complete program code.

#include <stdio.h> void main() { int marks; float temp = 0.0; char code; const k = 1; …. Main program }

Figure 5.2 – Example on declaration statement

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 4/23
b)  Input/Output statement Syntax of output statement: printf(“ < any strings to be print out>”); printf(“ < format type>”,<identifier>); puts(<any strings to be print out >); putchar(<a character >);  Actual code:

printf(“Hello there!”);
 Output:

Hello there!
 Example used in a complete program code. #include <stdio.h> void main() { int marks; float temp; char code; printf(“To know your grade, please enter your mark now:>”); }



Figure 5.2 – An example on output statement
Output: To know your grade, please enter your mark now:>_

 

Beside printing literals, printf() statement also can print out the content of a variable or constant by calling their identifiers. Observe the output from the program segment below: int x = 10; printf(“%d”,x); //printf(“ The value assigned into x is = %d”, x);//try this



Output: 10_

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 5/23
 Syntax of input statement: scanf(“ < format type>”,&<identifier>); gets(<any strings >); getchar(<a character >);  Actual code:

scanf(“%d”, &box);
* Note: Above instruction is only successfully executed if box has been declared earlier, else it will produce syntax error. The scanf() standard library function that is used to obtain data from the keyboard. The format type used in scanf () function is a conversion specifier that able to indicate data type.  Example used in a complete program code. #include <stdio.h> void main() { int marks; char grade; printf(“To know your grade, please enter your mark now:>”); scanf(“%d”,&marks); if ( (marks > 0) && (marks<=60)) grade = „F‟; else grade = „P‟; printf(“\n\n”); printf(“Your grade is %c”, grade); }

Figure 5.3 – An example on input statement

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 6/23  There are several symbols to work as an operator together with input/output instructions.
Operator & -> * %d %c %f %s Explanation Address locator To refer member in struct data type Pointer Integer value Character value Floating numbers String type

c)

Assignment, Arithmetic and Boolean expression Assignment expression in a C program using the equal(‘=’) operator. Example: 1) 2) Marks = 0; counter = counter +1; // the content of counter + 1 //assign back to counter

C provides several assignment operators for abbreviating assignment expressions. For example: c = c+ 3; can be abbreviated with the addition assignment operator += as c +=3; The += operator adds the value of the expressions on the right of the operator to the value of the variable on the left and stores the result in the variable on the left. Here are list of assignment operators which have been used in C Assignment Sample Explanation operators expression Assume int c = 3, d= 5, e = 4, f =6, g =12; += -= *= /= %= C D E F G += -= *= /= %= 7; 4; 5; 3; 9; c d e f g = = = = = c d e f g + * / % 7; 4; 5; 3; 9; Assigns

10 to c 1 to d 20 to e 2 to f 3 to g

Table 5.1 – Arithmetic assignment operators

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 7/23
C also provide unary increment operator, ++, and the unary decrement operator, --, and a summarized in Figure 2.2.It is only works on plus and minus expression with single variable and the value to increase or decrease is 1. c = c+ 1; can be abbreviated to c += 1; and into c++;

Figure 2.3 demonstrates the differences between pre-increment, pre-decrement, post-increment and post-decrement.

Operators ++

Sample expression ++a; a++; --b; b--;

Explanation Increment a by 1 then use the new value of a in the expression in which a resides Use the current value of a in the expression in which a resides, then increment by 1. Decrement b by 1 then use the new value of b in the expression in which b resides Use the current value of b in the expression in which b resides, then decrement by 1.

++

--

--

Table 5.2 The increment and decrement operators

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 8/23
Example: #include < stdio.h> void main() { int c; c=5; printf(“%d\t”,c); printf(“%d\t”,c++); printf(“%d\n\n”,c); c=5; printf(“%d\t”,c); printf(“%d\t”,++c); printf(“%d\t”,c); } //print 5 //print 5then increase by 1, //print 6 //print 5 //increase by 1, then print 6 //print 6

Figure 5.4 – An example of post and pre-increment operations
OUTPUT: 5 5 5 6 6 6

Arithmetic expression is mathematical formula being written using C language. It uses certain symbols to indicate the operation. Explanation Additional operation Subtraction operation Multiplication operation Division operation Modulo operation (return balance) Sample expression A = 3 + 4; //A=7 A = 4 - 1; //A=3 A = 3 * 4; //A=12 A = 4 / 2; //A=2 A = 4 % 2; //A=0

Operators + * / %

Table 5.3 – Arithmetic expression and operators

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 9/23
Example: 1. Give the correct C expression for the mathematical equation below: a)
b)

q=kA(T1 - T2) L
c+b(a-c) 3-q abc – j
2

c)

ANSWER: a) b) c) q = (k * A ( T1 –T2))/ L c + b*(a-c)/ (3 – q) a*b*c – j* j

2.

Given the equation y = ax3 +7, write the correct C expression.
ANSWER: y = a*x*x*x + 7;

3.

State the order of evaluation of the operators in each of the following C statements and show the value of x after each statement is performed. a) b) c) d) e) x = 7 + 3 * 6 / 2 – 1; x = 2 % 2 + 2 * 2 – 2 / 2; x = ( 3 * 9 * ( 3 + ( 9 * 3 / (3 ) ) ) );* x = 4 + ( 2 * (3 /3 +15) % 2)* x = 4 * 4 – 8/ 2 * ( 4 % 2 )

ANSWER: a) x=7+3*6/2-1 = 7 + 18 / 2 – 1 =7+9–1 = 15

b)

x = 2 % 2 + 2 * 2 – 2 / 2;
=0+4–1 =3

* the remaining equation will be discuss in class.

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 10/23
  Boolean expression or sometimes known as conditional expression which return value TRUE(1) or FALSE(0). For a simple Boolean expression, it is constitute of a variable, relational operator or equality operators or logical operators (any composite of them) and value for comparison. Relational Operators > < >= <= Equality Operators == != Explanation Greater than Smaller than Greater or equal than Smaller or equal than Explanation Equal Not Equal Sample expression 3 > 5; TRUE 5 < 3; FALSE 3>=2; TRUE 5 <= 0; FALSE Sample expression 1 == 0; FALSE 1 != 0 ; TRUE

Table 5.4 – Boolean expression and relational operators    C also provides logical operator that may be used to form more complex conditional expression. The logical operators are && (AND) and || (OR) and logical !(NOT also known as logical negation). If there is situation that require more than one condition to be TRUE, before a certain path of execution is chosen, therefore the option we have is to use the &&(AND) logical operator. Consider the following example: If ( (gender == 1) && ( semYear == 4 )) ++seniorFemale; /* the number of senior female student is increased if student gender is TRUE for type 1 and semYear is equal to 4.*/ Expression1 || Expression2 TRUE(1) TRUE(1) TRUE(1) FALSE(0)

Expression1 TRUE(nonzero) TRUE(nonzero) FALSE(zero) FALSE(zero)

Explanation2 TRUE(nonzero) FALSE(zero) TRUE(nonzero) FALSE(zero)

Table 5.5 – Truth table for the ||( Logical OR)operators

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 11/23

Expression1/Operand1 TRUE(nonzero) TRUE(nonzero) FALSE(zero) FALSE(zero)

Explanation2/Operand2 TRUE(nonzero) FALSE(zero) TRUE(nonzero) FALSE(zero)

Expression1 /Ope1 && Expression2?Ope2 TRUE(1) FALSE(0) FALSE(0) FALSE(0)

Table 5.6 – Truth table for the && ( Logical AND)operator Operand1 TRUE(nonzero) FALSE (zero) !Operand1 FALSE (0) TRUE(1) Table 5.7 – The ! Operator(not) Examples: 1. Assume the value of a = 4, b= 5 and c =10, determine the value return for each expressions below: a) b) c) d) e) f) g) h) i) j) k) a > 20 b <= (a + b) c>0 (a+c )>= (b + c) ((a> 10) &&(c < 20)) (a+c +6)>= (b + c) (!(a> 10) &&(c < 20)) || (c > 0) (c*5 )>= (b + a) !((a> 10) &&(c < 20)) && (c > 0) 0 >= (b + c) ((a> 10) &&!(c < 20)) || ! (c > 0)

ANSWERS a) b) c) d) e) FALSE or 0 TRUE or 1 TRUE FALSE ((a> 10) &&(c < 20)) ~( TRUE && TRUE) ~TRUE (a+c +6)>= (b + c)

f)

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 12/23
~20 > = 15 ~TRUE g) (!(a> 10) &&(c < 20)) || (c > 0) ~ ( !( FALSE) && (TRUE)) || (TRUE) ~ (TRUE && TRUE) || TRUE ~ TRUE || TRUE ~ TRUE

*NOTE: The remaining will be discussed in class Operator Precedence An operator precedence determines its order of evaluation. Table 5. _ lists the precedence of all C operators so far from the highest to lowest. The table shows the function calls to be evaluated first. The unary operator,!(not),+(plus), - (minus) and & (address of ) will be evaluated the second. Next, come the binary operator in the sequence: arithmetic, rational, equality and logical AND and OR. The assignment operator (=) will be evaluated the last. * Notice that the precedence of operators + and – depends on whether they have one operand or two. Example: -x-y * z Explanation the unary –x will be evaluated first and then followed by *(multiply) and then the second – (arithmetic operators). If x=4 ; y =5 and z * 2 The solution is  -x-y * z  (-4) - 5 * 2  - 4 -10  -14 Operator Function call !(not), +(positive) , -(negative) &(address) - unary operator *(multiply), /(divide) ,%(modulo) – binary operator +(add), -(subtract) – arithmetic operator <,<=, >=, > - logical operator ==, != - equality operator && || = Precedence Highest

Lowest

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 13/23
Exercises 5.1 1. Give the correct C expression for the mathematical equations below: a) K = 8j + 6m + 3ab 3j e = 3a + 6b – 4j2 w = /2p + 1q + 6r2 4ab + 3j C 5a + 4(a+b)2

b) c) d)

e) 2.

State the order of evaluation of the operators in each of the following C statements and show the value of a, b and c after each statement is performed. a) b) c) a = 7 * 3 + 6 / 2 * 1; b = 2 / 2 + 2 * 2 – 2 % 2; c = ( 3 + 9)/ ( 3 + ( 9 +3 / (3 ) ) ) ;

3.

What is the value of a and c after execution of the following statements, if a = 10, b = 5 and c= 10? a) a=a%b+5–c/2 b) c = c + b / 5 – ( 3 * a – 3) Find the result of the following expressions after execution. a) b) c) d) e) 5%4+2*3 2 * 3 – ( 3 /2 + 2) (2 * 3 + 2/2 ) * ( 2 + 9 / 3) 10 / 5 + 24 % 6 – 1 3 * 4 % 3 – ( 9 / 3 + 12)

4.

5. Assuming x is 15.0 and y is 25.0, what are the values of the following conditions? a) b) c) d) 6. x!=y x<x X >= Y –X x == y + x – y

Evaluate each of the following expressions if a is 5, b is 10, cis 15 and flag is 1. Which parts of these expressions are not evaluated due to short-circuit evaluation? a) b) c) d) c == a + b || ! flag a != 7 && flag || c > =6 !(b<=12) && a %2 == 0 !(a> 5) | | c < a + b)

Show answers in step by step.

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 14/23
7. Assuming x = 3.0, y = 4.0 ,z = 2.0 and flag = 0. Determine the results return by the following expressions. i. ii. iii. iv. 8. ! flag x + y /z < = 3.5 ! flag || ( y + z >+ x-z) !(flag || ( y +z >= x-z))

Write a single C statement to accomplish each of the following: a. Assign the sum of x and y to z and increment the value of x by 1 after the calculation. b. Multiply the variable product by 2 using the *= operator c. Multiply the variable product by 2 using the * and = operator d. Decrement the variable x by 1 and then subtract it from the variable total. e. print the floating point value 3.14159 with three digits to the right of decimal point. Show what is printed. f. Obtain two numbers from users and assign them to a and b. Predict what is the output of product if x is 3 and y is 2. a. product *=2; b. product - = --x; c. product += x--; d. product %= y;

9.

10.

Assume a = 1 and b = 2. What does each of the following statements print? a. printf(“%d”, a == a); b. printf(“%d”, a > = 1 && b < 4); c. printf(“%d”, a < 99 || !( a >= b)); d. printf(“%d”, !(a - a));

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 15/23
SELECTION STRUCTURE  Selection structure is used to choose among alternative courses of action. C provides 3(THREE) types of selection structures. o Single-alternative o Dual-alternatives o Multi-alternatives Single-alternative structure selects or ignores a single action. It will either performs an action if the condition is TRUE OR skips the action if the condition is false. The basic structure of single-selection structure is as follows: if ( < Boolean expression>) <statement> <next statement> Flowchart representation



<expression>

T

<statement>

F

<next statement>

Example 1 if ( grade >= 60 ) printf( “Passed\n”); printf( “End processing”);

grade >= 60

T

Print Passed
F

Print processing

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 16/23
Example 2 if ( (age >=0) && (age <=2) ) printf( “Fare type: Baby\n”); if ( (age > 2) && (age <=5) ) printf( “Fare type:Kids\n”); if ( age > 5 ) printf( “Fare type:Adults\n”);

age>0 && age<=2

Fare type: Baby T F

T

age>2 && age<=5

<18))
F

Fare type: Kids

age>5

T

Fare type: Adults

F

OUTPUT  What is the output of the program if age is; a) age=1 output: Fare type: Baby b) age=6 output: Fare type: Adult c) age=-1 output: next statement

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 17/23

Dual-Alternatives structures allows programmer to specify that different actions to be performed when the condition is TRUE than when the condition is FALSE. The basic structure of double-selection structure is as follows: if ( < Boolean expression>) <statement> else <statement> <next statement> FLOWCHART

<expression>

T

<statement1>

F

<statement2>

<next statement>

Example 1 if ( grade >= 60 ) printf( “Passed\n”); else printf( “Failed”); printf( “End processing”);

OUTPUT  What is the output of the program if the value of grade is; a) grade=70 output: Passed End processing b) grade=0 output: Failed End processing

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 18/23
If Statements with Compound Statements If statement can executes more than statements after the condition or the else if the statements start with braces .({ }) Example:
a) if(pop_today > pop_yesterday) { growth = pop_today –pop_yesterday; growth_pct= 100.0 * growth / pop_yesterday; printf(“ The growth percentage is %.2f\n”, growth_pct); } *b) if(ctri <= MAX_SAFE_CTRI) { printf(“ Car # %d: safe\n”, auto_id); safe = safe +1; } else { printf(“ Car # %d: unsafe\n”, auto_id); unsafe = unsafe +1; }

* Good programming style

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 19/23
Multi-selection structures performs one of many different actions depending on the value of expression. There are 2(TWO) basic structures of multi-selection structure. One is using if /else if and the other using the switch..case structure: 1. if ( < Boolean expression>) <statement1> else if ( < Boolean expression>) <statement2> else if ( < Boolean expression>) <statement3> ‘ ‘ else <statement> <next statement>

When to used switch case? The condition is an exact match.

2.

switch(expression/variable) { case <expression/value1>: <statement1>; break; case < expression/value2>: < statement2>; break; case < expression/value3>: < statement3>; break; default :< statement>; }

.

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 20/23
Flowchart representation

<expression1>

T

<statement1>

F

< expression2>

T

< statement2>

F T < statement3>

< expression3>

F < statement1>

< next statement>

Example 1 Using if/else if structure scanf(“%c”,&choice); if (choice = = „A‟) printf( “Letter A\n”); else if (choice = = „B‟) printf( “Letter A\n”); else if (choice = = „C‟) printf( “Letter C\n”); else printf( “Choice Failed”);

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 21/23

Using switch.. case structure scanf(“%c”,&choice); switch(choice) { case „A‟:printf(“Letter A\n”); break; case „B‟:printf(“Letter B\n”); break; case „C‟:printf(“Letter C\n”); break; default:printf(“Choice Failed”,); }

OUTPUT  What is the output of the program if the value of choice is; a) choice =’A’ output: Letter A b) choice =’z’ output: Choice Failed

EXAMPLES: switch(class) { case „B‟: case „b‟: printf(“Battleship\n”); break; case „C‟: case „c‟: printf(“Cruiser\n”); break; case „D‟: case „d‟: printf(“Destroyer\n”); break; case „F‟: case „f‟: printf(“Frigate\n”); break; default:printf(“Unknown shipclass %c”,class); } Predict the output if: 1) class = b 2) class = p

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 22/23
Exercise 5.2 1. 2. The statement (2 > 1) && (3 <= 0) will produce the value of ______________ Convert the if-else if-else structure below into switch-case structure scanf(“%d”,&value); if (value = = 1) printf( “Open a document\n”); else if (value = = 2) printf( “Close a document\n”); else if value = = 3) printf( “Refresh a document\n”); else printf( “Bad number !!”); 3. What do these statements display?
i. if ( 12 < 12) printf(“Less”); else printf(“Not less”); var1 = 25.12; var2= 15.00; if (var1 <= var2) printf(“less or equal”); else printf(“greater than”);

ii.

4.

What is the final value assigned to x when y is 15.00?
iii. x = 25; if ( y != (x -10.0)) x = x -10.0; else x = x /2.0; if (y < 15.0) if (y > =0.0) x = 5 * y; else x = 2 * y; else x = 3 * y; v. if( y < = 15.0 && y >==0.0) x = 5 * y; else x = 2 * y;

iv.

Prepared by SITI HARYANI MOHD HARIS

______________________________________________________________ 23/23

5. Write a program that prompt user to enter two integers value and prints the larger number followed by message “is larger than” the other number. If the numbers are equal, print the message “These numbers are equal”. 6. Write a program that reads an integer and prints whether it is odd or even. Hint: Use the modulus operator. Even number return no balance if divide by2.

Exercise 5.3 1. Convert the following if..else statements into switch case or vice versa. a. switch(class) { case „B‟: case „b‟: printf(“Battleship”); break; case „C‟: case „c‟: printf(“Cruiser”); break; case „D‟: case „d‟: printf(“Destroyer”); break; case „F‟: case „f‟: printf(“Frigate”); break; b. if (x = =1) { printf(“Winner”);} else if (x >=2)||(x<=3){ printf(“First Runner Up”);} else if (x >=4)||(x<=6){ printf(“Third place”);} else printf(“Consolation price”);

Prepared by SITI HARYANI MOHD HARIS


								
To top