Beruflich Dokumente
Kultur Dokumente
Course Material P.Sreenivasa Kumar, N.S.Narayanaswamy, Deepak Khemani, V. Kamakoti CS&E, IIT M 1
Course Outline Introduction to Computing Programming (in C) Exercises and examples are from the mathematical area of Numerical Methods. Problem solving using computers. Simulators
Theory (different ways of simulation) Practice (Programs that simulate, say queues)
Evaluation
Two Quizzes 25
Quiz 1, programming in C with some numerical methods Quiz 2, Numerical Methods and programming
Timing slots
Monday, Tuesday (Theory) and Thursday (Programming for next week)
PSK, NSN, DK, VK CS&E, IIT M 4
Lab work Instruction on Thursdays in regular class hours Programming - Two hours per week
6.00 to 8.00 PM Monday to Friday 50 students per batch Individual work - no groups Venue - Department Computing Facility of CSE Dept.
Every Lecture - Before and After Sit in the place marked for you else you will be marked absent. Attendance will be taken by the TAs 10 minutes after the commencement of the class. Please switch off your mobile phones Collect the feedback form from the TA at the start of every lecture and return the same at the end of every lecture
Lab work Please be available at the DCF of CSE Department at least 10 minutes before the start of the lab on the day allotted day. Purchase a 100 page (minimum) bound notebook which will be your record notebook. Bring the record notebook to every lab class.
What is this CS110 about? Computer and its components Computing personal, distributed, parallel Programming Languages Problem Solving and Limitations of a Computer
What IS a computer? A computer is a machine Something that operates mechanically But it is a flexible machine Its behaviour is controlled by a program A program is like a spell cast on a machine Programmers are like wizards Programs reside in the memory of the machine
Charles Babbage (1791-1871) The stored program concept
PSK, NSN, DK, VK CS&E, IIT M 9
Jaquard looms
The London Science Museum's replica Difference Engine, built from Babbage's design.
12
Augusta Ada King, Countess of Lovelace (December 10, 1815 November 27, 1852), born Augusta Ada Byron, is mainly known for having written a description of Charles Babbage's early mechanical general-purpose computer, the analytical engine.
2000: Intel Pentium 4 Processor Clock speed: 1.5 GHz # Transistors: 42 million Technology: 0.18m CMOS
15
MEMORY
01234. (say) 256 MEGABYTES
The computer is made up of a processor and a memory. The memory can be thought of as a series of locations to store information.
16
MEMORY
01234. 256 MEGABYTES
program
data
The processor treats part of the information in memory as instructions, and a part of it as data. A program is a sequence of instructions assembled for some given task. Most instructions operate on data. Some instructions control the flow of the operations. It is even possible to treat programs as data. By doing so a program could even modify itself.
PSK, NSN, DK, VK CS&E, IIT M 17
Random numbers Q: If the computer is a machine how can it generate random numbers? A: It cannot generate truly random numbers but what we call as pseudo random numbers. The sequence generated will have periodicity, but the period can be made arbitrarily large.
Mersenne Twister algorithm (1997) has a period of (219937 -1) iterations. Question: How big is 2100 ?
18
19
Variables Each memory location is given a name. The name is the variable that refers to the data stored in that location. Variables have types that define the interpretation data.
e.g. integers (1, 14, 25649), or characters (a, f, G, H)
All data is represented as binary strings. That is, it is a sequence of 0s and 1s, of a predetermined size word. A byte is made of 8 bits.
PSK, NSN, DK, VK CS&E, IIT M 20
Instructions Instructions take data stored in variables as arguments. Some instructions do some operation on the data and store it back in some variable. The instruction XX+1 on integer type says that Take the integer stored in X, add 1 to it, and store it back in (location) X.. Other instructions tell the processor to do something. For example, jump to a particular instruction next, or to exit
PSK, NSN, DK, VK CS&E, IIT M 21
Programming paradigms
Imperative programs are sequences of instructions. They are abstractions of how the von Neumann machine operates.
Pascal, C, Fortran
Object Oriented Programming Systems (OOPS) model the domain into objects and interactions between them.
Simula, CLOS, C++, Java
A Limitation Computer Arithmetic Number of digits that can be stored is limited Causes serious problem. Consider a computer that can store Sign, 3 digits and a decimal point. Sign and decimal point are optional example : 212., -212., -21.2, -2.12, -.212
PSK, NSN, DK, VK CS&E, IIT M 24
More Examples 113. + -111. = 2.00 2.00 + 7.51 = 9.51 -111. + 7.51 = -103.49 (exact arithmetic) But the computer can store only 3 digits. So it rounds 103.49 to 103. (as a rule) This is a very important thing to know as a System designer. Why?
PSK, NSN, DK, VK CS&E, IIT M 25
Why? Consider 113. + -111. + 7.51 To us addition is associative (a+b)+c = a+(b+c) (113. + -111.) + 7.51 = 2.00 + 7.51 = 9.51 113. + (-111. + 7.51) = 113. 103. = 10.0
26
Conclusion Computer is fast but restricted So we must learn to use its speed And manage its restrictions
27
Books C How to Program, Deitel and Deitel C The programming Language, Kernighan and Ritchie Unix The Programming Environment, Kernighan and Pike Numerical Recipes in C - Surf the website www.library.cornell.edu/nr/bookcpdf.html Make sure your machine has Adobe Acrobat Reader
PSK, NSN, DK, VK CS&E, IIT M 28
Review Computers: - almost everywhere these days - banks, shops, railway reservations, internet/web - engineering applications
VLSI chip design, machine design (CAD/CAM), structural analysis, process control etc etc - doing without computers - unimaginable
Building Blocks
Central Processing Unit
Computer Architecture
)
Arithmetic & Logic Unit
Control Unit
Input
Memory
ALU
Output
System Bus
31
Some More (Commands are in /bin, /usr/bin. Use ls) System Bus Essentially a set of wires, used by the other units to communicate with each other. transfer data at a very high rate
Finally (check man cp, man mv, man ls, man k search string) Control Unit Controls the interaction among other units. Knows each unit by its name, responds to requests fairly, reacts quickly on certain critical events. Gives up control periodically in the interest of the system. Together with the ALU is called the CPU.
PSK, NSN, DK, VK CS&E, IIT M 35
Compilers
Human friendly languages source code Source code in a Higher Level Language Compiler Assembly language code Assembler, linker, loader Source code in a Higher Level Language Compiler
Assembly language an x86/IA-32 processor can execute the following binary instruction as expressed in machine language: Binary: 10110000 01100001 mov al, 061h
Move the hexadecimal value 61 (97 decimal) into the processor register named "al". assembly language representation is easier to remember (more mnemonic)
From Wikipedia
PSK, NSN, DK, VK CS&E, IIT M 38
Higher level instructions = many assembly instructions For example X = Y + Z could require the following sequence
Fetch into R1 contents of Y Fetch into R2 contents of Z Add contents of R1 and R2 and store it in R1 Move contents of R1 into location named X
The C programming language C Language is an imperative general-purpose language used extensively in the development of UNIX extremely effective and expressive not a very high level nor a big language has compact syntax, modern control flow and data structures and a rich a set of operators extensive collections of library functions
PSK, NSN, DK, VK CS&E, IIT M 40
A C program typically goes through six phases 1. Editor: the program is created and stored on disk
vi and emacs are popular editors on UNIX usually part of IDE on windows platforms
6. Execute:
computer carries out the instructions of the program
43
The critical part is the solution design. One must work out the steps of solving the problem, analyse the steps, and then code them into a programming language.
PSK, NSN, DK, VK CS&E, IIT M 45
A tiny program /* A first program in C */ #include <stdio.h> Library of standard input output functions main( ) Every C program starts { execution with this printf(Hello, World! \n); function. } Statement & terminator
Body of the function - enclosed in braces Escape sequence - newline A comment
printf - a function from C Standard library stdio.h - prints a char string on the standard output46
Programming Basics
A variable changes value during the execution of a program. A variable has a name, e.g. name, value, speed, revspersec etc. Always referred to by its name The computation/computer uses its value or the address of the location corresponding to the variable name. &name denotes the address of name, &value, &speed etc. Note: physical address changes from one run of the program to another.
PSK, NSN, DK, VK CS&E, IIT M 47
Names
- made up of letters and digits
underscore ( _ ) : recommended for long names case sensitive : LaTeX and LateX are different maximum size: 31 chars ( 6 chars for external names)
Assignments and variables(what is a debugger) The value of a variable is modified due to an assignment. The modified value could be result of an evaluation, or could be a constant, or the value of another variable. The LHS is variable to be modified and the RHS is the value to be assigned. So RHS is evaluated first and then assignment performed. a = b+1, a=c, a=5, a=a+1, a = a*a
PSK, NSN, DK, VK CS&E, IIT M 49
Variable Declaration
Need to declare variables. A declaration: type variablename; Types : int, float, char int x; contents of the location corresponding to x is treated as an integer. Number of bytes assigned to a variable depends on its type. Assigning types helps write more correct programs. Automatic type checking can catch errors like integer = char +char;
PSK, NSN, DK, VK CS&E, IIT M 50
Exercise Type the above program using the vi editor. Compile it using cc Run the a.out file Write a program that outputs the coefficients of a quadratic and prints out its roots
52
Modifying Variables
Each C program is a sequence of modification of variable values A modification can happen due to operations like +, -, /, *, etc. Also due to some functions provided by the system like sizeof, sin etc. Also due to some functions (another part of your program) created by the programmer.
53
An addition program
#include <stdio.h> main( ) Declarations, must precede use { int operand1, operand2, sum; %d - conversion specifier printf(Enter first operand\n); scanf(%d, &operand1); d - decimal printf(Enter second operand\n); & - address of operand1 scanf(%d, &operand2); sum = operand1 + operand2; assignment printf(The sum is %d\n, sum); return 0; Returning a 0 is used to }
signify normal termination
PSK, NSN, DK, VK CS&E, IIT M 54
modulus operator : %
x % y : gives the remainder after x is divided by y applicable only for integers, not to float/double
PSK, NSN, DK, VK CS&E, IIT M 55
Order of evaluation (operator precedence) first parenthesized subexpessions - innermost first second , / and % - left to right third + and
- left to right
a+b cd%e f/g 4 1 2 3 6 5 a + ((( b c ) d ) % e ) (f / g ) good practice -- use parentheses rather than rely on precedence rules -- better readability
PSK, NSN, DK, VK CS&E, IIT M 56
Precedence another example Value = a * (b+c) % 5 + x / (3 + p) r - j Evaluation order 1. (b+c) and (3+p) : due to brackets 2. * and % and / have same precedence: a(b+c) is evaluated first, then mod 5. Also, x/(3+p). 3. Finally, the additions and subtractions are done from the left to right. 4. Finally, the assignment of the RHS to LHS is done. = is the operator that violates the left to right rule
PSK, NSN, DK, VK CS&E, IIT M 57
A logical variable can have two values {true, false} or {t,f} or {1,0}
! < , <= , > , >= = = , != && || unary logical negation operator comparison operators equality and inequality logical AND operator
logical OR operator logical operators return true/false order of evaluation - as given above note: assignment ( = ) equality ( = = )
PSK, NSN, DK, VK CS&E, IIT M 58
unusual operators - prefix or postfix only to variables + + adds 1 to its operand subtracts 1 from its operand N++ increments N after its use ++N increments N before its use N = 4 ; X = N++; Y = ++N; X = 4 , Y = 6 and N = 6 after the execution
PSK, NSN, DK, VK CS&E, IIT M 59
Assignment statement/expression
Form:variable-name = expression
total = test1_marks + test2_marks + end_sem_marks; int i; float x; i = x; fractional part of x is dropped x = i; i is converted into a float
Multiple assignment:
x=y=z=a+b x = ( y = ( z = a + b) )
60
Assignment operators expression n = n + 10; abbreviated form: n += 10; assignment operator most binary operators: corr. assignment operator X op= expr X = X op (expr) op : +, , , / , %
conciseness
61
Output Statement
printf(format-string, var1, var2, , varn); format-string indicates: how many variables to expect type of the variables how many columns to use for printing them any character string to be printed
sometimes this would be the only output
Examples - output int x; float y; x = 20; y = 16.7889; printf(Value x = %d and value y = %9.3f\n, x, y); %d, %9.3f : conversion specifiers d, f:conversion characters The output: Value x = 20 and value y = 16.789 - blank space (9 spaces)
PSK, NSN, DK, VK CS&E, IIT M 63
General form General conversion specifier: %w.p c w : total width of the field, p : precision (digits after decimal point) c : conversion character Conversion Characters: d - signed decimal integer u - unsigned decimal integer o - unsigned octal value x - unsigned hexadecimal value f - real decimal in fractional notation e - real decimal in exponent form
PSK, NSN, DK, VK CS&E, IIT M
optional
64
Input Statement scanf(format-string, &var1, &var2, , &varn); Format String: types of the data items to be stored in var1 etc enclosed in double quotes Example: scanf(%d%f , &marks, &aveMarks ); data line : 16 14.75 scanf skips spaces and scans more than one line to read the specified number of values
PSK, NSN, DK, VK CS&E, IIT M 65
d u o x f e c s
read a signed decimal integer read an unsigned decimal integer read an unsigned octal value read an unsigned hexadecimal value read a real decimal in fractional notation read a real decimal in exponent form read a single character read a string of characters
66
#include<stdio.h> #include<math.h> main() { float coeff_1, coeff_2, coeff_3; float discrim; float root_1, root_2; float denom; printf(first coefficient- \a); /* prompt */ scanf(%f,&coeff_1); /* read and stored */
PSK, NSN, DK, VK CS&E, IIT M 67
Quadratic (continued)
printf(2nd coefficient \a ); scanf(%f, &coeff_2); printf(3rd coefficient \a ); scanf(%f, &coeff_3); /* printf and scanf are input-output functions*/ discrim = pow(coeff_2,2) 4* coeff_1 * coeff_3; /* pow and sqrt are math functions */ denom = 2*coeff_1; root_1 = (-b + sqrt(discrim))/denom; root_2 = (-b sqrt(discrim))/denom;
PSK, NSN, DK, VK CS&E, IIT M
b2 4ac
68
Finally
(see http://www.gnu.org)
Modify the program so that the quadratic is also output. Summary: Variables are modified as the program runs.
PSK, NSN, DK, VK CS&E, IIT M 69
Problem Solving withVariables Write a program that will take two degree 5 polynomials as input and print out their product. ISSUES - How does one specify the inputs the program? Indeed, what are the inputs? coefficients from each polynomial. Six from each. We need 12 Input variables. Similarly we need 12 Output variables
70
Another exercise (www.howstuffworks.com) Write a program that takes as input 5 digit numbers and prints them out in English. Example: 512 Five Hundred and Twelve Solve the problem first, identify input variables, Output variables, intermediate variables. What values are taken by the intermediate variables, how they are calculated from input values, and output variables.
PSK, NSN, DK, VK CS&E, IIT M 71
Decisions with Variables If b^2 4ac negative, then we should report that the quadratic has no real roots. This displays the need for taking logical decisions during problem solving. The if-else programming construct provides the facility to make logical decisions. Rules for usage otherwise called syntax are if (condition is true){ evaluate this part } else {evaluate this part}
PSK, NSN, DK, VK CS&E, IIT M 72
Conditions They are specified using relational and equality operators Relational - >, <, >=, <= Equality ==, != Usage : for a,b values or variables a > b, a < b, a >= b, a <= b, a == b, a != b. A condition is satisfied or met, if the relational operator, or equality is satisfied. For a = 3, and b = 5, a < b, a <= b, and a != b are met.
PSK, NSN, DK, VK CS&E, IIT M 73
Completing the program if (discrim < 0) { printf(no real roots, only complex\n); exit(1); Terminates execution and returns argument (1) } else {root_1 = (-coeff_1 + sqrt(discrim))/denom; root_2 = (-coeff_2 - sqrt(discrim))/denom; }
PSK, NSN, DK, VK CS&E, IIT M 74
Statements Statement: a logical unit of instruction/command Program : declarations and one or more statements assignment statement selection statement repetitive statements function calls etc. All statements are terminated by semicolon ( ; )
Note: In C, semi-colon is a statement terminator rather than a separator!
PSK, NSN, DK, VK CS&E, IIT M 75
Assignment statement General Form: variable = expression | constant ; The declared type of the variable : should match the type of the result of expression/constant Multiple Assignment: var1 = var2 = var3 = expression; var1 = (var2 = (var3 = expression)); Assignment operator associates right-to-left.
PSK, NSN, DK, VK CS&E, IIT M 76
Compound Statements A group of declarations and statements collected into a single logical unit surrounded by braces
a block or a compound statement
scope of the variable declarations - part of the program where they are applicable - the compound statement
variables come into existence just after decl., continue to exist till end of the block. unrelated to variables of the same name outside the block block-structured fashion
PSK, NSN, DK, VK CS&E, IIT M 77
This i and k and the previously declared i and k are different. Not a good programming style.
Note: No semicolon after } A compound statement can appear wherever a single statement may appear
78
double selection:
if (marks < 40 ) passed = 0; else passed = 1; /* false = 0 */ /* true = 1 */
multiple selection:
switch statement - to be discussed later
79
If Statement if (<expression>) <stmt1> [ else <stmt2>] Semantics: optional Expression evaluates to true
stmt1 will be executed
Else part is optional Expression is true -- stmt1 is executed Otherwise the if statement has no effect
PSK, NSN, DK, VK CS&E, IIT M 80
Grading Example Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A int marks; char grade; Note the semicolon if (marks <= 50) grade = D; before else ! else if (marks <= 59) grade = C; else if (marks <=75) grade = B; else grade = A; Unless braces are used, an else part
goes with the nearest else-less if stmt
PSK, NSN, DK, VK CS&E, IIT M 81
Caution in use of else if ( marks > 40) /* WRONG */ if ( marks > 75 ) printf(you got distinction); else printf(Sorry you must repeat the course);
/*RIGHT*/ if ( marks > 40) { if ( marks > 75 ) printf(you got distinction); } else printf(Sorry you must repeat the course);
82
Switch Statement A multi-way decision statement Syntax: switch ( expression ) { case const-expr : statements case const-expr : statements [ default: statements ] }
PSK, NSN, DK, VK CS&E, IIT M 83
Fall Throughs Switch Statement: Execution starts at the matching case And falls through the following case statements
Unless prevented explicitly by break statement
Useful for specifying one action for several cases Break Statement:
control passes to the first statement after switch
Repetitive Statements A very important type of statement iterating or repeating a set of operations - a very common requirement in algorithms C offers three iterative constructs the for construct the while construct the do while construct
86
Programming problems Write a program to check if a given number is prime. (can this be done without using a logical decision?) Write a program to count the number of digits in a given number. Your answer should contain two parts, number of digits before and after the decimal. (can you do this only with assignments to variables, and decisions?)
87
Write a program that takes a keystroke as input, and displays the corresponding character in large using *. Use this program to display words and sentences. This is an assignment to be Graded by the TAs. Will be evaluated before quiz2. Tips: Find out the options with printf: how to move the cursor to a predefined point. How do you distinguish one keystroke from the other? Find out about ASCII codes. Explore procedures/subroutines/functions (more will be taught about this later)
PSK, NSN, DK, VK CS&E, IIT M 88
The while construct General form: while ( <expr> ) <statement> Semantics: repeat: Evaluate the expr. If the expr is true execute the statement else exit the loop. Obviously the expr must be modified in the loop!
PSK, NSN, DK, VK CS&E, IIT M 89
More on Loops Two kinds sentinel-controlled and counter controlled. Counter loop runs till counter reaches its limit. Use it when the number of repetitions is known. Sentinel loop runs till a certain condition is encountered. Example a \n is encountered in the input. Use it when the number of repetitions is a property of the input and not of the problem being solved.
PSK, NSN, DK, VK CS&E, IIT M 92
For loops
Counter controlled repetitions needs - Initial value, - modification of counter: +i, -i, any another at arithmetic based modification which is based on the problem, and - Final value. For repetition structure provides for the programmer to specify all these. Ofcourse, everything that is provided by the for can be achieved by using while. Use of for makes the program error free
PSK, NSN, DK, VK CS&E, IIT M 93
The for construct General form: for ( expr1; expr2; expr3) statement Semantics: evaluate expr1 - initialization operation(s) repeat - evaluate expression expr2 and if expr2 is true execute statement and expr3 else stop and exit the loop
PSK, NSN, DK, VK CS&E, IIT M 94
Example Replace our previous program by the following For(counter = 0; counter <=n; counter=counter+1) {if (counter == 0) printf(value is %d \n,1); else {value = 2 * value; printf(value is %d \n, value); } } Observe: a mistake in the earlier program is gone.
PSK, NSN, DK, VK CS&E, IIT M 95
Compute the sum of the first 20 odd numbers int i, j, sum; Set j to the first odd number sum = 0; i : Loop control variable j = 1; Termination condition for ( i = 1; i <= 20; i++) { sum += j; Increment sum by the ith odd number j += 2; Set j to the next odd number } The for construct expr1, expr2, expr3
PSK, NSN, DK, VK CS&E, IIT M
Calculating the compound interest Principal:1000/-; rate of interest: 5% (p.a); period: 10 yrs #include <stdio.h> #include <math.h> Character string main( ) { int year; double amount, principal = 1000.0, rate = .05; printf(%4s%21s\n, year, Amount in the deposit); for (year = 1; year < = 10; year++) { amount = principal * pow(1.0 + rate, year); printf(%4d%21.2f\n, year, amount); } }
PSK, NSN, DK, VK CS&E, IIT M 97
Example for while construct Print the reverse of a given integer: 234 432 Method: Till the number becomes a zero, extract the last digit - number modulo 10 make it the next digit of the result - multiply the current result by 10 and add the new digit
PSK, NSN, DK, VK CS&E, IIT M 98
An Example
x is the given number y is the number being computed y=0 y = 0*10 + 2 = 2 y = 2*10 + 4 = 24 y = 24*10 + 3 = 243 y = 243*10 + 6 = 2436 y = 2436*10 + 5 = 24365
PSK, NSN, DK, VK CS&E, IIT M
Reversing a number main( ){ int x = 0; int y = 0; printf("input an integer :\n"); scanf("%d", &x); while(x > 0){ y = 10*y + ( x % 10 ); Remember integer division x = (x / 10); truncates the quotient } printf("The reversed number is %d \n", y); }
PSK, NSN, DK, VK CS&E, IIT M 100
main ( ){ d<n will also do, but would int d = 2, n, sum = 1; do unnecessary work scanf(%d, &n); while ( d < = (n/2) ) { if ( n % d = = 0 ) sum += d; d++; } if (sum = = n) printf (Given number %d is perfect, n); else printf(Given number %d is not perfect, n); }
PSK, NSN, DK, VK CS&E, IIT M 101
The do while construct for and while check termination condition before each evaluation of the loop body Sometimes - execute the statement and check for condition general form: do < statement> while <expr> Semantics: execute the statement and check expr if expr is true, re-execute the stmt else exit
PSK, NSN, DK, VK CS&E, IIT M 102
int n; float prevGuess, currGuess, error, sqRoot; scanf(%d, &n); currGuess = (float) n / 2 ; error = 0.0001; do { prevGuess = currGuess; currGuess = ( prevGuess + n / prevGuess) / 2; } while (fabs (prevGuess currGuess) > error); sqRoot = currGuess; printf(%f, sqRoot); }
PSK, NSN, DK, VK CS&E, IIT M 103
NewtonRaphson method
Here, f ' denotes the derivative of the function f. Then by simple algebra we can derive
From http://en.wikipedia.org/wiki/Newton's_method
PSK, NSN, DK, VK CS&E, IIT M 104
t f
Sequence Structure
PSK, NSN, DK, VK CS&E, IIT M
If/Else Structure
105
Repetition Structures
For Structure
106
Rules
1 Begin with the simplest flowchart. 2 Any action box can be replaced by two action boxes in sequence. 3 Any action box can be replaced by any elementary structures (sequence, if, if/else, switch, while, do/while or for ). 4 Rules 2 and 3 can be applied as many times as required and in any order.
PSK, NSN, DK, VK CS&E, IIT M 107
Spaghetti programming
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. First line IF (condition1) Goto 13 Third line If (condition 2) go to 7 Fourth line Fifth line Go to 3 Sixth line If (condition 3) go to 12 Go to 8 Line number 11 Line 12 If (condition 4) go to 1 Print (Im done finally !) End
108
exercises Write a program that reads in the entries of a 3 by 3 matrix, and prints it out in the form of a matrix. The entries could be floating point entries too. Write a program that reads in orders of two matrices and decides whether two such matrices can be multiplied. Print out the decision. Write a program that reads in two matrices, and multiplies them. Your output should be the two matrices and the resulting product matrix.
PSK, NSN, DK, VK CS&E, IIT M 109
Switch Selection Structure In place of the else if for a multiway selection Syntax if (condition_1){execute these} else if (condition_2) {execute these} else if (condition_3) {execute these} and so on.. Switch replaces else if for a very special case Syntax switch(expression){ case const-expr: statements case const-expr: statements
PSK, NSN, DK, VK CS&E, IIT M 110
Example continued
case : case\n:case\t:nwhite++;break; default: nother++; break; } } printf(digits = ) for(i=0;i<10;i++) printf(%d occurred %d times \n,i,ndigit[i]); printf(white spaces = %d, other = %d\n,nwhite, nother); }
PSK, NSN, DK, VK CS&E, IIT M 112
Break and Continue break breaks out of the innermost loop or switch statement in which it occurs continue starts the next iteration of the loop in which it occurs. More on this later.
113
More Exercises Sort an array of numbers into ascending order. Assuming that arrays are expensive, your program should use only one array: read in the values into an array, sort in place, and print out the array. Matrix Sorting The input is a matrix. Identify a sequence of column interchanges such that in the resulting matrix the rows are all sorted in ascending order. Can every matrix be sorted?
PSK, NSN, DK, VK CS&E, IIT M 114
An Array A data structure containing items of same data type Declaration: array name, storage reservation
int marks[7] = {22,15,75,56,10,33,45}; - a contiguous group of memory locations named marks for holding 7 integer items - elements/components - variables
marks[0], marks[1], , marks[6] marks[i] i - position / subscript (0 i 6)
22 15 75 56 10 33 45
116
0 1 2 3 4 5 6
Polynomial Evaluation
Evaluate p(x) = anxn + an-1xn-1 + an-2xn-2 + a1x + a0 at a given x value. Computing each term and summing up
n + (n-1) + (n-2) + + 1 + 0 = n(n+1)/2 multiplications and n additions
B[2][4][3] 2 0
1
121
Note: rows/columns numbered from 0 Storage: row-major ordering elements of row 0, elements of row 1, etc Initialization: int A[4][3]={{4,5,6},{0,3,5},{1,7,8},{ 2,0,1}};
122
Row 0
{ {
4 5 6 0 3 5 1 7 8 2 0
} }
Row 1
Row 2
Row 3
123
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 use (m+1) (n+1) array and ignore cells (0,i),(j,0) Programs can use natural convention - easier to understand
124
scanf("%d%d", &bRows, &bCols); for(i = 1; i <= bRows; i++) for(j = 1; j <= bCols; j++) Remember scanf("%d", &b[i][j]); bRows must /* initialize entries in Matrix c to 0 */ for(i = 1; i <= aRows; i++) for(j = 1; j <= bCols; j++) c[i][j] = 0; /*continued on next slide */
PSK, NSN, DK, VK CS&E, IIT M
127
Matrix multiplication
aRows
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 atleast 16 bits, short is atleast 16 bits, long is atleast 32 bits, and int is no larger than long, and atleast as long as short
PSK, NSN, DK, VK CS&E, IIT M 131
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.
PSK, NSN, DK, VK CS&E, IIT M 132
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
The internal representation of binary, octal, and hexadecimal numbers is similar Octal - 2 7 3 2 5 6 0 6
135
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.
136
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 value by assignment statements in the program Otherwise they contain some random garbage values
PSK, NSN, DK, VK CS&E, IIT M 137
Constants At run time, each variable holds a constant, which changes from time to time!!!!! 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, VK CS&E, IIT M 138
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); return 0; } Here is the result for some system: 2147483647 -2147483648 -2147483647 4294967295 0 1
PSK, NSN, DK, VK CS&E, IIT M 139
32 bit numbers The unsigned 32 bit integers vary from -2147483648 to 2147483647 The signed 32 bit integers vary from 0 to 4294967295 Internally they are the 4294967296 (or 232) different permutations that 32 bits can represent. Beyond this number it starts all over again.
PSK, NSN, DK, VK CS&E, IIT M 140
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, VK CS&E, IIT M 141
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, VK CS&E, IIT M 143
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
144
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, VK CS&E, IIT M 145
Characters escape sequences \a \b \f \n \r \t \v alert (bell) backspace formfeed newline carriage return horizontal tab vertical tab \\ \? \ \ \ooo \xhh backslash question mark single quote double quote octal number hexadecimal
Non-printable characters
146
More Constants
Constant numbers, Constant characters, and now Constant Expressions Expressions all of whose operands are constants. Therefore, these can be evaluated at compile time. Examples: #define No_of_Rows 100 #define No_of_Colos 100 #define No_of_Melts No_of_Rows * No_of_Colos #define is preprocessor directive. Recall: #include
147
Enumerated Constants
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 value can be specified
PSK, NSN, DK, VK CS&E, IIT M 148
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
149
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, VK CS&E, IIT M 150
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, VK CS&E, IIT M 151
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 cannot participate in assignments and arithmetic Char mesg[] = hello; is a valid declaration Int numbers[5] = {0,1,2,3,4}; is a valid declaration But an assignment in the program is a syntax error.
PSK, NSN, DK, VK CS&E, IIT M 152
Functions to handle strings Strings being a non basic data type, in other words Constructed data type, require functions to handle. Typical functions are: a. Length of a string. b. Are two strings equal? c. Does a given pattern occur as a substring? d. Concatenate two strings and return the result These are exercises to gain programming knowledge. But use standard functions provided with string.h
PSK, NSN, DK, VK CS&E, IIT M 153
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
PSK, NSN, DK, VK CS&E, IIT M 154
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
PSK, NSN, DK, VK CS&E, IIT M 155
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;
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.
157
Quiz - I Answer Papers returned today Solutions in the website by this evening First Mark
EE07B058 - B. Ananda Narayanan 23.75/25 Congratulations
EP
CSE
ME 1 to 32
Stage
PSK, NSN, DK, VK CS&E, IIT M 161
Lab for this week Complete the backlogs Marks for first four weeks shall be freezed this Friday That has a weightage of 10 marks TAs will be available during lab hours
162
Enum Constants
enum colors {black, red, yellow,cyan, green} Variables
colors foreground = yellow, background = red;
163
\r Vs \n
\r does not feed new line \n feeds new line For example
printf(1234\r); printf(ab);
Shall Output
1234 ab
PSK, NSN, DK, VK CS&E, IIT M 164
Functions main() {
char lower, upper; char lower_to_upper(char lower); scanf(%c,&lower); upper = lower_to_upper(lower); printf(%c,upper);
165
166
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, VK CS&E, IIT M 167
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.
Add function 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
171
Recursion is possible
a function can call itself - directly or indirectly
PSK, NSN, DK, VK CS&E, IIT M 172
Function template Return-type function-name(argument declarations) { declaration and statements return expression; }
173
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
Power Function #include <stdio.h> function prototype int power (int, int); -- Computes the nth power of base. 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; Invocation with arguments for ( i = 1; i <= n ; i ++) A block p = p base; return p; }
PSK, NSN, DK, VK CS&E, IIT M 176
int power (int base, int n) { int i, p = 1; for ( i = 1; i <= n ; i ++) p = p base; return p; }
177
The issue now with data associated with other functions. Typically functions communicate using the arguments and return values
PSK, NSN, DK, VK CS&E, IIT M 179
Call by reference
variables are passed by reference
subject to modification by the function
180
Function definition
181
Call by Reference
#include <stdio.h> void quoRem(int, int, int*, int*); main(){ int x, y, quo, rem; scanf(%d%d, &x, &y); quoRem(x, y, &quo, &rem); printf(%d %d, quo , rem); } /*pointers*/ Passing addresses Does not return anything
void quoRem(int num, int den, int* quoAdr, int* remAdr){ *quoAdr = num / den; *remAdr = num % den; }
PSK, NSN, DK, VK CS&E, IIT M 182
power (3, 13) 36*36*3 = 729*729*3 = 1594323 power (3, 6) 33*33 = 27*27 = 729 power(3,3) 31*31*3 = 27 power(3,1) = 3
PSK, NSN, DK, VK CS&E, IIT M 183
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, VK CS&E, IIT M
184
fact(n) = n*fact(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!
PSK, NSN, DK, VK CS&E, IIT M 185
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 some values for future use
3 * (fact 2) 2 * (fact 1) 1
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 save any values!
187
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>
PSK, NSN, DK, VK CS&E, IIT M 188
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, VK CS&E, IIT M 189
#include <stdio.h> int main(void) { exit if one number int temp; printf ("Input your number: "); while (scanf("%d", &temp) != 1) { while (getchar() != '\n'); clear buffer before reading again printf ("Try again: "); } printf ("You entered %d\n", temp); return(0); }
from <http://cprogramming.com>
PSK, NSN, DK, VK CS&E, IIT M 190
always returns to 1 for positive . The members of the sequence produced by the Collatz problem are sometimes known as hailstone numbers.
From Wolfram Mathworld
http://mathworld.wolfram.com/CollatzProblem.html
PSK, NSN, DK, VK CS&E, IIT M 191
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 10
PSK, NSN, DK, VK CS&E, IIT M
192
Mathematical Recreations
http://users.swing.be/TGMSoft/hailstone.htm
Exercise : Write a program to accept an input and count the number of iterations needed to get to 1, and the highest number reached. Generate a table of results
PSK, NSN, DK, VK CS&E, IIT M 193