Sie sind auf Seite 1von 103

Introduction to C

Prof. Partha Saha


Integrated Programme in Management

CONTROL STATEMENT
Quick

Review

Arrays
Blocks and Compound Statements

Control Flow
Conditional Statements
If Statement

Switch Statements
Loops (While, for, do-while, break,
continue, exit())
2

QUICK
REVIEW

DEFINITIONS
Review
Variable -Name/reference to a stored value (usually in
memory)
Data Type -determines the size of a variable in memory,
what values it can take on, what operations are allowed
Operator -an operation performed using 1-3 variables
Expression -combination of literal values/variables and
operators/functions
4

DATA TYPES
Review
Various sizes (char, short, long, float, double)

Numeric types -signed/unsigned


Implementation -little or big endian
Careful mixing and converting (casting) types

OPERATORS
Review
Unary, binary, ternary (1-3 arguments)

Arithmetic Operators, Relational Operators, Binary


(bitwise and logical) Operators, Assignment Operators,
etc.
Conditional Expressions
Order of Evaluation (precedence, direction)
6

QUIZ-RI
1. long int variables hold bigger numbers, so why not
always use them instead of int variables?.

2. What happens if I assign a number with a decimal to an


integer?
3. What happens if I put a number into a type that isnt big
enough to hold it?
4. What happens if I put a negative number into an unsigned
variable?.
5. What are the practical differences between symbolic
constants created with the #define directive and those
created with the const keyword?

ANSWER-RI
1. A long int variable takes up more RAM than the smaller int.
Inefficient with Memory Space
2. The value assigned will have the decimal portion truncated.
3. Many compilers will allow this without signaling any
errors. The number is wrapped to fit and therefore wont be
correct. If you assign 32768 to a two-byte signed variable of
type short, it really contain the value -32768.
4. The compiler does the same wrapping as if you assigned a
number that was too big
8
5. The differences have to do with pointers and variable scope.

QUIZ-RII
1What effect do spaces and blank lines have on how a
program runs?

2. Is it better to code a compound if statement or to nest


multiple if statements?
3. What is the difference between unary and binary
operators?
4. Is the subtraction operator (-) binary or unary?.
5. Are negative numbers considered true or false?
9

ANSWER-RII
1. White space (lines, spaces, tabs) makes the code listing
more readable. No effect on the executable program.
2. Using a single compound statement, the expressions are
evaluated only until the entire statement evaluates to false.
3. unary operators work with one variable, and binary
operators work with two.

4. Its both! (x = -y; versus the binary use: x = a - b;)


5. Remember that 0 is false, and any other value is true. This
includes negative numbers..
10

ARRAYS

ARRAYS
Arrays:
An indexed group of data storage locations that have same name
Distinguished from each other by a subscript, or index (a
number following the variable name, enclosed in brackets)
An array declaration includes both the data type and the size
of the array (the number of elements in the array)

Index Number as an Offset:


int data[1000]; int index;
index = 100;
data[index] = 12; /* The same as data[100] = 12 */
Index number is as an Offset.
For the first item in the array, offset by nothing (or zero).
For the second item offset by one item so the index is one.

12

Pop Quiz (Do / Donts)

13

BLOCKS &
COMPOUND
STATEMENT

BLOCKS & COMPOUND STATEMENT


Expressions:
A simple statement ends in a semicolon: z = fn(x+y);

Multiple Statements:
temp = x+y;
z = fn(temp);

Curly Braces
Combine into compound statement/block.

15

BLOCKS
Blocks:
Block can substitute for simple statement

Compiled as a single unit


Variables can be Declared Inside
{
int temp = x+y;
z = foo(temp);
}
Block can be empty {}.
No semicolon at end
16

NESTED BLOCKS
Blocks nested inside each other
{
int temp = x+y;
z = fn(temp);
{
float temp2 = xy;
z += bar(temp2);
}
}
17

CONTROL
FLOW
CONDITIONAL
STATEMENTS
LOOPS

CONTROL CONDITIONS
in C99, bool type available (use stdbool.h)
Condition is an expression (or series of expressions)
e.g. n<3 or x<y || z<y
Expression is non-zero condition true

Expression must be numeric (or a pointer)


const char str[] = "some text" ;
if (str) / string is not null /
return 0;
19

The if statement
The switch
statement

The if Statement

if (x% 2 ==) y += x/2;


Evaluate condition
if (x %2==0)
If true, evaluate inner statement
y += x/2;

Otherwise, do nothing

21

The else keyword


if (x%2 == 0) y += x/2;
else
y += (x+1)/2;
Optional
Execute statement if condition is false

y += (x+1)/2;
Either inner statement may be block
22

The else if keyword


if (x%2 == 0)
y += x/2;
else if (x%4 == 1)
y+= 2 ((x+3)/4);
else
y += (x+1)/2;

Additional alternative control paths


Conditions evaluated in order until one is met;
inner statement then executed
If multiple conditions true, only first executed
Equivalent to nested if statements

23

Nesting if statements

if (x%4 == 0)
if (x%2 == 0)
y= 2;
else
y= 1;
To which if statement does the else keyword belong?

24

Nesting if statements

To associate else with outer if statement:


use braces
if (x%4 == 0)
{
if (x%2 == 0) y= 2;
} else y= 1;

25

The Loop statement


The for loop

The While loop


The do-while loop
The break and
Continue keywords

for Loop

The for loop


C programming construct that executes a block of one or
more statements a certain number of times.
It is called the for loop because program execution typically
loops through the statement more than once.
A for statement has the following structure:
for ( initial; condition; increment )
statement;
Initial, condition, and increment are all C expressions, and
statement is a single or compound C statement.
28

The for loop : Schematic Representation

1. The expression initial is evaluated. (Initial is usually an assignment statement


that sets a variable to a particular value.)
2. The expression condition is evaluated. (Condition is typically a relational
expression).
3. If condition evaluates to false (that is, it is equal to zero), the for statement
terminates and execution passes to the first statement following statement.
4. If condition evaluates to true (that is, it is equal to a nonzero value), the C
statement( s) in statement are executed.
29
5. The expression increment is evaluated, and execution returns to step 2.

The for loop


int factorial ( int n) {
int i, j=1;
for (i =1; i<= n; i++)
j = i; return j;
}
The counting loop
Inside parentheses, three expressions, separated by
semicolons:

Initialization: i=1
Condition: i <= n
Increment: i++
30
Expressions can be empty (condition assumed to be true)

The for loop


Equivalent to while loop:
int factorial ( int n)
{
int j =1; int i=1;
/ initialization /
while (i <= n/ condition /) {
j = i;
i ++; / increment /
}
return j;
}
31

The for loop


Compound expressions separated by commas
int factorial ( int n) {
int i, j;
for (i =1, j=1; i<= n; j = i , i++)
;
return j;
}
Comma: operator with lowest precedence,
evaluated left-to-right;
Not same as between function arguments
32

A simple for statement (forstate.c)


1:
2:
3:
4:
5:
6:
7:
8:

/* Demonstrates a simple for statement */


#include <stdio.h>

int count;
int main( void )
{

9:
10:
11:
12:
13:
14:
15:

/* Print the numbers 1 through 20 */


for (count = 1; count <= 20; count++)
printf(%d\n, count);
return 0;
}
33

Operation of for loop (forstate.c)

34

Output (forstate.c)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

35

COMMA Operator
Cs comma operator is most often used in for statements
Expression by separating two sub-expressions with comma operator.
Two sub-expressions are evaluated (in left-to-right order).
The entire expression evaluates to the value of the right sub-expression
By using the comma operator, you can make each part of a for statement
perform multiple duties
Two 1,000-element arrays, a[] and b[].
Program to copy the contents of a[] to b[] in reverse order:

for (i = 0, j = 999; i < 1000; i++, j--) b[j] = a[i];


The comma operator is used to initialize two variables, i and j.
It is also used to increment part of these two variables with
each loop
36

Three for loop Examples

37

Nested for loop Example

38

Nested for loop Output

39

Pop Quiz (Do / Donts)

40

while Loop

The while loop


while (/ condition /)
Statement
Simplest loop structure evaluate body as long as
condition is true
1. The expression condition is evaluated.
2. If condition evaluates to false (that is, zero), the while
statement terminates, and execution passes to the first
statement following statement.

3. If condition evaluates to true (that is, nonzero), the C


statement(s) in statement are executed.
42

4. Execution returns to step 1.

Operation of a While Loop

43

A simple while statement (whilest.c)


1: /* Demonstrates a simple while statement */
2:
3:
#include <stdio.h>
4:
5:
int count;
6:
7:
int main( void )
8:
{
9:
/* Print the numbers 1 through 20 */
10:
11:
count = 1;
12:
13:
while (count <= 20)
14:
{
15:
printf(%d\n, count);
16:
count++;
17:
}
18:
return 0;
19:
}

44

Output (whilest.c)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

45

Three while loop Examples

46

Nested while loop Example

47

Nested while loop (Output)

48

Pop Quiz (Do / Donts)

49

do while Loop

The do while loop


do
statement
while (condition);
condition is any C expression, and statement is a single
or compound C statement.
When program execution reaches a do...while statement,
the following events occur:
1. The statements in statement are executed.
2. Condition is evaluated. If its true, execution returns to
step 1. If its false, the loop terminates.
51

Operation of a Do While Loop

Statements associated with do...while loop always executed at least once.


Test condition is evaluated at the end, instead of the beginning, of loop.
In contrast, for and while loops evaluate the test condition at the start of
the loop,
Associated statements are not executed, if test condition is initially false.
52

The do-while loop


char c; do {
/ loop body /
puts ( "Keep going? (y/n) " );
c = getchar ( ) ;
/ other processing /
} while (c == y && / other conditions / );
Differs from while loop Condition evaluated
after each Iteration
Body executed at least once
Note Semicolon at End
53

A Simple do while loop

54

Input Output
1 - Add a Record
2 - Change a record
3 - Delete a record
4 - Quit
Enter a selection: 8
1 - Add a Record
2 - Change a record
3 - Delete a record
4 - Quit
Enter a selection: 4
You chose Menu Option 4

55

Three do while loop Examples

56

Pop Quiz (Do / Donts)

57

Pop Quiz (Do / Donts)

58

QUIZ-I
1. What is the index value of the first element in an array?
2. What is the difference between a for statement and a
while statement?

3. What is the difference between a while statement and a


do...while statement.
4. Is it true that a while statement can be used and still get
the same results as coding a for statement

59

ANSWER-I
1. The first index value of an array in C is 0.
2. A for statement contains initializing and increment
expressions as parts of the command.

3. A do...while contains the while statement at the end and


always executes the loop at least once.
4. Yes, a while statement can accomplish the same task as a
for statement, but you need to do two additional things. You
must initialize any variables before starting the while
command, and you need to increment any variables as a
part of the while loop..
60

QUIZ-II
5. What must you remember when nesting statements?
6. Can a while statement be nested in a do...while
statement?

7. What are the four parts of a for statement?


8. What are the two parts of a while statement?
9. What are the two parts of a do...while statement?

61

ANSWER-II
5. You cant overlap the loops. The nested loop must be
entirely inside the outer loop.

6. Yes, a while statement can be nested in a do...while loop.


You can nest any command within any other command.
7. The four parts of a for statement are the initializer, the
condition, the increment, and the statement(s).
8. The two parts of a while statement are the condition and
the statement(s).
9. The two parts of a do...while statement are the condition
and the statement(s).
62

QUIZ -III
1. Write a declaration for an array that will hold 50 type long
values.
2. Show a statement that assigns the value of 123.456 to the 50th
element in the array .
3. What is the value of x when the following statement is
complete?
for (x = 0; x < 100, x++) ;
4. What is the value of ctr when the following statement is
complete?
for (ctr = 2; ctr < 10; ctr += 3) ;
5. How many Xs does the following print?
for (x = 0; x < 10; x++)
for (y = 5; y > 0; y--)
puts(X);
63

ANSWER-III
1. long array[50];
2. Notice that in the following answer, the 50th element is
indexed to 49. Remember that arrays start at 0.
array[49] = 123.456;

3. When the statement is complete, x equals 100.


4. When the statement is complete, ctr equals 11. (ctr starts
at 2 and is incremented by 3 while it is less than 10.)
5. The inner loop prints five Xs. The outer loop prints the
inner loop 10 times. This totals 50 Xs.).
64

QUIZ -IV
6. Write a for statement to count from 1 to 100 by 3s.

7. Write a while statement to count from 1 to 100 by 3s.

8. Write a do...while statement to count from 1 to 100 by 3s.

65

ANSWER-IV
6. The code is as follows:
int x;
for( x = 1; x <= 100; x += 3) ;
7. The code is as follows:
int x = 1;
while( x <= 100 )
x += 3;

8. The code is as follows:


int ctr = 1;
do
{ ctr += 3;
} while( ctr < 100 );

66

QUIZ -V
9. BUG BUSTER: What is wrong with the following code
fragment?
record = 0;
while (record < 100) {
printf( \nRecord %d , record );
printf( \nGetting next number... );
}

10. BUG BUSTER: What is wrong with the following code


fragment? (MAXVALUES is not the problem!)
for (counter = 1; counter < MAXVALUES; counter++);
printf(\nCounter = %d, counter );
67

ANSWER- V
6. This program never ends. record is initialized to 0. The
while loop then checks to see whether record is less than
100. 0 is less than 100, so the loop executes, thus printing
the two statements. The loop then checks the condition
again. 0 is still, and always will be, less than 100, so the
loop continues. Within the brackerecord needs to be
incremented. You should add the following line after the
second printf() function call:
record++;
10. The semicolon doesnt belong at the end of the for
statement. This is a common bug.

68

INTRODUCTION TO C
Break
Continue
Infinite Loops

goto Statement
Switch Statement
Exit Statement

Execute functions automatically upon


program completion
Execute System Command
69

Exiting Loop
Early :
break
& continue

Break and Continue

71

The break keyword

Sometimes want to terminate a loop early


break: exits innermost loop/ switch statement
to exit early
Consider the modification of the do-while example:
char c;
do { / loop body /
puts ( "Keep going? (y/n) " );
c = getchar ( ) ;
if (c != y)
break ;
/ other processing /
72
} while (/ other conditions / );

The break keyword


Sometimes want to terminate a loop early
The break statement can be placed only in the body
of a for loop, while loop, do...while loop and switch
statement, too.
When a break statement is encountered, execution
immediately exits the loop.
for ( count = 0; count < 10; count++ )
{ if ( count == 5 )
break; }
Left to itself, the for loop would execute 10 times.
On the sixth iteration, however, count is equal to 5, and the
break statement executes, causing the for loop to terminate
73

The break keyword


breaking.c. Using the break statement
1:
/* Demonstrates the break statement. */
2:
#include <stdio.h>
3: char s[] = This is a test string. It contains two sentences.;
4:
int main( void )
5:
{
6:
int count;
7:
printf(\nOriginal string: %s, s);
8:
for (count = 0; s[count]!=\0; count++)
9:
{
10:
if (s[count] == .)
11:
{
12:
s[count+1] = \0;
13:
break;
14:
}
15:
}
16:
printf(\nModified string: %s\n, s);
17:
return 0;
18:
}

74

The Output
Original string: This is a test string. It contains two
sentences.
Modified string: This is a test string.

75

The break

76

The continue keyword


Like the break statement, the continue statement can be
placed only in the body of a for loop, a while loop, or a
do...while loop.

When a continue statement executes, the next iteration of the


enclosing loop begins immediately.
The statements between the continue statement and the end
of the loop arent executed

77

The continue keyword


Use to skip an iteration
continue; skips rest of innermost loop body,
jumping to loop condition
Example: #define min(a,b) ((a) < (b) ? (a) : (b))
int gcd ( int a, int b) {
int i , ret = 1, minval = min(a,b);
for (i = 2; i <= minval; i++) {
if (a%i) / i not divisor of a /
continue ;
if (b%i == 0) / i is divisor of both a and b /
ret = i; }
return ret ; }

78

The continue statement

79

The continue statement (output)

Enter a line of text:


This is a line of text
Ths s ln f txt

80

The continue statement

81

The goto keyword


The goto statement is one of Cs unconditional
jump, or branching, statements.
When program execution reaches a goto statement,
execution immediately jumps, or branches,
to the location specified by the goto statement.
This statement is unconditional because
execution always branches when a goto statement is
encountered; the branch doesnt depend on any
program conditions (unlike if statements)
The target of a goto statement is identified by a text label
followed by a colon at the start of a line
82

The goto statement

83

The goto statement (Output)

84

Switch ()

Cs most flexible program control statement.


If/ else-if, limited to evaluating an expression that
could have only two values (True/ False)
Switch() execute different statements based on an
expression that can have more than two values.
The general form of switch statement is as follows:
switch (expression)
{
case template_1: statement(s);
case template_2: statement(s);
...
case template_n: statement(s);
default: statement(s);
}

85

Switch ()
Switch (expression) is any expression that evaluates
to an integer value: type long, int, or char.
The switch statement evaluates expression and
compares the value against the templates following
each case label.
Then one of the following happens switch (expression)

If a match is found between expression and one of the templates, execution


is transferred to the statement that follows the case label.
If no match is found, execution is transferred to the statement following
the optional default label.
If no match is found and no default label exists, execution passes to the
first statement following the switch statements closing brace.
86

The switch statement


Alternative conditional statement
Integer (or character) variable as input
Considers cases for value of variable
switch (ch) {
case Y :/ ch == Y /
/ do something /
break ;
case N :/ ch == N /
/ do something else /
break ;
default :/ otherwise /
/ do a third thing /
break ; }

87

Multiple cases
Compares variable to each case in order
When match found, starts executing inner code until
break; reached
Execution falls through if break; not included

88

The switch statement


Contents of switch statement a block

Case labels: different entry points into block

Similar to labels used with goto keyword

89

First Switch () Code


1:
/* Demonstrates the switch statement. */
2:
#include <stdio.h>
3:
int main( void ) {
4:
int reply;
5:
puts(Enter a number between 1 and 5:);
6:
scanf(%d, &reply);
7:
switch (reply) {
8:
case 0:
9:
break;
10:
case 1:
11:
puts(You entered 1.);
12:
case 2:
13:
puts(You entered 2.);
14:
case 3:
15:
puts(You entered 3.);
16:
case 4:
17:
puts(You entered 4.);
18:
case 5:
19:
puts(You entered 5.);
20:
default:
21:
puts(Out of range, try again.);
20return 0;

90

Output ()
Enter a number between 1 and 5:
1
You entered 1.
Enter a number between 1 and 5:
6
Out of range, try again.
91

Second Switch () Code

92

Output ()
Enter a value between 1 and 10, 0 to exit:
11
Between 1 and 10, please!
Enter a value between 1 and 10, 0 to exit:
1
You entered 5 or less.
Enter a value between 1 and 10, 0 to exit:
6
You entered 6 or more.
Enter a value between 1 and 10, 0 to exit:
0

93

Pop Quiz (Do / Donts)

94

Exit ()
The exit() function terminates program execution
and returns control to the operating system.
This function takes a single type int argument that
is passed back to the operating system to indicate the
programs success or failure.
The syntax of the exit() function is
exit(status);
If status has a value of 0, it indicates that the
program terminated normally.
A value of 1 indicates that the program terminated
with some sort of error
95

Exit ()
To use the exit() function, a program must include
the header file stdlib.h.
This header file also defines two symbolic constants
for use as arguments to the exit() function:
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
Thus, to exit with a return value of 0, call
exit(EXIT_SUCCESS);
for a return value of 1,
call exit(EXIT_FAILURE).

96

Pop Quiz (Do / Donts)

97

QUIZ-I
1. When is it advisable to use the goto statement
in your programs?
2. Whats the difference between the break
statement and the continue statement?
3. What is an infinite loop, and how do you create
one?
4. What two events cause program execution to
terminate?
98

ANSWER-I
1. Never.

2. When a break statement is encountered, execution


immediately exits the for, do...while, or while loop that
contains the break. When a continue statement is encountered,
the next iteration of the enclosing loop begins immediately.
3. An infinite loop executes forever. You create one by writing
a for, do...while, or while loop with a test condition that is
always true.
4. Execution terminates when the program reaches the end of
main() or the exit() function is called.
99

QUIZ-II
5. To what variable types can a switch evaluate?
6.What does the default statement do?

7. What does the exit() function do?


8. What does the system() function do?

100

ANSWER-II
5. The expression in a switch statement can evaluate to a long,
int, or char value.
6. The default statement is a case in a switch statement. When
the expression in the switch statement evaluates to a value that
doesnt have a matching case, control goes to the default case.
7. The exit() function causes the program to end. A value can
be passed to the exit() function. This value is returned to the
operating system.
8. The system() function executes a command at the operating
system level.
101

SUMMARY
Topics covered:
Controlling program flow using conditional

statements and loops

Dividing a complex program into many simpler subprograms using functions and modular programming
techniques
Variable scope rules and extern, static, and register
variables
102

Thank You!

Das könnte Ihnen auch gefallen