Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Announcements
Monday lab scheduled on 22nd August will instead be held on Saturday, 27th August from 2:00 PM to 5:00 PM. Wednesday lab scheduled on 31st August will instead be held on Saturday, 3rd September from 2:00 PM to 5:00 PM. Quiz on lab days from 5th to 9th September in Lab at 2:00 PM.
Lec-13
Recap
Arrays y Two dimensional arrays
Lec-13
Functions
Function is a part of the program that carries out a specific, specific well-defined task. A function has some inputs, better known as arguments and an output, better known as result or return value A program may consist of any number of functions. Any function can call (or use) any other function. We have been writing only one function so far (called, main).
We have used functions, such as, printf, scanf, sqrt, etc.
Lec-13 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 3
Modular code
Easy to understand
It is easy to understand 5 programs of 20 lines each rather than one program of 100 lines.
Lec-13
Function - Syntax
<return-type> Function-name (type1 arg1, type2 arg2, , typen argn) Function-name is the name of the function.
This name is needed to use or call this piece of program. We have to follow the same naming convention as for any variable.
Function carries out some activity and has a result, which is returned to the caller of this function.
The type of this result has to be specified.
Lec-13 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 5
Function (contd.)
Functions are called from other functions as:
variable = function_name (argument list) i bl f ti ( t li t)
Example:
int sum (int a, int b) { return (a + b); } z = sum (x, y);
Lec-13
Functions (contd.)
It is not necessary for functions to return anything. anything
In such cases, the return type can be void
Lec-13
// Read an integer and store it in x // Read an integer and store it in y // Call sum function with parameters x, y // Print z, which stores the return value of sum // Function declaration two integer arguments // Return value is also an integer R t l i l i t // Need some memory area in this function // Compute the sum // Return the sum
Lec-13
// Print initial values of x and y // Expectation is that x and y will be swapped // If x and y are swapped, opposite values // should be printed, but does not happen.
10
Parameter Passing
C follows call by value parameter passing scheme:
Only values are passed to the arguments Changes to arguments in the function do not affect the callee
We will, later, find a way to ensure that changes in the function arguments are reflected in the parameters at callee.
Lec-13
11