Upload
sriharsha-p
View
113
Download
0
Embed Size (px)
DESCRIPTION
A keynote on Problem Solving using Computers
Citation preview
Course Material – P.Sreenivasa Kumar, N.S.Narayanaswamy, Deepak Khemani, V. Kamakoti– CS&E, IIT M1
CS110Computational Engineering
An Introduction toProblem Solving using Computers
V. Kamakoti
PSK, NSN, DK, VK – CS&E, IIT M 2
Common uses of a Computer• As a tool for storing and retrieving information
– Extracting and storing information regarding studentsentering IIT
• As a tool for providing services to customers– Billing, banking, reservation
• As a calculator capable of user-defined operations– Designing circuits layouts– Designing structures– Non-destructive testing and simulation
PSK, NSN, DK, VK – CS&E, IIT M 3
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)
PSK, NSN, DK, VK – CS&E, IIT M 4
Evaluation• Two Quizzes – 25
– Quiz 1, programming in C with some numerical methods– Quiz 2, Numerical Methods and programming
• Programming Assignment – 25• End of Semester Exam – 50
– Quiz 1 + Quiz2 + Simulation• Attendance – taken in the class + Lab.
– Sit according to the roll numbers– Report tampering of the stickers to the TAs
• Timing slots– Monday, Tuesday (Theory) and Thursday (Programming for
next week)
PSK, NSN, DK, VK – CS&E, IIT M 5
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.• Attendance compulsory for lab too!!
PSK, NSN, DK, VK – CS&E, IIT M 6
Every Lecture - Before and After
• Sit in the place marked for you else you will bemarked absent.
• Attendance will be taken by the TAs 10 minutesafter 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 theend of every lecture
PSK, NSN, DK, VK – CS&E, IIT M 7
Lab work
• Please be available at the DCF of CSEDepartment at least 10 minutes before the start ofthe lab on the day allotted day.
• Purchase a 100 page (minimum) bound notebookwhich will be your record notebook.
• Bring the record notebook to every lab class.
PSK, NSN, DK, VK – CS&E, IIT M 8
What is this CS110 about?
• Computer and its components
• Computing – personal, distributed, parallel
• Programming Languages
• Problem Solving and Limitations of a Computer
PSK, NSN, DK, VK – CS&E, IIT M 9
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 10
Early Computing Hardware
The Slide rule
The Chinese Abacus
The gear replaced the beads inearly mechanical calculators
“History of computing hardware”From Wikipedia, the free encyclopedia
PSK, NSN, DK, VK – CS&E, IIT M 11
Jaquard looms
Used punched cards to weave different patterns
PSK, NSN, DK, VK – CS&E, IIT M 12
The Difference Engine
The London Science Museum'sreplica Difference Engine, builtfrom Babbage's design.
Part of Babbage's differenceengine, assembled after hisdeath by Babbage's son, usingparts found in his laboratory.
PSK, NSN, DK, VK – CS&E, IIT M 13
The First Programmer
Augusta Ada King, Countess ofLovelace (December 10, 1815 –November 27, 1852), born AugustaAda Byron, is mainly known forhaving written a description ofCharles Babbage's early mechanicalgeneral-purpose computer, theanalytical engine.
The programming language ADA is named after her.
PSK, NSN, DK, VK – CS&E, IIT M 14
ENIAC – the first electronic computer
Physically, ENIAC wasmassive compared to modernPC standards. It contained17,468 vacuum tubes, 7,200crystal diodes, 1,500 relays,70,000 resistors, 10,000capacitors and around 5million hand-soldered joints.It weighed 30 short tons (27 t),was roughly 8 feet (2.4 m) by3 feet (0.9 m) by 100 feet (30m), took up 1800 square feet(167 m²), and consumed 150kW of power.
PSK, NSN, DK, VK – CS&E, IIT M 15
2000: Intel Pentium 4 ProcessorClock speed: 1.5 GHz# Transistors: 42 millionTechnology: 0.18µm CMOS
PSK, NSN, DK, VK – CS&E, IIT M 16
The computing machine
PROCESSOR
The computer is made up of a processor and a memory. The memorycan be thought of as a series of locations to store information.
MEMORY
01234……. (say) 256 MEGABYTES
PSK, NSN, DK, VK – CS&E, IIT M 17
The computing machine
PROCESSOR
The processor treats part of the information in memory as instructions,and a part of it as data. A program is a sequence of instructionsassembled for some given task. Most instructions operate on data. Someinstructions control the flow of the operations. It is even possible to treatprograms as data. By doing so a program could even modify itself.
MEMORY
01234……. 256 MEGABYTES
program data
PSK, NSN, DK, VK – CS&E, IIT M 18
Random numbers
Q: If the computer is a machine how can it generaterandom numbers?
A: It cannot generate truly random numbers butwhat we call as pseudo random numbers.
• The sequence generated will have periodicity, butthe period can be made arbitrarily large.– Mersenne Twister algorithm (1997) has a period of
(219937 -1) iterations.– Question: How big is 2100 ?
PSK, NSN, DK, VK – CS&E, IIT M 19
The middle-square methodJohn von Neumann devised the method
in 1946.
Take any number, square it, remove themiddle digits of the resulting numberas your "random number", then usethat number as the seed for the nextiteration. For example, squaring thenumber "1111" yields "1234321",which can be written as "01234321",an 8-digit number being the square ofa 4-digit number. This gives "2343"as the "random" number. Repeatingthis procedure gives "4896" as thenext result, and so on. Von Neumannused 10 digit numbers, but theprocess was the same.
Considered by many to be thegreatest scientist of the 20th
century!
PSK, NSN, DK, VK – CS&E, IIT M 20
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 0’s and 1’s, of a predeterminedsize – “word”. A byte is made of 8 bits.
PSK, NSN, DK, VK – CS&E, IIT M 21
Instructions
• Instructions take data stored in variables asarguments.
• Some instructions do some operation on the dataand store it back in some variable.
• The instruction “XX+1” on integer type saysthat “Take the integer stored in X, add 1 to it, andstore it back in (location) X”..
• Other instructions tell the processor to dosomething. For example, “jump” to a particularinstruction next, or to exit
PSK, NSN, DK, VK – CS&E, IIT M 22
Programs
• A program is a sequence of instructions.• Normally the processor works as follows,
– Step A: pick next instruction in the sequence– Step B: get data for the instruction to operate upon– Step C: execute instruction on data (or “jump”)– Step D: store results in designated location (variable)– Step E: go to Step A
• Such programs are known as imperativeprograms.
PSK, NSN, DK, VK – CS&E, IIT M 23
Programming paradigms• Imperative programs are sequences of instructions. They
are abstractions of how the von Neumann machineoperates.
• Pascal, C, Fortran
• Object Oriented Programming Systems (OOPS) modelthe domain into objects and interactions between them.
• Simula, CLOS, C++, Java
• Logic programs use logical inference as the basis ofcomputation.
• Prolog
• Functional programs take a mathematical approach offunctions.
• LISP, ML, Haskell
PSK, NSN, DK, VK – CS&E, IIT M 24
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 25
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 aSystem designer. Why?
PSK, NSN, DK, VK – CS&E, IIT M 26
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.51113. + (-111. + 7.51) = 113. – 103. = 10.0
PSK, NSN, DK, VK – CS&E, IIT M 27
Conclusion
• Computer is fast but restricted
• So we must learn to use its speed
• And manage its restrictions
PSK, NSN, DK, VK – CS&E, IIT M 28
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.htmlMake sure your machine has Adobe Acrobat
Reader
PSK, NSN, DK, VK – CS&E, IIT M 29
ReviewComputers:
- 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 - unimaginableComputer Software:
- collection of instructions to the computer
PSK, NSN, DK, VK – CS&E, IIT M 30
Software
Very critical component in a computer applicationConsiderable complexity
– large collection of programs
– subdivided into modules with specific purposes
– developed by a team of individuals
– involves - system design, choice of algorithms,
choice of data structures, language of implementation, testing, maintenance
PSK, NSN, DK, VK – CS&E, IIT M 31
Building Blocks (Computer Architecture)
Arithmetic& Logic Unit
Control Unit
Input Memory ALU Output
CentralProcessingUnit
System Bus
PSK, NSN, DK, VK – CS&E, IIT M 32
The Blocks, Their Functions• Input unit
Takes inputs from the external world via variety of input devices- keyboard, mouse,
temperature sensors, odometers, wirelessDevices etc.
• Output Unit Sends information (after retrieving, processing) to output devices –monitors/displays, projectors, audio devices, switches, relays, gearbox etc.
PSK, NSN, DK, VK – CS&E, IIT M 33
More (try more filename on your unix/linux machine)• Memory Place where information is stored. Primary memory – Electronic devices, used
primarily by other such devices, for temporary storage.Characterized by their speedy response.
Secondary Memory – Devices for Long term storage.Contained well tuned mechanical components,magnetic storage media – floppies, hard disks.Compact Disks use optical technology. Used to storeuser data (programs, inputs, results etc.), also usedextensively during computation.
PSK, NSN, DK, VK – CS&E, IIT M 34
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• ALU – Arithmetic and Logic Unit Processes data- add, subtract Decides – after comparing with another value, for example
PSK, NSN, DK, VK – CS&E, IIT M 35
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 36
THE CPU (editors vi, emacs used to create text)• Can fetch an instruction from memory• Execute the instruction• Store the result in memory• A program – a set of instructions• An instruction has the following structure
Operation, operands, destination• A simple operation – creating variables
Create a /* labels a memory location using the letter a*/Very important abstraction – use of alphanumeric stringsTo represent data. Simplifies the usage of a computer.
PSK, NSN, DK, VK – CS&E, IIT M 37
Compilers
Source code in aHigher Level Language
Source code in aHigher Level Language
Assembly language code
machine language code
Assembler, linker, loader
Compiler Compiler
Human friendly languages source code
Machine understandable language
PSK, NSN, DK, VK – CS&E, IIT M 38
Assembly language
• an x86/IA-32 processor can execute thefollowing binary instruction as expressed inmachine language:
Binary: 10110000 01100001mov al, 061h
– Move the hexadecimal value 61 (97 decimal) into theprocessor register named "al".
– assembly language representation is easier toremember (more mnemonic)
From Wikipedia
PSK, NSN, DK, VK – CS&E, IIT M 39
Higher Level Languages
• Higher level instructions = many assemblyinstructions
• For example “X = Y + Z” could require thefollowing 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
• HLLs can be at many levels
PSK, NSN, DK, VK – CS&E, IIT M 40
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 41
Origins of C
•Developed by Dennis Ritchie at Bell Labs– first implemented on DEC PDP-11 in 1972
•Based on two existing languages– BCPL and B languages– BCPL: Martin Richards, 1967 - systems
programming– B: Ken Thomson, 1970 - early versions of UNIXThe C Programming Language- Kernighan, Ritchie, 1978
•ANSI C: a standard adopted in 1990– unambiguous, machine-independent definition of CThe C Programming Language (2nd edition)- Kernighan,
Ritchie, 1988
PSK, NSN, DK, VK – CS&E, IIT M 42
Developing and using a C program
A C program typically goes through six phases1. Editor: the program is created and stored on disk
– vi and emacs are popular editors on UNIX– usually part of IDE on windows platforms
2. Preprocessor: handles preprocessor directives– include other files, macro expansions etc
3. Compiler: translates the program– into machine language code or object code– stores on disk
PSK, NSN, DK, VK – CS&E, IIT M 43
Other phases
4. Linker: combines– the object code of the program– object code of library functions and other functions
creates an executable image with no “holes”5. Loader:
– transfers the executable image to the memory6. Execute:
– computer carries out the instructions of the program
PSK, NSN, DK, VK – CS&E, IIT M 44
Programs = solutions
• A program is a sequence of instructions– This is from the perspective of the machine or the
compiler!
• A program is a (frozen) solution– From the perspective of a human a program is a
representation of a solution devised by the human.Once frozen (or written and compiled) it can beexecuted by the computer – much faster, and as manytimes as you want.
PSK, NSN, DK, VK – CS&E, IIT M 45
Programming = Problem Solving
• Software development involves the following– A study of the problem (requirements analysis)– A description of the solution (specification)– Devising the solution (design)– Writing the program (coding)– Testing
• The critical part is the solution design. One mustwork out the steps of solving the problem,analyse the steps, and then code them into aprogramming language.
PSK, NSN, DK, VK – CS&E, IIT M 46
A tiny program
/* A first program in C */#include <stdio.h>main( ){
printf(“Hello, World! \n”);}
A comment
Every C program startsexecution with thisfunction.
Body of the function- enclosed in braces
Statement & terminator
Escape sequence - newline
Library of standard input outputfunctions
printf - a function from C Standard library stdio.h- prints a char string on the standard output
PSK, NSN, DK, VK – CS&E, IIT M 47
Programming Basics (vi, emacs for programs)
• A variable – changes value during the execution of aprogram.
• 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 48
Variables and constantsNames
- made up of letters and digitsunderscore ( _ ) : recommended for long namescase sensitive : LaTeX and LateX are differentmaximum size: 31 chars ( 6 chars for external names)
- first character must be a letteravoid underscore as the first letter ( some library fns use it)
- choose meaningful and self-documenting namesfor constants as well as variables
- keywords - if, for, else, float etc - reserved
PSK, NSN, DK, VK – CS&E, IIT M 49
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 valueof another variable.
• The LHS is variable to be modified and the RHSis the value to be assigned.
• So RHS is evaluated first and then assignmentperformed.
• a = b+1, a=c, a=5, a=a+1, a = a*a
PSK, NSN, DK, VK – CS&E, IIT M 50
Variable Declaration (declaring variables, actually)
• 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 bytesassigned to a variable depends on its type.
• Assigning types helps write more correctprograms. Automatic type checking can catcherrors like integer = char +char;
PSK, NSN, DK, VK – CS&E, IIT M 51
Variables need DeclarationAnother simple C program#include<stdio.h>main(){int int_size; int chr_size; int flt_size; int_size = sizeof(int); chr_size =sizeof(char); flt_size = sizeof(float); printf(“int, char, and float use %d %d and %d bytes\n”,
int_size, chr_size; flt_size);}
12345678
9
A functionfrom stdio.h
PSK, NSN, DK, VK – CS&E, IIT M 52
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 ofa quadratic and prints out its roots
PSK, NSN, DK, VK – CS&E, IIT M 53
Modifying Variables (rm with –i option)
• Each C program is a sequence of modificationof variable values
• A modification can happen due to operationslike +, -, /, *, etc.
• Also due to some functions provided by thesystem like sizeof, sin etc.
• Also due to some functions (another part of yourprogram) created by the programmer.
PSK, NSN, DK, VK – CS&E, IIT M 54
An addition program#include <stdio.h>main( ){
int operand1, operand2, sum;printf(“Enter first operand\n”);scanf(“%d”, &operand1);printf(“Enter second operand\n”);scanf(“%d”, &operand2);sum = operand1 + operand2;printf(“The sum is %d\n”, sum);return 0;
}
Declarations, must precede use
“ %d ” - conversion specifier
d - decimal & - address of operand1
assignment
Returning a 0 is used tosignify normal termination
PSK, NSN, DK, VK – CS&E, IIT M 55
Arithmetic operators in C
Four basic operators+ , – , ∗ , /addition, subtraction, multiplication and divisionapplicable to integers and floating point numbersinteger division - fractional part of result truncated
12/ 5 2, 5/9 0
modulus operator : %x % y : gives the remainder after x is divided by yapplicable only for integers, not to float/double
PSK, NSN, DK, VK – CS&E, IIT M 56
Order of evaluation (operator precedence)
first parenthesized subexpessions - innermost first
second ∗ , / and % - left to right
third + and – - left to right
a + b ∗ c ∗ d % 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 57
Precedence – another exampleValue = a * (b+c) % 5 + x / (3 + p) – r - jEvaluation order –1. (b+c) and (3+p) : due to brackets2. * 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 toright rule
PSK, NSN, DK, VK – CS&E, IIT M 58
Relational and logical operators
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/falseorder of evaluation - as given abovenote: assignment ( = ) equality ( = = )
PSK, NSN, DK, VK – CS&E, IIT M 59
Increment and decrement operators unusual operators - prefix or postfix
only to variables+ + adds 1 to its operand– – subtracts 1 from its operandN++ increments N after its use++N increments N before its useN = 4 ; X = N++; Y = ++N;X = 4 , Y = 6 and N = 6 after the execution
PSK, NSN, DK, VK – CS&E, IIT M 60
Assignment statement/expression
• Form:variable-name = expressiontotal = 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 + bx = ( y = ( z = a + b) )
PSK, NSN, DK, VK – CS&E, IIT M 61
Assignment operators
expression n = n + 10;abbreviated form: n += 10; assignment operator
most binary operators: corr. assignment operatorX op= exprX = X op (expr)op : +, – , ∗, / , %conciseness
PSK, NSN, DK, VK – CS&E, IIT M 62
Output Statement
printf(format-string, var1, var2, …, varn);
format-string indicates:how many variables to expecttype of the variableshow many columns to use for printing themany character string to be printed– sometimes this would be the only output
enclosed in double quotes
PSK, NSN, DK, VK – CS&E, IIT M 63
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 charactersThe output:
Value x = 20 and value y = ��–16.789� - blank space (9 spaces)
PSK, NSN, DK, VK – CS&E, IIT M 64
General formGeneral conversion specifier: %w.p cw : total width of the field,p : precision (digits after decimal point)c : conversion characterConversion Characters:d - signed decimal integeru - unsigned decimal integero - unsigned octal valuex - unsigned hexadecimal valuef - real decimal in fractional notatione - real decimal in exponent form
optional
PSK, NSN, DK, VK – CS&E, IIT M 65
Input Statement
scanf(format-string, &var1, &var2, …, &varn);Format String:
types of the data items to be stored in var1 etcenclosed in double quotes
Example: scanf(“%d%f ”, &marks, &aveMarks );
data line : 16 14.75scanf skips spaces and scans more than one line
to read the specified number of values
PSK, NSN, DK, VK – CS&E, IIT M 66
Conversion Specifiers for “scanf”
d - read a signed decimal integeru - read an unsigned decimal integero - read an unsigned octal valuex - read an unsigned hexadecimal valuef - read a real decimal in fractional notatione - read a real decimal in exponent formc - read a single characters - read a string of characters
PSK, NSN, DK, VK – CS&E, IIT M 67
Solving a quadratic equation (rm –i is safe)
#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 68
Quadratic (continued) (use vi to create files)
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;
b2 – 4ac
PSK, NSN, DK, VK – CS&E, IIT M 69
Finally (see http://www.gnu.org)
printf(“the roots were %f %f \n”, root_1, root_2);}
Exercise:
Modify the program so that the quadratic is alsooutput.
Summary: Variables are modified as the programruns.
PSK, NSN, DK, VK – CS&E, IIT M 70
Problem Solving withVariables
• Write a program that will take two degree 5polynomials as input and print out their product.
• ISSUES - How does one specify the inputs theprogram?
• Indeed, what are the inputs? – coefficients fromeach polynomial. Six from each.
• We need 12 Input variables.• Similarly we need 12 Output variables
PSK, NSN, DK, VK – CS&E, IIT M 71
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 intermediatevariables, how they are calculated from inputvalues, and output variables.
PSK, NSN, DK, VK – CS&E, IIT M 72
Decisions with Variables
• If b^2 – 4ac negative, then we should report thatthe quadratic has no real roots.
• This displays the need for taking logicaldecisions during problem solving.
• The if-else programming construct provides thefacility 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 73
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 74
Completing the program
if (discrim < 0){ printf(“no real roots, only complex\n”); exit(1);}
else{root_1 = (-coeff_1 + sqrt(discrim))/denom; root_2 = (-coeff_2 - sqrt(discrim))/denom;}
Terminates execution andreturns argument (1)
PSK, NSN, DK, VK – CS&E, IIT M 75
Statements
Statement: a logical unit of instruction/commandProgram : declarations and one or more statements
assignment statementselection statementrepetitive statementsfunction 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 76
Assignment statement
General Form: variable “ = ” expression | constant “;”The declared type of the variable : should match
the type of the result of expression/constantMultiple Assignment:
var1 = var2 = var3 = expression;var1 = (var2 = (var3 = expression));
Assignment operator associates right-to-left.
PSK, NSN, DK, VK – CS&E, IIT M 77
Compound Statements
A group of declarations and statements collectedinto 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 78
An Example
{ int i, j, k;i = 1; j =2; k =3;if ( expr ) {int i, k;
}…
}
This i and k and the previouslydeclared i and k are different.Not a good programming style.
Note: No semicolon after }
A compound statement can appearwherever a single statement may appear
PSK, NSN, DK, VK – CS&E, IIT M 79
Selection Statements
Three formssingle selection:
if ( att < 75 ) grade = “W”;
double selection:if (marks < 40 ) passed = 0; /* false = 0 */else passed = 1; /* true = 1 */
multiple selection:switch statement - to be discussed later
Note: There is nothen reserved word
PSK, NSN, DK, VK – CS&E, IIT M 80
If Statement
if (<expression>) <stmt1> [ else <stmt2>]Semantics:
Expression evaluates to “true”– stmt1 will be executed
Expression evaluates to “false”– stmt2 will be executed
Else part is optional Expression is “true” -- stmt1 is executed
Otherwise the if statement has no effect
optional
PSK, NSN, DK, VK – CS&E, IIT M 81
Grading Example
Note the semicolonbefore else !
Unless braces are used, an else partgoes with the nearest else-less if stmt
Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A
int marks; char grade;…if (marks <= 50) grade = ‘D’;else if (marks <= 59) grade = ‘C’; else if (marks <=75) grade = ‘B’;
else grade = ‘A’;…
PSK, NSN, DK, VK – CS&E, IIT M 82
Caution in use of “else”
if ( marks > 40) if ( marks > 75 ) printf(“you got distinction”);else printf(“Sorry you must repeat the course”);
if ( marks > 40) { if ( marks > 75 ) printf(“you got distinction”);}else printf(“Sorry you must repeat the course”);
/* WRONG */
/*RIGHT*/
PSK, NSN, DK, VK – CS&E, IIT M 83
Switch Statement
A multi-way decision statementSyntax:switch ( expression ) {
case const-expr : statementscase const-expr : statements…[ default: statements ]
}
PSK, NSN, DK, VK – CS&E, IIT M 84
Counting Evens and Odds
int num, eCount = 0, oCount = 0;scanf (“%d”, &num);while (num >= 0) {
switch (num%2) {case 0 : eCount++; break;case 1 : oCount++; break;
}scanf (“%d”, &num);
}printf( “Even: %d ,Odd: %d\n”, eCount, oCount);
Counts the number ofeven and odd integersin the input.Terminated by giving anegative number
Defensive programming !
PSK, NSN, DK, VK – CS&E, IIT M 85
Fall Through’s
Switch Statement:Execution starts at the matching caseAnd falls through the following case statements
Unless prevented explicitly by break statementUseful for specifying one action for several
casesBreak Statement:
control passes to the first statement after switchA feature requiring exercise of caution
PSK, NSN, DK, VK – CS&E, IIT M 86
Repetitive Statements
A very important type of statementiterating or repeating a set of operations- a very common requirement in algorithms
C offers three iterative constructsthe for constructthe while … constructthe do … while construct
PSK, NSN, DK, VK – CS&E, IIT M 87
Programming problems
• Write a program to check if a given number isprime. (can this be done without using a logicaldecision?)
• Write a program to count the number of digits ina given number. Your answer should containtwo parts, number of digits before and after thedecimal. (can you do this only with assignmentsto variables, and decisions?)
PSK, NSN, DK, VK – CS&E, IIT M 88
Exercise in using printf (try banner word)
Write a program that takes a keystroke as input, anddisplays the corresponding character in large using *.Use this program to display words and sentences.
This is an assignment to be Graded by the TAs. Willbe evaluated before quiz2.
Tips: Find out the options with printf: how to move thecursor 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 89
The while construct
General form: while ( <expr> ) <statement>
Semantics:repeat: Evaluate the “expr”.
If the “expr” is trueexecute the “statement”
else exit the loop.Obviously the “expr” must be modified in the loop!
PSK, NSN, DK, VK – CS&E, IIT M 90
Repetition Structure - WhileSyntax – while (condition is true){ evaluate this piece of
code}#include<stdio.h>#include<math.h>main(){ int n, counter, value;
printf(“ value for n – “); scanf(“%d”, &n); counter = 0;
value = 1;contd..
Print powers of 2 till 2N
PSK, NSN, DK, VK – CS&E, IIT M 91
Program using whilecounter = 0; /*repeated*/value = 1; /*repeated*/printf(“current value is %d \n”, value);while (counter <= n)
{value = 2 * value; printf(“current value is %d \n”, value);
counter = counter + 1;}
}Exercise: try this program and identify problems
PSK, NSN, DK, VK – CS&E, IIT M 92
More on Loops
• Two kinds – sentinel-controlled and countercontrolled.
• Counter – loop runs till counter reaches its limit.Use it when the number of repetitions is known.
• Sentinel – loop runs till a certain condition isencountered. Example – a \n is encountered inthe input. Use it when the number ofrepetitions is a property of the input and not ofthe problem being solved.
PSK, NSN, DK, VK – CS&E, IIT M 93
For loopsCounter controlled repetitions needs –
- Initial value,- modification of counter: +i, -i, any another atarithmetic based modification which is based on theproblem, and- Final value.
For repetition structure provides for the programmer tospecify all these.
Ofcourse, everything that is provided by the for can beachieved by using while.
Use of for makes the program error free
PSK, NSN, DK, VK – CS&E, IIT M 94
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 95
Example
Replace our previous program by the followingFor(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 96
Simple example of for statementCompute the sum of the first 20 odd numbers
int i, j, sum;sum = 0;j = 1;for ( i = 1; i <= 20; i++){ sum += j;j += 2;
}The for construct expr1, expr2, expr3
-- involving the loop control variable only
Increment sum by the ith odd number
Set j to the next odd number
i : Loop control variable
Termination condition
Set j to the first odd number
PSK, NSN, DK, VK – CS&E, IIT M 97
Calculating the compound interestPrincipal:1000/-; rate of interest: 5% (p.a); period: 10 yrs#include <stdio.h>#include <math.h>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);
}}
Character string
PSK, NSN, DK, VK – CS&E, IIT M 98
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 99
An Example
Termnation condition:Stop when x becomes zero
x is the given numbery is the number being computed
y = 0 x = 56342y = 0*10 + 2 = 2 x = 5634y = 2*10 + 4 = 24 x = 563y = 24*10 + 3 = 243 x = 56y = 243*10 + 6 = 2436 x = 5y = 2436*10 + 5 = 24365 x = 0
PSK, NSN, DK, VK – CS&E, IIT M 100
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 ); x = (x / 10);
} printf("The reversed number is %d \n", y);}
Remember integer divisiontruncates the quotient
PSK, NSN, DK, VK – CS&E, IIT M 101
Perfect number detectionPerfect : sum of proper divisors add up to the number.main ( ){
int d = 2, n, sum = 1;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);
}
d<n will also do, but woulddo unnecessary work
PSK, NSN, DK, VK – CS&E, IIT M 102
The do while construct
for and while check termination condition beforeeach evaluation of the loop body
Sometimes - execute the statement andcheck 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 103
Square root of a number
main( ) {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);
}
How do you solve the equation “x = n2” ?
PSK, NSN, DK, VK – CS&E, IIT M 104
Newton–Raphson method
Here, f ' denotes the derivative of thefunction f. Then by simple algebrawe can derive
Fromhttp://en.wikipedia.org/wiki/Newton's_method
PSK, NSN, DK, VK – CS&E, IIT M 105
Sequence and Selection Structures
SequenceStructure
If Structure
If/Else Structure
t
f
tf
Single EntrySingle Exit
PSK, NSN, DK, VK – CS&E, IIT M 106
Repetition Structures
t
t
f
t
f
f
While StructureDo/WhileStructure
For StructureSingle EntrySingle Exit
PSK, NSN, DK, VK – CS&E, IIT M 107
Structured Programming
To produce program that are– easier to develop, understand, test, modify– easier to get correctness proof
Rules1 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 asrequired and in any order.
PSK, NSN, DK, VK – CS&E, IIT M 108
Spaghetti programming1. First line2. IF (condition1) Goto 133. Third line4. If (condition 2) go to 75. Fourth line6. Fifth line7. Go to 38. Sixth line9. If (condition 3) go to 1210. Go to 811. Line number 1112. Line 1213. If (condition 4) go to 114. Print (“I’m done finally !”)15. End
PSK, NSN, DK, VK – CS&E, IIT M 109
exercises
Write a program that reads in the entries of a 3 by3 matrix, and prints it out in the form of amatrix. The entries could be floating pointentries too.
Write a program that reads in orders of twomatrices and decides whether two such matricescan be multiplied. Print out the decision.
Write a program that reads in two matrices, andmultiplies them. Your output should be the twomatrices and the resulting product matrix.
PSK, NSN, DK, VK – CS&E, IIT M 110
Switch Selection Structure
In place of the else if for a multiway selectionSyntax – 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 caseSyntax – switch(expression){
case const-expr: statementscase const-expr: statements
PSK, NSN, DK, VK – CS&E, IIT M 111
Example(kernighan & ritchie, p.59)#include<stdio.h>main(){ int c, i, nwhite, nother, ndigit[10]; nwhite = nother = 0; for(i=0;i<10;i++) ndigit[i]=0; while((c = getchar()) ! = EOF){
switch(c){case’0’:case’1’:case’2’:case’3’:case’4’:case’5’:
case’6’:case’7’:case’8’:case’9’: ndigit[c-’0’]++; break;
An array of ten integers
PSK, NSN, DK, VK – CS&E, IIT M 112
Example continuedcase’ ‘:
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 113
Break and Continue
break breaks out of the innermost loop or switchstatement in which it occurs
continue starts the next iteration of the loop inwhich it occurs.
PSK, NSN, DK, VK – CS&E, IIT M 114
More Exercises
Sort an array of numbers into ascending order.Assuming that arrays are expensive, yourprogram should use only one array: read in thevalues into an array, sort in place, and print outthe array.
Matrix Sorting – The input is a matrix. Identify asequence of column interchanges such that inthe resulting matrix the rows are all sorted inascending order. Can every matrix be sorted?
PSK, NSN, DK, VK – CS&E, IIT M 115
Exercise – week starting Feb 5Read a text file and report the following,1. The total number of non-white characters2. The total number of words3. The average length of a word4. The mode length of a word5. The total number of lines6. The average length of a line7. The length of the longest line
Any assumptions your program makes must be statedin the comments. What if lines are logical ending withappropriate punctuation?
PSK, NSN, DK, VK – CS&E, IIT M 116
An Array
• A data structure containing items ofsame data type
• Declaration: array name, storage reservationint 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)
- the value of marks[2] is 75- new values can be assigned to elements
marks[3] = 36;
22
15
75
56
10
33
45
0
1
2
3
4
5
6
PSK, NSN, DK, VK – CS&E, IIT M 117
Example using arraysRead five numbers into an array and compute their average#include <stdio.h>int main( ){
int numbers[5] = {1,3,2,6,-5}; int sum = 0, i;
float average;for ( i = 0; i < 5; i++) sum = sum + numbers[i];
average = (float) sum/5;printf(“The average of numbers is: %f”, average);return 0; /* should be there in all programs */
}
numbers[] is initializedduring declaration
PSK, NSN, DK, VK – CS&E, IIT M 118
Example using arrays (Read values from keyboard)Read ten numbers into an array and compute their average#include <stdio.h>int main( ){
int numbers[10], sum = 0, i;float average;for ( i = 0; i < 10; i++) scanf(“%d”, &numbers[i]);
for ( i = 0; i < 10; i++) sum = sum + numbers[i];
average = (float) sum/10;printf(“The average of numbers is: %f”, average);return 0; /* should be there in all programs */
}
PSK, NSN, DK, VK – CS&E, IIT M 119
Polynomial EvaluationEvaluate 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 multiplicationsand n additions
Improved Method – Horner’s Method:p(x) = a0 + x(a1 + x(a2 + x(a3 + … + x(an-1 + xan))))for instance, p(x) = 10x3 + 4x2 + 5x + 2
= 2 + x(5 + x(4 + 10x))n multiplications and n additions – will run faster!
PSK, NSN, DK, VK – CS&E, IIT M 120
Program for Polynomial Evaluation
#include <stdio.h>main( ){ int coeff[20], n, x, value, i; /*max. no. of coeff ’s is 20 : a0 to a19 */ scanf(“%d%d”, &n, &x); /*read degree and evaluation point*/ for(i = 0; i <= n; i++)
scanf(“%d”, &coeff[i]); /* read in the coefficients */ value = coeff[n]; /* an */ for(i = (n-1); i >= 0; i--) /* evaluate p(x) */
value = x*value + coeff[i]; printf(“The value of p(x) at x = %d is %d\n”, x, value);}
PSK, NSN, DK, VK – CS&E, IIT M 121
Multi-dimensional Arrays
Arrays 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 2A[4][3] B[2][4][3]
PSK, NSN, DK, VK – CS&E, IIT M 122
Declaration: int A[4][3] : 4 rows and 3 columns, 4 × 3 arrayElements: A[i][j] - element in row i and column j of array A
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}};
Two Dimensional Arrays
0
1
2
3
0 1 2A[4][3]
PSK, NSN, DK, VK – CS&E, IIT M 123
int A[4][3]={{4,5,6},{0,3,5},{1,7,8},{ 2,0,1}};
4 56
0
3
5
1
7 82
0
1
}Row 1
{Row 0
}Row 3
{Row 2
PSK, NSN, DK, VK – CS&E, IIT M 124
Matrix Operations
An 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 use (m+1) × (n+1) array and ignore cells (0,i),(j,0)Programs can use natural convention - easier tounderstand
Should perform : Read; Write; Initiliazation; Multiplication;
PSK, NSN, DK, VK – CS&E, IIT M 125
Matrix Multiplication : Outline
main(){ 1. declare all variables required 2. read in Matrix A
3. read in Matrix B 4. check if A and B are compatible to be multiplied 5. initialize Matrix C to have zeroes to begin with 6. multiply A and B to give C 7. print Matrix C} Of course, all the steps above have to
follow C language’s syntax rules
PSK, NSN, DK, VK – CS&E, IIT M 126
Using Matrix Operations : Read a Matrix
main(){ int a[11][11], b[11][11], c[11][11]; / *max size 10 by 10 */ int i,j,k;
int aRows, aCols, bRows, bCols, cRows, cCols;
scanf("%d%d", &aRows, &aCols); for(int i = 1; i <= aRows; i++) for(int j = 1; j <= aCols; j++) scanf("%d", &a[i][j]);
/*continued on next slide */
PSK, NSN, DK, VK – CS&E, IIT M 127
Read the other Matrix; Initialize the product
scanf("%d%d", &bRows, &bCols); for(i = 1; i <= bRows; i++) for(j = 1; j <= bCols; j++) scanf("%d", &b[i][j]);
/* 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 */
Remember bRows must equal aCols c is a aRows x bCols matrix
PSK, NSN, DK, VK – CS&E, IIT M 128
Matrix multiplication
Multiply two numbers
Sum of N products
bRows
aCols
aRows
PSK, NSN, DK, VK – CS&E, IIT M 129
Multiply Matrices and Print the Result/* multiply both the matrices and store in matrix c */for(i =1; i <= aRows; i++) for(j = 1; j <= bCols; j++) for(k = 1; k <= aCols; k++) c[i][j] += a[i][k]*b[k][j];
/* print matrix c */for(i = 1; i <= aRows; i++){ for(j = 1; j <= bCols; j++) /* print a row */ printf("%d ", c[i][j]); /* notice missing \n */
printf("\n"); /* print a newline at the end a row */ }} /* End of main program */
PSK, NSN, DK, VK – CS&E, IIT M 130
Points to Ponder
• Some repetition in the program– Reading in matrix A seems to be similar to reading in
matrix B• Except for changes in the number of rows and columns
• You will learn how to write functions in C later– Functions are written to avoid repeated actions– Example C program would look like
readMat(A, aRows, aCols); readMat(B, bRows, bCols);
– Function readMat( ) must perform the operationsdesired
PSK, NSN, DK, VK – CS&E, IIT M 131
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 atleast16 bits, long is atleast 32 bits, and int is nolarger than long, and atleast as long as short
PSK, NSN, DK, VK – CS&E, IIT M 132
char, signed and unsigned
• Qualifier signed or unsigned can be applied toint or char
• Unsigned numbers are non-negative• Signed char holds numbers between –128 and
127. Whether char is signed or unsigneddepends on the system. Find out on yoursystem. Print integers between 0 to 255 ascharacters, and integers between –128 to 127 onyour system.
PSK, NSN, DK, VK – CS&E, IIT M 133
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)– 0, 1, …, 9, A, B, C, D, E, F, 10, 11, … 19, 1A, 1B, …
PSK, NSN, DK, VK – CS&E, IIT M 134
The internal representation of binary, octal, andhexadecimal 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
PSK, NSN, DK, VK – CS&E, IIT M 135
A funny infinite loop - arithmeticThis program of mine, ran into an infinite loop. I only
wanted to find which numbers corresponded to whichcharacters, the significance of signed and unsignedcharacters, basically relationship between whichintegers 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 adecimal number
Print it as acharacter
Try omitting one parameter…
PSK, NSN, DK, VK – CS&E, IIT M 136
Float and Double
• Two types, one for single-precision arithmetic,and the other for double precision arithmetic
• Long double is used for extended-precisionarithmetic.
• The size of floating pointing objects areimplementation defined.
PSK, NSN, DK, VK – CS&E, IIT M 137
Variable Initialization
• Variables may be initialized either at the time ofdeclaration, 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 assignmentstatements in the program
• Otherwise they contain some random garbagevalues
PSK, NSN, DK, VK – CS&E, IIT M 138
Constants
• At run time, each variable holds a constant,which changes from time to time!!!!!
1234 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 byan f, or by l, the type is float or long double,
respectively
PSK, NSN, DK, VK – CS&E, IIT M 139
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 -21474836474294967295 0 1
PSK, NSN, DK, VK – CS&E, IIT M 140
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 canrepresent. Beyond this number it starts allover again.
PSK, NSN, DK, VK – CS&E, IIT M 141
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 sameinternal representationBoth have the sameinternal representation
PSK, NSN, DK, VK – CS&E, IIT M 142
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 asa normal is okay
PSK, NSN, DK, VK – CS&E, IIT M 143
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-bitnumber, it looks like 00000000000000010000000000000001.Using the %hd specifier persuaded printf() to look at just the last16 bits; therefore, it displayed the value as 1.
PSK, NSN, DK, VK – CS&E, IIT M 144
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
PSK, NSN, DK, VK – CS&E, IIT M 145
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 characterset. For example, ‘1’ has the value 49 in theASCII character set. That is, number 49,interpreted as a character code stands for ‘1’
• Character constants can participate inarithmetic. What does ‘1’+’2’ hold? (not ‘3’!)Understand this distinction. Characterarithmetic is used mainly for comparisons.
PSK, NSN, DK, VK – CS&E, IIT M 146
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\t horizontal tab \xhh hexadecimal\v vertical tab
Non-printable characters
PSK, NSN, DK, VK – CS&E, IIT M 147
More ConstantsConstant numbers, Constant characters, and nowConstant 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
PSK, NSN, DK, VK – CS&E, IIT M 148
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 value can be specified
By default enumtype begin with 0
PSK, NSN, DK, VK – CS&E, IIT M 149
Enum and #define
• Better than #define, the constant values aregenerated 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 validvalue for enumeration
PSK, NSN, DK, VK – CS&E, IIT M 150
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”.
PSK, NSN, DK, VK – CS&E, IIT M 151
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 whilecompilation.
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 152
Assignment and Arithmetic Rules
• Basic data types, numbers and characters can beassigned to their corresponding variables.
Example: char c = ‘a’; char no = ‘1’; int j = 25;Arrays cannot participate in assignments and
arithmeticChar mesg[] = “hello”; is a valid declarationInt numbers[5] = {0,1,2,3,4}; is a valid declarationBut an assignment in the program is a syntax
error.
PSK, NSN, DK, VK – CS&E, IIT M 153
Functions to handle stringsStrings being a non basic data type, in other wordsConstructed 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 resultThese are exercises to gain programming
knowledge. But use standard functionsprovided with string.h
PSK, NSN, DK, VK – CS&E, IIT M 154
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 theelement in the i-th row and j-th coloumn
PSK, NSN, DK, VK – CS&E, IIT M 155
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 156
How to use these in a program
• They are used when composite conditions are tobe 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 the testconditions is true
• Which is while all the test conditions are true
• The loop is exited when the test conditionbecomes false
• Which is when one of the test conditions becomes false• For example when an enter is read from keyboard
PSK, NSN, DK, VK – CS&E, IIT M 157
Exercise
• Write a program which will exit when a certainnumber of occurences of any keystroke is read.
• You need arrays• Loops• Loops with logical operations and so on.
PSK, NSN, DK, VK – CS&E, IIT M 158
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• Once you learn it, your code is concise• Matter of taste
PSK, NSN, DK, VK – CS&E, IIT M 159
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 willuse and develop different set of functions
PSK, NSN, DK, VK – CS&E, IIT M 160
Modular Programming
Subprogramsfunctions in C, C++, procedures and functions in Pascalfacilitate modular programming
Overall task is divided into modulesEach module - a collection of subprograms
a subprogram may be invoked at several pointsA commonly used computation
hiding the implementationincorporating changes
easier
PSK, NSN, DK, VK – CS&E, IIT M 161
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 you area of study, create libraries.
• Functions for use in different software.• Say, functions for web services
PSK, NSN, DK, VK – CS&E, IIT M 162
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
PSK, NSN, DK, VK – CS&E, IIT M 163
Add function to your Program
• A program was a set of variables, andassignments 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 writestructured program composed of functions
PSK, NSN, DK, VK – CS&E, IIT M 164
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
PSK, NSN, DK, VK – CS&E, IIT M 165
Function template
Return-type function-name(argument declarations){
declaration and statementsreturn expression;
}
PSK, NSN, DK, VK – CS&E, IIT M 166
Function Definition in Creturn-type function-name (argument declarations){ variable/constant declarations and
statements }Arguments or parameters:
the means of giving input to the functiontype and name of arguments are declared
names are formal - local to the function
Return Value: for giving the output valuereturn ( expression ); -- optional
Invoking a function: funct-name(exp1,exp2,…,expn)
Matching thenumber and typeof arguments
No functiondeclarations here!
PSK, NSN, DK, VK – CS&E, IIT M 167
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
PSK, NSN, DK, VK – CS&E, IIT M 168
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 withargumentsA block
PSK, NSN, DK, VK – CS&E, IIT M 169
Calling Power Function with i=3printf(“%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;
}
int power (int base, int n) {int i, p = 1;for ( i = 1; i <= n ; i ++)
p = p ∗ base;return p;
}
27-64
PSK, NSN, DK, VK – CS&E, IIT M 170
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 adifferent file
• Each module will have a separate associated header filewith the variable declaration global to that module
• You could compile each module separately and a .o filewill be created
• You can then cc the differnet .o files and get an a.out file• This helps you to debug each module separately
PSK, NSN, DK, VK – CS&E, IIT M 171
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 slower
than in the case of a long big program
• The issue now with data associated with otherfunctions.
• Typically functions communicate using thearguments and return values
PSK, NSN, DK, VK – CS&E, IIT M 172
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
– achieved by passing the “address of” variables
PSK, NSN, DK, VK – CS&E, IIT M 173
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
PSK, NSN, DK, VK – CS&E, IIT M 174
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 returnanything
Passingaddresses
PSK, NSN, DK, VK – CS&E, IIT M 175
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; }
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
The base case exp = 1Guarantees termination
PSK, NSN, DK, VK – CS&E, IIT M 176
Factorial (n)
• n! = 1 * 2 * 3 * .... * (n-2) * (n-1) * nIterative 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 maynot be enough!
PSK, NSN, DK, VK – CS&E, IIT M 177
Factorial (n) – recursive program
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 178
Pending computations
• In this recursive version the calling version still has pending work afterit gets the return value.
(fact 4)4 * (fact 3)
3 * (fact 2)2 * (fact 1)1
2*1 =23*2 = 6
4*6 = 24
int fact(int n){if (n == 1) return 1;
return n * fact(n - 1);}
It needs to savesome values for
future use
PSK, NSN, DK, VK – CS&E, IIT M 179
Tail recursion
int fact(n){ return fact_aux(n, 1); }
int fact_aux(int n, int result){if (n == 1) return result;return fact_aux(n - 1, n * result)}
The recursive callis in the returnstatement. Thefunction simplyreturns what itgets from the callit makes. Thecalling versiondoes not havesave any values!
Auxiliary variable
PSK, NSN, DK, VK – CS&E, IIT M 180
scanf and getchar
• getchar() reads and returns one character• scanf – formatted input, stores in variable
– scanf returns an integer = number of inputs itmanaged 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 181
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 thevariable and leave ZZZ in the buffer.
• The next read statement will get ZZZ and mayignore the actual input!
• One may need to write a statement to clear thebuffer…
while (getchar() != '\n'); This reads and ignores input till the end of line.
PSK, NSN, DK, VK – CS&E, IIT M 182
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 beforereading again
from <http://cprogramming.com>
PSK, NSN, DK, VK – CS&E, IIT M 183
Experiments with numbers1
The Collatz problem asks if iterating
always returns to 1 for positive α. The membersof the sequence produced by the Collatz problemare sometimes known as hailstone numbers.
From Wolfram Mathworldhttp://mathworld.wolfram.com/CollatzProblem.html
PSK, NSN, DK, VK – CS&E, IIT M 184
Hailstone numbers
• A Hailstone Sequence is generated by a simplealgorithm.Start with an integer N. If N is even, the nextnumber in the sequence is N / 2. If N is odd, thenext 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… 210
PSK, NSN, DK, VK – CS&E, IIT M 185
Exercise : Write a program to accept an input and count the number ofiterations needed to get to 1, and the highest number reached. Generate a tableof results…
Mathematical Recreationshttp://users.swing.be/TGMSoft/hailstone.htm