Gaining Control in c
-
Upload
fazal-mcpherson -
Category
Documents
-
view
218 -
download
0
Transcript of Gaining Control in c
-
8/13/2019 Gaining Control in c
1/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 1of 11
GAINING CONTROL in C
Lecture Outline:
1. Expressions and statements,2. Blocks & Compound statements,3. Flow- Control Constructs4. Nested Constructs5. Using logical operators6. Using Relational operators
1. Expressions and StatementsIn C, any assignment such as x = 0is called an expression and has a value.
An expression becomes a statement when it is followed by a semicolon, e.g.:
x=0;
printf(.);
N.B.:The semicolon is a statement terminator.
2. Blocks and Compound StatementsCurly brackets are used to group declarations and statements together into a compound
statement, or codeblock, so that they are syntactically equivalent to a single statement. For
example, curly brackets are used to surround the statements of a function, like:
int main()
{
printf(Hello there!);
return 0;
}
N.B.: There is no semicolon after the right (closing) bracket that ends a block.
-
8/13/2019 Gaining Control in c
2/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 2of 11
3. Control-Flow ConstructsControl-flow constructs are statements which specify the order in which instructions are
performed. There are three control types of control constructs in C:
1. SequentialThe next instruction to be executed comes immediately after the preceding statement.
2. SelectionThe next instruction to be executed is determined by the result of some decision
3. RepetitionOne or more instructions are executed repeatedly while some condition remains true.
Execution of the instruction(s) stops when the condition becomes false.
3.1. Sequential ConstructsExamples:
x = a + b;
printf(The sum of %d and %d is: %d \n,a, b, x);
3.2. Selection Constructs Used to express decisions
These include:
if if-else and else-if ?: switch
3.2.1. The if statement tests the numeric value of an expression if not followed by a bracketed code block, only the first statement immediately after
the if statement is executed in relation to the if statement once it evaluates to true
The syntax:
-
8/13/2019 Gaining Control in c
3/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 3of 11
if (expression)
statement1
Example:
if(progNum == 0715)
printf(You are a UG Computer Science student doing your diploma.);
printf(This is not related to the previous if statement).
NB: in the example above, the indented printf statement corresponds to the if statement. The
second printf will execute regardless of the condition of the if statement.
3.2.2. The if-elsestatementThe syntax:
if (expression)
statement1
else
statement2
Examples:
if(siblings >= 1)
{ printf(How many brothers do you have?\n);
scanf(%d,&bro);
printf(\nHow many sisters do you have?\n);scanf(%d,&sis);
}
else
printf(Seems like youre an only child.);
printf(This is not related to the previous if-else statement).
if(progNum == 0715)
printf(You are a UG Computer Science student doing your diploma.);
else if(progNum == 0719)
printf(You are a UG Computer Science student doing your degree.);
else
printf(Youre not in the UG Computer Science department.\n).
printf(This is not related to any of the previous if statements).
3.2.2bThe syntax for the else-ifstatement:
if(expression)
{ statement1statement3
statement4
} else if(expression)
{ statement5
statement6
}
-
8/13/2019 Gaining Control in c
4/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 4of 11
N.B.:
use indentations to show the relationship of sequential-flow statements to theircorresponding if-else statements.
Use brackets to surround multiple statements that are associated with the if-elsestatements.
3.2.3. The ternary operator ? : This is an alternate way to write an if-else statement.
The syntax: Meaning
exp1 ? exp2: exp3 conditional expression ? TRUE : FALSE
The conditional expression exp1is evaluated first. If it is non-zero (true), then exp2is evaluated,
otherwise, exp3is evaluated.
E.g.
If-else statement Ternary equivalent
if( a > b)
max = a;
else
max = b;
max = ( a > b) ? a : b;
if (n==1)
c = ;
else
c= s;
printf(Number of Item%c:%d,c,n);
printf(Number of Item%s:
%d,(n==1)? : s,n);
-
8/13/2019 Gaining Control in c
5/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 5of 11
3.2.4. The switchstatement Used for multi-way decisions
The syntax:
switch ( expression){
case value1: Code to execute if expression== value1
break;
case value2: Code to execute if expression== value2
break;
default: Code to execute if expressiondoes not match any of the
values following any of the cases
break;
}
Example:/* A simplified calculator */
int operand1, operand2;
int result = 0;
char operation;
printf(Enter first operand: );
scanf(%d,&operand1);
printf(Enter operation to perform ( +, -, *, /,): );
scanf(\n%c,&operation);
printf(Enter second operand: );
scanf(%d,&operand2);
/* Perform the calculation */
switch(operation)
{case +: result = operand1 + operand2;
break;
case -: result = operand1 - operand2;
break;
case *: result = operand1 * operand2;
break;
case /: if( operand2 !=0) // error checking
result = operand1 / operand2;
elseprintf(Divide by 0 error!\n);
break;
default: printf(Invalid operation entered);
break;
}
printf(The answer is %d\n, result);
-
8/13/2019 Gaining Control in c
6/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 6of 11
Notes:
If the case matches the expression, execution starts at that case. All case expressions must be different. Each case must end with a breakstatement. Breakis a keyword that breaks execution
out of the current code block. It causes an immediate exit from the switch construct and
redirects the program flow to the statement after the closing brace of the switch.
The case labeled defaultis optional. It executes if the switch expression matches noneof the case constants. If it isnt there and the expression matches none of the case
constants then none of the cases within the switch are executed.
3.3Reptition Consructs:These include:
while dowhile for
3.3.1.The whilestatement
Tests a termination condition at the beginning of the loop. The while loop repeatsthe execution of the statements in its code block while the condition is true.
The syntax:
while (expression)
{
statements
}
Example:
int x = 1;
int a = 0;
printf(The first three even whole numbers are: );
while( x
-
8/13/2019 Gaining Control in c
7/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 7of 11
Note:Execution proceeds as follows:
1. The expressionis evaluated.2. If expressionis true (nonzero), the body of the whilestatement is executed and the
process is repeated beginning at step 1.
If expressionis false, the body of the whilestatement is never executed, and control
passes to the next statement after the closing brace of the whilestatement.
3.3.2.The do-whilestatement
Tests a termination condition at the end of the loop. The do-while loop alwaysperforms at least one iteration of the its code block and repeats the execution its
code block while the condition expression is true. It is equivalent to the Pascal
repeat-untilstatement. NB: the do-while expression terminates with a semicolon.
The syntax:
do
{
statements
} while (expression);
Example:
int x, a;
a = 0;
printf("How many results do you want to see?");
scanf("%d",&x);
printf("The first %d even whole numbers are:",x);
do
{
printf("%d ", a);
a+=2;
x=x-1;
} while( x > 0);
printf("\nmoving on...\n");
Note:Execution proceeds as follows:
1. The statement body is executed.
-
8/13/2019 Gaining Control in c
8/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 8of 11
2. Next, expressionis evaluated. If expressionis false, the do-whilestatement terminatesand control passes to the next statement in the program. If expressionis true (nonzero),
the code block is repeated.
3.3.1.The forstatement
The forstatement allows you to repeat a code block a specified number of times. Ittests a termination condition at the beginning of the loop.
The syntax:
for ( init-expression opt; cond-expression opt; loop-expression opt)
{
statements
}
Example:
int x = 1;
int a = 0;
printf("The first three even whole numbers are: ");
for(x=1; x
-
8/13/2019 Gaining Control in c
9/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 9of 11
statement within the statement body is executed, or when a goto(to a labeled
statement outside the forstatement body) is executed.
o If cond-expressionis false (0), execution of the forstatement terminates andcontrol passes to the next statement in the program.
4. Nested Constructs
When we compose a construct that contains another construct it is referred to asnesting.
Example:
if(n>0)
for( i=0; i21) && ( age
-
8/13/2019 Gaining Control in c
10/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 10of 11
6. Using Relational Operators
Used to test the relationship between two values. If the condition evaluates to true then1 is the value after execution otherwise the condition evaluates to 0 when false.
The Relational operators in C:
Operator Operation Example
> greater than x > y
>= Greater than or equal x >= y
< Less than x < y
-
8/13/2019 Gaining Control in c
11/11
Lecturer: Aurel Liddell CSI 2101 September, 2013
Page 11of 11
Exercises:
1. Write a program that reads the prices of 10 items and their item number.The program should print the name of the item with the highest price.
Assume that the items dont have the same price.
2. Write a program to read eleven numbers find their average and print it. Theprogram should also print the number of times the number 6 occurs.
3. Write a program to validate a date in the twenty-first century. It shouldcheck that the number of months in a year cannot exceed 12, and that the
number of days in each month has not been exceeded. The program should
also report on Leap years.
Hint: Implement this program using a switchstatememt.