Cs1100lec08 11
Cs1100lec08 11
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
329
102 101 100
3x100 + 2x10 + 9x1 = 329
101
21
22
20
0 1
001 010 011
-1
111
000
1
001 010 011
6 110
101
-2 110
101
100
-3
100
3
7
Signed
-4
6 110
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?
PSK, NSN, DK, TAG CS&E, IIT M 8
10
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
11
Constants
At run time, each variable holds a value, which changes from time to time Constant has a value that does not change 1234 is of type int 123456789L is a long constant 123456789ul is an unsigned long constant 123.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
PSK, NSN, DK, TAG CS&E, IIT M 12
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 machines 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.
PSK, NSN, DK, TAG CS&E, IIT M 13
ASCII Table
14
More Constants
Constant 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
16
Enumerated Constants
enum boolean {No, Yes}
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
PSK, NSN, DK, TAG CS&E, IIT M 17
18
Declaring Constants
The 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?
PSK, NSN, DK, TAG CS&E, IIT M 19
20
CS1100 Lecture 9
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]
21
Strings
A 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 string Exercise: understand the difference between x and x.
PSK, NSN, DK, TAG CS&E, IIT M 22
32 bit numbers
Internally: 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,295 0 to 232-1
23
Recall Signed/Unsigned
0 7 111 6 5 110 101 100 4 000 1 001 010 011 3 Unsigned -3 Signed 2 -2 -1 111 110 101 100 -4 0 000 1 001 010 011 3 2
m bit internal representation am-1am-2 ... a2a1a0 Signed Interpretation = -[2(m-1)*am-1]+2(m-2)*am-2+...+2(2)*a2+2(1)*a1+2(0)*a0 Unsigned Interpretation = +...+2(2)*a2+2(1)*a1+2(0)*a0 2
PSK, NSN, DK, TAG CS&E, IIT M
2(m-1)*am-1+2(m-2)*am24
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
PSK, NSN, DK, TAG CS&E, IIT M 25
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 representation
PSK, NSN, DK, TAG CS&E, IIT M 26
Printing directives
#include <stdio.h> int main() { short end = 200; /* and 16-bit short */ printf("end = %hd and %d\n", end, end); return 0; }
short decimal
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.
PSK, NSN, DK, TAG CS&E, IIT M 28
Printing directives
#include <stdio.h> int main() { long long verybig = 12345678908642; printf("verybig= %lld and not %ld\n", verybig, verybig); 64 bits Truncated 32 bits return 0; } verybig= 12345678908642 and not 1942899938
29
These are exercises to gain programming knowledge. But use standard functions provided with string.h
PSK, NSN, DK, TAG CS&E, IIT M 31
Recap
Variables Assignments relational operators (comparisons) Selection and repetition constructs: control structures Data types and their limitations Arrays arrayname[n], single dimensional array Arrayname[m][n] 2D array, arrayname[i] [j] gives the element in the i-th row and j-th coloumn 32
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
33
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
34
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.
35
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
CS110 Lecture 10
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]
37
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.
As engineers from different disciplines you will use and develop different set of functions
PSK, NSN, DK, TAG CS&E, IIT M 38
Modular Programming
Subprograms functions in C, C++, procedures and functions in Pascal facilitate modular programming Overall task is divided into modules Each module - a collection of subprograms a subprogram may be invoked at several points A commonly used computation hiding the implementation incorporating changes 39 PSK, NSN, DK, TAG CS&E, IIT M
Power Function
#include <stdio.h> function prototype int power (int, int); -- Computes the nth main () { power of base. 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; Invocation with arguments for ( i = 1; i <= n ; i ++) A block p = p base; return p; }
PSK, NSN, DK, TAG CS&E, IIT M 41
36*36*3 = 729*729*3 = 1594323 power (3, 13) 33*33 = 27*27 = 729 power (3, 6) 31*31*3 = 27 power(3,3) = 3 power(3,1)
PSK, NSN, DK, TAG CS&E, IIT M 42
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; }
PSK, NSN, DK, TAG CS&E, IIT M
43
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.
Instead of one long program, we now write structured program composed of functions
46
Features
C program -- a collection of functions
function main ( ) - mandatory - program starts here.
Recursion is possible
a function can call itself - directly or indirectly
PSK, NSN, DK, TAG CS&E, IIT M 47
Function template
Return-type function-name(argument declarations) { declaration and statements return expression; }
48
Function Definition in C
return-type function-name (argument declarations) { variable/constant declarations and statements } No function declarations here! Arguments or parameters: the means of giving input to the function type and name of arguments are declared names are formal - local to the function the Matching number and type Return Value: for giving the output value of arguments
return ( expression ); -- optional
Invoking a function: funct-name(param1,param2, PSK, NSN, DK, TAG CS&E, IIT M ,paramn)
49
Function Prototype
defines
the number of parameters, type of each parameter, type of the return value of a function
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
51
The issue now with data associated with other functions. Typically functions communicate using the arguments and return values
PSK, NSN, DK, TAG CS&E, IIT M 52
Call by Value
In 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
53
Function definition
54
Call by Reference
#include <stdio.h> void quoRem(int, int, int*, int*); /*pointers*/ main(){ Passing int x, y, quo, rem; addresses scanf(%d%d, &x, &y); quoRem(x, y, &quo, &rem); printf(%d %d, quo , rem); Does not return } anything void quoRem(int num, int den, int* quoAdr, int* remAdr){ *quoAdr = num / den; *remAdr = num % den; }
PSK, NSN, DK, TAG CS&E, IIT M
55
Pending computations
In this recursive version the calling version still has pending work after it gets the return value. (fact 4) 4 * (fact 3) It needs to save 3 * (fact 2) some values for future use 2 * (fact 1) 1 2*1 =2 3*2 = 6
PSK, NSN, DK, TAG CS&E, IIT M
56
Tail recursion
int fact(n) { return fact_aux(n, 1); }
Auxiliary variable
The recursive call is in the return statement. The function simply returns what it gets from the call it makes. The calling version does not have to save any values!
57
CS110 Lecture 11
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]
58
Multi-dimensional Arrays
Arrays with two or more dimensions can be defined B[2][4][3]
A[4][3] 0 1 0 1 2 3
PSK, NSN, DK, TAG CS&E, IIT M
2 0 1 2 3
1
59
Matrix Operations
An m-by-n matrix: M: m rows and n columns Rows : 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);
PSK, NSN, DK, TAG CS&E, IIT M 60
Remember bRows=aCols
61
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 */ } }
PSK, NSN, DK, TAG CS&E, IIT M 62
Matrix multiplication
Multiply two numbers N
N
PSK, NSN, DK, TAG CS&E, IIT M
Sum of N products
63
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.
PSK, NSN, DK, TAG CS&E, IIT M 64
from <http://cprogramming.com>
PSK, NSN, DK, TAG CS&E, IIT M 65
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.
PSK, NSN, DK, TAG CS&E, IIT M 66
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
PSK, NSN, DK, TAG CS&E, IIT M 68