Session 02
Control Statements & Storage Specifiers
1
Session Objectives • To learn about different types of Control Statements • To learn about different Storage Class Specifiers
2
Session Topics • Decision Structures – if statement, if-else statement, nested if statement • The switch statement • Repetition or Iteration structure - for statement, continue statement, nested loop, while loop • Storage class
3
Decision making and Branching • To change the order of execution based on certain conditions or repeat a group a statements until certain specified conditions are met. • Any expression can be used as a program statement by following the expression with a ‘;’ (semicolon). • ANSI C has the following categories of statements – – – – – –
Selection – if, switch Iteration – for, do, while Jump – continue, break, goto, return Label – case, default, (goto) label statement Expression – valid expression Block – { … } (also called compound statements) 4
C Control Structure Decision Compound Statements {...}
if - else
switch - case break
break
5
C Control Structure Looping • The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed. • The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once. • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.
6
C Control Structure Looping w hile
do-w hile
for
n - tim es
7
The if – else Statement • Structure
if (expression) statement_1 else statement_2
• The else part is optional • The expression is evaluated: if expression is TRUE (I.e. non zero) then statement_1. If expression is FALSE (i.e. zero) then statement_1 is executed if present. For multiple if’s, the else goes with the closest if without an else condition. 8
The if – else Statement- Examples #include <stdio.h> int main() { int b; printf("Enter a value:"); scanf("%d", &b); if (b < 0) printf("The value is negative\n"); else if (b == 0) printf("The value is zero\n"); else printf("The value is positive\n"); return 0; }
9
The switch-case Statement – Multiple branch selection statement – Tests the value of an expression against a list of integer or char constants – When a match is found, then statement associated with that constant is executed. – Structure switch (expression) { case I1: statements; case I2: statements; case I3: statements; case In: statements; default: statements; // optional } 10
The switch-case Statement contd… • Operation: the expression is evaluated; then execution continues at the statements following the case statement that matches the result or after the label default if there are no matches. If the default case does not exist, then execution continues after the last case statement. • Execution continues through remaining cases in the switch structure unless the break instruction is encountered. If a break is encountered, then execution continues after the present switchcase instance. 11
The while Statement • Structure while(expression) or
statement;
while(expression) { statement_1; statement_2; }
The while Statement Example while (a < b) { printf("%d\n", a); a = a + 1; }
* Operation: expression is evaluated and if TRUE then statement (or statement_1 and statement_2) is executed. The evaluation and executions sequence is repeated until the expression evaluates to be FALSE. If the expression is initially FALSE then statement is not executed at all. 12
Understanding a while loop b=1; While(b<2) { blah blah b=b+1; } blah blah
When the computer reaches while statement, it tests to see if the Boolean expression is true. If true, it jumps into the block of code immediately below the while statement.
13
Understanding a while loop b=1; While(b<2) { blah blah b=b+1; } blah blah
When the computer reaches last line in the while loop’s block of code, it jumps back up to the while statement. It re-tests the Boolean expression. If still true, it enters the block of code again.
14
Understanding a while loop b=1; While(b<2) { blah blah b=b+1; } blah blah
When the Boolean expression becomes false , the computer skips the while loop statement’s block of code and continues with the remainder of the program.
15
The do-while Statement • Structure do { statement; } while(expression);
• Operation: Similar to the while control except that statement is executed before the expression is evaluated. This guarantees that statement is always executed at least one time even if expression is FALSE. do { printf("%d\n", a); a = a + 1; } while (a < b);
16
The for Statement • Structure:
for(expr1; expr2; expr3) { statement; } • Operation: The for loop in C is simply a shorthand way of expressing a while statement: expr1; while(expr2) { statement; expr3 } • The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section). 17
Auxiliary Control Statements • Break – Causes the innermost control structure to be exited immediately. Execution continues with the statement immediately following the control structure just exited. • Continue – Causes immediate execution of the next loop to begin. • Goto - Rumour has it that the goto statement should be avoided because the program flow will jump all over the place, generating what's known as SPAGHETTI CODE! No harm in using it in the most simplest of programs though, but don't make a habit of using it!! • The goto keyword is followed by a label, which is basically some identifier placed elsewhere in the program - like a hyperlink the points to a place on the same web page. 18
Looping: A Real Example • Let's say that you would like to create a program that prints a Fahrenheit-to-Celsius conversion table. This is easily accomplished with a for loop or a while loop: #include <stdio.h> int main() {
}
int a; a = 0; while (a <= 100) { printf("%4d degrees F = %4d degrees C\n", a, (a - 32) * 5 / 9); a = a + 10; } return 0;
19
C Errors to Avoid • Putting = when you mean == in an if or while statement • Forgetting to increment the counter inside the while loop - If you forget to increment the counter, you get an infinite loop (the loop never ends). • Accidentally putting a ; at the end of a for loop or if statement so that the statement has no effect - For example: for (x=1; x<10; x++); printf("%d\n",x); only prints out one value because the semicolon after the for statement acts as the one line the for loop executes.
20
Storage Class Specifiers •
• • • •
C has four kinds of storage classes – Automatic – Register – Static – External Storage class is used to denote to the compiler where memory is to be allocated for variables Storage class tells, what will be the initial value of the variable, if the initial value is not specifically assigned.(i.e the default initial value). Storage class informs the compiler the scope of the variable.Scope refers to which functions the value of the variable would be available. Storage class informs the compiler the life of the variable. Life refers to how long would the variable exist.
21
Automatic Storage Class • All variables declared within a function are called local variables, by default belong to the automatic storage class.
Storage
Memory
Default Initial Value
Garbage Value
Scope
Local to the block in which the variable is defined
Life
Till the control remains within the block in which it is defined 22
Example for Automatic Storage Class main() { auto int i; printf(“%d \n %d \n”,i,j); }
Output 1211 876
23
Example for Automatic Storage Class Main()
Output:
{ auto int j=1;
3
{ auto int j=2; { auto int j=3;
2 1
printf(“%d\n”,j); } printf(“%d\n”,j); } printf(“%d\n”,j); }
24
Register Storage Class • Register storage class allocates memory in CPU’s high speed registers.
Storage
CPU Registers
Default Initial Value
Garbage Value
Scope
Local to the block in which the variable is defined
Life
Till the control remains within the block in which it is defined 25
Example for Register Storage Class main() { register int i; for(i=1;i<=10;i++) printf(“%d\n”,i); } Note: The register storage class cannot be used for all types of variables. Example:
register float q; register double s; register long r;
26
Static Storage Class • Static storage class informs the compiler that the value stored in the variables are available between function calls
Storage
Memory
Default Initial Value
Zero
Scope
Local to the block in which the variable is defined
Life
Value of the variable persists for different function calls
27
Example for Static Storage Class main()
main()
{
{
function(); function(); function();
function(); function(); function(); }
}
function()
function()
{
{
auto int i=1;
static int i=1;
printf(“%d\n”,i);
printf(“%d\n”,i); i=i+1; }
i=i+1;
Output 1
}
Output 1
2
1
3
1
28
External Storage Class • Variables declared outside functions have external storage class
Storage
Memory
Default Initial Value
Zero
Scope
Global
Life
As long as the program’s execution doesn’t come to an end
29
Example for External Storage Class increment()
int i;
{
main()
i=i+1; printf(“On incrementingi = %d\n”,i);
{ printf(“i=”,i);
} decrement()
increment();
{ i=i-1;
increment();
printf(“On incrementing
decrement();
i=%d\n”,i);
decrement(); }
}
Output: i=0 On incrementing i=1 On incrementing i=2 On decrementing i=1 On decrementing i=0
30
Summary • The different decision structure are if statement, if – else statement, multiple choice else if statement. • The while loop keeps repeating an action until an associated test returns false. • The do while loops is similar, but the test occurs after the loop body is executed. • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. • Storage class is used to denote to the compiler where memory is to be allocated for variables • C has four kinds of storage classes – Automatic – Register – Static – External 31
Thank You!
32