






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: Header, Files, Scope, Identifiers, Functions, Reference, Value, Call, Declaration, Definition, Frequent, Prototypes, Calculation, Code, Block
Typology: Study notes
1 / 11
This page cannot be seen from the preview
Don't miss anything!







Deitel & Deit l – C++e How to Program Chapter 3 , 3.
Header Files Scope of Identifiers
and other is Definition. Declaration can also be called as 'Prototype'.
the
file
t file with '.h' extension ('.h' a rule of good programming practice).
Functions
You have already been using a header file from day-zero. You know that we used to write at the top before the start of the main() function , with ‘.h’ as an extension, you might have got the idea that it is a header file.
Now we will see why a Header file is used.
In the previous lecture, we discussed a little bit about Function Prototypes. One thing is Declaration Normally, if we have lot of functions and want to use them in some other function or program, then we are left with only one way i.e. to list the prototypes of all of them before the body of the function or program and then use them inside the function or program. But for frequent functions inside a program, this technique increases complexity (of a program). This problem can be overcome by putting all these function prototypes in one file and writing a simple line of code for including the in the program. This code line will indicate that this is the file, suppose 'area.h' containing all the prototypes of the used functions and see the prototypes from that file. This is the basic concept of a header file.
So what we can do is: Make our own header file which is usually a simple tex extension is not mandatory but it is
ction rototy es inside that file. (Recall that prototype is just a simple line of ode co ing return value, function name and an argument list of data types with emi-colon at the end.) ncluded in your own program by using the ‘#include’ directive and plicitly writing that list of function prototypes.
unction prototypes are not the only thing that can be put into a header file. If you
a and given a name like 'pi': double pi = 3.1415926;
his eaningful name ‘pi’ can be used in all calculations instead of writing the horrendous
here are some preprocessor directives which we are going to cover later. At the he constants using this reprocessor directive as:
15926
a funny thing as it is not creating a variable. Rather it associates a ame with a value which can be used inside the program exactly like a variable. (Why e you can’t use it on the left hand side of any assignment.). short hand, what actually happens. You defined the value of the ‘pi’ en started using ‘pi’ symbol in your program. Now we the program after the writing ess. Wherever it finds the symbol ‘pi’, replaces the symbol with the value
tion process the symbols or constants are replaced with actual values f them. But for us as human beings, it is quite readable to see the symbol ‘pi’. meaningful names for variables and see a line ‘2 * pi * radius’, us that circumference of a circle is being calculated. Note that in the bove s teme id not define any ed ‘pi’ and ‘radius’ but defining 2 would be over killing.
cope of Identifiers
e that the user creates in his/her program. These names of an identifier means its of Variables in our discussion.
Write fun p p c ntain s That file can be i that would be similar to ex
F remember that we wrote a program for calculating Area of a Circle in our previous lectures. We used the value of 'pi' inside that and we have written the value of 'pi' as 3.1415926. This kind of facts are considered as Universal Constants or Constants within our domain of operations. It would be nice, if we can assign meaningful names to them. There are two benefits of doing this. See, We could have declared variable of type double inside the program
Then everywhere in the subsequent calculations we can use 'pi'. But it is better to pre-define the value of the constant in a header file ( one set for all) and simply including that header file, the constant ‘pi’, is defined. Now, t m number 3.1415926 again and again.
T moment, we will discuss about ‘#define’ only. We define t p
#define pi 3.
The above line does n it is not a variable?, becaus Basically, it is a with ‘#define’ directive and th will see what a compiler does when it is handed over proc 3.1415926 and finally compiles the program. Thus, in compila o Additionally, if we use it becomes obvio a ta nt, ‘2 * pi * radius’; 2 is used as a number as we d constant for it. We have defin
An 'Identifier' means any nam can be of variables, functions and labels. Here the scope visibility. We will focus Scope
docsity.com
hat will happen if we use the same names of variables at both function level scope nd inn level scope? Consider the following code:
ne
. void increment() . { . int num; //Function level scope
um; //Bad practice, not recommended
. num ++; //inner num is incremented
a er block
Li 1 2 3
4....
Note that there is no compilation error if the variable of the same name ‘num’ is declared at line 6 inside the inner code block (at block level scope). Although , there no error in naming the variables this way, yet this is not recommended as this can
hich variable is being used at line 8? The answer is the ‘num’ variable declared for k (at block level scope). Why is so? It is just due to the fact that the uter variable ‘num’ (at function level scope) is hidden in the inner code block as ere is a local variable of the same name. So the local variable ‘num’ inside the inner ode block over-rides the variable ‘num’ in the outer code block.
emember, the re-use of a variable is perfectly alright as we saw in the code snippet ’ variable inside the inner code block. But re-declaring a ariable of the same name like we did for variable ‘num’ in the inner code block, is a
a variable only once and then use it inside all ilar task when we wrote a function prototype of all the functions. The same thing applies to declaration of ariabl. You essible ns of that file. Notice that we have just used a new word ‘file’. file or a source code file with extension ‘.c’ or ‘.cpp’ can have many functions one main() function maximum and rest of the functions as
. If you want a variable to be accessible from within all functions, e body of any function like the following code red such a variable ‘size’ below.
include
is create confusion and decrease readability. It is better to use different names for these variables.
W inner code bloc o th c
R above while using ‘outer v bad practice.
Now, is there a way that we declare functions. We have already done a sim outside the body v es declare variables outside of a function body (so that variable declarations are not part of any function) and they become visible and acc inside all functio A inside. A file will contain many as required you declare the variable outside th snippet has decla
... // Declare your global variables here
docsity.com
or ut it oes have some pitfalls. You may inadvertently change the value of the variable ‘size’ cause your program to behave
essence, we should take care of three levels of scopes associated with identifiers:
//Declare your global variables here
out << “\n” << “Back in main(), the value of i is: “ << i;
i; i = 20;
int size;
... int main {
}
Now, this ‘size’ is visible in all functions including main(). We call this as 'file scope variable' or a 'global variable'. There are certain benefits of using global variables. F example, you want to access the variable ‘size’ from anywhere in your program b d considering it a local variable of the function and differently or affect your program logic.
Hence, you should try to minimize the use of global variables and try to use the local variables as far as possible. This philosophy leads us to the concept of Encapsulation and Data Hiding that encourages the declaration and use of data locally.
In global scope, function level scope and block level scope.
Let's take a look of very simple example of global scope:
#include
int i;
i = 10; cout << “\n” << “In main(), the value of i is: “ << i; f(); c }
void f() { cout << “\n” << ”In f(), the value of i is: “ <<
}
Note the keyword ‘void’ here, which is used to indicate that this function does not
n main(), the
return anything.
The output of the program is: I value of i is: 10 In f(), the value of i is: 10
main()
docsity.com
cout << “\n” << “ In f(), the value of i is: “ << i;
void f (int i) { i *= 2;
}
The output of this program is as under: In main(), the value of i is: 10 In f(), the value of i is: 20 Back in main(), the value of i is: 10
alue of the variable ‘i’ inside function main() did not value.
some values we want to pass on to the function for further processing, it ake a copy of those values , put it somewhere else and ask the processing. The original one with us will be ecure.
y value, which is bit more relevant. Suppose we ant to write a function that does the square of a number. In this case, the number can cision number as seen below:
ouble);
oid main()
num = 123.456;
C' does not have built-in mathematical operators to perform square, square root, log and trigonometric functions. The C language compiler comes along a complete library
As the output shows the v change, it proves the point that the call was made by
If there are will be better to m function to take that copy to use for its s
Let's take another example of call b w be a double pre
#include
double square (d
v { double num;
cout << “\n” << “ The square of “ << num << “ is “ << square(num); cout << “\n” << “ The current value of num is “ << num; }
double square (double x)
return x*x; }
docsity.com
e
mber, these functions are not built-in ones but library is supplied with the C- ompiler. It may be of interest to you that all the functions inside ‘’ are ions,
on and a result is returned back, based on the calculation on that copy.
able. Let's consider the square(double) function again, this time we
lt, on the contrary to the ‘Call by Value’, it affected the calling functions original variable. So these kinds of functions are ‘Call by Reference’ functions.
Let us see, what actually happens inside Call by Reference? As apparent from the name ‘By Reference’, we are not passing the value itself but some form of reference or address. To understand this, you can think in terms of variables which are names of memory locations. We always access a variable by its name (which in fact is accessing a memory location), a variable name acts as an address of the memory location of the variable.
If we want the called function to change the value of a variable of the calling function, we must pass the address of that variable to the called function. Thus, by passing the address of the variable to the called function, we convey to the function that the number you should change is lying inside this passed memory location, square it and put the result again inside that memory location. When the calling function gets the control back after calling the called function, it gets the changed value back in the same memory location.
In summary, while using the call by reference method, we can’t pass the value. We have to pass the memory address of the value. This introduces a new mechanism which is achieved by using ‘&’ (ampersand) operator in C language. This ‘&’ operator is used to get the address of a variable. Let's look at a function, which actually is a modification of our previous square() function.
#include
double x; x = 123.456; cout << “\n” << “ In main(), before calling square(), x = “ << x; square(&x); //Passing address of the variable x
for that. All the prototypes of those functions are inside ‘’. In order to use any of the functions declared inside ‘’, the following line will be added.
#includ
Reme c called by value. Whatever variable you will pass in as an argument to these funct nothing will happen to the original value of the variable. Rather a copy is passed to the functi
Now, we will see why Call by Reference is used. We would like to use 'call by reference' while using a function to change the value of the original vari want the original variable ‘x’ to be squared. For this purpose, we passed a variable to the square() function and as a resu
void square(double *);
main() docsity.com
Let us take simple example of x^10 , how will we calculate it? There are many ways of m a simple perspective, we can say that by definition x^10 = x * x 9.^ So
o compute it, we can always write a program to take the power of some number.
teger ‘n’ is defined as:
(n-1)! = (n-1) * (n-2)!
n)
return 1; else n * fact(n-1); }
e iterative functions and constructs we have udied until now. So the question is: do we need to use recursive functions? Yes, it e of the function but there is a huge price to pay for this. s use may lead to the problems of having memory overhead. There may also be stacking overhead as lots of function calls are made. A lot of functions can be written without recursion (iteratively) and more efficiently.
So as a programmer, you have an option to go for elegant code or efficient code, sometimes there is a trade-off. As a general rule, when you have to make a choice out of elegance and efficiency, where the price or resources is not an issue, go for elegance but if the price is high enough then go for efficiency.
doing it. But fro what is x^9? It is x^9 = x * x 8 and so on.
We can see the pattern in it: xn^ = x * xn-
T How to do it? The power function itself is making recursive call to itself. As a recursive function writer, you should know where to stop the recursive call (base case). Like in this case, you can stop when the power of x i.e. n is 1 or 0.
Similarly, you can see lot of similar problems like Factorials. A factorial of a positive in n! = (n) * (n-1) * (n-2) * ….. * 2 * 1
Note that n! = (n) * (n-1)! and
This is a clearly a recursive behavior. While writing a factorial function, we can stop recursive calling when n is 2 or 1.
long fact(long { if (n <= 1)
return
Note that there are two parts (branches) of the function: one is the base case ( which indicates when the function will terminate) and other is recursively calling part.
All the problems can be solved using th st adds little elegance to the cod It
docsity.com
‘C’ language facilitates us for recursive functions like lot of other languages but not all computer languages support recursive functions. Also, all the problems can not be solved by recursion but only those, which can be separated out for base case, not iterative ones.
Tips
Header file is a nice mechanism to put function prototypes and define constants (global constants) in a single file. That file can be included simply with a single line of code. There are three levels of scopes to be taken care of, associated with identifiers: global scope, function level scope and block level scope. For Function calling mechanism, go for ‘Call by Value’ unless there is a need of ‘Call by Reference’. Apply the recursive function where there is a repetitive pattern, elegance is required and there is no resource problem.
docsity.com