+ All Categories
Home > Documents > Esc101 l10

Esc101 l10

Date post: 27-Jul-2015
Category:
Upload: nakul-surana
View: 59 times
Download: 1 times
Share this document with a friend
Popular Tags:
25
1 Example Loops in C Lecture-10
Transcript

1

Example Loops in C

Lecture-10

2

For Loops

Lecture-10

3

Administrative matters

Long quiz in early September People who need mentoring, please send

a mail to: [email protected],

[email protected] and to me.

4

For statement in C General form

init_expr is the initialization expression. update_expr is the update expression. test_expr is the expression that evaluates to

either TRUE (non-zero) or FALSE (zero).

Execution:

for (init_expr; test_expr; update_expr) statement;

1. First evaluate init_expr;2. Evaluate test_expr;3. If test_expr is TRUE then

4. execute statement;5. execute update_expr;6. go to Step 2.

5

For loop in terms of while loop

Execution is (almost) equivalent to

Almost? Exception if there is a continue; inside statement– this will be covered later.

init_expr; while (test_expr) {

statement;update_expr;

}

for (init_expr; test_expr; update_expr) statement;

6

Enough definitions

Let’s do some examples. Print the sum of the reciprocals of the

first 100 natural numbers.

int i; /* counter: runs from 1..100 */float reciproc_sum = 0.0; /* sum of reciprocals */for (i=1; i<=100; i=i+1) { /* the for loop */

reciproc_sum = reciproc_sum + (1.0/i); }printf(“sum of reciprocals of 1 to 100 is %f “, reciproc_sum);

7

1. Evaluate init_expr; i.e., i=1;

2. Evaluate test_expr i.e., i<=4 TRUE

3. Enter body of loop and execute.

4. Execute update_expr; i=i+1; i is 2

5. Evaluate test_expr i<=4: TRUE

6. Enter body of loop and execute.

7. Execute i=i+1; i is 3

8. Evaluate test_expr i<=4: TRUE

#include <stdio.h> main() {int i; float reciproc_sum = 0.0;

for (i=1; i<=4; i=i+1) { reciproc_sum = reciproc_sum + (1.0/i); }printf(“sum of reciprocals of 1 to 4 is %f “, reciproc_sum); }

i

0.0

1.0

1

2

1.53

1.833333..4

2.0833333..5

sum of reciprocals of 1 to 4 is 2.083333 $

9. Enter body of loop and execute.

10. Execute i=i+1; i is 4

11. Evaluate test_expr i<=4: TRUE

12. Enter body of loop and execute.

13. Execute i=i+1; i is 5

14. Evaluate test_expr i<=4: FALSE

15. Exit loop jump to printf statement

8

Simple example Input is given in two lines.

The first line contains a single number m that specifies the number of integers that follow.

The second line contains m integers. Output the sum of the m numbers.

Strategy is simple:1. Read the first integer into m.2. Keep a variable say sum that is intended to store

the sum of all the numbers in the second line read so far. Initialize sum to 0.

3. Run a for loop, reading a new number and adding it to sum—this loop is set to run m times.

52 -1 15 3 6

Sample input

9

int m, i, sum, num; /* num stores the next integer, i is used as for loop counter, sum is the partial sum of numbers read. */scanf(“%d”, &m); /* read the length of seq. */sum=0;for (i=0; i < m; i = i+1) {/* for loop: to run m times */

scanf(“%d”, &num); /* read the next number */sum = sum+num; /* add to running sum */

}printf(“sum of given %d numbers is %d”,m, sum);

52 -1 15 3 6

Sample input

i

num

sum

m5

0

0

2

2

1

-1

1

2

15

16

3

3

6

19

4

25

5

sum of given 5 numbers is 25

Output(on one line)

10

Initializing multiple variables using

The program on right is equivalent to the original prog. (left). The expression for initialization is sum=0, i=0 It assigns to the variable sum the value 0 and then assigns to

the variable i the value 0.

int m, i, sum, num; scanf(“%d”, &m); sum=0;for (i=0; i < m; i = i+1) {

scanf(“%d”, &num);sum = sum+num;

}printf(“sum of given %d numbers is %d”,m, sum);

Earlier Program

int m, i, sum, num; scanf(“%d”, &m);

scanf(“%d”, &num);sum = sum+num;

}printf(“sum of given %d numbers is %d”,m, sum);

Equivalent Program

for(sum=0,i=0; i<m; i= i+1) {

14

Data Types in C -char

Lecture-10

15

Characters in C: char

C allows a few more basic types than int and float.

The char datatype is one byte (i.e., 8 bits) wide and can hold exactly one character, e.g.,

‘0’…’9’ ‘a’ … ‘z’ ‘A’ … ‘Z’ ‘?’ ‘@’ ‘#’ ‘$’ ‘^” ‘+’ ‘-’ ‘_’ ‘(‘ ‘)’ ‘=‘ and so

on.# include <stdio.h>main() { char ch; ch= ‘A’; printf(“%c\n”, ch);}

Output: A $

# include <stdio.h>main() { char ch =‘A’; printf(“%c\n”, ch);}

OR

Character constants are enclosed in single quotes, e.g., ‘A’ , ‘0’ …

16

The char data type

1. The value of a character constant is the integer value of that character in the machine’s character set, which is universally the ASCII set.

2. ASCII stands for the American Standard Code for Information Interchange. It is the standard mapping used by computers and devices today for characters.

What can we do with a variable of the char data type? 1. We can assign character constants ‘A’-’Z’ ‘0’-’9’ etc. to a variable of type char. What does this mean?

17

Table entries are in hexadecimal (base 16): 8 rows X 16 columns = 128 entries.

Base 16: the symbols are 0-9, A-F, where, A stands for 10, B for 11, C for 12, D for 13, E for 14 and F for 15.

hex number 7A equals in decimal 7*16 + 10 = 112.hex number 23 equals in decimal 2*16 + 3 = 35

18

The first 32 characters (rows 1 and 2) with ASCII code 0—31 correspond to special characters (functions) and are not printable.Code x20 (decimal 32) corresponds the space character.Code x21 (decimal 33) corresponds to the ‘!” character, etc.

19

1. Printable characters: ASCII codes 32 onwards till 126.

2. Upper case ‘A’ – ‘Z’ have consecutive ASCII codes 65—90.

3. Lower case ‘a’—’z’ have consecutive ASCII codes 97—122.

4. Digits ‘0’—’9’ have successive ASCII codes 48-57.

20

What do we (C Programmers)need this table for?

There are some ideas behind the design of the table that C uses. There is no need to memorize.

21

Character constants A character constant is an integer, namely the

ASCII code for that character. The following two code segments are equivalent, that is, ch gets the same value.

A character is printed as a character using the %c option in printf. scanf reads a character using %c option

Printing a character as an integer prints its ASCII code.

char ch;ch = ‘A’;

char ch;ch = 65;

char ch;ch = ‘A’;printf(“%c ”,ch); printf(“%d”, ch);

Output: A 65

22

Using arbitrary characters Any 8-bit character with hexadecimal

representation xhh can be specified as ‘\xhh’.

# include <stdio.h>main () {

char bellch, vtabch,ch;/* sounds a bell when printed */ bellch = ‘\x7’ ; /* prints vertical space when printed */

vtabch = ‘\xb’;/* hex 41=decimal 65: ASCII code for ‘A’ */

ch=‘\x41’; printf(“%c%c%c”,

bellch,vtabch,ch);}

$./a.out

A$

first a bell rang!then a tab wasprinted, followedby ‘A’

23

Escape Sequences in CEscape sequences refer to character constants with special

meaning. They start with a ‘\’ followed by a single character. For e.g., ‘\n’ refers to the newline character. It looks like two characters but represents only one.

Escape sequence

Meaning

\a Alert (bell)

\b Backspace

\f Formfeed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

Escape sequence

Meaning

\\ Backslash

\? Question mark

\’ Single Quote

\’’ Double Quote

\xhh hexadecimal number xhh

\ooo Octal number

\0 NULL character

24

Print the Alphabet The ASCII codes of upper case letters are

consecutive and in the English alphabet order. Same is true for lower case letters and digits.

E.g., to print upper case letters in alphabetic order:

main () { char ch; for (ch = ‘A’; ch <= ‘Z’; ch = ch +1) { printf(“%c”,ch); }}

ABCDEFGHIJKLMNOPQRSTUVWXYZ$Output

25

char ch; for (ch = ‘A’; ch <= ‘Z’; ch = ch +1) { printf(“%c”,ch); }

ABCDEFGHIJKLMNOPQRSTUVWXYZ$

Output

1.Characters are stored as 8 bit integers. 2.They can be assigned as integers, incremented, decremented etc., 3.Suppose ‘A’ has ASCII code 65. ch = ‘A’ sets ch to 65.4.ch = ch+1 sets ch to 66.5.printf(“%c”,ch) prints ch as a character, this prints ‘B’.

Relational operations <, >, >=, <= are defined on chars by comparing their integer representations (ASCII codes). So ‘A’ < ‘B’ since ‘A’ is represented

as 65 and ‘B’ as 66.

26

Uppercase Lowercase or digit

if (ch >= ‘A’ && ch <= ‘Z’) printf(“Upper case\n”);

Code snippet to check whether a char is in upper case

Code snippet to check whether a char is in lower case

if (ch >= ‘a’ && ch <= ‘z’) printf(“Lower case\n”);

Code snippet to check whether a char is a

digit

if (ch >= ‘0’ && ch <= ‘9’) printf(“Digit\n”);

27

if (ch >=‘a’ && ch <=‘z’) { ch = ch –’a’ + ‘A’ ;

}

if ch is a lower case letter of the English alphabet, then it converts it to upper case. Otherwise it does nothing

28

Scanning char versus int int number; char letter;

12

12

scanf(“%d”,&n);

scanf(“%c”,&letter)

0000 0000 0000 0000 0000 0000 0000 1100

32 bits= 4 bytes

0011 0001

8 bits= 1 bytechar ‘1’ = ASCII 49 = 31 in hexadecimal = 0011 0001 in binary

letter=‘1’

number=12

input


Recommended