C programming language
Chapter 4 Functions
c function can be classified into two categories namely:
1. Library function
2.User-defined functions.
main() is a example of user defined function. printf and scanf belong to a the category of library function.
2.User-defined functions :
There are times when some type of operation or calculation is repeated at many points throughout a program. In such situation we may repeat the program statements whenever they are needed. Another approach is to design a function that can be called and used whenever required. This saves both time and space.
A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories.
1. Function with no arguments and no return values :
When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value. the calling function does not receive any data from the called function. In effect, there is no data transfer between the calling function and the called function. In fig. the dotted lines indicate that there is only a transfer of control but not data.
Example :
#include<stdio.h>
main()
{
void sqr();
sqr();
}
void sqr()
{
int no;
printf("Enter no : ");
scanf("%d",&no);
printf("sqr is %d",no*no);
}
2. Function with arguments and no return values :
The function receives data from the calling function through arguments, but does not send back any value. Such functions will have one-way data communitcation.The actual and formal arguments should match in number, type , and order.
Example :
#include<stdio.h>
main()
{
void sqr(int no);
int n;
printf("\n Enter no : ");
scanf("%d",&n);
sqr(n);
}
void sqr(int no)
{
printf("sqr is %d",no*no);
}
3. Function with arguments and return values :
The function value in fig receives data from the calling function through arguments. And send a value to calling function. Such functions will have two-way data communication.
Example:
#include<stdio.h>
main()
{
int sqr(int no);
int s,n;
printf("\n Enter no : ");
scanf("%d",&n);
s=sqr(n);
printf("sqr is %d",s);
}
int sqr(int no)
{
return(no*no);
}
Recursion :
When a called function in turn calls another function a process of 'chaining' occurs. Recursion is a special case of this process, where a function calls itself. A very simple example of recursion presented below :
main() | |
{ | |
printf(" Cdac computer centre"); | |
main(); | |
}\ | |
When executed, this program will produce an output something like this :
Cdac computer centre Cdac computer centre Cdac computer centre Cdac computer centre Cdac computer centre Cdac computer centre Cdac computer centre......
Execution is terminated abruptly.
Another useful example of recursion is the evaluation of factorials of given number.
/* Calculate factorial of given no. using recursion*/
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int fact(int m);
int n,factno;
printf("INPUT N :");
scanf("%d",&n);
factno=fact(n);
printf("factorial = %d",factno);
getch();
}
int fact(int n)
{
if(n>1)
return(n*fact(n-1));
else
return(1);
}
Posted by
Rozy Munshi
Chapter 3 Arrays
A array is a group of related data items that share a common name.
One - Dimensional Arrays :
A list of items can be given one variable name using only one subscript and such variable is called singled subscripted variable or a one-dimensional array. The subscript(index) begin with number 0 (zero)
The general form of one-d array declaration is :
Type array_name [size];
Ex :
int x [5];
x[0] |
| |||||
x[1] | ||||||
x[2] | ||||||
x[3] | ||||||
x[4] |
The general form of initialization of array :
int x[5] = {1,2,3,4,5};
x[0] |
| |||||
x[1] | ||||||
x[2] | ||||||
x[3] | ||||||
x[4] |
/* To find out the sum of given 10 numbers. using arrays */
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],i,sum=0;
clrscr();
for(i=0;i<10;i++)
{
printf("\n enter the number : ");
scanf("%d",&a[i]);
sum = sum+a[i];
}
printf("\n sum is : %d",sum);
getch();
}
Two - Dimensional Arrays :
There will be situations where a table of values will have to be stored. The general form of declared two-dimensional array :
type array_name [row] [col];
Ex :
int a[3][4];
| a[3][4] | 0 | 1 | 2 | 3 | cols | ||||||||||||
| 0 | |||||||||||||||||
| 1 | |||||||||||||||||
| 2 | |||||||||||||||||
| rows | |||||||||||||||||
initialization of 2-D array :
int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,1,2,3}};
| a[3][4] | 0 | 1 | 2 | 3 | cols | ||||||||||||
| 0 |
| ||||||||||||||||
| 1 | |||||||||||||||||
| 2 | |||||||||||||||||
| rows | |||||||||||||||||
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n enter matrix a:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\n enter matrix b:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\n sum of given matrix is :\n");
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(" %3d",c[i][j]);
printf("\n");
}
getch();
}
Multi - Dimensional Arrays :
c allows arrays of three or more dimensions. the exact limit is determined by compiler. The general form of a multi dimensional array is
type array_name [s1][s2][s3]...[sm];
Posted by
Rozy Munshi
Chapter 1 Elementary Programming
Chapter 1 Elementary Programming
The structure of a simple program :
Documentation Section | ||
Link Section | ||
Definition Section | ||
Global Declaration Section | ||
main() | Function Section | |
{ | ||
Declaration Part | ||
Executable Part | ||
} | ||
Subprogram function | ||
function1 | (User define function) | |
function2 | ||
..... | ||
functionn | ||
The documentation section consists of a set of comment lines giving the name of the program, the author and other details which the programmer would like to use later. | |
The link section provides instruction to the compiler to link function from the system library. | |
The definition section defines all symbolic constants. | |
There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. | |
Every C program must have one main() function. This section contains two parts, declaration part and executable part. The declaration parts declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. | |
The subprogram section contains all the user-defined functions that are called in the main function. | |
All section, except main function section may be absent when they are not required. |
Example :
#include <stdio.h>
main()
{
printf(" Welcome to C programming \n");
}
#include <stdio.h>
main()
{
printf(" Welcome to C programming \n");
}
Output :
Welcome to C programming
Posted by
Rozy Munshi
chapter7 Extra topoic
Inline function :
One of objectives of using functions is to save some memory space, which becomes apperciable when a function is likely to be called many times. However, every time a function is called , it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function. When a function is small, a substantial percentage of execution time may be spent in such over heads.
C++ has a different solution to this problem. To eliminate the cost of calls to small function, c++ proposes a new feature calledinline function. An inline function is a function that is expanded in line when it is invoked. That is , the compiler replaces the function call with the corresponding function code. The inline functions are defined as follows :
inline function-header | |
{ | |
function body | |
} | |
Example :
inline double cube(double a) | |
{ | |
return(a*a*a) | |
} | |
The above inline function can be invoked by statements like :
c= cube(3.5);
d=cube(2.5+4.5);
Usually, the functions are made inline when they are small enough to be defined in one or two lines.
Some of the situations where inline expansion may not work are :
1. For functions returning values, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exists.
3. If functions containg static variables.
4. if inline functions are recursive.
Block in c++ are ofter nested.
Block 2 is contained in block1. Note that a declaration in an inner block hides a declaration of the same variablein an outer block and therefore, each declaration of x causes it to reger to a different data object. Whitin the inner block, the variable x will refer to the data object declared therein.
In c, global version of a variable cannot be accessed from within the inner block. c++ resolves this problem by introducing a new operator :: scope resolution operator. This can be used to uncober a hidden variable. It takes the following form
:: variable_name
This operator allows access to the global version of a variable.
Memory management operators :
In c++ two unary operators new and delete that perform the task of allocating and freeing the memory.
new :
The new operator can be used to create objects of any type. It takes the following form :
pointer-variable = new data-type ; |
Here, pointer-variable is a pointer of type data-type. The new operator allocates sufficient memory to hold a data object of type data-type and returns the address of the object. The data-type may be any valid data-type. The pointer-variable holds the address of the memory space allocated.
Example :
int *p = new int;
float *q = new float;
*p = 25;
*q = 7.5;
We can also initialize the memory using the new operator. This is done as follows :
pointer-variable = new data-type(value); |
Here , value specifies the initial value.
Examples :
int *p = new int(25);
float *q = new float(7.5);
New can be used to create a memory space for any data type includeing user-defined type such as array, structrues and classes.The general form for a one-dimensional array is :
pointer-variable = new data-type[size]; |
Here, size specifies the number of elements in array.
Example :
Example :
int *p= new int[10];
creates a memory space for an array of 10 integers.
delete:
When a data object is no longer needed, it is destroyed to release the memory space for reuse. The general form of its use is :
delete pointer-variable; |
The pointer-variable is the pointer that points to a data object created with new.
Example :
delete p;
delete q;
If you we want to free a dynamically allocated array, we must use the following form of delete :
delete [size] pointer-variable; |
Call by references :
In traditional c, a function call passes arguments by value. The called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of values.
Provision of the reference variable in c++ permits us to pass parameters to the functions by reference. When we pass arguments by reference, the 'formal' arguments in the called function become aliases to the 'actual' arguments in the calling function. This means that when the function is working its own arguments, it is actually working on the original data. consider the following function.
| void swap(int & a, int & b) | |
| { | |
| int t=a; | |
| a=b; | |
| b=t; | |
| } | |
Now, if m and n are two integer variables, then function call
swap(m,n);
will exchange the values of m and n using their aliases (reference variables) a nd b.
Return by reference :
A function can also return a reference. consider the following function :
| int & max(int & x, int & y) | ||
| { | ||
| if (x>y) | ||
| return x; | ||
| else | ||
| return y; | ||
| } | ||
Since the return type of max() is int &, the function returns reference to x or y (and not the values).Then a function call such as max(a,b) will yield a reference to either a or b depending on their values. This means that this function call can appear on the left-hand side of an assignment statement. That is, the statement
max(a,b)=-1;
is legal and assigns -1 to a if it is larger, otherwise -1 to b.
Default Arguments :
c++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. Here is an example of a prototype with default values :
float amount(float principal, int period, float rate=0.15);
The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declares a default value of 0.15 to the argument rate. A subsequent function call like
value = amount(5000,7) // one argument missing
passes the 5000 to principal and 7 to period and then lets the function use default values of 0.15 for rate. The call
value= amount(5000,5,0.12); // no missing argument
passes an explicit value of 0.12 to rate.
One important point to note is that only the trailing arguments can have default arguments can have default values. That is, we must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. Default arguments are useful in situations where some arguments always have the same value.
Posted by
Rozy Munshi
chapter 6 Files
Classes for file stream operations :
The I/O system of c++ contains a set of classes that define the file handling methods. These include ifstream,ofstream andfstream. These classes are derived from fstreambase and from correspoinding iostream.h class. These classes, designed to manage the disk files, are declared in fstream.h and therefore we must include this file in any program that uses files.
| class | contents | |
| filebuf | Its urpose is to set the file buffers to read and write. | |
| fstreambase | Provides operations common to the file streams. | |
| ifstream | Provides input operations. | |
| ofstream | Provides output operations. | |
| fstream | Provides support for simulatneous input and ourput operations. |
Posted by
Rozy Munshi
chapter 5 Inheritance
Inheritance :
C++ strongly supports the concept of reusability. The c++ classes can be reused in several ways. Once a class has been written and tested, it can be adopted by other programmers to suit their requirements. This is basically done by creating new classes, reusing the properties of the existing ones. The mechanism of deriving a new class from old one is called inheritance (orderivation). The old class is referred to as the base class and the new one is called the derived class.
Various Forms of inheritance :
1. | Single inheritance : A derived class with only one base class is called single inheritance. |
2. | A derived class with several base classes is called multiple inheritance. A class can inherit the attributes of two or more classes as shown in Fig. This know as multiple inheritance. Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of another. |
3. | Hierarchical inheritance : One class inherited by more than one base class is called Hierarchical inheritance. |
4. | The mechanism of deriving a class from another 'derived class' is known as multilevel inheritance. It is not uncommon that a class is derived from another derived class as show fig. The class A serves as a base class for the derived class B which is turn serves as a base class for the derived class C.The class B is known as intermediate base class since it provides a link for the inheritance between A and C.The chain ABC is known as inheritance path. A derived class with multilevel inheritance is declared as follows : class A { ...... }; class B : public A { ...... }; class C: public B { ...... }; This process can be extended to any number of levels. |
5. | There could be situation where we need to apply two or more types of inheritance to design a program. We just discussed a situation which would require the use of both the multiple and multilevel inheritance. Consider a situation where all the three kinds of inheritance, namely, multilevel, multiple and hierarchical inheritance, are involved. This illustrated in fig. The 'child' has two direct base classes 'parent1' and 'parent2' which themselves have a common base class 'grandparent'. The 'child' inherits the traits of 'grandparent' via two separate paths. It can also inherit directly as shown by the broken line. The 'grandparent' is sometimes referred to as indirect base class. Inheritance by the 'child' as shown in fig. might pose some problems. All the public and protected members of 'grandparent' are inherited into 'child' twice, first via 'parent1' and again via 'parent2'. This means 'child' would have duplicate sets of the members inherited from 'grandparent'. This introduces ambiguity and should be avoided. The duplication of inherited members due to these multiple paths can be avoided by making the common base class (ancestor class) as virtual base class while declaring the direct or intermediate base classes . |
Posted by
Rozy Munshi
Subscribe to:
Posts (Atom)