A Critique of the Proposed National Education Policy Reform
Lec1- CS110 Computational Engineering
1. CS110
Computational Engineering
An Introduction to
Problem Solving using Computers
V. Kamakoti
Course Material – P.Sreenivasa Kumar, N.S.Narayanaswamy, Deepak Khemani, V. Kamakoti– CS&E, IIT M
1
2. Common uses of a Computer
• As a tool for storing and retrieving information
– Extracting and storing information regarding students
entering 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
2
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
3
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
4
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
5
6. 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
PSK, NSN, DK, VK – CS&E, IIT M
6
7. 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.
PSK, NSN, DK, VK – CS&E, IIT M
7
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
8
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
9
10. Early Computing Hardware
The Slide rule
The Chinese Abacus
The gear replaced the beads in
early mechanical calculators
“History of computing hardware”
From Wikipedia, the free encyclopedia
PSK, NSN, DK, VK – CS&E, IIT M
10
12. The Difference Engine
Part of Babbage's difference
engine, assembled after his
death by Babbage's son, using
parts found in his laboratory.
The London Science Museum's
replica Difference Engine, built
from Babbage's design.
PSK, NSN, DK, VK – CS&E, IIT M
12
13. The First Programmer
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.
The programming language ADA is named after her.
PSK, NSN, DK, VK – CS&E, IIT M
13
14. ENIAC – the first electronic computer
Physically, ENIAC was
massive compared to modern
PC standards. It contained
17,468 vacuum tubes, 7,200
crystal diodes, 1,500 relays,
70,000 resistors, 10,000
capacitors and around 5
million hand-soldered joints.
It weighed 30 short tons (27 t),
was roughly 8 feet (2.4 m) by
3 feet (0.9 m) by 100 feet (30
m), took up 1800 square feet
(167 m²), and consumed 150
kW of power.
PSK, NSN, DK, VK – CS&E, IIT M
14
16. The computing machine
PROCESSOR
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.
PSK, NSN, DK, VK – CS&E, IIT M
16
17. The computing machine
PROCESSOR
MEMORY
01234…….
program
256 MEGABYTES
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
18. 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 ?
PSK, NSN, DK, VK – CS&E, IIT M
18
19. The middle-square method
John von Neumann devised the method
in 1946.
Take any number, square it, remove the
middle digits of the resulting number
as your "random number", then use
that number as the seed for the next
iteration. For example, squaring the
number "1111" yields "1234321",
which can be written as "01234321",
an 8-digit number being the square of
a 4-digit number. This gives "2343"
as the "random" number. Repeating
this procedure gives "4896" as the
next result, and so on. Von Neumann
used 10 digit numbers, but the
process was the same.
Considered by many to be the
greatest scientist of the 20th
century!
PSK, NSN, DK, VK – CS&E, IIT M
19
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 predetermined
size – “word”. A byte is made of 8 bits.
PSK, NSN, DK, VK – CS&E, IIT M
20
21. 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
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 imperative
programs.
PSK, NSN, DK, VK – CS&E, IIT M
22
23. 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
• Logic programs use logical inference as the basis of
computation.
• Prolog
• Functional programs take a mathematical approach of
functions.
• LISP, ML, Haskell
PSK, NSN, DK, VK – CS&E, IIT M
23
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
24
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 a
System designer. Why?
PSK, NSN, DK, VK – CS&E, IIT M
25
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
27
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.html
Make sure your machine has Adobe Acrobat
Reader
PSK, NSN, DK, VK – CS&E, IIT M
28
29. 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
Computer Software:
- collection of instructions to the computer
PSK, NSN, DK, VK – CS&E, IIT M
29
30. Software
Very critical component in a computer application
Considerable 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
30
32. The Blocks, Their Functions
• Input unit
Takes inputs from the external world via
variety of input devices- keyboard, mouse,
temperature sensors, odometers, wireless
Devices 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
32
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 store
user data (programs, inputs, results etc.), also used
extensively during computation.
PSK, NSN, DK, VK – CS&E, IIT M
33
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
34
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
35
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 strings
To represent data. Simplifies the usage of a computer.
PSK, NSN, DK, VK – CS&E, IIT M
36
37. Compilers
Human friendly languages source code
Source code in a
Higher Level Language
Source code in a
Higher Level Language
Compiler
Compiler
Assembly language code
Assembler, linker, loader
machine language code
Machine understandable language
PSK, NSN, DK, VK – CS&E, IIT M
37
38. 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
39. Higher Level Languages
• 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
• HLLs can be at many levels
PSK, NSN, DK, VK – CS&E, IIT M
39
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
40
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 UNIX
The C Programming Language- Kernighan, Ritchie, 1978
•ANSI C: a standard adopted in 1990
– unambiguous, machine-independent definition of C
The C Programming Language (2nd edition)- Kernighan,
Ritchie, 1988
PSK, NSN, DK, VK – CS&E, IIT M
41
42. Developing and using a C program
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
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
42
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 memory
6. Execute:
– computer carries out the instructions of the program
PSK, NSN, DK, VK – CS&E, IIT M
43
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 be
executed by the computer – much faster, and as many
times as you want.
PSK, NSN, DK, VK – CS&E, IIT M
44
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 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
46. A tiny program
A comment
/* 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
PSK, NSN, DK, VK – CS&E, IIT M
Escape sequence - newline
printf - a function from C Standard library stdio.h
- prints a char string on the standard output46
47. Programming Basics
(vi, emacs for programs)
• 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
48. Variables and constants
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)
- first character must be a letter
avoid underscore as the first letter ( some library fns use it)
- choose meaningful and self-documenting names
for constants as well as variables
- keywords - if, for, else, float etc - reserved
PSK, NSN, DK, VK – CS&E, IIT M
48
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 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
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 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
51. Variables need Declaration
1
2
3
4
5
6
7
8
9
Another simple C program
#include<stdio.h>
A function
main()
from stdio.h
{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 bytesn”,
int_size, chr_size; flt_size);
}
PSK, NSN, DK, VK – CS&E, IIT M
51
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 of
a quadratic and prints out its roots
PSK, NSN, DK, VK – CS&E, IIT M
52
53. Modifying Variables
(rm with –i option)
• 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.
PSK, NSN, DK, VK – CS&E, IIT M
53
54. An addition program
#include <stdio.h>
main( )
Declarations, must precede use
{
int operand1, operand2, sum;
“ %d ” - conversion
specifier
printf(“Enter first operandn”);
scanf(“%d”, &operand1);
d - decimal
printf(“Enter second operandn”);
& - address of operand1
scanf(“%d”, &operand2);
sum = operand1 + operand2;
assignment
printf(“The sum is %dn”, sum);
return 0;
Returning a 0 is used to
}
signify normal termination
PSK, NSN, DK, VK – CS&E, IIT M
54
55. Arithmetic operators in C
Four basic operators
+, – , ∗ , /
addition, subtraction, multiplication and division
applicable to integers and floating point numbers
integer division - fractional part of result truncated
12/ 5 2,
5/9 0
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
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
56
57. 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
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/false
order of evaluation - as given above
note: assignment ( = ) equality ( = = )
PSK, NSN, DK, VK – CS&E, IIT M
58
59. Increment and decrement operators
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
60. 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) )
PSK, NSN, DK, VK – CS&E, IIT M
60
61. 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
PSK, NSN, DK, VK – CS&E, IIT M
61
62. 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
enclosed in double quotes
PSK, NSN, DK, VK – CS&E, IIT M
62
63. Examples - output
int x; float y;
x = 20; y = – 16.7889;
printf(“Value x = %d and value y = %9.3fn”, 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
64. 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
65. 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
66. Conversion Specifiers for “scanf”
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
PSK, NSN, DK, VK – CS&E, IIT M
66
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;
PSK, NSN, DK, VK – CS&E, IIT M
b2 – 4ac
68
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 also
output.
Summary: Variables are modified as the program
runs.
PSK, NSN, DK, VK – CS&E, IIT M
69
70. 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
PSK, NSN, DK, VK – CS&E, IIT M
70
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 intermediate
variables, how they are calculated from input
values, and output variables.
PSK, NSN, DK, VK – CS&E, IIT M
71
72. 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
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
73
74. Completing the program
if (discrim < 0)
{
printf(“no real roots, only complexn”);
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
75. 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
76. 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
77. 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
78. An Example
{ int i, j, k;
i = 1; j =2; k =3;
if ( expr ) {
int i, k;
}
…
}
PSK, NSN, DK, VK – CS&E, IIT M
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
79. Selection Statements
Three forms
single selection:
if ( att < 75 ) grade = “W”;
Note: There is no
then reserved word
double selection:
if (marks < 40 ) passed = 0;
else passed = 1;
/* false = 0 */
/* true = 1 */
multiple selection:
switch statement - to be discussed later
PSK, NSN, DK, VK – CS&E, IIT M
79
80. If Statement
if (<expression>) <stmt1> [ else <stmt2>]
Semantics:
optional
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
PSK, NSN, DK, VK – CS&E, IIT M
80
81. 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
82. 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”);
PSK, NSN, DK, VK – CS&E, IIT M
82
83. 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
84. Counting Evens and Odds
int num, eCount = 0, oCount = 0;
Counts the number of
scanf (“%d”, &num);
even and odd integers
in the input.
while (num >= 0) {
Terminated by giving a
switch (num%2) {
negative number
case 0 : eCount++; break;
case 1 : oCount++; break;
}
Defensive programming !
scanf (“%d”, &num);
}
printf( “Even: %d ,Odd: %dn”, eCount, oCount);
PSK, NSN, DK, VK – CS&E, IIT M
84
85. Fall Through’s
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
A feature requiring exercise of caution
PSK, NSN, DK, VK – CS&E, IIT M
85
86. 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
PSK, NSN, DK, VK – CS&E, IIT M
86
87. 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?)
PSK, NSN, DK, VK – CS&E, IIT M
87
88. Exercise in using printf
(try banner word)
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
89. 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
90. Repetition Structure - While
Syntax – while (condition is true){ evaluate this piece of
code}
Print powers of 2 till 2N
#include<stdio.h>
#include<math.h>
main()
{ int n, counter, value;
printf(“ value for n – “);
scanf(“%d”, &n);
counter = 0;
value = 1;
contd..
PSK, NSN, DK, VK – CS&E, IIT M
90
91. Program using while
counter = 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
91
92. 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
93. 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
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
94
95. 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
96. Simple example of for statement
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
-- involving the loop control variable only
PSK, NSN, DK, VK – CS&E, IIT M
96
97. 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%21sn”, “year”, “Amount in the deposit”);
for (year = 1; year < = 10; year++) {
amount = principal * pow(1.0 + rate, year);
printf(“%4d%21.2fn”, year, amount);
}
}
PSK, NSN, DK, VK – CS&E, IIT M
97
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
98
99. 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
x = 56342
x = 5634
x = 563
x = 56
x=5
x=0
Termnation condition:
Stop when x becomes zero
99
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 );
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
101. Perfect number detection
Perfect : sum of proper divisors add up to the number.
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
102. 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
103. Square root of a number
main( ) {
How do you solve the equation “x = n2” ?
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
104. Newton–Raphson 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
105. Sequence and Selection Structures
t
If Structure
f
Single Entry
Single Exit
f
Sequence
Structure
PSK, NSN, DK, VK – CS&E, IIT M
t
If/Else Structure
105
107. Structured Programming
To produce program that are
– easier to develop, understand, test, modify
– easier to get correctness proof
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
109. 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
110. 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
111. Example(kernighan & ritchie, p.59)
#include<stdio.h>
An array of ten integers
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;
PSK, NSN, DK, VK – CS&E, IIT M
111
113. 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.
PSK, NSN, DK, VK – CS&E, IIT M
113
114. 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
115. Exercise – week starting Feb 5
Read a text file and report the following,
1. The total number of non-white characters
2. The total number of words
3. The average length of a word
4. The mode length of a word
5. The total number of lines
6. The average length of a line
7. The length of the longest line
Any assumptions your program makes must be stated
in the comments. What if lines are logical ending with
appropriate punctuation?
PSK, NSN, DK, VK – CS&E, IIT M
115
116. 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)
- the value of marks[2] is 75
- new values can be assigned to elements
marks[3] = 36;
PSK, NSN, DK, VK – CS&E, IIT M
22
0
15
1
75
2
56
3
10
4
33
5
45
6
116
117. Example using arrays
Read five numbers into an array and compute their average
numbers[] is initialized
#include <stdio.h>
during declaration
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 */
}
PSK, NSN, DK, VK – CS&E, IIT M
117
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
118
119. 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
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
119
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 %dn”, x, value);
}
PSK, NSN, DK, VK – CS&E, IIT M
120
121. Multi-dimensional Arrays
Arrays with two or more dimensions can be defined
A[4][3]
0
1
2
0
0
2
3
2
1
2
1
0
1
1
B[2][4][3]
2
0
3
0
PSK, NSN, DK, VK – CS&E, IIT M
1
121
122. Two Dimensional Arrays
Declaration: int A[4][3] : 4 rows and 3 columns, 4 × 3 array
Elements: A[i][j] - element in row i and column j of array A
A[4][3]
0
1
2
0
1
2
3
PSK, NSN, DK, VK – CS&E, IIT M
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
124. 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
Should perform :
Read; Write; Initiliazation; Multiplication;
PSK, NSN, DK, VK – CS&E, IIT M
124
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
125
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
126
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++)
Remember
scanf("%d", &b[i][j]);
bRows must
equal aCols
c is a aRows x bCols matrix
/* 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
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
129
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 operations
desired
PSK, NSN, DK, VK – CS&E, IIT M
130
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 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
132. 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
134. Binary, Octal and Hexadecimal
The internal representation of binary, octal, and
hexadecimal numbers is similar
Octal - 2
7
3
2
5
6
0
6
Binary - 010111011010101110000110
Hexadecimal -
PSK, NSN, DK, VK – CS&E, IIT M
5
5
13
D
10 11 8
A B 8
6
6
134
135. A funny infinite loop - arithmetic
This program of mine, ran into an infinite loop. I only
wanted to find which numbers corresponded to which
characters, the significance of signed and unsigned
characters, basically relationship between which
integers can be printed as characters we recognize.
Why did the infinite loop happen, how to avoid it?
#include<stdio.h>
Print it as a
Print it as a
main()
character
decimal number
{char c;
for(c=-128; c <= 127; c++) printf(“%d -- %c n”, c, c);
}
PSK, NSN, DK, VK – CS&E, IIT M
Try omitting one parameter…
135
136. 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.
PSK, NSN, DK, VK – CS&E, IIT M
136
137. 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
138. 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
139. Overflow in integers…
#include <stdio.h>
int main() {
int i = 2147483647;
unsigned int j = 4294967295;
printf("%d %d %dn", i, i+1, i+2);
printf("%u %u %un", 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
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 can
represent. Beyond this number it starts all
over again.
PSK, NSN, DK, VK – CS&E, IIT M
140
141. Printing directives
#include <stdio.h> int main() {
unsigned int un = 3000000000;
/* system with 32-bit int */
printf("un = %u and not %dn", un, un);
return 0; }
un = 3000000000 and not -1294967296
Both have the same
internal representation
PSK, NSN, DK, VK – CS&E, IIT M
141
142. Printing directives
#include <stdio.h> int main() {
short end = 200;
/* and 16-bit short */
printf("end = %hd and %dn", end, end);
return 0; }
short decimal
end = 200 and 200
Printing a short decimal as
a normal is okay
PSK, NSN, DK, VK – CS&E, IIT M
142
143. Printing directives
#include <stdio.h> int main() {
long big = 65537;
printf("big = %ld and not %hdn", 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
144. Printing directives
#include <stdio.h> int main() {
long long verybig = 12345678908642;
printf("verybig= %lld and not %ldn", verybig,
verybig);
64 bits
Truncated 32 bits
return 0; }
verybig= 12345678908642 and not 1942899938
PSK, NSN, DK, VK – CS&E, IIT M
144
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 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
146. Characters – escape sequences
a
b
f
n
r
t
v
alert (bell)
backspace
formfeed
newline
carriage return
horizontal tab
vertical tab
PSK, NSN, DK, VK – CS&E, IIT M
?
’
”
ooo
xhh
backslash
question mark
single quote
double quote
octal number
hexadecimal
Non-printable characters
146
147. 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
PSK, NSN, DK, VK – CS&E, IIT M
147
148. Enumerated Constants
• enum boolean {No, Yes}
By default enum
type begin with 0
– 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
PSK, NSN, DK, VK – CS&E, IIT M
148
149. 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
PSK, NSN, DK, VK – CS&E, IIT M
149
150. 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
151. 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
152. 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
153. 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
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 the
element in the i-th row and j-th coloumn
PSK, NSN, DK, VK – CS&E, IIT M
154
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
155
156. How to use these in a program
• They are used when composite conditions are to
be tested in decision statements.
– For(I=0;I < lim – 1 && (c = getchar()) != ‘n’ && c !=EOF; I++) s[I] = c;
• The loop is executed as long as the test
conditions is true
• Which is while all the test conditions are true
• The loop is exited when the test condition
becomes 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
156
157. 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.
PSK, NSN, DK, VK – CS&E, IIT M
157
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
158
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 will
use and develop different set of functions
PSK, NSN, DK, VK – CS&E, IIT M
159
160. Modular Programming
Subprograms
functions in C, C++, procedures and functions in Pascal
facilitate modular programming
Overall task is divided into modules
Each module - a collection of subprograms
a subprogram may be invoked at several points
A commonly used computation
hiding the implementation
incorporating changes
easier
PSK, NSN, DK, VK – CS&E, IIT M
160
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
161
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
162
163. 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
PSK, NSN, DK, VK – CS&E, IIT M
163
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
164
166. 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
Return Value: for giving the output value
return ( expression ); -- optional
Matching the
number and type
of arguments
Invoking a function: funct-name(exp1,exp2,…,expn)
PSK, NSN, DK, VK – CS&E, IIT M
166
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
167
168. 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 %dn”, 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
168
169. Calling Power Function with i=3
printf(“%d %d %dn”, i, power(3,i), power(-4,i);}
-64
27
int power (int base, int n) {
int i, p = 1;
for ( i = 1; i <= n ; i ++)
p = p ∗ base;
return p;
}
PSK, NSN, DK, VK – CS&E, IIT M
int power (int base, int n) {
int i, p = 1;
for ( i = 1; i <= n ; i ++)
p = p ∗ base;
return p;
}
169
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 a
different file
• Each module will have a separate associated header file
with the variable declaration global to that module
• You could compile each module separately and a .o file
will be created
• You can then cc the differnet .o files and get an a.out file
• This helps you to debug each module separately
PSK, NSN, DK, VK – CS&E, IIT M
170
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 other
functions.
• Typically functions communicate using the
arguments and return values
PSK, NSN, DK, VK – CS&E, IIT M
171
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
172
173. Call by Value - an example
main( ) {
Function prototype
int p = 1, q = 2, r = 3, s;
int test(int, int, int);
Function call
…;
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);
}
PSK, NSN, DK, VK – CS&E, IIT M
Function definition
173
174. 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
174
175. Recursive Function Example
int power (int num, int exp) {
int p;
if (exp = = 1) return num;
p = power(num, exp/2);
if (exp % 2 = = 0) return p*p;
else return p*p*num;
}
The base case exp = 1
Guarantees termination
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
175
176. 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
In practice int may
not be enough!
176
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
177
178. Pending computations
• In this recursive version the calling
version still has pending work after
it gets the return value.
int fact(int n)
{
if (n == 1) return 1;
return n * fact(n - 1);
}
(fact 4)
4 * (fact 3)
It needs to save
some values for
future use
3 * (fact 2)
2 * (fact 1)
1
2*1 =2
3*2 = 6
4*6 = 24
PSK, NSN, DK, VK – CS&E, IIT M
178
179. Tail recursion
int fact(n)
{ return fact_aux(n, 1); }
Auxiliary variable
int fact_aux(int n, int result)
{
if (n == 1) return result;
return fact_aux(n - 1, n * result)
}
PSK, NSN, DK, VK – CS&E, IIT M
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!
179
180. 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 %dn", i, j);
else printf ("You failed to enter 2 numbersn");
from <http://cprogramming.com>
PSK, NSN, DK, VK – CS&E, IIT M
180
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 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
181
182. Code to insist on one number only
#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 %dn", temp);
return(0); }
from <http://cprogramming.com>
PSK, NSN, DK, VK – CS&E, IIT M
182
183. Experiments with numbers1
The Collatz problem asks if iterating
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
183
184. 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
2
184