WELCOME
HAI FRIENDS...
THIS IS OUR BLOG,ADD YOUR POSTS HERE TO SHOW OUR CALIBER TO THE WHOLE WORLD.....
THIS IS OUR BLOG,ADD YOUR POSTS HERE TO SHOW OUR CALIBER TO THE WHOLE WORLD.....
Roads from plastic waste
The debate on the use and abuse of plastics vis-a-vis
environmental protection can go on, without yielding
results until practical steps are initiated at the grassroots
level by everyone who is in a position to do something
about it. The plastic wastes could be used in road
construction and the field tests withstood the stress and
proved that plastic wastes used after proper processing
as an additive would enhance the life of the roads
and also solve environmental problems. The present
write-up highlights the developments in using plastics
waste to make plastic roads.
Plastic is everywhere in today’s lifestyle. It is used for
packaging, protecting, serving, and even disposing
of all kinds of consumer goods. With the industrial
revolution, mass production of goods started and
plastic seemed to be a cheaper and effective raw
material. Today, every vital sector of the economy
starting from agriculture to packaging, automobile,
building construction, communication or infotech has
been virtually revolutionised by the applications of
plastics. Use of this non-biodegradable (according to
recent studies, plastics can stay unchanged for as long
as 4500 years on earth) product is growing rapidly and
the problem is what to do with plastic-waste. Studies
have linked the improper disposal of plastic to problems
Inventions With Impact
Polymers for chemical sensing and a process for alternative fuels reap prizes
Linda Wang
Two researchers whose inventions are making—or have the potential to make—a broad impact on society are being recognized with prestigious awards from the Lemelson-MIT Program.
Lemelson-MIT Program
DETECTING Swager demonstrates a handheld monitor that checks people, clothing, and automobiles for trace explosives.
Timothy M. Swager, the John D. MacArthur Professor of Chemistry and head of the chemistry department at MIT, is the winner of this year's $500,000 Lemelson-MIT Prize. The award recognizes Swager's development of highly sensitive semiconducting fluorescent polymers that can detect traces of chemicals found in explosives.
Swager's invention is widely used by American soldiers in Iraq to detect explosives. Specifically, it is being used in handheld monitors to check people, clothing, and automobiles for trace TNT.
Swager is now working on electrical resistance-based polymers that can detect changes in the levels of nitric oxide, an important indicator of a person's health. These sensors could be used by doctors, for example, as an early diagnostic of a respiratory infection.
Mascoma Corp.
LYND
COMMON REACTION MECHANISMS
A reaction mechanism is a series of smaller reactions that form an overall reaction. Substitutions and elimination reactions are very important in the study of organic chemistry mechanisms.[2]
[change]Unimolecular substitution (SN1)
A unimolecular substitution mechanism occurs in steps. First, an atom called the leaving group breaks away from a molecule, leaving the molecule with a positive electric charge. This intermediate is called a carbocation. Second, a nucleophile forms a chemical bond with the carbocation. If the nucleophile has a neutral charge, a third step is required. The third step uses a reagent to remove the positive charge. The shorthand symbol for unimolecular substitution is SN1.
[change]Bimolecular substitution (SN2)
In a bimolecular substitution, a nucleophile, which is a reagent that forms a chemical bond, replaces another atom attached to a molecule. The original atom is called the leaving group because it leaves the molecule. The bonding of the nucleophile and the departure of the leaving group are concerted and happen at the same time instead of one at a time. The shorthand symbol for a bimolecular substitution is SN2.
[change]Unimolecular elimination (E1)
The first step of a unimolecular elimination reaction is an atom, the leaving group, breaks away from a molecule. The loss of this atom forms an intermediate carbocation. Then a basic reagent attacks a hydrogen atom and forces a double bond. The reagent in an elimination reaction is a base. These are the same steps as in a bimolecular elimination, but they are not concerted and occur one at a time. The shorthand symbol for unimolecular elimination is E1.
[change]Bimolecular elimination (E2)
The reagent in an elimination reaction is a base. The base takes a proton from the leaving group, forcing electrons to form a double chemical bond and break the bond to the leaving group. Like bimolecular substitution, this is a concerted step. The shorthand symbol for bimolecular elimination is E2.
ENERGY
In the context of chemistry, energy is an attribute of a substance as a consequence of its atomic, molecular or aggregate structure. Since a chemical transformation is accompanied by a change in one or more of these kinds of structure, it is invariably accompanied by an increase or decrease of energy of the substances involved. Some energy is transferred between the surroundings and the reactants of the reaction in the form of heat or light; thus the products of a reaction may have more or less energy than the reactants. A reaction is said to be exergonic if the final state is lower on the energy scale than the initial state; in the case of endergonic reactions the situation is the reverse. A reaction is said to be exothermic if the reaction releases heat to the surroundings; in the case of endothermic reactions, the reaction absorbs heat from the surroundings.
Read More...
Chemical reactions are invariably not possible unless the reactants surmount an energy barrier known as the activation energy. The speed of a chemical reaction (at given temperature T) is related to the activation energy E, by the Boltzmann's population factor e − E / kT - that is the probability of molecule to have energy greater than or equal to E at the given temperature T. This exponential dependence of a reaction rate on temperature is known as the Arrhenius equation. The activation energy necessary for a chemical reaction can be in the form of heat, light, electricity or mechanical force in the form of ultrasound.[45]
A related concept free energy, which also incorporates entropy considerations, is a very useful means for predicting the feasibility of a reaction and determining the state of equilibrium of a chemical reaction, inchemical thermodynamics. A reaction is feasible only if the total change in the Gibbs free energy is negative, ; if it is equal to zero the chemical reaction is said to be at equilibrium.
There exist only limited possible states of energy for electrons, atoms and molecules. These are determined by the rules of quantum mechanics, which require quantization of energy of a bound system. The atoms/molecules in a higher energy state are said to be excited. The molecules/atoms of substance in an excited energy state are often much more reactive; that is, more amenable to chemical reactions.
The phase of a substance is invariably determined by its energy and the energy of its surroundings. When the intermolecular forces of a substance are such that the energy of the surroundings is not sufficient to overcome them, it occurs in a more ordered phase like liquid or solid as is the case with water (H2O); a liquid at room temperature because its molecules are bound by hydrogen bonds.[46] Whereas hydrogen sulfide (H2S) is a gas at room temperature and standard pressure, as its molecules are bound by weaker dipole-dipole interactions.
The transfer of energy from one chemical substance to another depends on the size of energy quanta emitted from one substance. However, heat energy is often transferred more easily from almost any substance to another because the phonons responsible for vibrational and rotational energy levels in a substance have much less energy than photons invoked for the electronic energy transfer. Thus, because vibrational and rotational energy levels are more closely spaced than electronic energy levels, heat is more easily transferred between substances relative to light or other forms of electronic energy. For example, ultraviolet electromagnetic radiation is not transferred with as much efficacy from one substance to another as thermal or electrical energy.
The existence of characteristic energy levels for different chemical substances is useful for their identification by the analysis of spectral lines. Different kinds of spectra are often used in chemical spectroscopy, e.g. IR, microwave, NMR, ESR, etc. Spectroscopy is also used to identify the composition of remote objects - like stars and distant galaxies - by analyzing their radiation spectra.
The term chemical energy is often used to indicate the potential of a chemical substance to undergo a transformation through a chemical reaction or to transform other chemical substances.
The Nobel Prize 2010 in Chemistry announced- "Palladium catalysed cross-coupling in organic synthesis
"The key word here is versatility," Negishi said. "One of our dreams is to be able to synthesize any organic compounds of importance, whether it is medicinally important
compounds ... or important from the point of view of material science. And we believe that our technology or our chemistry will be applicable to a very wide range of compounds, without knowing what they might be."
Read More...
The 2010 Nobel Prize in chemistry was awarded Wednesday to three professors for a tool to make carbon-carbon bonds in organic chemistry, the Royal Swedish Academy of Sciences announced.
The professors are Richard Heck of the University of Delaware, Ei-Ichi Negishi of Purdue University and Akira Suzuki of Hokkaido University.
The tool the professors devised is called palladium-catalyzed cross-coupling, according to the committee.
Negishi told reporters by phone from the United States that he was asleep when he heard the news an hour earlier. He said winning the prize was a dream of his, but he didn't know whether he would win.
The tool has applications in a wide range of fields, from agriculture and pharmaceuticals to coatings for electronic components, like chips, the Nobel committee said.
The tool the professors devised is called palladium-catalyzed cross-coupling, according to the committee.
Negishi told reporters by phone from the United States that he was asleep when he heard the news an hour earlier. He said winning the prize was a dream of his, but he didn't know whether he would win.
The tool has applications in a wide range of fields, from agriculture and pharmaceuticals to coatings for electronic components, like chips, the Nobel committee said.
compounds ... or important from the point of view of material science. And we believe that our technology or our chemistry will be applicable to a very wide range of compounds, without knowing what they might be."
CP Notes
Functions• A function is a section of a program that performs a specific task
• Solving a problem using different functions makes programming much simpler with fewer defects
Advantages of Functions (1 of 3):
• The functions can be developed by different people and can be combined together as one application
• Easy to code and debug
• Functions support reusability. That is, once a function is written it can be called from any other module without having to rewrite the same. This saves time in rewriting the same code
Classification of Functions
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other
user-defined function
Classification of Functions:
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other user-defined function
Elements of a Function
�� Function Declaration or Function Prototype :
− The function should be declared prior to its usage
�� Function Definition :
− Implementing the function or writing the task of the function
− Consists of
• Function Header
• Function Body
�� Function Invocation or Function call:
− To utilize a function’s service, the function have to be invoked (called)
Declaring Function Prototypes (1 of 2)
• A function prototype is the information to the compiler regarding the userdefined function name, the data type and the number of values to be passed to the function and the return data type from the function
• This is required because the user-defined function is written towards the end of the program and the ‘main’ does not have any information regarding these functions
• The function prototypes are generally written before ‘main’. A function prototype should end with a semicolon
Declaring Function Prototypes (2 of 2)
• Function Prototypes declare ONLY the signature of the function before actually defining the function
• Here signature includes function name, return type, list of parameter data types and optional names of formal parameters
• Syntax:Return_data_type FunctionName ( data_type arg1,
data_type arg2,...,data_type argn );
• Example:
int iValidate_Date(int iDay,int iMonth, int iYear);
Writing User-Defined Functions
• A function header and body looks like this:
Return-data-type function-name(data-type argument-1, data-type argument-2,….)
{
Local variable declarations;
/* Write the body of the function here */
Statement(s);
return (expression);
}
• The return data type can be any valid data type in C
• If a function does not return anything then the void is the return type
• A function header does not end with a semicolon
• The return statement is optional. It is required only when a value has to be returned
Writing User-Defined Functions
void fnDisplayPattern(unsigned int iCount)
{
unsigned int iLoopIndex;
for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {
printf(“*”);
}
/* return is optional */
return;
}
Writing User-Defined Functions
int fnAdd(int iNumber1, int iNumber2)
{
/* Return the result */Can also be written as return (iNumber1 + iNumber2);
}
/* Function to display “Infosys Technologies Ltd.” */
void fnCompanyNameDisplay()
{
printf(“Infosys Technologies Ltd.”);
}
Returning values
• The result of the function can be given back to the calling functions
• Return statement is used to return a value to the calling function
• Syntax:
return (expression) ;
• Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * i);
Calling User-Defined Functions
• A function is called by giving its name and passing the required arguments
• The constants can be sent as arguments to functions
/* Function is called here */
iResult = fnAdd(10, 15);
• The variables can also be sent as arguments to functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
• Calling a function which does not return any value
/* Calling a function */
fnDisplayPattern(15);
• Calling a function that do not take any arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Formal and Actual Parameters
• The variables declared in the function header are called as formal parameters
• The variables or constants that are passed in the function call are called as actual parameters
• The formal parameter names and actual parameters names can be the same or different
Example – Finding the sum of two numbers using functions ( No parameter passing and no return)
#include< stdio.h >
void fnSum();
int main( int argc, char **argv ) {
fnSum();
return 0;
}
void fnSum() {
int iNum1,iNum2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNum1,&iNum2);
iSum = iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions ( parameter passing )
#include< stdio.h >
void fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ) {
int iNumber1,iNumber2;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
fnSum(iNumber1,iNumber2);
return 0;
}
void fnSum(int iNum1,int iNum2){
int iSum;
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions (parameter passing and returning value)
#include< stdio.h >
int fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ){
int iNumber1,iNumber2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
iSum = fnSum(iNumber1,iNumber2);
printf("\nThe sum is %d\n",iSum);
return 0;
}
int fnSum(int iNum1,int iNum2){
int iTempSum;
iTempSum=iNum1 + iNum2;
return iTempSum;
}
File test.c:
int fnSum (int iNum1, int iNum2);
int main(int argc,char ** argv ){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fndiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c:
int fnSum (int iNumc1, int iNumc2) {
return(iNumc1+iNumc2);
}
The above program gives a compilation error because fndiff is not declared
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNumc1, int iNumc2){
return(iNumc1 + iNumc2);
}
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
#include <stdio.h>
int main(int argc, char ** argv){
int iTemp;
i_Temp=10;
}
int fnSum(int iNumc1, int iNumc2){
return (iNumc1+iNumc2);
}
Example Three
The above programs will give a linker error because there are multiple main functions
Example Four
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iNum1,iNum2;
int iResult;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fnDiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int icNum1,int icNum2) {
return(icNum1+icNum2);
}
The above program gives linker error as the definition of the fnDiif function is not available
Example Five
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1, int iNum2);
int main(int argc, char ** argv){
int iResult;
int iVar1,iVar2;
scanf(“%d%d”,&iVar1,&iVar2);
iResult = fnSum(iVar1,iVar2);
printf(“%d”, iResult);
iResult = fnDiff(iVar1,iVar2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNum1, int iNum2) {
return (iNum1 + iNum2);
}
int fnDiff (int iNumc1, int iNumc2){
return (iNumc1-iNumc2);
}
Program compiles and links successfully
Function Calls and Stack
• A stack is a Last In First Out (LIFO) arrangement of memory in which the item that is added last is the one to be removed first
• Items are added and removed only at one end called as top of the stack
• Inserting an item in to the stack is called as PUSH and removing an item from the stack is called as POP
Local Variables:
• The variables that are declared inside a function are called as local variables
• Their scope is only within the function in which they are declared
• These variables cannot be accessed outside the function
• Local variables exist only till the function terminates its execution
• The initial values of local variables are garbage values
#include <stdio.h>
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
int Number1, iNumber2;
printf("Enter the first number ");
scanf("%d",&iNumber1);
printf("Enter the second number ");
scanf("%d",&iNumber2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = iNumber1 + iNumber2; /* Find the sum */
printf("The sum is %d",iResult);
}
Global Variables:
• The variables that are declared outside all the functions (above ‘main’ ) are called as global variables
• These variables can be accessed by all the functions
• The global variables exist for the entire life-cycle of the program
• The global variables are by default initialized to zero
• Coding Standard:
– Each global variable should start with the alphabet ‘g’
– Example:
int giValue;
float gfSalary;
Global Variables
#include <stdio.h>
/* Global varaibles are declared here */
int giValue1, giValue2;
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
printf("Enter the first number ");
scanf("%d",&giValue1);
printf("Enter the second number ");
scanf("%d",&giValue2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = giValue1 + giValue2; /* Find the sum */
printf("\nThe sum is %d\n",iResult);
Disadvantages of Global Variables:
• Lifetime of global variables is throughout the program.
– Hence usage of global variables leads to wastage of memory
• Scope of the global variable is throughout the program.
– Hence more than one function can modify the value of the global variable. This makes debugging difficult.
What is the output of the following code snippet?
int giGlobal ;
int main(int argc, char **argv) {
int iLocal;
printf(“ Value of Local = %d \n, Value of Global = %d”, iLocal, giGlobal);
}
The output is:
Value of Local = <some garbage value>
Value of Global = 0
Program stack and heap
• During execution of a program, the storage of program and data is as follows:
– The executable code is stored into the code /Text segment
– The global variables are stored into data segment
– The heap memory is used for dynamic memory allocation
– The local variables are stored into the stack
• Heap: A section of memory within the user job area that provides a capabilityfor dynamic allocation.
Parameter Passing Techniques
• When a function is called and if the function accepts some parameters, then there are two ways by which the function can receive parameters
– Pass by value
– Pass by reference
Pass by Value
• When parameters are passed from the called function to a calling function, the value of the actual argument is copied onto the formal argument
• Since the actual parameters and formal parameters are stored in different memory locations, the changes in formal parameters do not alter the values of actual parameters
Pass by Value
#include<stdio.h>
void fnUpdateValues (int, int); /* function prototype */
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
fnUpdateValues(iValue1, iValue2); /* Call the function */
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return 0 to the operating system */
}
void fnUpdateValues(int iNumber1, int iNumber2)
{
iNumber1 = iNumber1 + 15; /* Update the values */
iNumber2 = iNumber2 - 10;
}
Pass By Reference
#include<stdio.h>
void fnUpdateValues(int *, int *); /* Function prototype */
int main(int argc, char **argv)
{
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return success code to the operating system */
}
void fnUpdateValues(int *piNumber1, int *piNumber2)
{
*piNumber1 = *piNumber1 + 15; /* Update the values */
*piNumber2 = *piNumber2 - 10;
}
Passing array elements to a function – Pass by value
• There are two ways to pass array elements to a function.
– Pass by Value
– Pass by Reference
/* Demo of Pass by Value */
void fnDisplay(int iMarks);
int main(int argc, char **argv) {
int iIndex;
int aiMarks[] = {55,65};
for(iIndex=0;iIndex<=1;iIndex++) {
fnDisplay( aiMarks[iIndex] );
}
return 0;
}
void fnDisplay ( int iMarks) {
printf( “%d” , iMarks);
}
Passing arrays to a function-Pass by reference
• Arrays are always passed by reference.
• While passing arrays to a function, base address of 0th element gets passed.
• Any changes made to the array by the called function are reflected back into the original array in calling function.
Ex: void fnFindSq (int []); /* Function prototype*/
int main(int argc, char **argv) {
int iIndex;
int aiNum[] = {5,6,10};
fnFindSq( aiNum , 3 ); /* Function Call */
return 0;
}
void fnFindSq ( int aiSqNum[], int iMax) {
int iCnt;
for(iCnt = 0; iCnt < iMax; iCnt++)
aiSqNum[iCnt] = aiSqNum[iCnt] * aiSqNum[iCnt];
}
Summary
• The section of a program that performs a specific task is called as a function
• Advantages of functions
– Reusability
– Modularity
– Easy to code and debug
– Reduced application development time
• To Identify the functions, identify the sub problems to be solved
• Function prototypes should be exactly same as the function header
• The variables declared in the function header are called as formal parameters
• The variables and the constants that are passed in the function call are called as actual parameters
• Scope of variables: The portion of the program where the variables can be accessed
– Local variables: The variables that are declared inside a function
– Global variables: The variables that are declared outside all the functions
• Parameter passing techniques
– Pass by value: The actual values are passed to the function
– Pass by reference: The address of the variables are passed to the function
• When arrays are passed as arguments to the function they are passed by reference
Recursive Functions
• When a function calls itself it is called as Recursion
• Many mathematical, searching and sorting algorithms, can be simply expressed in terms of a recursive definition
• A recursive definition has two parts:
Base condition : When a function will terminate
Recursive condition :The invocation of a recursive call to the function
• When the problem is solved through recursion the source code looks elegant
/* Finding the factorial of an integer using a
recursive function */
int fnFact(int iNumber); /* Function Prototype */
int main(int argc, char **argv) {
int iFactorial;
iFactorial=fnFact(4);
printf("The factorial is %d\n\n",iFactorial);
return 0;
}
int fnFact(int iNumber)
{
int iFact;
if (iNumber <= 1) {
return 1;
}
else {
iFact = iNumber * fnFact(iNumber - 1);
}
return iFact;
}
• Find the output of the following code snippet when the function is called as
fnReverse(5);
void fnReverse(int iValue)
{
if (iValue > 0) {
fnReverse(iValue-1);
}
printf("%d\t",iValue);
}
Output will be 0 1 2 3 4 5
• Find the output of the following code snippet when the function is called as
fnReverse();
int giValue = 5; /* Global Variable Declaration */
void fnReverse()
{
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}
Output: prints 0 six times
• Find the output of the following code snippet when the function is called as
fnReverse();
char gacString[] = "Test";
int giIndex = 0;
void fnReverse()
{
if (gacString[giIndex] != '\0') {
giIndex++;
fnReverse();
}
giIndex--;
if (giIndex >= 0)
{
printf("%c",gacString[giIndex]);
}
}
Output: Prints the string “tseT”
.............................................................................
Linked Lists • A linked list is a versatile data structure used to hold a collection of data
• A linked list essentially consists of nodes
• Each node comprises of data and a pointer (link) to the next node in the list
• The pointer in each node points to the next element in the linked list
• The last element in the linked list will point to NULL indicating the end of the linked list
• The linked list shown in below is a singly linked list
• This kind of linked list allows only uni-directional traversal from the first node to the last node in the list
• The first element of the linked list is called as the ‘head’ and the last element is called as ‘tail’
• The advantage of a linked list is that insertion and deletion is easier in contrast to an array where insertion and deletion requires the elements of the array to be moved down or moved up which require considerable amount of time
• Insertion of a new node in a linked list requires setting of two pointers
• The node, after which the new node has to be inserted, must be made to point to the new node
• The new node inserted must be set to point to the next node to complete the chain
• Deleting a node requires simply changing the pointer to point to the node next to the deleted node
• Linked list allows only sequential access. That is to search for the third node the traversal starts from the first node, then the second node and last the third node
• An array allows random access. That is any element can be accessed by supplying its index
Structures :
• Data used in real life is complex
• The primitive data types which are provided by all programming languages are not adequate enough to handle the complexities of real life data
• Examples:
Date: A date is a combination of day of month, month and year
Address: Address of a person can consist of name, plot number, street, city, pin (zip) code and state.
Account Details: Bank account information can contain the account number, customer ID and Balance
• A structure is a set of interrelated data
• A structure (also known as data structure or struct in short) in C, is a set of primitive data types which are related to business and are grouped together to form a new data type
• A structure is a mechanism provided by the language to create custom and complex data types
Declaring a Structure :
• In C, a structure can be declared using the ‘struct’ keyword
• The set of variables that form the structure must be declared with a valid name similar to declaring variables
• Each variable inside a structure can be of different data type
• Syntax:
struct tag-name
{
data-type member-1;
data-type member-2;
……
data-type member-n;
};
• A structure declaration ends with a semicolon
• Example:
Date is a simple data structure, but not available as a built-in data type in C
A date has three components:
– day of month (integer, Range: 1-31)
– month (integer, Range: 1-12)
– year (integer, four digits)
struct date {
short iDay;
short iMonth;
short iYear;
};
• Each variable declared inside a structure is known as a ‘member’ variable
• In the date structure, iDay, iMonth and iYear are member variables
• A structure is generally declared globally above function ‘main’
• The member variables cannot be initialized within a structure
• The structure is allocated memory only after declaring a variable of type Structure
Accessing Member Variables of a Structure
• Each member variable in a structure can be accessed individually
• Once a structure is declared, it can be used just like any primitive data type
• Inorder to access the structure members, a variable of structure should be created
• Example:
struct date sToday;
• To access individual members of the structure, the ‘.’ operator is used
• Example:
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
int main (int argc, char** argv) {
/* Declare two instances of date structure */
struct date sToday, sTomorrow;
/* Set 'day', 'month' and 'year' in instance sToday */
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
/* Set sTomorrow's values */
sTomorrow.iDay = 1;
sTomorrow.iMonth = 7;
sTomorrow.iYear = 2005;
/* Print the contents of structure */
printf ("Today's date is: %d-%d-%d\n", sToday.iDay, sToday.iMonth, sToday.iYear);
printf ("Tomorrow's date is: %d-%d-%d\n", sTomorrow.iDay, sTomorrow.iMonth, sTomorrow.iYear);
}
typedef Keyword :
• C allows one type of data to be renamed with a different name using the ‘typedef’ keyword (typedef is a short form of ‘define type’)
• A struct date had to be instantiated by using:
/* Create an instance of date structure */
struct date today;
• Alternately, typedef can be used to create the date structure
• It is a good practice while defining the structure and doing a typedef to keep the tag name same as the structure’s name with an underscore (‘_’) prefix
• Example:
/* Declare the structure date */
struct _date {
short iDay;
short iMonth;
short iYear;
};
/* Define the structure ‘_date’ as a new data type ‘date’ */
typedef struct _date date;
/* Create an instance of date structure */
date today;
Coding Standards and Best Practices for Structures
• Each structure should have a small header on the similar lines of a function header
/********************************************************************
* Structure: <structure name>
* Description: <brief description of its use
*
* Member Variables:
* <variable name> - <description of the variable>
* <variable name> - <description of the variable>
* ... ...
*********************************************************************/
• The name of the structure should all be in lowercase
• Examples: date, address, accountdetails
• The names of structure instance variables should have a prefix of ‘s’
Structures in Memory
• A structure instance occupies memory space
• The amount of memory occupied by a structure is the sum of sizes of all member variables
• The members of a structure are stored in contiguous locations
typedef struct _accountdetails {
int iAccountNumber;
char cAccountType;
char acCustomerName[10];
date sOpenDate;
double dBalance;
} accountdetails;
/* Declare an instance of accountdetails */
accountdetails sAccount;
Structure within a Structure (2 of 3)
sAccount.iAccountNumber = 702984;
sAccount.cAccountType = 'S';
sAccount.dBalance = 5000.0;
/* Populating the date sturucture within the accountdetails structure */
sAccount.sOpenDate.iDay = 1;
sAccount.sOpenDate.iMonth = 6;
sAccount.sOpenDate.iYear = 2005;
Structure within a Structure (3 of 3)
Accessing Member Variables using Pointer
• Example:
date psToday;
psToday->iDay = 30;
psToday->iMonth = 6;
psToday->iYear = 2005;
Passing Structures to Functions
• Like built in data types in C, structures can also be passed by value or by reference to functions
• When it is passed by value, the structure can be returned if the structure
members are updated
Passing Structures to Functions (2 of 3)
date fnInitialize(date sTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
sToday = fnInitializeDate(sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
date fnInitialize(date sTemp)
{
sTemp.iDay = 30;
sTemp.iMonth = 6;
sTemp.iYear = 2005;
return(sTemp);
}
• The above example is passing structure using pass by value
Passing Structures to Functions (3 of 3)
void fnInitialize(date *psTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
fnInitializeDate(&sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
void fnInitialize(date *psTemp)
{
psTemp->iDay = 30;
psTemp->iMonth = 6;
psTemp->iYear = 2005;
}
• The above example is passing structure using pass by reference
Reading Structure Members
int main (int argc, char** argv) {
date sToday;
printf(“Enter Today’s Date in format day month year”);
scanf(“%d %d %d”,&sToday.iDay, &sToday.iMonth, sToday.iYear);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
• Solving a problem using different functions makes programming much simpler with fewer defects
Advantages of Functions (1 of 3):
• The functions can be developed by different people and can be combined together as one application
• Easy to code and debug
• Functions support reusability. That is, once a function is written it can be called from any other module without having to rewrite the same. This saves time in rewriting the same code
Classification of Functions
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other
user-defined function
Classification of Functions:
Library functions
- defined in the language
- provided along with the compiler
Example: printf(), scanf() etc.
User Defined functions
- written by the user
Example: main() or any other user-defined function
Elements of a Function
�� Function Declaration or Function Prototype :
− The function should be declared prior to its usage
�� Function Definition :
− Implementing the function or writing the task of the function
− Consists of
• Function Header
• Function Body
�� Function Invocation or Function call:
− To utilize a function’s service, the function have to be invoked (called)
Declaring Function Prototypes (1 of 2)
• A function prototype is the information to the compiler regarding the userdefined function name, the data type and the number of values to be passed to the function and the return data type from the function
• This is required because the user-defined function is written towards the end of the program and the ‘main’ does not have any information regarding these functions
• The function prototypes are generally written before ‘main’. A function prototype should end with a semicolon
Declaring Function Prototypes (2 of 2)
• Function Prototypes declare ONLY the signature of the function before actually defining the function
• Here signature includes function name, return type, list of parameter data types and optional names of formal parameters
• Syntax:Return_data_type FunctionName ( data_type arg1,
data_type arg2,...,data_type argn );
• Example:
int iValidate_Date(int iDay,int iMonth, int iYear);
Writing User-Defined Functions
• A function header and body looks like this:
Return-data-type function-name(data-type argument-1, data-type argument-2,….)
{
Local variable declarations;
/* Write the body of the function here */
Statement(s);
return (expression);
}
• The return data type can be any valid data type in C
• If a function does not return anything then the void is the return type
• A function header does not end with a semicolon
• The return statement is optional. It is required only when a value has to be returned
Writing User-Defined Functions
void fnDisplayPattern(unsigned int iCount)
{
unsigned int iLoopIndex;
for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {
printf(“*”);
}
/* return is optional */
return;
}
Writing User-Defined Functions
int fnAdd(int iNumber1, int iNumber2)
{
/* Return the result */Can also be written as return (iNumber1 + iNumber2);
}
/* Function to display “Infosys Technologies Ltd.” */
void fnCompanyNameDisplay()
{
printf(“Infosys Technologies Ltd.”);
}
Returning values
• The result of the function can be given back to the calling functions
• Return statement is used to return a value to the calling function
• Syntax:
return (expression) ;
• Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * i);
Calling User-Defined Functions
• A function is called by giving its name and passing the required arguments
• The constants can be sent as arguments to functions
/* Function is called here */
iResult = fnAdd(10, 15);
• The variables can also be sent as arguments to functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
• Calling a function which does not return any value
/* Calling a function */
fnDisplayPattern(15);
• Calling a function that do not take any arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Formal and Actual Parameters
• The variables declared in the function header are called as formal parameters
• The variables or constants that are passed in the function call are called as actual parameters
• The formal parameter names and actual parameters names can be the same or different
Example – Finding the sum of two numbers using functions ( No parameter passing and no return)
#include< stdio.h >
void fnSum();
int main( int argc, char **argv ) {
fnSum();
return 0;
}
void fnSum() {
int iNum1,iNum2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNum1,&iNum2);
iSum = iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions ( parameter passing )
#include< stdio.h >
void fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ) {
int iNumber1,iNumber2;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
fnSum(iNumber1,iNumber2);
return 0;
}
void fnSum(int iNum1,int iNum2){
int iSum;
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
}
Example – Finding the sum of two numbers using functions (parameter passing and returning value)
#include< stdio.h >
int fnSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ){
int iNumber1,iNumber2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
iSum = fnSum(iNumber1,iNumber2);
printf("\nThe sum is %d\n",iSum);
return 0;
}
int fnSum(int iNum1,int iNum2){
int iTempSum;
iTempSum=iNum1 + iNum2;
return iTempSum;
}
File test.c:
int fnSum (int iNum1, int iNum2);
int main(int argc,char ** argv ){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fndiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c:
int fnSum (int iNumc1, int iNumc2) {
return(iNumc1+iNumc2);
}
The above program gives a compilation error because fndiff is not declared
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNumc1, int iNumc2){
return(iNumc1 + iNumc2);
}
File test.c
#include <stdio.h>
int fnSum(int iNum1,int iNum2);
int main(int argc, char** argv){
int iResult;
int iNum1,iNum2;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
#include <stdio.h>
int main(int argc, char ** argv){
int iTemp;
i_Temp=10;
}
int fnSum(int iNumc1, int iNumc2){
return (iNumc1+iNumc2);
}
Example Three
The above programs will give a linker error because there are multiple main functions
Example Four
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1,int iNum2);
int main(int argc, char ** argv){
int iNum1,iNum2;
int iResult;
scanf(“%d%d”, &iNum1,&iNum2);
iResult = fnSum(iNum1,iNum2);
printf(“%d”, iResult);
iResult = fnDiff(iNum1,iNum2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int icNum1,int icNum2) {
return(icNum1+icNum2);
}
The above program gives linker error as the definition of the fnDiif function is not available
Example Five
File test.c
int fnSum(int iNum1,int iNum2);
int fnDiff(int iNum1, int iNum2);
int main(int argc, char ** argv){
int iResult;
int iVar1,iVar2;
scanf(“%d%d”,&iVar1,&iVar2);
iResult = fnSum(iVar1,iVar2);
printf(“%d”, iResult);
iResult = fnDiff(iVar1,iVar2);
printf(“%d”, iResult);
return 0;
}
File share.c
int fnSum(int iNum1, int iNum2) {
return (iNum1 + iNum2);
}
int fnDiff (int iNumc1, int iNumc2){
return (iNumc1-iNumc2);
}
Program compiles and links successfully
Function Calls and Stack
• A stack is a Last In First Out (LIFO) arrangement of memory in which the item that is added last is the one to be removed first
• Items are added and removed only at one end called as top of the stack
• Inserting an item in to the stack is called as PUSH and removing an item from the stack is called as POP
Local Variables:
• The variables that are declared inside a function are called as local variables
• Their scope is only within the function in which they are declared
• These variables cannot be accessed outside the function
• Local variables exist only till the function terminates its execution
• The initial values of local variables are garbage values
#include <stdio.h>
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
int Number1, iNumber2;
printf("Enter the first number ");
scanf("%d",&iNumber1);
printf("Enter the second number ");
scanf("%d",&iNumber2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = iNumber1 + iNumber2; /* Find the sum */
printf("The sum is %d",iResult);
}
Global Variables:
• The variables that are declared outside all the functions (above ‘main’ ) are called as global variables
• These variables can be accessed by all the functions
• The global variables exist for the entire life-cycle of the program
• The global variables are by default initialized to zero
• Coding Standard:
– Each global variable should start with the alphabet ‘g’
– Example:
int giValue;
float gfSalary;
Global Variables
#include <stdio.h>
/* Global varaibles are declared here */
int giValue1, giValue2;
void fnSumOfNumbers(); /* Function prototype */
int main(int argc, char **argv)
{
printf("Enter the first number ");
scanf("%d",&giValue1);
printf("Enter the second number ");
scanf("%d",&giValue2);
fnSumOfNumbers(); /* Call the function */
}
void fnSumOfNumbers()
{
int iResult;
iResult = giValue1 + giValue2; /* Find the sum */
printf("\nThe sum is %d\n",iResult);
Disadvantages of Global Variables:
• Lifetime of global variables is throughout the program.
– Hence usage of global variables leads to wastage of memory
• Scope of the global variable is throughout the program.
– Hence more than one function can modify the value of the global variable. This makes debugging difficult.
What is the output of the following code snippet?
int giGlobal ;
int main(int argc, char **argv) {
int iLocal;
printf(“ Value of Local = %d \n, Value of Global = %d”, iLocal, giGlobal);
}
The output is:
Value of Local = <some garbage value>
Value of Global = 0
Program stack and heap
• During execution of a program, the storage of program and data is as follows:
– The executable code is stored into the code /Text segment
– The global variables are stored into data segment
– The heap memory is used for dynamic memory allocation
– The local variables are stored into the stack
• Heap: A section of memory within the user job area that provides a capabilityfor dynamic allocation.
Parameter Passing Techniques
• When a function is called and if the function accepts some parameters, then there are two ways by which the function can receive parameters
– Pass by value
– Pass by reference
Pass by Value
• When parameters are passed from the called function to a calling function, the value of the actual argument is copied onto the formal argument
• Since the actual parameters and formal parameters are stored in different memory locations, the changes in formal parameters do not alter the values of actual parameters
Pass by Value
#include<stdio.h>
void fnUpdateValues (int, int); /* function prototype */
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
fnUpdateValues(iValue1, iValue2); /* Call the function */
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return 0 to the operating system */
}
void fnUpdateValues(int iNumber1, int iNumber2)
{
iNumber1 = iNumber1 + 15; /* Update the values */
iNumber2 = iNumber2 - 10;
}
Pass By Reference
#include<stdio.h>
void fnUpdateValues(int *, int *); /* Function prototype */
int main(int argc, char **argv)
{
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0; /* Return success code to the operating system */
}
void fnUpdateValues(int *piNumber1, int *piNumber2)
{
*piNumber1 = *piNumber1 + 15; /* Update the values */
*piNumber2 = *piNumber2 - 10;
}
Passing array elements to a function – Pass by value
• There are two ways to pass array elements to a function.
– Pass by Value
– Pass by Reference
/* Demo of Pass by Value */
void fnDisplay(int iMarks);
int main(int argc, char **argv) {
int iIndex;
int aiMarks[] = {55,65};
for(iIndex=0;iIndex<=1;iIndex++) {
fnDisplay( aiMarks[iIndex] );
}
return 0;
}
void fnDisplay ( int iMarks) {
printf( “%d” , iMarks);
}
Passing arrays to a function-Pass by reference
• Arrays are always passed by reference.
• While passing arrays to a function, base address of 0th element gets passed.
• Any changes made to the array by the called function are reflected back into the original array in calling function.
Ex: void fnFindSq (int []); /* Function prototype*/
int main(int argc, char **argv) {
int iIndex;
int aiNum[] = {5,6,10};
fnFindSq( aiNum , 3 ); /* Function Call */
return 0;
}
void fnFindSq ( int aiSqNum[], int iMax) {
int iCnt;
for(iCnt = 0; iCnt < iMax; iCnt++)
aiSqNum[iCnt] = aiSqNum[iCnt] * aiSqNum[iCnt];
}
Summary
• The section of a program that performs a specific task is called as a function
• Advantages of functions
– Reusability
– Modularity
– Easy to code and debug
– Reduced application development time
• To Identify the functions, identify the sub problems to be solved
• Function prototypes should be exactly same as the function header
• The variables declared in the function header are called as formal parameters
• The variables and the constants that are passed in the function call are called as actual parameters
• Scope of variables: The portion of the program where the variables can be accessed
– Local variables: The variables that are declared inside a function
– Global variables: The variables that are declared outside all the functions
• Parameter passing techniques
– Pass by value: The actual values are passed to the function
– Pass by reference: The address of the variables are passed to the function
• When arrays are passed as arguments to the function they are passed by reference
Recursive Functions
• When a function calls itself it is called as Recursion
• Many mathematical, searching and sorting algorithms, can be simply expressed in terms of a recursive definition
• A recursive definition has two parts:
Base condition : When a function will terminate
Recursive condition :The invocation of a recursive call to the function
• When the problem is solved through recursion the source code looks elegant
/* Finding the factorial of an integer using a
recursive function */
int fnFact(int iNumber); /* Function Prototype */
int main(int argc, char **argv) {
int iFactorial;
iFactorial=fnFact(4);
printf("The factorial is %d\n\n",iFactorial);
return 0;
}
int fnFact(int iNumber)
{
int iFact;
if (iNumber <= 1) {
return 1;
}
else {
iFact = iNumber * fnFact(iNumber - 1);
}
return iFact;
}
• Find the output of the following code snippet when the function is called as
fnReverse(5);
void fnReverse(int iValue)
{
if (iValue > 0) {
fnReverse(iValue-1);
}
printf("%d\t",iValue);
}
Output will be 0 1 2 3 4 5
• Find the output of the following code snippet when the function is called as
fnReverse();
int giValue = 5; /* Global Variable Declaration */
void fnReverse()
{
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}
Output: prints 0 six times
• Find the output of the following code snippet when the function is called as
fnReverse();
char gacString[] = "Test";
int giIndex = 0;
void fnReverse()
{
if (gacString[giIndex] != '\0') {
giIndex++;
fnReverse();
}
giIndex--;
if (giIndex >= 0)
{
printf("%c",gacString[giIndex]);
}
}
Output: Prints the string “tseT”
.............................................................................
Linked Lists • A linked list is a versatile data structure used to hold a collection of data
• A linked list essentially consists of nodes
• Each node comprises of data and a pointer (link) to the next node in the list
• The pointer in each node points to the next element in the linked list
• The last element in the linked list will point to NULL indicating the end of the linked list
• The linked list shown in below is a singly linked list
• This kind of linked list allows only uni-directional traversal from the first node to the last node in the list
• The first element of the linked list is called as the ‘head’ and the last element is called as ‘tail’
• The advantage of a linked list is that insertion and deletion is easier in contrast to an array where insertion and deletion requires the elements of the array to be moved down or moved up which require considerable amount of time
• Insertion of a new node in a linked list requires setting of two pointers
• The node, after which the new node has to be inserted, must be made to point to the new node
• The new node inserted must be set to point to the next node to complete the chain
• Deleting a node requires simply changing the pointer to point to the node next to the deleted node
• Linked list allows only sequential access. That is to search for the third node the traversal starts from the first node, then the second node and last the third node
• An array allows random access. That is any element can be accessed by supplying its index
Structures :
• Data used in real life is complex
• The primitive data types which are provided by all programming languages are not adequate enough to handle the complexities of real life data
• Examples:
Date: A date is a combination of day of month, month and year
Address: Address of a person can consist of name, plot number, street, city, pin (zip) code and state.
Account Details: Bank account information can contain the account number, customer ID and Balance
• A structure is a set of interrelated data
• A structure (also known as data structure or struct in short) in C, is a set of primitive data types which are related to business and are grouped together to form a new data type
• A structure is a mechanism provided by the language to create custom and complex data types
Declaring a Structure :
• In C, a structure can be declared using the ‘struct’ keyword
• The set of variables that form the structure must be declared with a valid name similar to declaring variables
• Each variable inside a structure can be of different data type
• Syntax:
struct tag-name
{
data-type member-1;
data-type member-2;
……
data-type member-n;
};
• A structure declaration ends with a semicolon
• Example:
Date is a simple data structure, but not available as a built-in data type in C
A date has three components:
– day of month (integer, Range: 1-31)
– month (integer, Range: 1-12)
– year (integer, four digits)
struct date {
short iDay;
short iMonth;
short iYear;
};
• Each variable declared inside a structure is known as a ‘member’ variable
• In the date structure, iDay, iMonth and iYear are member variables
• A structure is generally declared globally above function ‘main’
• The member variables cannot be initialized within a structure
• The structure is allocated memory only after declaring a variable of type Structure
Accessing Member Variables of a Structure
• Each member variable in a structure can be accessed individually
• Once a structure is declared, it can be used just like any primitive data type
• Inorder to access the structure members, a variable of structure should be created
• Example:
struct date sToday;
• To access individual members of the structure, the ‘.’ operator is used
• Example:
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
int main (int argc, char** argv) {
/* Declare two instances of date structure */
struct date sToday, sTomorrow;
/* Set 'day', 'month' and 'year' in instance sToday */
sToday.iDay = 30;
sToday.iMonth = 6;
sToday.iYear = 2005;
/* Set sTomorrow's values */
sTomorrow.iDay = 1;
sTomorrow.iMonth = 7;
sTomorrow.iYear = 2005;
/* Print the contents of structure */
printf ("Today's date is: %d-%d-%d\n", sToday.iDay, sToday.iMonth, sToday.iYear);
printf ("Tomorrow's date is: %d-%d-%d\n", sTomorrow.iDay, sTomorrow.iMonth, sTomorrow.iYear);
}
typedef Keyword :
• C allows one type of data to be renamed with a different name using the ‘typedef’ keyword (typedef is a short form of ‘define type’)
• A struct date had to be instantiated by using:
/* Create an instance of date structure */
struct date today;
• Alternately, typedef can be used to create the date structure
• It is a good practice while defining the structure and doing a typedef to keep the tag name same as the structure’s name with an underscore (‘_’) prefix
• Example:
/* Declare the structure date */
struct _date {
short iDay;
short iMonth;
short iYear;
};
/* Define the structure ‘_date’ as a new data type ‘date’ */
typedef struct _date date;
/* Create an instance of date structure */
date today;
Coding Standards and Best Practices for Structures
• Each structure should have a small header on the similar lines of a function header
/********************************************************************
* Structure: <structure name>
* Description: <brief description of its use
*
* Member Variables:
* <variable name> - <description of the variable>
* <variable name> - <description of the variable>
* ... ...
*********************************************************************/
• The name of the structure should all be in lowercase
• Examples: date, address, accountdetails
• The names of structure instance variables should have a prefix of ‘s’
Structures in Memory
• A structure instance occupies memory space
• The amount of memory occupied by a structure is the sum of sizes of all member variables
• The members of a structure are stored in contiguous locations
typedef struct _accountdetails {
int iAccountNumber;
char cAccountType;
char acCustomerName[10];
date sOpenDate;
double dBalance;
} accountdetails;
/* Declare an instance of accountdetails */
accountdetails sAccount;
Structure within a Structure (2 of 3)
sAccount.iAccountNumber = 702984;
sAccount.cAccountType = 'S';
sAccount.dBalance = 5000.0;
/* Populating the date sturucture within the accountdetails structure */
sAccount.sOpenDate.iDay = 1;
sAccount.sOpenDate.iMonth = 6;
sAccount.sOpenDate.iYear = 2005;
Structure within a Structure (3 of 3)
Accessing Member Variables using Pointer
• Example:
date psToday;
psToday->iDay = 30;
psToday->iMonth = 6;
psToday->iYear = 2005;
Passing Structures to Functions
• Like built in data types in C, structures can also be passed by value or by reference to functions
• When it is passed by value, the structure can be returned if the structure
members are updated
Passing Structures to Functions (2 of 3)
date fnInitialize(date sTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
sToday = fnInitializeDate(sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
date fnInitialize(date sTemp)
{
sTemp.iDay = 30;
sTemp.iMonth = 6;
sTemp.iYear = 2005;
return(sTemp);
}
• The above example is passing structure using pass by value
Passing Structures to Functions (3 of 3)
void fnInitialize(date *psTemp); /* Prototype declaration */
int main (int argc, char** argv) {
date sToday;
fnInitializeDate(&sToday);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
void fnInitialize(date *psTemp)
{
psTemp->iDay = 30;
psTemp->iMonth = 6;
psTemp->iYear = 2005;
}
• The above example is passing structure using pass by reference
Reading Structure Members
int main (int argc, char** argv) {
date sToday;
printf(“Enter Today’s Date in format day month year”);
scanf(“%d %d %d”,&sToday.iDay, &sToday.iMonth, sToday.iYear);
printf(“Today is %d-%d-%d”,sToday.iDay,sToday.iMonth,sToday.iYear);
return 0;
}
Subscribe to:
Posts (Atom)