How are you today?
Name: Deab Sina
Major: D4 TMD ITB Batch 6
Control-flow
The control-flow of a language specify the order in which
computations are performed. We have already met the most common control-flow
constructions in earlier examples; here we will complete the set, and be more
precise about the ones discussed before.
1
Statements and Blocks
An expression such as x = 0 or i++ or printf(...) becomes a
statement when it is followed by a semicolon, (;) as in
x = 0;
i++;
printf(...);
In C, the semicolon(;) is a statement terminator, rather
than a separator as it is in languages like Pascal.
Braces { and } are used to group declarations and statements
together into a compound statement, or block, so that they are syntactically
equivalent to a single statement.
2 If-Else
The if-else statement is used to express decisions. Formally
the syntax is
if (expression)
statement1
else
statement2
where the else part is optional. The expression is
evaluated; if it is true (that is, if expression has a non-zero value), statement1 is executed. If it is false (expression is zero)
and if there is an else part, statement2 is executed instead.Since an if tests the numeric value of an expression,
certain coding shortcuts are possible. The most obvious is writing
if (expression)
instead of
if (expression != 0)
Sometimes this is natural and clear; at other times it can
be cryptic. Because the else part of an if-else is optional, there is an
ambiguity when an else if omitted from a nested if sequence. This is resolved by associating the else with the closest
previous else-less if. For example, in
if (n > 0)
if (a > b)
z = a;
else
z = b;
the else goes to the inner if, as we have shown by
indentation. If that isn’t what you want, braces must be used to force the
proper association:
if (n > 0) {
if (a > b)
z = a;
}
else
z = b;
The ambiguity is especially pernicious in situations like
this:
if (n > 0)
for (i = 0; i < n; i++)
if (s[i] > 0) {
printf("...");
return i;
}
else /* WRONG */
printf("error -- n is negative\n");
The indentation shows unequivocally what you want, but the
compiler doesn’t get the message, and associates the else with the inner if.
This kind of bug can be hard to find; it’s a good idea to use braces when there
are nested ifs. By the way, notice that there is a semicolon(;) after z = a in
if (a > b)
z = a;
else
z = b;
This is because grammatically, a statement follows the if,
and an expression statement like ‘‘z = a;’’ is always terminated by a
semicolon.
3 Else-If
The construction
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
Occurs so often that it is worth a brief separate
discussion.This sequence of if statements is the most general way of writing a
multi-way decision. The expressions are evaluated in order; if an expression is
true, the statement associated with it is executed, and this terminates the
whole chain. As always, the code for each statement is either a single
statement, or a group of them in braces. The last else part handles the ‘‘none of the above’’ or
default case where none of the other conditions is satisfied. Sometimes there
is no explicit action for the default; in that case the trailing
else
statement
can be omitted, or it may be used for error checking to
catch an ‘‘impossible’’ condition.
4 Switch
The switch statement is a multi-way decision that tests
whether an expression matches one of a number of constant integer values, and
branches accordingly.
switch (expression) {
caseconst-expr: statements
caseconst-expr: statements
default: statements
}
Each case is labeled by one or more integer-valued constants
or constant expressions. If a case matches the expression value, execution
starts at that case. All case expressions must be different. The case labeled
default is executed if none of the other cases are satisfied. A default is
optional; if it isn’t there and if none of the cases match, no action at all
takes place. Cases and the default clause can occur in any order.
5 Loops -
While and For
We have already encountered the while and for loops. In
while (expression)
statement
the expression is evaluated. If it is non-zero, statement is
executed and expression is re-evaluated. This cycle continues until expression becomes zero, at which point execution resumes
after statement. The for statement
for (expr1; expr2; expr3)
statement
is equivalent to
expr1;
while (expr2) {
statement
expr3;
}
Grammatically, the three components of a for loop are
expressions. Most commonly, expr1 and expr3 are assignments or function calls
and expr2 is a relational expression. Any of the three parts can be omitted,
although the semicolons must remain. If expr1 or expr3 is omitted, it is simply
dropped from the expansion. If the test, expr2, is not present, it is taken as permanently
true, so
for (;;) {
...
}
is an ‘‘infinite’’ loop, presumably to be broken by other
means, such as a break or return.
Whether to use while or for is largely a matter of personal
preference. For example, in
while ((c = getchar()) == ’ ’ || c == ’\n’ || c = ’\t’)
; /* skip white space characters */
there is no initialization or re-initialization, so the
while is most natural. The for is preferable when there is a simple
initialization and increment since it keeps the loop control statements close together
and visible at the top of the loop. This is most obvious in
for (i = 0; i < n; i++)
...
which is the C idiom for processing the first n elements of
an array, the analog of the Fortran DO loop or the Pascal for. The analogy is
not perfect, however, since the index variable i retains its value when the
loop terminates for any reason. Because the components of the for are arbitrary
expressions, for loops are not restricted to arithmetic progressions.
Nonetheless, it is bad style to force unrelated computations into the
initialization and increment of a for, which are better reserved for loop control
operations.
6 Loops -
Do-While
The syntax of the do is
do
statement
while (expression);
The statement is executed, then expression is evaluated. If
it is true, statement is evaluated again, and so on. When the expression
becomes false, the loop terminates. Except for the sense of the test, do-while
is equivalent to the Pascal repeat-until statement.
7 Break and
Continue
It is sometimes convenient to be able to exit from a loop
other than by testing at the top or bottom. The break statement provides an
early exit from for, while, and do, just as from switch. A break causes the
innermost enclosing loop or switch to be exited immediately. The following function, trim, removes trailing blanks, tabs
and newlines from the end of a string, using a break to exit from a loop when
the rightmost non-blank, non-tab, non-newline is found.
/* trim: remove trailing blanks, tabs, newlines */
int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ’ ’ && s[n] != ’\t’ && s[n] !=
’\n’)
break;
s[n+1] = ’\0’;
return n;
}
strlen returns the length of the string. The for loop starts
at the end and scans backwards looking for the first character that is not a
blank or tab or newline. The loop is broken when one is found, or when n
becomes negative (that is, when the entire string has been scanned). You should
verify that this is correct behavior even when the string is empty or contains
only white space characters. The continue statement is related to break, but less often
used; it causes the next iteration of the enclosing for, while, or do loop to
begin. In the while and do, this means that the test part is executed
immediately; inthe for, control passes to the increment step. The continue
statement applies only to loops, not to switch. A continue inside a switch
inside a loop causes the next loop iteration. As an example, this fragment processes only the non-negative
elements in the array a; negative values are skipped.
for (i = 0; i < n; i++)
if (a[i] < 0) /* skip negative elements */
continue;
... /* do positive elements */
The continue statement is often used when the part of the
loop that follows is complicated.
8 Goto and
labels
C provides the infinitely-abusablegoto statement, and labels
to branch to. Formally, the goto statement is never necessary, and in practice
it is almost always easy to write code without it. We have not used goto in
this book. Nevertheless, there are a few situations where gotos may find a
place. The most common is to abandon processing in some deeply nested
structure, such as breaking out of two or more loops at once. The break
statement cannot be used directly since it only exits from the innermost loop.
Thus:
for ( ... )
for ( ... ) {
...
if (disaster)
goto error;
}
...
error:
/* clean up the mess */
This organization is handy if the error-handling code is
non-trivial, and if errors can occur in several places.
A label has the same form as a variable name, and is followed
by a colon. It can be attached to any statement in the same function as the
goto. The scope of a label is the entire function. As another example, consider the problem of determining
whether two arrays a and b have an element in common. One possibility is
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (a[i] == b[j])
goto found;
/* didn’t find any common element */
...
found:
/* got one: a[i] == b[j] */
...
Code involving a goto can always be written without one,
though perhaps at the price of some repeated tests or an extra variable. For
example, the array search becomes
found = 0;
for (i = 0; i < n && !found; i++)
for (j = 0; j < m && !found; j++)
if (a[i] == b[j])
found = 1;
if (found)
/* got one: a[i-1] == b[j-1] */
...
else
/* didn’t find any common element */
...
With a few exceptions like those cited here, code that
relies on goto statements is generally harder to understand and tomaintain than
code without gotos. Although we are not dogmatic about the matter, it does seem that goto statements shouldbe used rarely, if
at all.
Coding of this video
#include <stdlib.h>
#include <math.h>// calling library math.h for calculate math
int main(void)
{
int i;
float a, s, h, r, volumepyramide, volumesphere;
/*
a: apothem length
s: side
h: height
r: radius
*/
do
{
printf("\n\nPlease type number 1 for calculate volume of Triangular Pyramide\n");
printf("\n\nPlease type number 2 for calculate volume of Sphere\n");
printf("Please type:");
scanf_s("%d",&i);
switch(i) // to control condition
{
case 1 :
{
printf("\n\nYou type number 1 for calculate volume Triangular Pyramide.");
printf("\n\nInput apothem length =");
scanf_s("%f",&a);
printf("\n\nInput side");
scanf_s("%f",&s);
printf("\n\nInput Height");
scanf_s("%f",&h);
volumepyramide=1.0/6.0*a*s*h;// Syntax of volume triangular
printf("\n\nSo volume of Triangular Pyramide = %.2f \n\n",volumepyramide);
break; // To break a case 1
}
case 2:
{
printf("\n\nYou type number 2 for calculate volume Sphere.");
printf("\n\nInput Radius of Sphere =");
scanf_s("%f",&r);
volumesphere=4.0/3.0*3.14*pow(r,3);// Syntax of volume sphere
printf("\n\nSo volume of Sphere = %.2f \n\n", volumesphere);
break; // TO break a case 2
}
// default: If we input wrong number, it will show message " Sorry! You don't input number 1 or 2. Please try again..." until we input correct number.
default : printf("\n Sorry! You don't input number 1 or 2. Please try again...\n\n");
break;
}
system("pause");
system("cls");
}while((i!=1)&&(i!=2)); // To check number: 1 or 2? If number 1, it will let us to calculate volume of Triangular Pyramide. If number 2, it will let us to calculate volume of Sphere. If different 1 or 2, it will show message " Sorry! You don't input number 1 or 2. Please try again..." until we input correct number.
return 0;
}
Video
Link to this video
http://youtu.be/InsDCpQoPvs
Thanks,
No comments:
Post a Comment