Subscribe to our RSS Feeds
Hello, this is a sample text to show how you can display a short information about you and or your blog. You can use this space to display text or image introduction or to display 468 x 60 ads and to maximize your earnings.

File

0 Comments »

Overview of functions

Most of the C file input/output functions are defined in stdio.h (cstdio header in C++).

Byte
character
Wide
character
Description
File access fopen opens a file
freopen opens a different file with an existing stream
fflush synchronizes an output stream with the actual file
fclose closes a file
setbuf sets the buffer for a file stream
setvbuf sets the buffer and its size for a file stream
fwide switches a file stream between wide character I/O and narrow character I/O
Direct
input/output
fread reads from a file
fwrite writes to a file
Unformatted
input/output
fgetc
getc
fgetwc
getwc
reads a byte/wchar_t from a file stream
fgets fgetws reads a byte/wchar_t line from a file stream
fputc
putc
fputwc
putwc
writes a byte/wchar_t to a file stream
fputs fputws writes a byte/wchar_t string to a file stream
getchar getwchar reads a byte/wchar_t from stdin
gets N/A reads a byte string from stdin (deprecated in C99, obsoleted in C11)
putchar putwchar writes a byte/wchar_t to stdout
puts N/A writes a byte string to stdout
ungetc ungetwc puts a byte/wchar_t back into a file stream
Formatted
input/output
scanf
fscanf
sscanf
wscanf
fwscanf
swscanf
reads formatted byte/wchar_t input from stdin,
a file stream or a buffer
vscanf
vfscanf
vsscanf
vwscanf
vfwscanf
vswscanf
reads formatted input byte/wchar_t from stdin,
a file stream or a buffer using variable argument list
printf
fprintf
sprintf
snprintf
wprintf
fwprintf
swprintf
prints formatted byte/wchar_t output to stdout,
a file stream or a buffer
vprintf
vfprintf
vsprintf
vsnprintf
vwprintf
vfwprintf
vswprintf
prints formatted byte/wchar_t output to stdout,
a file stream, or a buffer using variable argument list
perror N/A writes a description of the current error to stderr
File positioning ftell returns the current file position indicator
fgetpos gets the file position indicator
fseek moves the file position indicator to a specific location in a file
fsetpos moves the file position indicator to a specific location in a file
rewind moves the file position indicator to the beginning in a file
Error
handling
clearerr clears errors
feof checks for the end-of-file
ferror checks for a file error
Operations
on files
remove erases a file
rename renames a file
tmpfile returns a pointer to a temporary file
tmpnam returns a unique filename

2:45 AM

Structures

0 Comments »

Structures
Structure is a mechanism that provides a means to aggregate variables of different type. Thus a single structure might contain integer elements, floating-point elements, and character elements. Pointers, arrays, and other structures can also be included as elements within a structure. The individual structure elements are referred to as members.
Unlike structure, the array is a mechanism that provides a means to aggregate variables of similar type. That is, all elements in the array are of same data type.
Defining/Declaring a Structure
Structure declarations are somewhat more complicated than array declarations, since a structure must be defined in terms of its individual members. Its general form is given below:
struct structurename {
            member 1;
            member 2;
            ..........
            memver m;
};

Here, struct is a keywork, structurename is a name of the structure, and member 1, member 2,…, member m are individual members.
These individual members can be ordinary variables, arrays, pointers, or other structures. The member names within a particular structure must be distinct from one another, though a member name can be the same as the name of a variable that is defined outside the structure. A storage class (e.g. auto, extern, static, or register) cannot be assigned to an individual member, and individual members cannot be initialized within a structure.
Once the composition of the structure has been defined, individual structure-type variables can be declared as follows:
storage-class struct structurename variable 1, variable 2, …, variable n;
Here, storage-class is optional, struct is a required keyword, structurename is the name that appeared in the structure declaration, and variable 1, variable 2,…, variable n are structure variables of type structurename.
For example, a typical structure declaration is shown below. This structure is named account (i.e., the structurename account). It contains four members: an integer quantity (acct_no), a single character (acct_type), an 80-element character array (name[80]), and a floating-point quantity (balance).
struct account {
int acct_no;
            char acct_type;
            char name[80];
            float balance;
};
We can now declare the structure variables oldcustomer and newcustomer as follows:
struct account oldcustomer, newcustomer;
It is also possible to combine the declaration of the structure composition with that of the structure variables, as shown below:
storage-class struct structurename {
            member 1;
            member 2;
            ..........
            memver m;
} variable 1, variable 2, …, variable n;
In this situation, storage-class and structurename are optional. For example,
struct account {
int acct_no;
            char acct_type;
            char name[10];
            float balance;
} oldcustomer, newcustomer;
OR
struct {
int acct_no;
            char acct_type;
            char name[10];
            float balance;
} oldcustomer, newcustomer;
A structure variable may be defined as a member of another structure. A structure that contains other structures as members is called nested structure. In such situations, the declaration of embedded structure must appear before the declaration of the outer structure. For example,
struct date {
            int month;
            int day;
            int year;
};
struct account {
            int acct_no;
            char acct_type;
            char name[10];
            float balance;
            struct date lastpayment;
};
struct account oldcustomer, newcustomer;
The members of a structure variable can be assigned initial values in much the same manner as the elements of an array. The initial values must appear in the order in which they will be assigned to their corresponding structure members, enclosed in braces and separated by commas. The general form is:
storage-class struct structurename variable = {value 1, value 2, …, value m};
Here, value 1 refers to the value of the first member, value 2 refers to the value of the second member, and so on. For example,
struct date {
            int month;
            int day;
            int year;
};
struct account {
int acct_no;
            char acct_type;
            char name[10];
            float balance;
            struct date lastpayment;
};
account customer = {1234, 'C', "Nawaraj", 1234.7, {5, 24, 90}};
It is also possible to define an array of structures; i.e., an array in which each element is a structure. For example,
struct date {
            int month;
            int day;
            int year;
};
struct account {
            int acct_no;
            char acct_type;
            char name[10];
            float balance;
            struct date lastpayment;
};
struct account customer[100];
An array of structures can be assigned initial values just as any other array. For example,
struct account customer[] = {{1234, 'C', "Nawaraj", 1234.7, {5, 24, 90}}, {4567, 'C', "Ram", 1034.5, {12, 24, 99}}};
Processing a Structure
The members of a structure are processed (accessed) as separate entities using period (.) that separates variable name from the member name. Its general form is:
variable.member
Here, variable refers to the name of a structure-type variable, and member refers to the name of a member within the structure. For example,

struct date {
            int month;
            int day;
            int year;
};
struct account {
int acct_no;
            char acct_type;
            char name[10];
            float balance;
            struct date lastpayment;
};
struct account customer;
Now, you can access acct_no using customer.acct_no, acct_type using customer.acct_type, name using customer.name, balance using customer.balance, month using customer.lastpayment.month, day using customer.lastpayment.day, and year using customer.lastpayment.year.
For arrays of structures, we write
array[index].member
For example,
struct account customer[100];
Now, you can access acct_no using customer[i].acct_no, acct_type using customer[i].acct_type, name using customer[i].name, balance using customer[i].balance, month using customer[i].lastpayment.month, day using customer[i].lastpayment.day, and year using customer[i].lastpayment.year.
A Complete Example
Program to display customer information of customers having balance greater than 1000 using previous structures.
#include<stdio.h>
#include<conio.h>
#define N 100
void main() {
            struct date {
                        int month;
                        int day;
                        int year;
            };
            struct account {
                        int acct_no;
                        char acct_type;
                        char name[10];
                        float balance;
                        struct date lastpayment;
            };
            struct account customer[N];
            int n,i;
            clrscr();
            printf("How many customers:");
            scanf("%d",&n);
            for(i=0;i<n;i++) {
                        printf("\nEnter data for customer %d:\n",i+1);
                        printf("Enter account number:");
                        scanf("%d",&customer[i].acct_no);
                        printf("Enter account type:");
                        scanf(" %c",&customer[i].acct_type);
                        printf("Enter name:");
                        scanf(" %[^\n]",customer[i].name);
                        printf("Enter balance:");
                        scanf("%f",&customer[i].balance);
                        printf("Enter month:");
                        scanf("%d",&customer[i].lastpayment.month);
                        printf("Enter day:");
                        scanf("%d",&customer[i].lastpayment.day);
                        printf("Enter year:");
                        scanf("%d",&customer[i].lastpayment.year);
            }
            printf("\nCustomers having balance greater than 1000:\n");
            for(i=0;i<n;i++) {
                        if(customer[i].balance > 1000) {
                                    printf("Account number: %d\n",customer[i].acct_no);
                                    printf("Account type: %c\n",customer[i].acct_type);
                                    printf("Name: %s\n",customer[i].name);
                                    printf("Balance: %f\n",customer[i].balance);
                                    printf("Month: %d\n",customer[i].lastpayment.month);
                                    printf("Month: %d\n",customer[i].lastpayment.day);
                                    printf("Month: %d\n",customer[i].lastpayment.year);
}
            }
            getch();
}
Structures and Pointers
We can use pointers with structure variables in the same manner as any other variables. For example,
struct account {
            int acct_no;
            char acct_type;
            char name[10];
            float balance;
};
struct account customer, *pc;
pc = &customer;
In this example, customer is a structure variable of type account, and pc is a pointer to customer.
An individual structure member can be accessed in terms of its corresponding pointer variable by using -> operator. For example,
scanf("%d", &pc->acct_no);
Note: A structure may include one or more pointers as its members. For example,
struct account {
            int *acct_no;
            char *acct_type;
            char *name;
            float *balance;
};
Passing Structures to Functions
We can pass structure variables to a function by passing a structure type pointer as an argument. A structure passed in this manner will be passed by reference rather than by value. Hence, if any of the structure members are altered within the function, the alteration will be recognized outside the function. For example,
#include<stdio.h>
#include<conio.h>
struct account {
int acct_no;
            char acct_type;
            char name[10];
            float balance;
};
void main() {
struct account customer;
            void update(struct account *pt);
            clrscr();
            printf("Enter account number:");
            scanf("%d",&customer.acct_no);
printf("Enter account type:");
            scanf(" %c",&customer.acct_type);
            printf("Enter name:");
            scanf(" %[^\n]",customer.name);
            printf("Enter balance:");
            scanf("%f",&customer.balance);
            update(&customer);
            printf("Account number: %d\n",customer.acct_no);
            printf("Account type: %c\n",customer.acct_type);
            printf("Name: %s\n",customer.name);
            printf("Balance: %f\n",customer.balance);
            getch();
}
void update(struct account *pt) {
            pt->balance = pt->balance * 1.07;
}
Note: Newer version of C also permit an entire structure to be transferred directly to a function as an argument and returned directly from a function via a return statement. Here, the transfer is by value rather than by reference. Therefore, if any of the structure members are altered within the function, the alteration will not be recognized outside the function.
Self-referential Structure
It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type. Hence, a structure which contains a reference to itself is called self-referential structure. In general terms, this can be expressed as:
struct structurename {
            member 1;
            member 2;
            …….
            struct structurename *name;
};
For example,
struct list_element {
            int item[40];
struct list_element *next;
}
This is a structure of type list_element. The structure contains two members: a 40-element integer array called item, and a pointer to a structure of the same type (i.e., a pointer to a structure of type list_element), called next. Therefore this is a self-referential structure.

Unions
Unions, like structures, contain members whose individual data types may differ from one another. However, the members within a union all share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique storage area. Thus, unions are used to conserve memory. They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time. In general terms, the composition of a union may be defined as
union unionname {
            member 1;
            member 2;
            …..
            member m;
};
Here, union is a required keyword and the other terms have the same meaning as in a structure definition. Individual union variables can then be declared as:
storage-class union unionname variable 1, variable 2, …, variable n;
Here, storage-class is optional, union is a required keyword, unionname is the name that appeared in the union definition, and variable 1, variable 2, …, variable n are union variable of type unionname. For example,
union id {
            char color[12];
            int size;
};
union id shirt, blouse;
Here, we have two union variables, shirt and blouse, of type id. Each variable can represent either a 12-character string (color) or an integer quantity (size) at any one time.
Two declarations may be combined, just as we did with structures. Thus, we can write it as follows:
storage-class union unionname {
            member 1;
            member 2;
            …..
            member m;
} variable 1, variable 2, …, variable n;
3:51 PM

Introduction to Program and Programming Language

0 Comments »


Introduction to Program and Programming Language
If you want to get something done by a person, you will tell him what to do in a language that he understands. Similarly, if you want to make the computer to do some task for you, you have to tell the computer what to do in a language the computer understands. Hence, the programming language is a set of rules that provides a way of instructing the computer to perform certain operations.
            A program is a set of instructions written in a specific programming language that a computer can interpret and execute. A computer requires programs to function.
            Programming languages are said to be lower to higher, depending on whether they are closer to the language the computer itself uses (lower, which means 0s and 1s) or to the language that people use (higher, which means more English like). Here, we will consider following groups of languages:
1.      Machine Language / First-generation Language
2.      Assembly Language / Second-generation Language
3.      High-level Language
a.         Procedural and Object-oriented Language / Third-generation Language
b.      Problem-oriented Language / Fourth-generation Language
c.          Natural language /Fifth-generation Language
Machine Language
It is the lowest level of programming language. In this language, information is represented as 0s and 1s. This programming is very tedious and time consuming. A programmer must keep track of a tremendous amount of detail. Programming in machine code has one advantage over programming at other language level – its execution is very fast and efficient because the computer can accept the machine code as it is. Since there is no standard machine language, a program written in machine language for one computer model may not on different model computer.
Assembly Language
In the 1950s, to reduce programming complexity and provide some standardization, assembly languages were developed. Assembly languages, also known as symbolic languages use abbreviations or mnemonic code – codes more easily memorized – to replace the 0s and 1s machine language. For example, ADD and SUB for addition and subtraction operations.
            For an assemble language program to be executed, it must be translated to machine code. This translation is done by translators called assemblers. The program before translation, the assembly language program, is called a source program and the program after translation, the machine language program, is an object program. Assembly language offers several advantages:
·         Standard and easier to use than machine language.
·         Operate very efficiently, although not as efficient as the machine languages.
·         Easier to debug because programs locate and identify syntax errors
However, there are still some disadvantages:
·         Programs are usually very long.
·         Programs are still complex.
·         Assembly languages are still machine-dependent.
High-level Language
High level languages are simple and easy to understand. These languages assist programmers by reducing further the number of computer operation details they had to specify, so that they could concentrate more on the logic needed to solve the problem. There are three different types of high-level languages:
  • Procedural and Object-oriented language: These languages are general purpose programming languages. Procedural programming is a type of programming where a structured method of creating programs is used. With procedure-oriented programming, a problem is broken up into parts and each part is then broken up into further parts. All these parts are known as procedures. They are separate but work together when needed. A main program centrally controls them all. Some procedure-oriented languages are COBOL, FORTRAN, and C.
Object-oriented programming is the newest and most powerful paradigms. Object-oriented programming requires the designer to specify the data as well as the operations to be applied on those data as a single unit. The pairing of data and the operations that can be done on it is called an object. A program made using this language is therefore made up of a set of cooperating objects instead of an instructions list. Some examples are C++, Java, and Smalltalk.
These languages have many advantages over machine and assembly languages. These are listed below:
    • Program statements resemble English and hence are easier to work with.
    • Less time is required to program a problem.
    • Programs are easier to understand and modify.
    • Programming languages are machine-independent.
However, these languages still have some disadvantages compared to machine and assembly languages:
    • Programs execute more slowly.
    • These languages use computer resources less efficiently.
  • Problem-oriented language: These languages are designed to solve specific problems or develop specific applications by enabling you to describe what you want rather than step-by-step procedures. These languages are categorized into several kinds of application development tools as given below:
    • Personal computer applications software like word processors, spreadsheets, database managers etc.
    • Query languages and report generators like SQL (Structured Query Language, QBE (Query by Example) etc. to search a database using certain selection commands.
    • Decision support systems that help managers to make decisions and financial planning languages.
    • Application generators to develop a particular application without writing detail logic.
  • Natural language: Natural languages are used in the areas of artificial intelligence and expert systems. These languages are used to make computers more humanlike and allow the computer to become smarter. That is, simulate the learning process by remembering and improving upon earlier information. Two popular natural languages are LISP and PROLOG.
Compilers and Interpreters
For a high level language to work on the computer it must be translated into machine language. There are two kinds of translators – compilers and interpreters. So, high level languages are called compiled and/or interpreted languages.
In a compiled language, a translation program is run to convert the programmer’s entire high-level program, which is called the source code, into a machine language code. This translation process is called compilation. The machine language code is called the object code and can be saved and either run (executed) immediately or later. Some of the most widely used compiled languages are COBOL, C, C++, FORTAN etc.
In an interpreted language, a translation program converts each program statement into machine code just before the program statement is to be executed. Translation and execution occur immediately, one after another, one statement at a time. Unlike compiled languages, no object code is stored and there is no compilation. The most frequently used interpreted language is BASIC.
Some languages are both compiled and interpreted. One popular such language is JAVA.
Program Design
Before writing computer programs we can use different tools to design it. This design helps the programmer to write computer programs more easily, correctly, and quickly. Some most useful program design tools are: algorithm, flowchart, and pseudocode.
Algorithm
An algorithm is a finite sequence of instructions for solving a stated problem. A stated problem is a well-defined task that has to be performed and must be solvable by an algorithm.  The algorithm must eventually terminate, producing the required result. For example, the following algorithm can be used to compute interest given the values of p, n, and r.
  1. Enter the values of p, n, and r.
  2. Calculate interest i using the formula p × n × r / 100.
  3. Display interest i as a result.
Properties of a good algorithm:
  • Input: A number of quantities are provided to an algorithm initially before the algorithm begins. These quantities are inputs which are processed by the algorithm.
  • Definiteness: The processing rules specified in the algorithm must be unambiguous and lead to a specific action.
  • Effectiveness: Each instruction must be sufficiently basic such that it can, in principle, be carried out in a finite time by a person with paper and pencil.
  • Finiteness: The total time to carry out all the steps in the algorithm must be finite.
  • Output: An algorithm must have output.
  • Correctness: Correct set of output must be produced from the set of inputs. For the same input, it must always produce the same output.


Flowchart
A flowchart is a common type of chart that represents an algorithm or a computer program showing the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields. A typical flowchart may have the following kinds of symbols.
  • Circles, ovals, or rounded rectangles: Usually containing the word "Start" or "End", or another phrase signaling the start or end of a process.
  • Arrows: Shows flow control. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.
  • Rectangle: Represents processing steps.
  • Parallelogram: Represents input and output.
  • Diamond: Represents condition or decision. These typically contain a Yes/No question or True/False test. This symbol is unique in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. The arrows should always be labeled.


For example, the flowchart to calculate simple interest (if balance is greater than or equal to 100000, interest is 5%, otherwise, interest is 3%) is given below:
Pseudocode
It is also called program design language (PDL) or structured English. It is a language and syntax for designing a computer program based on the relative strengths of structured programming and Natural English. At first glance, PDL looks like a modern programming language. The difference between PDL and a real programming language lies in the use of narrative text embedded directly within PDL statements. In pseudocode, we can use language constructs like IF, SWITCH, FOR, WHILE, and DO-WHILE along with Natural English. For example,
GET student’s grade
IF student’s grade is greater than or equal to 50
            PRINT “passed”
ELSE
            PRINT “failed”
ASCII
It is the acronym for the American Standard Code for Information Interchange. ASCII is a code for representing English characters as numbers, with each letter assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77. Most computers use ASCII codes to represent text, which makes it possible to transfer data from one computer to another.
Text files stored in ASCII format are sometimes called ASCII files. Text editors and word processors are usually capable of storing data in ASCII format, although ASCII format is not always the default storage format.
The standard ASCII character set uses just 7 bits for each character, meaning it can have 128 identifiers, two to the seventh power (27). There are several larger character sets that use 8 bits, which gives them 128 additional characters. The extra characters are used to represent non-English characters, graphics symbols, and mathematical symbols.
Text Editor
A text editor, such as Notepad, is an application program that can be used to create, view, edit, save, and print text files. Text files only contain plain text. These programs provide fewer formatting options than word processors. Text editors can be used to write computer programs or create other documents. Text editors are often provided with operating systems or software development packages.
Software (Information System) Development
Most organizations use a standard set of steps, called a systems development methodology to develop and support their information systems. It is a standard process followed in an organization to conduct all the steps necessary to analyze, design, implement, and maintain information systems. And systems development life cycle (SDLC) is the traditional methodology used to develop, maintain, and replace information systems. It includes different phases as shown in the figure below. This representation of SDLC is sometimes referred to as the waterfall model or classic life cycle.
  
Fig: The systems development life cycle

The first phase is called planning. In this phase, someone identifies the need for a new or enhanced system. These needs are then analyzed, prioritized and arranged into a plan for the information systems department. Here, a potential information systems project is explained and an argument for continuing or not continuing with the project is presented; a detailed plan is also developed for conducting the remaining phases of the SDLC for the proposed system.
The next phase is called analysis. During this phase, the analyst studies the current system and proposes alternative replacement systems. Here, the analyst thoroughly studies the organization’s current procedures and the information systems used to perform organizational tasks. The analyst work with users to determine what the users want from a proposed system. The analyst carefully studies any current systems, manual and computerized, that might be replaced or enhanced as part of this project. The analyst studies the requirements and structures them according to their interrelationships and eliminates any redundancies; generates alternative initial designs to match the requirements; compare these alternatives to determine which best meets the requirements within the cost, labor, and technical levels the organization is willing to commit to the development process. The output of this phase is a description of the recommended alternative solution. Once the recommendation is accepted by owners, you can begin to make plans to acquire any hardware and system software necessary to build or operate the system as proposed.
            The next phase is called design. During this phase, you convert the description of the recommended alternative solution into logical and then physical system specification. Here, you must design all aspects of the system form input and output screens to reports, databases, and computer processes. Logical design is the part of the design process that is independent of any specific hardware or software platform. Theoretically, the system could be implemented on any hardware and systems software. Physical design is the part of the design phase in which the logical specifications of the system form logical design are transformed into technology-specific details from which all programming and system construction can be accomplished.
The next phase is called implementation. In this phase, the information system is coded, tested, installed, and supported in the organization. During coding, programmers write the programs that make up the information system. During testing, programmers and analysts test individual programs and the entire system in order to find and correct errors. During installation, the new system becomes a part of the daily activities of the organization. Implementation activities also include initial user support such as the finalization of documentation, training programs, and ongoing user assistance.
            The final phase of SDLC is called maintenance. In this phase, information system is systematically repaired and improved. When a system is operating in an organization, users sometimes find problems with how it works and often think of better ways to perform its functions. Also the organization’s needs with respect to the system change over time. In maintenance, you make the changes that users ask for and modify the system to reflect changing business conditions.
3:48 PM

Pointers

0 Comments »

Pointers
A pointer is a variable that holds address (memory location) of another variable rather than actual value. Also, a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location.  So, a pointer variable points to a memory location and we can access and change the contents of this memory location via the pointer. Pointers are used frequently in C, as they have a number of useful applications. In particular, pointers provide a way to return multiple data items from a function via function arguments.
Pointer Declaration
Pointer variables, like all other variables, must be declared before they may be used in a C program. We use asterisk (*) to do so. Its general form is:
data-type *ptrvar;
For example,
int* ptr;
This statement declares the variable ptr as a pointer to int, that is, ptr can hold address of an integer variable.
Once we declare a pointer variable we can point by it to something. We can do this by assigning to the pointer the address of the variable you want to point as in the following example:
int var=11,*ptr;
ptr=&var;
This places the address where var is stores into the variable ptr. For example, if var is stored in memory 21260 address then the variable ptr has the value 21260.
We can access the contents of the variable pointed by pointer using an asterisk (*) in front of a variable name. For example,
int var=11,*ptr;
ptr=&var;
*ptr=45; //It changes the value of var to 45
Example:
#include<stdio.h>
#include<conio.h>
void main() {
            int var=11,*ptr;
            clrscr();
printf("%d\n",var); //prints 11
            printf("%d\n",&var); //prints address of var
printf("%d\n",*&var); //prints 11
            ptr=&var;
            printf("%d\n",ptr); //prints address of var
            printf("%d\n",*ptr); //prints 11
            *ptr=45;
            printf("%d\n",var); //prints 45
            printf("%d\n",*ptr); //prints 45
            getch();
}
The operator ‘&’ is called “address of” operator. The expression &var returns the address of the variable var. The operator ‘*’ called “value at address” operator. It gives the value stored at a particular address. The “value at address” operator is also called “indirection operator”.
Passing (call) by Value and Passing (call) by Reference
Arguments can generally be passed to functions in one of the two ways:
  • Sending the values of the arguments (pass by value)
  • Sending the addresses of the arguments (pass by reference)
Pass by value: In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. The following program illustrates ‘call by value’.
#include<stdio.h>
#include<conio.h>
void main()
{
            int a,b;
            void swap(int, int );
            clrscr();
            a = 10;
            b = 20;
            swap(a,b);
            printf("a = %d\tb = %d",a,b);
            getch();
}
void swap(int x, int y)
{
            int t;
            t = x;
            x = y;
            y = t;
            printf("x = %d\ty = %d\n",x,y);
}
The output of the above program would be
x = 20 y = 10
a = 10 b = 20
Note that values of a and b remain unchanged even after exchanging the values of x and y.
Pass by reference: In this method, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. The following program illustrates this fact.

#include<stdio.h>
#include<conio.h>
void main()
{
            int a,b;
            void swap(int*, int*);
            clrscr();
            a = 10;
            b = 20;
            swap(&a,&b);
            printf("a = %d\tb = %d",a,b);
            getch();
}
void swap(int *x, int *y)
{
            int t;
            t = *x;
            *x = *y;
            *y = t;
            printf("x = %d\ty = %d\n",*x,*y);
}
The output of the above program would be
x = 20 y = 10
a = 20 b = 10
Note: We can use call by reference to return multiple values from the function.
Pointers and Arrays
An array name by itself is an address, or pointer. A pointer variable can take different addresses as values. In contrast, an array name is an address, or pointer, that is fixed.
Pointers and One-dimensional Arrays
In case of one dimensional array, an array name is really a pointer to the first element in the array. Therefore, if x is a one-dimensional array, then the address of the first array element can be expressed as either &x[0] or simply x. Moreover, the address of the second array element can be expressed as either &x[1] or as (x+1), and so on. In general, the address of array element (x+i) can be expressed as either &x[i] or as (x+i). Thus we have two different ways to write the address of any array element: we can write the actual array element, preceded by an ampersand; or we can write an expression in which the subscript is added to the array name.
Since, &x[i] and (x+i) both represent the address of the ith element of x, it would seem reasonable that x[i] and *(x+i) both represent the contents of that address, i.e., the value of the ith element of x. The two terms are interchangeable. Hence, either term can be used in any particular situation. The choice depends upon your individual preferences. For example,
/* Program to read n numbers in an array and display their sum and average */
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
            float a[SIZE],sum=0,avg;
            int n,i;
            clrscr();
            printf("How many numbers?");
            scanf("%d",&n);
            printf("Enter numbers:\n");
            for(i=0;i<n;i++)
            {
                        scanf("%f",(a+i)); // scanf("%f",&a[i]);
                        sum=sum+*(a+i); //sum=sum+a[i];
            }
            avg=sum/n;
            printf("Sum=%f\n",sum);
            printf("Average=%f",avg);
            getch();
}
Pointers and Multidimensional Arrays
Since one-dimensional array can be represented in terms of a pointer, a multidimensional array can also be represented with an equivalent pointer notation. A two-dimensional array, for example, is actually a collection of one-dimensional arrays. Therefore, we can define a two-dimensional array as a pointer to a group of contiguous one-dimensional arrays.
Suppose x is a two-dimensional integer array having 10 rows and 20 columns. We can declare x as
int (*x)[20];
rather than
int x[10][20];
In the first declaration, x is defined to be a pointer to a group of contiguous, one-dimensional, 20-element integer arrays. Thus, x points to the first 20-element array, which is actually the first row (i.e., row 0) of the original two-dimensional array. Similarly, (x+1) points to the second 20 element array, which is the second row (row 1) of the original two-dimensional array, and so on. Now, we can access the element in row 2 (third row) and column 5 (sixth column) by writing either x[2][5] or *(*(x+2)+5). In general, we can access the element in row i and column j by writing x[i][j] or *(*(x+i)+j). For example,
#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 2
void main()
{
int a[ROW][COL],b[ROW][COL],i,j,sum;
            clrscr();
            printf("Enter elements of first matrix:\n");
            for(i=0;i<ROW;i++)
            {
                        for(j=0;j<COL;j++)
                                    scanf("%d",(*(a+i)+j));
                        printf("\n");
            }
            printf("Enter elements of second matrix:\n");
            for(i=0;i<ROW;i++)
            {
                        for(j=0;j<COL;j++)
                                    scanf("%d",(*(b+i)+j));
                        printf("\n");
            }
            printf("Addition matrix is:\n");
            for(i=0;i<ROW;i++)
            {
                        for(j=0;j<COL;j++)
                        {
                                                sum=*(*(a+i)+j)+*(*(b+i)+j);
                                    printf("%d\t",sum);
                        }
                        printf("\n");
            }
            getch();
}
Dynamic Memory Allocation
Dynamic memory allocation is the process of allocating memory in a program dynamically at run time. C provides two basic functions calloc() and malloc() for this purpose. The name calloc stands for “contiguous allocation” and the name malloc stands for “memory allocation”.
The programmer uses calloc() and malloc() to dynamically create space arrays, structures, and unions.
The function calloc() takes two arguments both of unsigned integral type. When we call this function, it allocates contiguous space in memory. For example,
/* Program to read n floating point numbers and display their sum and average using pointer and dynamic memory allocation*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
            float *a,sum=0,avg;
            int n,i;
            clrscr();
            printf("How many numbers?");
            scanf("%d",&n);
            a=(float*)calloc(n,sizeof(float));
            printf("Enter numbers:\n");
            for(i=0;i<n;i++)
            {
                        scanf("%f",(a+i)); //scanf("%f",&a[i]);
                        sum=sum+*(a+i); //sum=sum+a[i];
            }
            avg=sum/n;
            printf("Sum=%f\n",sum);
            printf("Average=%f",avg);
            free(a);
            getch();
}
In the above program a points to the first memory block in the allocated memory.
The programmer uses malloc() in a similar fashion. This function takes a single argument of unsigned integral type. For example,
a=(float*)mallocc(n*sizeof(float));
When we use calloc(), the space is initialized with all bits set to zero. Unlike, calloc(), the function malloc() does not initialize the space in memory that it makes available. In a large program, malloc() may take less time.
Space that has been dynamically allocated with either calloc() or malloc() does not destroyed automatically. The programmer must use free() explicitely to destroy it. For example,
free(a);
Operations on Pointers (Pointer Arithmetic)
Not all operations are applied for pointers. Permissible operations that can be applied for pointers are given below:
  1. A pointer variable can be assigned the address of an ordinary variable. For example, pv = &v, where pv is a pointer variable and v is an ordinary variable.
  2. A pointer variable can be assigned the value of another pointer variable provided both pointers point to objects of the same data type. For example, pv = px, where both pv and px are pointer variables of the same data type.
  3. A pointer variable can be assigned a null (zero) value. For example, pv = NULL, where NULL is a symbolic constant that represent the value zero and pv is a pointer variable.
  4. An integer quantity can be added to or subtracted from a pointer variable. For example, pv+3, ++pv etc. where pv is a pointer variable.
  5. One pointer variable can be subtracted from another provided both pointers point to elements of the same array.
  6. Tow pointer variables can be compared provided both pointers point to objects of the same data type.
Other arithmetic operations on pointers are not allowed. Thus, a pointer variable cannot be multiplied by constant; two pointer variables cannot be added; and so on.
Pointer Constant and Pointer to Constant
Pointer constant or constant pointer means the pointer is constant. For example, int *const ptr2 indicates that ptr2 is a pointer which is constant. This means that ptr2 cannot be made to point to another integer after it points to some integer. However the integer pointed by ptr2 can be changed. For example,
int a=2,b=3;
int *const ptr2 = &a;
ptr2=&b; //error
It is not a pointer to constant. A pointer to constant is written like
const int *ptr1. It indicates that ptr1 is a pointer that points to a constant integer. The integer is constant and cannot be changed. However, the pointer ptr1 can be made to point to some other integer constant. For example,
const int a=2;
const int *ptr2 = &a;
*ptr2=8; //error
3:45 PM