Fundamentals of C and C++ Programming Control Structures and Functions The Assignment Operators The assignment operator: “=“ assigns a value to a variable. The addition.

Download Report

Transcript Fundamentals of C and C++ Programming Control Structures and Functions The Assignment Operators The assignment operator: “=“ assigns a value to a variable. The addition.

Fundamentals of C and C++
Programming
Control Structures and Functions
The Assignment Operators
The assignment operator: “=“ assigns a
value to a variable.
The addition assignment operator: “+=“
adds the value of the expression on its
right to the value of the variable on its left,
and saves the result to the variable on the
left.
Can also be done with the other arithmetic
operators: -= *= /= %=
EEL 3801 – Lotzi Bölöni
The Inc/Decrement Operators
Unary increment and decrement operators
increment and decrement the value of an
integer variable by 1.
++ and -- are the operators.
Placed before the variable, they are preincrement and pre-decrement: the value is
incremented or decremented before it is
used in the expression in which it
appears.
EEL 3801 – Lotzi Bölöni
The Inc/Decrement Operators
Placed after, they are known as the postincrement and post-decrement operators.
The value of the variable is incremented or
decremented after it is used in the
expression in which it appears.
In general, the use of pre-increment and
decrement operators it is a programming
artifact, which is strongly discouraged in
modern programming.
EEL 3801 – Lotzi Bölöni
The Inc/Decrement Operators
Example:
main() {
int c=5;
printf(“%d ”, c);
printf(“%d ”, c++);
printf(“%d ”, c);
return 0;
}
Output ==> 5 5 6
EEL 3801 – Lotzi Bölöni
The Inc/Decrement Operators
Example:
main() {
int c=5;
printf(“%d ”, c);
printf(“%d ”, ++c);
printf(“%d ”, c);
return 0;
}
Output ==> 5 6 6
EEL 3801 – Lotzi Bölöni
Logical Operators
&& this is the logical conjunction (AND)
|| this is the logical disjunction (OR)
! This is the logical negation (NOT)
== This is the equality operator. (Do not
confuse with the assignment operator =).
< <= > >= These are self explanatory.
!= This is the inequality operator.
EEL 3801 – Lotzi Bölöni
Functions
C allows, nay encourages, the
development of many functions.
The C Standard Library has several
functions already available for use by the
programmer.
These libraries are included using the
#include preprocessor directive.
EEL 3801 – Lotzi Bölöni
Functions
The most common ones are stdio.h and
math.h for C.
Functions can be called from within other
functions at an arbitrary level of nesting.
Functions cannot be defined within other
functions.
Functions must be prototyped as discussed
previously.
EEL 3801 – Lotzi Bölöni
Functions
Definition of a function requires the
following:
–the type of value returned (if any)
–the name of the function
–the type of arguments passed to it
–declaration of local (automatic) variables
–the body of the function
–return a value of the correct type (if any)
EEL 3801 – Lotzi Bölöni
Functions
Example:
float square(float x) {
float y;
y = x * x;
return y;
}
EEL 3801 – Lotzi Bölöni
Functions
A function that does not return any value
is designated as void for its return value.
A function that does not accept any
arguments also has void in its
paramenter definition.
EEL 3801 – Lotzi Bölöni
Passing Arguments
Two ways:
–Call by value: Only the value of the variable being
referenced is passed, not its address. The called
function cannot make any changes to the original
variable.
–Call by Reference: The address of the variable is
passed. The called function can make changes to
the original variable.
C is naturally Call by Value
EEL 3801 – Lotzi Bölöni
Passing Arguments
In order to do Call by reference, a pointer
to the variable must be passed.
We’ll see this when we get to pointers.
EEL 3801 – Lotzi Bölöni
Basic Program Control Structure
Most programming languages implement
sequential execution - one statement after
the other.
Certain instructions permit control of the
next statement (instruction) to be executed.
The basic one is the GOTO instruction.
GOTO’s are the basic machine instruction,
but aren’t desirable in high level languages.
EEL 3801 – Lotzi Bölöni
Basic Program Control Structure
Bohm and Jacopini found that programs
could in fact be written without GOTO’s
Instead of the the GOTO in HLL’s:
–The Sequential Structure
–The Selection Structure
–The Repetition Structure
Called Structured Programming
EEL 3801 – Lotzi Bölöni
The Sequential Structure
The sequential structure is the most basic
structure in computer programming, and
the basis of instruction sequences
Unless told otherwise, the processor
executes the next instruction in the
instruction sequence.
Self-explanatory
EEL 3801 – Lotzi Bölöni
The Selection Structure
Three types of selection structures;
–The if structure: performs an action if the
condition is true, or skips that action and
continues. Called the single selection structure.
–The if/else structure: performs an action if the
condition is true; performs a different action if
false. Called the double selection structure.
–The switch structure: selects among several
different actions. Called multiple select. struct.
EEL 3801 – Lotzi Bölöni
The IF Structure
Has the following syntax:
if (test)
<action>
If the action is more than one statement,
then:
if (test){
<action1>
<action2>
}
-this notation is encouraged
EEL 3801 – Lotzi Bölöni
The IF Structure - Example
The following is an example of the if
structure:
if (grade >= 60){
printf(“Passed\n”);
}
<next statement>;
Note that nothing is printed if the grade <
60, as it goes to the <next statement>.
EEL 3801 – Lotzi Bölöni
The IF-ELSE Structure
Allows the programmer to specify
alternative action if the test is not true.
The syntax is:
if (test)
<action>;
else
<alternative action>;
EEL 3801 – Lotzi Bölöni
The IF-ELSE Structure
If more than one statement comprises the
action or alternative actions, then we can
use a brace to group several statements.
if (test) {
<statement 1>;
<statement 2>;
}
else {
<alt. statement1>;
<alt. Statement2>; }
EEL 3801 – Lotzi Bölöni
The IF-ELSE Structure
An example of the IF-ELSE structure is as
follows:
if (grade >= 60) {
printf(“Passed\n”);
} else {
printf(“Failed\n”);
}
EEL 3801 – Lotzi Bölöni
The IF-ELSE Structure
IF-ELSE structures can be nested so as to
perform other tests before another action is
executed. The syntax is:
if (grade >= 90)
printf(“A\n”);
else if (grade >= 80)
printf(“B\n”);
else
printf(“Failed\n”);
EEL 3801 – Lotzi Bölöni
The IF-ELSE Structure
 Has a shortcut. Its syntax is:
<control expression> ? <then expression>
: <else expression>
Example:
m>0 ? M+5 : m*2;
EEL 3801 – Lotzi Bölöni
The switch Structure
Is the multiple selection structure.
Consists of a series of case labels and an
optional default case.
The labels are like in assembly
programming, a name and a colon:
The value of the label must agree with the
value of the test.
EEL 3801 – Lotzi Bölöni
The break Statement
The break statement is important in the
definition of some control structures.
When executed in a repetition control
structure or in the switch selection
structure, causes an immediate exit from
that structure, to the first statement after
the structure.
It is transparent to other selection
structures.
EEL 3801 – Lotzi Bölöni
The switch Structure
Each statement or group of statements
corresponding to a label must be followed
by the break statement.
break will cause the processor to break
out of the switch structure and not
evaluate the other statements in the
sequence. Goes to the first statement
after the switch. Usually very important.
EEL 3801 – Lotzi Bölöni
The switch Structure
If no match is found between the test and
the labels, then the statements
corresponding to the default label are
executed.
No braces are needed to group together
the statements corresponding to each
label. This is counter to all else in C.
default not required.
EEL 3801 – Lotzi Bölöni
The switch Structure
The default typically goes last. However,
this is not a requirement.
The default statement block does not need
a break statement, but it is typically
supplied in order to clarify the issue.
Test can only be an expression that
evaluates to a constant integer value.
Characters enclosed in single quotes.
EEL 3801 – Lotzi Bölöni
The switch Struct. - Example
Switch (grade)
{
case ‘A’:
++acount;
break;
case ‘B’:
++bcount;
break;
case ‘C’:
++ccount;
break;
default:
printf(“This is an error.\n”);
break:
}
EEL 3801 – Lotzi Bölöni
The Repetition Structure
Permits an action to be repeated several
times, as in a loop, either
–as long as a condition is true (sentinel control)
–for a fixed number of times (counter control)
There are 3 of them:
–The while loop: sentinel control (entry cond.)
–The for loop: counter control (entry condition)
–The do/while loop: sentinel ctrl (exit cond.)
EEL 3801 – Lotzi Bölöni
The continue Statement
Like the break, the continue statement
affects the execution of repetition
structures.
Causes the processor to skip the
remaining statements in the loop body,
but goes back to the next iteration.
Typically associated with a selection
structure.
EEL 3801 – Lotzi Bölöni
The continue Statement
In the for loop, the increment expression is
executed and the loop continuation test is
evaluated thereafter.
In the while loop, the loop continuation test
is evaluated immediately after the continue
statement.
In the do/while loop, the loop continuation
test is evaluated immediately after the
continue statement.
EEL 3801 – Lotzi Bölöni
The for Structure
Counter controlled.
Requires control variable to be defined.
Handles details of running the loop
automatically.
Carries out the loop continuation test
immediately after the counter is
incremented (at top of loop).
EEL 3801 – Lotzi Bölöni
The for Structure
Requires the following information:
–Name of the control variable
–Initial value of counter
–Increment or decrement of the counter
–Final value of the counter. Defines exit
conditions. Continues as long as test is true.
Programmer must ensure that the control
variable will converge to the final value.
EEL 3801 – Lotzi Bölöni
The for Structure
The syntax for the for loop is as follows:
for (<ctrl var> = <init val>;
<ctrl var> = <final value>
<incrementation def>) {
<body of loop>
}
EEL 3801 – Lotzi Bölöni
The for Structure
Final value and increment can be
mathematical functions.
The increment can be negative decrement.
If loop continuation condition is initially
false, body will never be executed.
Control variable does not need to be used
in body of loop, but can be, such as for
arrays.
EEL 3801 – Lotzi Bölöni
The for Structure
Example:
main()
{
int sum = 0, n;
for (n=2;n<=100;n+=2)
sum += n;
printf(“Sum = %d”, n);
return 0;
}
EEL 3801 – Lotzi Bölöni
The while Structure
Specifies action to be repeated as long as
condition remains true.
The loop continuation condition is
“implicit”, but variable initialization and
updating has to be programmed explicitly.
Checks for loop continuation at the
beginning of the loop body.
EEL 3801 – Lotzi Bölöni
The while Structure
Basically a sentinel controlled loop, but
can also be used as counter controlled.
Can be used in place of the for loop in
most cases.
One exception is when a continue is
used and the increment/decrement
expression is placed after the continue
statement.
EEL 3801 – Lotzi Bölöni
The while Structure
The syntax is as follows:
cont_var=<initial val>;
while (loop cont test on cont_var){
<statement1>;
<statement 2>;
<statement 3>;
}
EEL 3801 – Lotzi Bölöni
The while Structure
Example:
product = 2;
while (product <= 1000)
product = 2*product;
EEL 3801 – Lotzi Bölöni
The do/while Structure
Same as the while loop, with the
exception that the loop continuation test
is done after the body of the loop has
been executed.
Thus, the body of the do/while loop is
guaranteed to be executed at least once.
Braces not required if only one statement,
but typically used anyway for clarity.
EEL 3801 – Lotzi Bölöni
The do/while Structure
The syntax is as follows:
cont_var=<initial val>;
do {
<statement1>;
<statement 2>;
<statement 3>; }
while (loop cont test on
cont_var);
EEL 3801 – Lotzi Bölöni
Interesting Note
C++ allows the declaration of the control
variables directly within the specification
of the repetition structure.
C does not.
Example:
for (int n=0; n>=10;n++)
Same for the while and do/while.
EEL 3801 – Lotzi Bölöni
Control Structures - Summary
C/C++ only has 7 control structures.
Structures are single-entry/single-exit,
which facilitate programming.
Repetition structures can be nested within
one another at an arbitrary level of
nesting.
This nesting is what can cause
combinatorial explosion.
EEL 3801 – Lotzi Bölöni