66
PSK, NSN, DK, TAG – CS&E, IIT M 1 CS1100 Computational Engineering Tutors: Shailesh Vaya Anurag Mittal [email protected] [email protected]

cs1100Lec08-11

Embed Size (px)

Citation preview

Page 1: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 1

CS1100Computational Engineering

Tutors:

Shailesh Vaya Anurag [email protected] [email protected]

Page 2: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 2

Data, Types, Sizes,Values• int, char, float, double

• char – single byte, capable of holding one character

• Integer Qualifiers – short and long

• short int – 16 bits, long int – 32 bits

• Compiler dependent, based on the underlying hardware – int is at least 16 bits, short is at least 16 bits, long is at least 32 bits, and int is no larger than long, and at least as long as short

Page 3: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 3

char, signed and unsigned• Qualifier signed or unsigned can be applied to

int or char

• Unsigned numbers are non-negative

• Signed char holds numbers between –128 and 127. Whether char is signed or unsigned depends on the system. Find out on your system. Print integers between 0 to 255 as characters, and integers between –128 to 127 on your system.

Page 4: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 4

Number Systems• Decimal (base 10 – uses 10 symbols {0..9})

– 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 …

• Unary (base 1)– 1, 11, 111, 1111, 11111 …

• Binary (base 2) – uses 2 symbols {0,1})– 0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010 …

• Octal (base 8 – start with a 0 in C)– 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13…– 00, 01, 02, 03, 04, 05, 06 … C treats them as octal

• Hexadecimal(base 16 – start with 0x;uses A-F for 10-15)– 0, 1, …, 9, A, B, C, D, E, F, 10, 11, … 19, 1A, 1B, …

Page 5: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 5

Quick Primer on Binary• Number representation in base n

– Take every bit and assign weights in increasing powers of n

– For binary representation, the weight is 2

• You can represent 2m unique values using m bits

329102 101 100

10122 21 20

3x100 + 2x10 + 9x1 = 329 1x4 + 0x2 + 1x1 = 5

mostsignificant

leastsignificant

Page 6: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 6

The internal representation of binary, octal, and hexadecimal numbers is similar

Binary, Octal and Hexadecimal

Binary - 010111011010101110000110

Octal - 2 7 3 2 5 6 0 6

Hexadecimal - 5 13 10 11 8 65 D A B 8 6

Converting back and forth between binary, octal and hexadecimal is very easy

Page 7: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 7

m-bits and 2m Unique Numbers• You could technically map a m-bit sequence to

any value– Practically useless though

• Two useful mappings (with m = 3)

000001

010

011100

101

110

111

01

2

3

4

5

6

7000

001

010

011100

101

110

111

01

2

3

-4

-3

-2

-1

Unsigned Signed

Page 8: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 8

Unsigned and Signed Forms

• Both have the same internal representation (blue)• They have different external representations (red)• What is peculiar about the bit patterns of +ve numbers

in unsigned form?

000001

010

011100

101

110

1111

2

3

4

5

6

7000

001

010

011100

101

110

1111

2

3

-4

-3

-2

-1

Unsigned Signed

0 0

Page 9: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 9

A funny infinite loop - arithmeticThis program of mine, ran into an infinite loop. I only

wanted to find which numbers corresponded to which characters, the significance of signed and unsigned characters, basically relationship between which integers can be printed as characters we recognize. Why did the infinite loop happen, how to avoid it?

#include<stdio.h>main(){char c; for(c=-128; c <= 127; c++) printf(“%d -- %c \n”, c, c);}

Print it as a decimal number

Print it as a character

Try omitting one parameter…

Page 10: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 10

Float and Double• Two types, one for single-precision arithmetic,

and the other for double precision arithmetic

• Long double is used for extended-precision arithmetic.

• The size of floating pointing objects are implementation defined.

Page 11: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 11

Variable Initialization• Variables may be initialized either at the time of

declaration, for example, #define MAXLINE 200 char esc = ‘\\’; int i =0; int limit = MAXLINE + 1; float eps = 1.0e-5

• Or they may be assigned values by assignment statements in the program

• Otherwise they contain some random values

Page 12: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 12

Constants • At run time, each variable holds a value, which

changes from time to time• Constant has a value that does not change1234 is of type int123456789L is a long constant123456789ul is an unsigned long constant123.4 is a floating point constant, so is 1e-2 which

denotes .01. Their type is double. If suffixed by an f, or by l, the type is float or long double,

respectively

Page 13: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 13

Character Constants …• …are integers, written as one character within

single quotes. Example – ‘a’, ‘x’, ‘1’, ‘2’ etc.• The value of a character constant is the numeric

value of the character in the machine’s character set. For example, ‘1’ has the value 49 in the ASCII character set. That is, number 49, interpreted as a character code stands for ‘1’

• Character constants can participate in arithmetic. What does ‘1’+’2’ hold? (not ‘3’!) Understand this distinction. Character arithmetic is used mainly for comparisons.

Page 14: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 14

ASCII Table

Page 15: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 15

Characters – escape sequences

\a alert (bell) \\ backslash

\b backspace \? question mark

\f formfeed \’ single quote

\n newline \” double quote

\r carriage return \ooo octal number

Ex: \101 is 'A'

\t horizontal tab \xhh hexadecimal

\v vertical tab Ex: 41 is 'A'

Non-printable characters

Page 16: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 16

More ConstantsConstant numbers, Constant characters, and now

Constant Expressions – Expressions all of whose operands are constants. These can be evaluated at compile time. Examples:

#define NUM_ROWS 100

#define NUM_COLS 100

#define NUM_ELTS NUM_ROWS * NUM_COLS

#define is preprocessor directive. Recall: #include

Page 17: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 17

Enumerated Constants• enum boolean {No, Yes}

– defines two constants No = 0, and Yes = 1.

• enum months {jan = 1, feb, march, april, may, jun, jul, aug, sep, oct, nov, dec}– when a value is explicitly specified (jan=1) then it

starts counting from there

• enum escapes {BELL = ‘\a’, BACKSPACE = ‘\b’, TAB = ‘\t’, NEWLINE =‘\n’}– more than one constant can be specified explicitly

By default enum values begin with 0

Page 18: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 18

Enum and #define• Better than #define, the constant values are

generated for us. • Values from 0 on wards unless specified

• Not all values need to be specified

• If some values are not specified, they are obtained by increments from the last specified value

• Variables of enum type may be declared, but the compilers need not check that what you store is a valid value for enumeration

Page 19: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 19

Declaring ConstantsThe qualifier const applied to a declaration

specifies that the value will not be changed. const int J = 25; /* J is a constant through out the

program */Response to modifying J depends on the system.

Typically, a warning message is issued while compilation.

const char MESG[] = “how are you?”;The character array MESG is declared as a

constant which will store “how are you?”

Page 20: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 20

Constants cannot change values

const numStudents = 180;

numStudents = numStudents + 1; /* Incorrect */

const numGirls = 40;

const numBoys = 40;

const numStudents = numGirls + numBoys;

Page 21: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 21

CS1100 Lecture 9

Tutors:

Shailesh Vaya Anurag [email protected] [email protected]

Page 22: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 22

StringsA string is a array of characters terminated by the

null character, ‘\0’.A string is written in double quotes.Example: “This is a string”.‘This is rejected by the C Compiler’Anything within single quotes gets a number

associated with it“” – empty stringExercise: understand the difference between ‘x’

and “x”.

Page 23: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 23

32 bit numbersInternally: 4,294,967,296 (232) different

permutations that 32 bits can represent

Signed 32 bit integers vary from-2,147,483,648 to 2,147,483,647

-231 to 231-1

Unsigned 32 bit integers vary from

0 to 4,294,967,2950 to 232-1

Page 24: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 24

Recall Signed/Unsigned

• m bit internal representation – am-1

am-2

... a2a

1a

0

• Signed Interpretation = -[2(m-1)*a

m-1]+2(m-2)*a

m-2+...+2(2)*a

2+2(1)*a

1+2(0)*a

0

• Unsigned Interpretation = 2(m-1)*am-1

+2(m-2)*am-

2+...+2(2)*a

2+2(1)*a

1+2(0)*a

0

000001

010

011

100

101

110

111

1

2

3

4

5

6

7000

001

010

011

100

101

110

111

1

2

3

-4

-3

-2

-1

Unsigned Signed

0 0

Page 25: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 25

Overflow in integers…#include <stdio.h> int main() { int i = 2147483647; unsigned int j = 4294967295; printf("%d %d %d\n", i, i+1, i+2); printf("%u %u %u\n", j, j+1, j+2); }

Here is the result for some system: 2147483647 -2147483648 -2147483647 4294967295 0 1

Page 26: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 26

Printing directives#include <stdio.h> int main() { unsigned int un = 3000000000;

/* system with 32-bit int */ printf("un = %u and not %d\n", un, un); return 0; }

un = 3000000000 and not -1294967296

Both have the same internal representationBoth have the same internal representation

Page 27: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 27

Printing directives#include <stdio.h> int main() { short end = 200; /* and 16-bit short

*/ printf("end = %hd and %d\n", end, end); return 0; }

end = 200 and 200

short decimal

Printing a short decimal as a normal int is okay

Page 28: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 28

Printing directives#include <stdio.h> int main() { long big = 65537; printf("big = %ld and not %hd\n", big,

big); return 0; }big = 65537 and not 1

When the value 65537 is written in binary format as a 32-bit number, it looks like 00000000000000010000000000000001. Using the %hd specifier persuaded printf() to look at just the last 16 bits; therefore, it displayed the value as 1.

Page 29: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 29

Printing directives#include <stdio.h> int main() { long long verybig = 12345678908642; printf("verybig= %lld and not %ld\n",

verybig, verybig); return 0; }

verybig= 12345678908642 and not 1942899938

64 bits Truncated 32 bitsTruncated 32 bits

Page 30: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 30

Assignment and Arithmetic Rules• Basic data types, numbers and characters can be

assigned to their corresponding variables.

Example: char c = ‘a’; char no = ‘1’; int j = 25;

Arrays can be initialised when declared:

char mesg[] = “hello”; is a valid declaration

int numbers[5] = {0,1,2,3,4}; is a valid declaration

But an assignment to an array in the program is a syntax error.

Page 31: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 31

Functions to handle stringsString is a non-basic data type

– Constructed data type– require functions to handle– regular datatypes have operators in C directly

• Typical functions on strings are:– Length of a string– Are two strings equal?– Does a given pattern occur as a substring?– Concatenate two strings and return the result

These are exercises to gain programming knowledge. But use standard functions provided with string.h

Page 32: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 32

Recap• Variables

• Assignments

• relational operators (comparisons)

• Selection and repetition constructs: control structures

• Data types and their limitations

• Arrays – arrayname[n], single dimensional arrayArrayname[m][n] – 2D array, arrayname[i][j] gives the

element in the i-th row and j-th coloumn

Page 33: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 33

Logical Operators• Recall relational operators {<=, <, >, >=} to compare values

• && and || • Called boolean and, boolean or

• Expressions involving these as operations take boolean values, and their operands also take boolean values.

• Called truth values also.

• E1 && E2 is true if and only if both E1 and E2 are true

• E1 || E2 is true if and only if either E1 or E2 or both are

• Precedence of && is higher than ||, and both are lower than relational or equality operators

Page 34: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 34

How to use these in a program• They are used when composite conditions are to

be tested in decision statements.for(i=0; i < lim – 1 && (c = getchar()) != ‘\n’ && c !=EOF; i++)

s[i] = c;

• The loop is executed as long as all the test conditions are true

• The loop is exited when any test condition becomes false

• For example when an <Enter> is read from keyboard

Page 35: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 35

Exercise• Write a program which will exit when a certain

number of occurences of any keystroke is read.• You need arrays

• Loops

• Loops with logical operations and so on.

Page 36: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 36

Operators• Increment operator : effect is to increment value of a

variable• x = j++ // x gets the value of j, and then j is incremented

• x = ++j // j is incremented first, then assigned to x

• Decrement operators – decrements values• x = j-- //x gets the value of j, then j is decremented by 1

• x = --j //j is first decremented, and then assigned to x

• Assignment operator short cut• E1 op= E2 is equivalent to the assignment E1 = E1 op E2

• x -= 5; same as: x = x - 5;

• Once you learn it, your code is concise

• Matter of taste

Page 37: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 37

CS110 Lecture 10

Tutors:

Shailesh Vaya Anurag [email protected] [email protected]

Page 38: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 38

Functions = outsourcing• Break large computing tasks into small ones• Helps you to build on what others have done

• You and others write functions• When you want to build a program, find out how to use

the function and use it.

• Use standard functions provided by the library.• You are hidden from the implementation• Example – you don’t have to worry about how pow(m,n)

is implemented

• As engineers from different disciplines you will use and develop different set of functions

Page 39: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 39

Modular ProgrammingSubprograms

functions in C, C++, procedures and functions in Pascal

facilitate modular programmingOverall task is divided into modules

Each module - a collection of subprograms

a subprogram may be invoked at several pointsA commonly used computation

hiding the implementation

incorporating changes easier

Page 40: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 40

Example of function sets• String manipulation

• Mathematical

• Finite Element Method • Used in structural analysis by Mechanical, Civil, Aero,

etc. for stress calculations etc.

• Most function libraries cost a lot• Business opportunity – identify functions that are useful

to your area of study, create libraries.

• Functions for use in different software. • Say, functions for web services

Page 41: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 41

Power Function#include <stdio.h>int power (int, int);main () {for ( int i = 0; i < 20; i ++ )

printf(“%d %d %d\n”, i, power(3,i), power(-4,i);}int power (int base, int n) {

int i, p = 1;for ( i = 1; i <= n ; i ++)

p = p base;return p;

}

-- Computes the nth

power of base.

function prototype

Invocation with argumentsA block

Page 42: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 42

Recursive Function Exampleint power (int num, int exp) {

int p;if (exp = = 1) return num;p = power(num, exp/2);if (exp % 2 = = 0) return p*p;else return p*p*num; }

The base case exp = 1

Guarantees termination

36*36*3 = 729*729*3 = 1594323 33*33 = 27*27 = 729

31*31*3 = 27 = 3

power (3, 13) power (3, 6)

power(3,3) power(3,1)

Page 43: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 43

Factorial (n)• n! = 1 * 2 * 3 * .... * (n-2) * (n-1) * n

Iterative version

int fact(int n) {    int i;    int result;       result = 1;    for (i = 1; i <= n; i++)

      result = result * i;       return result; }

In practice int may not be enough!

Page 44: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 44

Factorial(n) – recursive program

n! = n(n-1)!

int fact(int n) {     if (n == 1) return(1);     return(n * fact(n - 1)); }

• Shorter, simpler to understand• Uses fewer variables• Machine has to do more work running this one!

Page 45: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 45

Basics• Function is a part of your program.

• It cannot be a part of any other function• main() is a function: it is the main function. Execution starts there or

the control flow starts there• From there it can flow from one function to another, return after a

computation with some values, probably, and then flow on.

• Transfer of control is affected by calling a function• With a function call, we pass some parameters• These parameters are used within the function• A value is computed • The value is returned to the function which initiated the call• The calling function can ignore the value returned• It could use it in some other computation• A function could call itself, these are called recursive function calls

Page 46: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 46

Add functions to your Program• A program was a set of variables, and

assignments to variables

• Now add function to it.• Set of variables

• Some functions including main()

• Communicating values to each other

• Computing and returning values for each other

• Instead of one long program, we now write structured program composed of functions

Page 47: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 47

Features• C program -- a collection of functions

– function main ( ) - mandatory - program starts here.

• C is not a block structured language– a function can not be defined inside another function– only variables can be defined in functions / blocks

• Variables can be defined outside of all functions– global variables - accessible to all functions– a means of sharing data between functions - caution

• Recursion is possible– a function can call itself - directly or indirectly

Page 48: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 48

Function template

Return-type function-name(argument declarations)

{

declaration and statements

return expression;

}

Page 49: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 49

Function Definition in Creturn-type function-name (argument declarations){ variable/constant declarations and

statements }

Arguments or parameters:the means of giving input to the function

type and name of arguments are declarednames are formal - local to the function

Return Value: for giving the output valuereturn ( expression ); -- optional

Invoking a function: funct-name(param1,param2,…,paramn)

Matching the number and type of arguments

No function declarations here!

Page 50: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 50

Function Prototype• defines

– the number of parameters, type of each parameter,– type of the return value of a function

• used by the compiler to check the usage– prevents execution-time errors

• function prototype of power function– int power ( int, int ); – no need for naming the parameters

• function prototypes - given in the beginning

Page 51: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 51

More on Functions• To write a program

• You could create one file with all the functions

• You could/are encouraged to identify the different modules and write the functions for each module in a different file

• Each module will have a separate associated header file with the variable declaration global to that module

• You could compile each module separately and a .o file will be created

• You can then cc the differnet .o files and get an a.out file

• This helps you to debug each module separately

Page 52: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 52

Running with less memory• Functions

• Provided to break up our problem into more basic units

• Control flow – flows from function to function, saving the current context, changing contexts, then returning…..

• Helps the program to run with lesser memory, but slightly slower than a monolithic program without functions

• The issue now with data associated with other functions.

• Typically functions communicate using the arguments and return values

Page 53: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 53

Call by ValueIn C, function arguments are passed “by value”

– values of the arguments given to the called function in temporary variables rather than the originals

– the modifications to the parameter variables do not affect the variables in the calling function

“Call by reference”– variables are passed by reference

• subject to modification by the function

– achieved by passing the “address of” variables

Page 54: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 54

Call by Value - an examplemain( ) {int p = 1, q = 2, r = 3, s; int test(int, int, int);…; s = test (p, q, r); … /* s is assigned 9 */} /* p,q,r don’t change, only their copies do

*/

int test( int a, int b, int c){ a ++; b ++; c ++;

return (a + b + c);}

Function prototype

Function call

Function definition

Page 55: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 55

Call by Reference#include <stdio.h>void quoRem(int, int, int*, int*); /*pointers*/main(){

int x, y, quo, rem;scanf(“%d%d”, &x, &y);quoRem(x, y, &quo, &rem);printf(“%d %d”, quo , rem);

}

void quoRem(int num, int den, int* quoAdr, int* remAdr){

*quoAdr = num / den; *remAdr = num % den;

}

Does not return anything

Passing addresses

Page 56: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 58

CS110 Lecture 11

Tutors:

Shailesh Vaya Anurag [email protected] [email protected]

Page 57: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 59

Multi-dimensional ArraysArrays with two or more dimensions can be

defined

0 1 2 0 1 2

0

1

2

3

0 1

0

1

2

3

0 1 2

A[4][3]

B[2][4][3]

Page 58: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 60

Matrix OperationsAn m-by-n matrix: M: m rows and n columnsRows : 1, 2, … , m and Columns : 1, 2, … , n

M(i,j) : element in ith row, jth column, 1 i m, 1 j n Array indexes in C start with 0. We could use (m+1) (n+1) array and ignore cells (0,i),(j,0); Programs can use natural convention - easier to understand. Our example later ignores 1st row and column.

Functions: matRead (a,int,int); matWrite(a,int,int); matInit(a,v); matAdd(a,b,c,int,int); matMult(a,b,c,int,int,int);

Page 59: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 61

Using Matrix Operationsmain(){

int a[11][11], b[11][11], c[11][11]; / * max size 10 by 10 */

int aRows, aCols, bRows, bCols, cRows, cCols;

scanf("%d%d", &aRows, &aCols); matRead(a,aRows, aCols);

scanf("%d%d", &bRows, &bCols); matRead(b,bRows,bCols);

initMat(c, 0);

matMult(a, b, c, aRows, aCols, bCols);

cRows = aRows; cCols = bCols;

matWrite(c, cRows, cCols);

}

Remember bRows=aCols

Page 60: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 62

Reading and Writing a Matrixvoid matRead(int mat[ ][11], int rows, int cols){ for(int i = 1; i <= rows; i++) for(int j = 1; j <= cols; j++) scanf("%d", &mat[i][j]);}

void matWrite(int mat[][11], int rows, int cols){ for(int i = 1; i <= rows; i++){ for(int j = 1; j <= cols; j++) /* print a row */ printf("%d ", mat[i][j]); /* notice missing \n */

printf("\n"); /* print a newline at the end a row */}

}

For the compiler to figure out the address of mat[i][j], the first dimension value is not necessary. (Why?)

Page 61: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 63

Matrix multiplication

Multiply two numbers

Sum of N products

N

N

Page 62: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 64

Matrix Multiplication

void matMult(int mat1[ ][11], int mat2[ ][11],

int mat3[ ][10], int m, int n, int p){

for(int i =1; i <= m; i++)

for(int j = 1; j <= p; j++)

for(int k = 1; k <= n; k++)

mat3[i][j] += mat1[i][k]*mat2[k][j];

} Remember it was initialized to zero in the main program. It could have been done in this function as well – probably a better idea.

Page 63: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 65

scanf and getchar• getchar() reads and returns one character

• scanf – formatted input, stores in variable– scanf returns an integer = number of inputs it

managed to convert successfully

printf ("Input 2 numbers: "); if (scanf("%d%d", &i, &j) == 2)

printf ("You entered %d and %d\n", i, j); else printf ("You failed to enter 2 numbers\n");

from <http://cprogramming.com>

Page 64: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 66

Input buffer• Your input line is first stored in a buffer.• If you are reading a number with scanf (%d) and

enter 1235ZZZ, scanf will read 1235 into the variable and leave ZZZ in the buffer.

• The next read statement will get ZZZ and may ignore the actual input!

• One may need to write a statement to clear the buffer…

while (getchar() != '\n'); This reads and ignores input till the end of line.

Page 65: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 67

Code to insist on one number only#include <stdio.h> int main(void) { int temp; printf ("Input your number: "); while (scanf("%d", &temp) != 1)

{ while (getchar() != '\n');

printf ("Try again: "); }

printf ("You entered %d\n", temp); return(0); }

exit if one number

clear buffer before reading again

Page 66: cs1100Lec08-11

PSK, NSN, DK, TAG – CS&E, IIT M 68

Hailstone numbers• A Hailstone Sequence is generated by a simple

algorithm.Start with an integer N. If N is even, the next number in the sequence is N / 2. If N is odd, the next number in the sequence is (3 * N) + 1.

• 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, ... repeats

• 12, 6, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1 ….• 909, 2726, 1364, 682, 341, 1024, 512, 256, 128,

64, 32, 16, 8, 4, 2, 1, 4, 2, 1…