• No results found

C Entire Notes

N/A
N/A
Protected

Academic year: 2021

Share "C Entire Notes"

Copied!
127
0
0

Loading.... (view fulltext now)

Full text

(1)

---

Presents

A Module

on

(2)

---

C

Program is set of instructions, these instructions are executing by the system, that system is providing result.

Ken Thomson developed BCPL (Basic Combined Programming Language) programming language. This programming is difficult to learn and execute. His co-programmer Dennis Ritche was introduced a programming called ‘C’. Is from Bell Laboratories in 1972.

Here is nothing, in BCPL from second letter C – Combined programming language. It is high level structured programming language.

Every Program must have one main () function. This section contains two parts: 1) Declaration Part 2) Executable Part.

The Declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The Program execution begins at the opening brace and ends at the closing brace. All statements in the declaration and executable parts ends with a semicolon.

The Sub Program section contains all the user defined functions that are called in the main function.

Executing a C Program:

The Steps involved in executing a C Program are: 1. Creating the Program.

2. Compiling the Program.

3. Linking then Program with function that is needed from C Library. 4. Execute C Program.

Basic Structure of C Program:

Documentation Section - suggestion Link Section - optional Definition Section - optional Global Declaration Section - optional

(3)

---

The Documentation section consists of a set of comment Liner giving the name of the Program

the author and other details. Which the Programmer would like to use Later.

The Link section Provides instructions to the compiler to link functions from the system Library. The Definition section defines all symbolic constants.

There are some variables that are used in more than one function such variables are called global variables and declared in the global declaration section i.e., outside of all functions.

Getting Started with C:

There is a Close analogy between learning English Language and learning C Language. The Classical method of learning English is to first learn the alphabets or characters used in the language, then learn to combine these alphabets to form words. Which in turn are combined to learn sentences and sentences are combined to form paragraphs. Learning C is much similar and much easier.

Like English to learn C. We must first know what alphabets, numbers and special symbols are used in C, then how using these constants, variables and keywords are constructed, and finally how are combined these to form an instruction. A group-s of instructions would be combined to form a program.

Steps in Learning English Language:

Alphabets--->Words--->Sentences--->Paragraph Steps in Learning C:

Alphabets, Constants

Main () function section - necessary {

Declaration Part Executable Part }

Sub Program Section Function 1 Function 2

(4)

--- Digits, ---> Variables ---> Instructions --->Program

Special Symbols Keywords

Character set Tokens The C Character Set:

The C character denotes any alphabet, digit or special symbol used to represent information. Alphabets A,B,C,<<<<..Y,Z. a,b,c<<<<<.y,z. Digits 0,1,2,3,4,5,6,7,8,9 Special Symbols {, }, [,], (, ) , !, C Tokens:

The smallest individual units in a C Program are Known as C Tokens. C Tokens

Keywords Constants Variables C Keywords:

Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. The keywords are also called ‘Reserved words’. Keywords serve as basic building blocks for program statements.All keywords must be in lowercase letters. Some compilerws may use additional keyword that must be identified from the manual.

There are only 32 keywords available in C. Following is the List of keywords in c. Auto double int static

Break else long struct Case enum volatile switch Char extern register type def

(5)

--- Const float return union

Continue far short unsigned Default go to signed void Do if size of while Constants:

A constant is a fixed value that do not change during the execution of a Program for example in the equation

3x+y=20

Since 3 and 20 cannot change, they are called constants, where as the quantities x&y can vary or change hence are called variables.

Constants Numeric constants Character constants Integer constants Real constants

Single character constants String constants

Integer Constants:

An integer constants refers to a sequence of digits. There are 3 types of integers namely decimal, octal and hexadecimal.

Decimal integer constants of set of digits, 0 through 9, preceded by an optional – or + sign.

Eg: 123 -321 +78 0

An octal integer constants consists of any combination of digits from the set 0 through 7 with leading 0.

Eg: 037 0435

(6)

--- 0551

0

A sequence of digits preceded by 0x or 0x is considered as hexadecimal integer. They may also include alphabets A through F or a through f. The Letters A through F represents the numbers 10 through 15.

Eg: 0x2 0x9f 0xbcd 0x

Rules for Constructing Integer Constants:

1) An Integer constant must have at least one digit. 2) It must not haver a decimal point.

3) It could be either positive or negative.

4) If no sign preceds on integer constant it is assumed to be +ve. 5) No commas or blanks are allowed within an integer constant. 6) The allowable range for integer constants is -32768 to 32767. Real Constants:

Integer numbers are inadequate to represent quantities that vary continuously. Such as distances, heights, temperatures, prices and so these quantities are represented by numbers containing actional parts like 17.548. Such numbers are called real or floating point constants. Eg: 0.0083

-0.75 435.36 247.0

A real number may also be expressed in exponential (scientific) notation. The general form is Mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer number with an optional plus or minus sign. The letter e separting the mantissa and the exponent can be written in either lowercase or uppercase.

Eg: 0.65e4 12e-2 3018e3 -102e-1

For example the value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 102.

(7)

--- Rules for constructing Real Constants:

Following rules must be observed while constructing real constants expressed in fractional form.

1) A real constant must have at least one digit. 2) It must have a decimal point.

3) It could be either positive or negative 4) Default sign is positive.

5) No commas or blanks are allowed within a real constant.

Following rules must be observed while constructing real constant expressed in exponential form:

1) The mantissa part and the exponential part should be separated by a letter e. 2) The mantissa part may have a positive or negative sign.

3) Default sign of mantissa part is positive.

4) The exponent must have at least one digit which must be a positive or negative. Default sign is positive.

5) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Character Constants:

There are 2 types of character constants.

1) Single character constants 2) String constants

Single Character constants:

A character constant is either a single alphabet, a single digit or a single special symbol enclosed within single inverted commas.

The maximum length of a character constant can be 1 character. Eg: ‘A’ , ‘1’, ‘5’, ‘=’

String Constants:

String constant is a sequence of characters enclosed in double quotes. The characters may be letters numbers, Special characters and blank space.

(8)

--- Variables:

Variable names are names given to locations in the memory of computer where different constants are stored. These locations can contain integer, real or character constants, unlike constants the variables remains unchanged during the execution of a program a variable may take different values at different times during execution.

Rules for constructing variable names:

1) A variable name is any combination of 1 to 8 alphabets, digits or underscores. Some compilens allow variable names whose length could be up to 40 characters.

2) The first character in the variable name must be an alphabet. 3) No commas or blanks are allowed within a variable name.

4) No special symbol other than an underscore can be used in a variable name.

A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program.

Eg: average, Height, Total, Counter-1, Class-strength

The data value stored by a variable can be of integer, float, real number or character constant. So the variable is declared with a data type depending on the type of the data value each data item in a ‘c’ Program related with a type known as data type.

Declaration of variables:

The declaration of variables must be done before they are used in the program variable declaration does there things.

1) It tells the compiler what the variable name is. 2) It specifies what type of data the variable will hold

3) What set of operations that are performed against this location. The syntax for declaring a variable is as follows:

Data type v1, v2, <<. vn;

V1, v2,<<.vn are the names of variables. Varaibles are separated by commas. A declaration statement must end with a semicolon.

Eg: int count;

(9)

--- Double ratio;

Assigning values to variables:

1) Values can be assigned to variables using the assignment operator = as follows. Variable name = constant;

Eg: a = 10; B = 20;

Balance = 75.84;

ANSI C supports four classes of data types. 1) Primary dat types

2) User defined data types 3) Derived data types 4) Empty data type.

2) C point multiple assignments in one line. Eg: a = 10; b = 20;

3) It is also possible to assign a value to a variable at the time the variable is declared.

The general form is

Data type variable-name = constant; Eg: int a =10;

Char ch =’x’;

Double balance = 75.84;

4) The process of giving initial values to variables is called initialization C permits the initialization of more than one variables in one statement using multiple assignment operations.

Eg: p = q =s =0; X =y =z =max

The first statement initializes the variables p,q and s to aero, while the second initialize x,y and z with max.

Note that max is a symbolic constant defined at the beginning. Operators :-

(10)

--- Operator is a symbol it can operate the two or more operands.

1) Arithmetic operator :-

It is used to construct the mathematical expressions as in algebra. +, - *, / , % a+b , a-b, a/b, a*b, a%b = reminder value

2) Relational operator :- to compare the two quantities. <, <=, >, >=, = =, !=

a>b a>=b a<b a<=b a==b a!=b

3) Logical Operators:- are && and || are used when we want to form compound conditions by combining two or more relations.

&& -> logical AND, ||-> logical OR, ! -> logical NOT

4) Assignment operators are used to assign the value of an expression to a variable. ‚=‚. V = exp or value;

a = 10; or a= b + c;

5) Increment ++ operator is to adds 1 to the operand while Decrement -- operator is to subtracts 1.

Pre post

++ a a++ = a=a+1 --a a- - = a= a-1

6) Conditional operator ? : is a ternary operator exp1 ? exp2 : exp3 ;

X= (a>b)? a is big : b is big ;

7) Bit wise operators are for manipulation of data at values of bit level. These are used for testing the bits or shifting them to the right or left.

&,!, ~, ^, <<, >>

8) Special operators of interest for sizeof(), typedef(), *(pointer), this operator, arrow () operator

Input/ Output functions :-

To read the data from the key board, and to print the data on screen using the I/O functions. 1. Character I/O functions

2. String I/O functions 3. Formatted I/O functions

(11)

--- 1. Character I/O functions :-

getchar( ):- to read the single character from the key board. x=getchar( );

putchar( ):- to write the single character on the screen. Putchar(x);

2. String I/O functions:-

gets( ):- to read the string(group of characters). x=gets();

put( ):- to write the string. puts(x);

getch( ):- is a reading function, but it can’t print the value.

getche( ):- is a reading function, it can print the value. Ex:- k it can print the k. 3. Formatted I/O functions:-

scanf ( ):- to read any type of data, means int, float, char, string and double scanf(“controle string”,&v1,&v2<<);

control strings are:- %d - integer %c - single char %s - string %f - float %g - double %u - unsigned values %ld - long int <<<<<<.. Ex:- scanf(“%d%c%f”,&a,&b,%c); printf( ):- to print the any type of data.

printf(“control string”, v1,v2<<..); Ex:- printf(“control strings”,v1,v2<.);

(12)

--- Decision Making Statements (We are calling Control statements.)

 If statements  Switch statements

 Conditional operator statements.

IF Statement :-

 If statement is a powerful DMS and is used to control the flow of executing statements. It is a two-way decision statements and is used in conjunction with an expression.

 if ( test expression) Example :- if ( age > 58) { Printf(‚Employee is retired ‚); }

Simple if statement :- here the condition is checks first, if it is true execute the body statements, O.w another stmts are execute.

Syntax :- if (test exp) { statement block; } Statement –x;

(13)

--- Program:- #include<stdio.h> #include<conio.h> Void main() { int age;

printf(‚enter the age‛); scanf(‚%d‛,&age); if(age> 58)

{

Printf(‚the employee is retired‛): }

}

If – else: -

Here the condition is checks first, if it is true execute the body statements, if it is false execute the else part.

if (test exp) { statement x; } else { statement y; } Statement –z; #include<stdio.h> #include<conio.h> Void main() { int age;

printf(‚enter the age‛); scanf(‚%d‛,&age); if(age > 18)

(14)

--- {

Printf(‚the preson is major‛); }

else {

Printf(‚the preson is minor‛); }

getch(); }

Nested if :- here the condition is checks first, if it is true, again it checks the within the condition, it is true then execute the body stmt, or else stmt, or outer if else part will be execute

if (test exp) { if(test exp) { statement x; } else { statement y; } } else { Statement –z } Statement x; #include<stdio.h> #include<conio.h> Void main() { int a,b,c;

(15)

--- printf(‚enter the a b c values‛);

scanf(‚%d%d%d‛,&a,&b,&c); if(a > b) { if(a>c) { printf(‚ a is big‛); } else { Printf(‚ c is big‛); } } else if(b>c) { Printf(‚ b is big‛); } else { Printf(‚ c is big‛); } getch(); }

Else if or Ladder if :- here the condition is checks first, if it is true execute the body statements, o.w it can false it will checks the another else if stmt and so on<<.. up to the conditions are true.

(16)

--- if (cond 1) statement 1; else if (cond2) statement 2; else if (cond3) statement 3; <<<. <<<. else default stmt; <<<<< Statement x;

Program to print the different colors: #include<stdio.h>

#inlude<conio.h> Void main() {

int choice;

Printf(‚enter the choice‛); Scanf(‚%d‛,&choice); If( choice==1)

{

(17)

--- }

Else If( choice==2) {

Printf(‚the color is Orange‛); }

Else If( choice==3) {

Printf(‚the color is Yellow‛); }

Else If( choice==4) {

Printf(‚the color is Green‛); }

Else If( choice==5) {

Printf(‚the color is Blue‛); }

Else If( choice==6) {

Printf(‚the color is Indigo‛); }

Else If( choice==7) {

Printf(‚the color is Violet‛); }

Else

Printf(‚you choice is invalid number ‛); getch();

}

Switch statement:-

 The switch stmt tests the value of a given variable against a list if case value and when a match is found, a block of stmt associated with that case is executed.

(18)

--- Switch(v or exp) { case 1: stmt 1; break; case 2: stmt 2; break; <<<<<<<< <<<<<<<< default: stmt x; }

Program to print the different colors.

#include<stdio.h> #inlude<conio.h> Void main() {

int choice;

Printf(‚enter the choice‛); Scanf(‚%d‛,&choice);

(19)

--- Switch(choice)

{ case 1:

Printf(‚the color is Red‛); break;

case 2:

Printf(‚the color is Orange‛); break;

case 3:

Printf(‚the color is Yellow‛); break;

case 4 :

Printf(‚the color is Green‛); break;

case 5:

Printf(‚the color is Blue‛); break;

case 6:

Printf(‚the color is Indigo‛); break;

case 7:

Printf(‚the color is Violet‛); break;

default :

Printf(‚you choice is invalid number ‛); getch();

}

Decision Making Looping Statements :-

A statement is executing more than one time with in the condition. 1. Entry level looping stmt

2. Exit level looping stmt

We have 3 looping statements are there, 1. While

2. Do – while 3. For loop

(20)

--- 1. While : it is an entry level looping statement and first test the condition, it can be true then execute the body of the loop statements up to the given condition is false, if not execute the out of the body statements.

Initialization; While(condition) {

Body of the statements; Increment/ decrement stmt; }

Program to print the math table. #include<stdio.h>

#include<conio.h> Void main() {

Int a,i=1;

Printf(‚enter the a value‛); Scanf(‚%d‛,&a);

While(i<=10) {

C= a * i;

Printf(‘\n%d * %d = %d‛,a, i, c); i=i+1; // i++; // i+=1; }

getch(); }

2. Do- while: it is an exit level looping statement and first execute the body of the statement and check the given condition, if it can be true again execute the body of the loop statement up to the given condition is false, if false it exit that from the loop.

Initialization; do

{

Body of the statements; Increment/ decrement stmt; } While(condition);

(21)

--- Program to print the math table.

#include<stdio.h> #include<conio.h> Void main() {

Int a,i=1;

Printf(‚enter the a value‛); Scanf(‚%d‛,&a);

do { C= a * i;

Printf(‘\n%d * %d = %d‛,a, i, c);

i=i+1; // i++; // i+=1; } While(i<=10);

getch(); }

3. For loop :- it is also entry level looping statement, it more comfortable to execute the statements, because in that stmt initialize and test condition and inc/decrement stmts are writing in single line.

for( init ; test-condition; incr/decr) {

Body of the loop; }

Program to print the math table. #include<stdio.h>

#include<conio.h> Void main() {

int a,i;

Printf(‚enter the a value‛); Scanf(‚%d‛,&a); for(i=1;i<=10;i++) C= a * i; Printf(‘\n%d * %d = %d‛,a, i, c); } getch(); }

(22)

--- Nested for loop:-

A loop statement is executed within the another looping is called nested loop. for(init; test-condition 1; incr/decr)

{

for( init ; test-condition 2 ; incr/decr) {

Body of the loop; }

}

Program to print the multiple math table.

#include<stdio.h> #include<conio.h> Void main() {

int a,i;

Printf(‚enter the a value‛); Scanf(‚%d‛,&a); for(a=1;a<=5;a++) { for(i=1;i<=10;i++) { c= a * i; Printf(‘\n%d * %d = %d‛,a, i, c); } Printf(‛\n‛); } getch(); }

(23)

---

Arrays and Strings :-

Array is similar type of data collection name.

It is a collection of same data type elements. An array is a group of related data items, which share common name. it is a set of homogeneous data.

Ex:- in a class room if 30 students are there, they have snos, names we declare 30 variable, some it is not possible so we are rectifying this problem using an array.

Types of Array: 1. Linear Array 2. Non Linear Array

Linear Array:- This type of array is also called One dimensional array. This is also called list array. in this array only one subscript is used. It is written either in row or in column form.

Syntax:- datatype arrayname[size]; Where data types are int, float or char.

Array name is any name or word or character. Ex:= int a[20];

Float sal[10]; Char name[20];

Size should be one cell more than the given data length, because last cell should be empty or null cell that is the end of the string has null character.

Char name[10]; K e e r t h i 0 1 2 3 4 5 6 int a[5];

a[0]=20, a[1]=30, a[2]=40, a[3]=50, a[4]=60. Assigning Values to an array:-

Data type arrayname[size]={list of values}; Int a[5]={4,5,6,7,8,9};

(24)

--- #include<stdio.h> #include<conio.h> Void main() { int a[5],i;

Printf(‚enter the a values‛); for(i=0;i<5;i++)

{

Scanf(‚%d‛,&a*i+); }

Printf(‚the entered values‛); for(i=0;i<5;i++) { printff(‚\n%d‛,a*i+); } getch(); }

Non Linear Array:- Array of having different dimensions or n subscripts is in the form of non linear array.

1. Two dimensional array 2. Three dimensional array. 3. <<<<<<<<< 4. N dimensional array.

1. Two dimensional array:- these arrays are also called double dimensional array. Is tabular or rectangular array. these array are in row and column form.

datatype arrayname[rowsize][columnsize]; int a[2][2];

int a[2][2] = {2,3,4,5};

a[0][0]=2, a[0][1]=3, a[1][0]=4, a[11]=5 2 3

4 5

(25)

--- 2. Three dimensional array:- called space array. in this space, row and column are taken.

These are also called xyz array. int a[2][2][2];

a[0][0][0], a[0][0][1], a[0][1][0], a[0][1][1], a[1][1][1];

To read and print the two dimensional array elements #include<stdio.h>

#include<conio.h> Void main() {

int a[5][5],i,j;

Printf(‚enter the a values‛); for(i=0;i<5;i++) { for(j=0;j<5;j++) { Scanf(‚%d‛,&a*i+*j+); } }

Printf(‚the entered values‛); for(i=0;i<5;i++) { for(j=0;j<5;j++) { printff(‚%d‛,a*i+*j+); } } getch(); }

(26)

---

Strings :-

More than on character is string. Group of characters is a string. ‚ I LOVE INDIA‛

Printf(‚ I Love India‛);

But if the string is stored in variable, then such type of variable should be of character type. Also character variable should be declared in the array form (one dimensional array)

data type arrayname[10]; Char name[10]; Printf(‚%S‛, name); Char name*10+=,‘k’,’e’,’e’,’r’,’t’,’h’,’i’}; Multiple string Char name[4][10]; for(i=0;i<5;i++) { Printf(‚%s‛, name*i+); }

data type arrayname[2][10];

Char name*2+*10+=,,‘k’,’e’,’e’,’r’,’t’,’h’,’i’},,‘v’,’a’,’r’,’d’,’h’,’a’,’n’}}; String Handling Functions:-

Operate some operations with string. We use some powerful string handling functions. All these function are linked with the ‚string.h‛ header file stored in the include.

1. Strcat() 2. Strcmp() 3. Strcpy() 4. Strlen() 5. Strrev()

Strcat :- this is to concatenate or combined two different strings together. Strcat(string1,string2);

String1[10], string2[10];

String1= ‚keerthi‛, string2= ‚vardhan‛ Puts(string1);

(27)

--- Strcmp :- this is to compare two strings. It will check which string is alphabetically above the

other.(ASCII) values are used. Strcmp(string1,string2)

Strcpy :- this is to copy one string into another string. Note that, destination field should be larger than the source filed. In other words size of the string1 should be larger to receive the contents of the string2.

Strcpy(string1,string2) Printf(‚%s‛, string1);

Strlen :- is to count the number of character in a string, to find the length of the string. n = strlen(string1);

printf(‚%d‛,n);

strrev : - is to reverse a string. This function takes string variable as its single argument. here the first char becomes last and last becomes first in a string. This is to find string palindrome or not ‚madam‛ .

strrev(string1)

Program On String Functions #include<stdio.h> #include<conio.h> Void main() { char a[10],b[10]; int n;

printf(‚enter the string a,b‛);

gets(a); // scanf(‚%s‛,&a); // scanf(‚%c‛,&a*i+); here i is define gets(b); n = strlen(a); printf(‚%d‛,n); strcpy(a,b); printf(‚%s‛,a); strrev(a); printf(‚%s‛,a); getch(); }

(28)

---

Function:-

Definition

Function is block or part of program. When any program is very long or same code is repeating many times then we try to cut the program in different parts (or blocks) so that whole program became more understandable, easier to debug (error checking) and size of code will be lesser.

Syntax of function in c programming

Data type function(parameters); Or

Data type function() { Statements –x; Statements-y; --- --- }

Functions are dividing in to types

1.

Function no arguments and no return type

2.

Function with arguments and no return type

3.

Function with arguments and with return type.

Simple example of function structure int sum (int,int); //function declaration void main()

{

int p;

p=sum(3,4); //function call printf(‚%d‛,sum);

}

int sum( int a,int b) //function definition {

int s; //function body s=a+b;

return s; //function returning a value }

(29)

--- Detail explanation of syntax of function:

(1) Function_name :

Function naming rule in c programming:

Rule 1. Name of function includes alphabets, digit and underscore. Valid name: world, addition23, sum_of_number etc. Invalid name: factorial#, avg value, display*number etc.

Rule2. First character of name of any function must be either alphabets or underscore.

Valid name: _calulate, _5,a_, __ etc. Invalid name: 5_, 10_function, 123 etc.

Rule 3. Name of function cannot be any keyword of c program.

Invalid name: interrupt, float, asm, enum etc. Rule 4. Name of function cannot be global identifier.

Valid name: __TOTAL__, __NAME__ ,__TINY__etc.

Invalid name: __TIME__,__DATE__, __FILE__,__LINE__,__STDC__ Note: It is good practice to not write the variable name in the above format. Rule 5: Name of function cannot be register Pseudo variables

Rule 6. Name of function cannot be exactly same as of name of other function or identifier within the scope of the function.

Rule 7. Name of function is case sensitive.

Rule 8. Only first 32 characters are significant of the function’s name. Example: abcdefghijklmnopqrstuvwxyz123456aaa,

abcdefghijklmnopqrstuvwxyz123456bbb, abcdefghijklmnopqrstuvwxyz123456cad

All three function name are same because only first 32 characters has meaning. Rest has not any importance.

(30)

--- Return type of function in c programming

return is keyword of c. When the control reaches to the return keyword it immediately terminates the execution of that function and transfer the control to the calling function.

Syntax of return statement:

Here expression is optional which has indicated by [ ]. Example: void dev(); void main() { clrscr(); printf("one\n"); dev(); printf("two\n"); getch(); } void dev() { printf("three\n"); return; printf("four\n"); } Output: one three two

Return type of function can be:

1. Primitive data type.

Primitive data types are: char, int, float, double, void Examples:

a. function which is returning char data type b. function which is returning int data type c. function which is returning float data type d. function which is returning double data type e. function which is returning void data type 2. Derived data type.

(31)

--- Derived data types are: array, function, pointer

Examples:

a. Function which is returning array b. function which is returning function c. function which is returning pointer 3. User defined data type.

User defined data types are: structure, union, enum Examples:

a. Function which is returning structure b. Function which is returning union c. Function which is returning enum

Feature of function’s parameter in c 1.Default parameter of function is void.

2.Only register storage class is allowed with function parameter. int devD(register int,register int);

void main(){ int temp; temp=devD(5,25); printf("%d",temp); getch(); }

int devD(int register x,int register y) {

static int num; num=x+y+1; return num; }

Output: 20

3. Default storage class of function parameter is auto.

4. If function declaration has not written then during the function call it doesn’t check prototype of function if function return type is int data type and parameter is not float data type.

(32)

--- Nesting of Functions:-

When a function call another function or a function processing occurs in within another function. It is used in the handling of multi function.

Main() fun2() { { <<<..; <<<.. fun1(); return; <<<... } } fun1() { <<<<. fun2(); <<<< return; }

Example on nested functions: - #include<stdio.h> main() { int a,b,c; float ratio(); Clrscr();

Printf(‚enter the three number:‛); Scanf(‚%d%d%d‛,&a,&b,&c); Printf(‚ratio is =%f‛, ratio(a,b,c)); getch();

}

float ratio(int x,int y, int z) { if diff(y,z) { return(x/(y-z)); } else { return (0.0); }} diff(p,q) Int p,q; { if(p!=q) { return(1); } else { return(0); } Return; }

(33)

---

RECURSION:

When called function in turn calls another function, then a process of chaining occurs Main()

{

printf(‚ krest‛); main();

}

Recursion is a special case of this process or chain. So when a function calls itself, then it is called recursion.

This chain continues till a specific condition met. If it has not any stop condition, then if will create an infinite loop.

Recursion is used to solve for the problems, which cannot be solved by the iterative procedure for, while and do loops. It is useful to solve repetitive problems, where input of one sub program can be used as staring value having the previous output.

Condition:

1) A recursive function should have specific condition.

2) A recursive function should have smaller argument each time than the previous argument value in the every recursive loop.

Factorial with recursion main()

{

int n, fact();

printf(‚enter a value‛); scanf(‚%d‛,&n);

Printf(‚ %d factorial is %d‛,n,fact(n)); getch(); } Fact(n) Int n; { int m; If(n==1) { return(n); }

(34)

---

Use of Array in function(Passing Array to function)

Array plays an important role in the function handling. Arraying are declared with the function definition and so can be used in the function declaration stmt.

1) Passing one Dimensional array to fun:- syn:- fun-name(array-name, array-size);

Ex:- sort(a,n); => an array defined as int a[20]; and n is size of array, n<=20. 2) Passing 2-D array to fun:-

syn:- fun-name(array-name, row-size, col-size);

Ex:- sort(a,n,m); => an array defined as int a[10][10]; and n is row size of array, n<=10,m is col size of array m<=10.

1) 1D ex biggest No main()

{

int a[10],I,b,big(),n;

printf(‚enter the size of array‛); scanf(‚%d‛,&n);

printf(‚enter the elements of array‛); for(i=0;i<n;i++) , scanf(‚%d‛,&a*i+); } b=big(a,n); printf(‚biggest number is %d‛,b); getch(); } int big(x,m) int x[],m; { int bi,I; bi=x[0]; for(i=1;i<m;i++) { ifx[i]>bi) { bi=x[i]; } } retrun(bi); }

(35)

---

Storage Classes Of Variables:

Variables execute in the function program locally, but others execute globally. Also variable are stored in the memory in different ways by using the function. Every time the execution period and boundary of the variable vary in the function subprograms. Every variable in c language has a powerful characteristic called Storage-class. So there be need to specify the storage class of a variable along with the data-type.

a) Local variable

A local variable will be visible to the function in which it is declared, but not to other. It is declare inside the function. A local variable is also called automatic variable, because it is automatically created and destroyed.

b) Global variable

A global variable is to visible to all the functions and it is declared outside the function. The proper place of declaration of global variable is at the beginning of the main program or before the function.

1) Auto 2) Register 3) static 4) extern

Auto storage class:

It is the default storage class to be used within a program or file. An auto variable is defined and accessed within a function. An auto variable has no defined value and storage until the function in with it is defined is called. Auto variable stored on the stack, which provides temporary storage.

Int x; => auto int x

Register storage class:

The lifetime and visibility of register storage class is similar to that of auto default storage class. The default initial value is unpredictable, it may be some garbage value. These variables are accessed much quickly than other variables as they reside in the registers of the microprocessor(8, 16 bits). Register variables are only of char or int data type. As these are declared in registers, so these can not be referred by the pointer variable. We are taking limited variables in registers.

(36)

--- Register int countr1, countr2;

Static storage class:

It is a storage which is also quite similar to auto except that the variable once defined any where do not die till program ends and the value of variable will also be retained, but will be assessed only by the function declaring it. Static storage variables have initial value is zero and not garbage. Static auto variable has a global lifetime and local visibility. It cannot be accessed from another function.

Main() { fun(); fun(); getch(); } fun() { static int a; a++; printf(‚\n%d‛,a); }

External storage class

When there is a need for a variable to be assessed in all the functions in a c. the external variables serve the purpose. Scope of the external variable is global. These variable are assessed globally and has the initial value as zero and not the garbage value, so these variables do not die at the start or at the end of any function program. But die at the end of the whole program.

These are used to transfer the value from one function to another, their scope is from the position of their declaration to the end of the program. Here no fresh memory is allotted.

int a; main() { a=a+1; printf(‚%d‛,a); fun1(); fun2(); fun3();

(37)

--- fun4(); printf(‘%d‛, a); getch(); } fun1() { a=a+10; Printf(‚%d‛,a); } fun2() { a=a+5; Printf(‚%d‛,a); } fun3() { a=a-2; Printf(‚%d‛,a); } fun4() { a=a-8; Printf(‚%d‛,a); } Out put :- 1 11 16 14 22 22

(38)

---

POINTERS :-

Pointers are memory address variable i.e the variables, which have address of the variable having some value, stored in the memory, pointers are directly linked to the memory address. Actually pointer is a variable having address of another variable and not the value.

Variable name memory value memory address memory variable q 280 6000 p

Here q is int variable having 280, is stored at the memory address 6000 this variable is p(pointer).

P which is a memory variable and is stored further in the memory and again it has some memory address. (Pointer to pointer).

Variable name memory value memory address memory variable q 280 6000 p pointer

p 6000 5980 r pointer to pointer Advantages:

1. Pointers increases the execution speed of the c-program and more efficient. 2. Pointer reduces the length and complexity of the program.

3. Pointer access the memory elements very easily.

4. Use of the pointer to the character arrays are easier to handle and represent with the pointers.

5. Pointers have direct link with structure and union.

6. Pointer saves the memory space. This can be done by using the dynamic memory allocation technique.

Declaring a pointer variable

A pointer variable should be declared before they are used, similar to the common variable. The pointer variable be declared in data type.

data –type *pointer-variable;

Where data-type may be integer(int), float, char or double. Also here * (asteric sign) means it is pointer operator and pointer variable is any variable linked with * sign. The symbol * is called indirection operator.

int *x; float *y; char *z;

Note:- pointer are classified on the basis of its declaration. i.e whether a pointer variable holds the address of an integer or a float or a char variable.

(39)

--- p = &q;

printf(‚%d is stored at address %u ‚, q,p);

Here 280 is stored at address 6000

Note :- code in the control string of printf () statement be %u . Becoz address are always unsigned integer.

&*p  address 6000 &q  6000 *&p  value of p 280 *(&q)  280

Will display the contents(value stored) of pointer variable(the * represents the value at the address) and & display the address of pointer variable( the & represents the address of the value). We can write the above stmt.

main() {

int q,*p,n; q=280; p=&q;

printf(‚ \n %d is stored at address %u‛, x, &x); printf(‚ \n %d is stored at address %u‛, x, q); printf(‚ \n %d is stored at address %u‛,*q, q); printf(‚ \n %d is stored at address %u‛, *&x, &x); getch();

}

Note :- some invalid statements to accessing the address of pointer are &12;

&(x+y); int &x(10);

Pointer Expressions :-

pointer deals with the arithmetic, relational, logical and assignment expressions. Pointers are not directly used in the arithmetic, relational, logical and assignment expressions only pointer value are used. Some of the arithmetic expression used with pointer p1 and p2..

int x, y, z, a, b, c, *p1,*p2; x=10; y=20;

(40)

--- p1 = &x; p2 = &y; z=(*p1) / (*p2); a=(*p1) + (*p2); b=(*p1) * (*p2); c=(*p1) - (*p2); int a,b, *p1,*p2; b=280; p1=&b; a=200; p2=&a; if(*p1>*P2) { stmts; } #include<stdio.h> #include<conio.h> int *p1, *p2, *p3; int i=1; int j=2; int a[5]={1,2,3,4,5,}; main() { int m,n,x; p1=&j; p2=&j; p3=&a[0]; m=p1-p2; n=*p1+*p2; x=*p3+2; if(p1>p2) printf(‚%d%d%d‛,m,n,x); if(p1<=p2) printf(‚%u%u%u‛,p1,p2,p3); }

(41)

--- Increment / Decrement operator the address pointer as :

p1 = p1 +1; p1 = p1 – 1; p1 ++; p1 - - ;

the statement p1++ will increment the address value in the pointer variable depending on the type of the variable. If the pointer is of int type, then the pointer address is value will be incremented by 2 and if it is of char type, then the value will be incre by 1; this increase or decrease is according to cells in the memory and cells works according to the scale factor. Scale factor is a scale or measurement of the length of the cells of different data type in terms in terms of bits or bytes.

data – type memory space char 1

int 2

float 4

double 8

note :- pointer can be incr /decr’ed. These can not be arithmetic and logical and relational and assignment operators

Pointer with array :-

pointer have close relationship with array. an array name is in fact a pointer to the array. pointer are linked with array by taking its first element number and its base address.

ststic int a[5]={23,24,25,26,27};

a[0] a[1] a[2] a[3] a[4] 23 24 25 26 27 1000 1002 1004 1006 1008 address of x[element no]= base address + element no. * scale factor 3rd element of the array and you have base address 100,

x[3] = 1000 + 3 * 2 = 1006 x[4] = 1000 + 4 * 2 = 1008 x[10] = 1000 + 0 * 2 = 1000 int a[5], *p; p=a; P=&a;

(42)

--- p=&a[0];

Above all are same

Address value address value address value &a[0] a[0] a+0 *a p *p

&a[1] a[1] a+1 *(a+1) p+1 *(p+1) &a[2] a[2] a+2 *(a+2) p+2 *(p+2)

So on<<<<<<<<<<<<<<<<<<<<<<<<<<.

#include<stdio.h> main()

{

ststic int a[5]={23,24,25,26,27}; int i, n, *p; p=a; n=5; for(i=0;i<n ; i++) { printf(‚%4d‛, *(p+i)); } printf(‚reversed data is ‚); for(i=n-1;i>0; --i) { printf(‚%4d‛,*(a+i)); } getch(); }

Type of array pointer:-

1) one dimensional array pointer:-

Is works according to the given base address, the number of elements in an array and the data type of array.

#include<stdio.h> main()

{

int a[20], *p1, i, n, sum=0; clrscr();

printf(‚\n enter the value of n:‛):

scanf(‚%d‛,&n);

(43)

--- for(i=0;i<n;i++)

{

scanf(‚%d‛, &a*i+); }

printf(‚\n \t element \t value \t address‛); p1=&a[0];

for(i=0; i<n; i++) {

sum =sum + a [i];

printf(‚\n \t a[%d] \t %d \t %u‛, i+1, a*i+, p1); }

printf(‚sum is =%d‛, sum);

printf(‚ the sum is stored at address %u‛, &sum); getch();

}

b) Two dimensional array :- varies according to their addresses. It can be viewed as a collection of 1D array. the various portions of pointer with 2 D array vary according to their row and column numbers.

pointer to ith row p[i]=&p[i]

value of p+ ith row and first element is *(p+i) = p[i][0] pointer to the jth element in the ith row is *(p+i)+j = p[i][j]

data-type (*array –name)[column size]; int a[2][6];  int (*a)[6];

Pointers And Functions

Pointer has deep relationship with function. We can pass pointer to the function and also pointer addresses can be passed to the function as pointer arguments. This can be represented by two ways as defined below:

a) Pointer as function argument b) Pointer to function

A) Pointer as function argument:

Pointer as function argument occurs with its address cell i.e, in this function is called by using address of the variable. It is also called call by reference. In call by reference the addresses of the actual argument are passed to the function. The call of function by sending its value as argument in the function calling statement is called call by value. In call by value

(44)

--- concept, the names of the actual argument are used in the function call. So call by value of the actual argument passed to the function.

Best explanation of call by value and call by reference can be done by taking the example of swapping the numeric data..

Swapping:

Swapping is part of pointer as function argument. Swapping is the exchange of value from one variable to another. We can say, if we take two variables x, y and we can exchange value of x into y and y into x, then it is the process of swapping (or exchanging). We explain the process of swapping by the following program:

Call By Value:

/*Program to illustrate the concept of call by value (argument passing without pointer)*/ main ()

{ int a,b; a = 5; b = 10;

printf(‚\n Value of a = %d and Value of b = %d before swap‛, a, c); swap (a, b);

printf(‚\n Value of a = %d and Value of b = %d after swap‛, a, b); getch();

}

swap (int x, int y) { int temp; temp = x; x = y; y = temp; return; }

The output is:

Value of a = 5 and Value of b = 10 before swap Value of a = 5 and Value of b = 10 after swap

(45)

--- Call By Reference: main () { int a, b *aa, *bb; a =5; b = 10; aa = &a; bb = &b;

printf(‚\n Value of a = %d and Value of b =%d before swap‛, a, b); swap(aa,bb);

printf(‚\n Value of a = %d and Value of b =%d after swap‛, a, b); getch();

}

Swap( int *x, int *y) { int *temp; temp = x; x = y; y = temp; return; }

The output is:

Value of a = 5 and Value of b = 10 before swap Value of a = 10 and Value of b = 5 after swap

B) Pointer to function:

A function works like a variable. It has also similar dat type declaration like the other variable. Pointer to a function variable occurs when you define a while function as pointer by using ‘ * ‘. As function has address location in memory the syntax used to declare pointer to function is as:

data-type (*function name)() ; type (*fptr)( );

(46)

--- where type is the data type which may ne integer, float or character, fptr () is function name and * (fptr) () is pointer to function. For example, the procedure to illustrate this concept is as follows:

int mul ( ). (*p1) ( ): p1 = & mul ;

By using the above example, we can say that mul ( ) is a simple function. But p1 is pointer variable which work as pointer to function and in second statement the address of the mul ( ) function is assigned to p1 variable which is the memory variable and you know memory variables or pointer. So p1 ( ) pointer function is linked to the function mul.

main( ) {

int mul ( ). (*p1)( ), x,y ,z; scanf (‚% d % d‛, & x, & y); p1 = &mul ;

z =*p1 (x, y); printf (‚ % d‛,z); getche( );

}

mul (int p, int q) {

int m ; m = p * q; return (m); }

POINTERS AND STRINGS:

Pointers plays an important role in inputting, outputting and processing the strings and line of text. Pointers linked with array with two ways:

i) Array of pointers to strings

ii) Passing array of strings to function

iii) An array of pointer to string can be declared as in the case of basic type variables. This can be declared in terms of variable and constants. Two-dimensional arrays in terms of pointer *t[20] and a[20][30] are defined.

This can be represented as: Static char *t[20], a[20][30];

Unsigned int i; For(i=0;i<30;i++) {

(47)

--- }

This procedure completely states the definition of array of pointers to the strings. As the variable a is itself an array of type char, so an array of pointers to strings t is an array of pointer to char. For example, below is a c program illustrate the concept of array of pointer to string as:

1. Program to print the string cities and their addresses using array of pointer to the string concept

main() {

char *city*+ = ,‚krest‛,‛ameerpet‛,‛dilsukhnager‛}; int i;

for(i =0; i<3; i++) {

printf(‚\n%scity has address %u‛,*(city+1),(city+1); }

getche(); }

The output is:

Krest city has address 1200 ameerpet city has address 1202 dilsukhnagar city has addresss 1204

ii) Array of strings can be passed to a function as arguments. Note that formal parameter can be declared as a pointer to a pointer to type character. This can be done by representing as:

char** v where v is of character type variable.

For example, write a c program to illustrate the concept of passing array of strings to a function as:

Void main() {

Char *city*3+ = ,‚Krest‛,‛Ameerpet‛,‛Dilsukhnagar‛}; Void pass (char **,int);

Pass (city, 3); getche(); }

(48)

--- Void pass (char **m, int n)

{ int i;

for (I =0; i<n; i++) {

printf(‚\n %s‛,m*1+); }

return; }

The output is: Krest

Ammerpet dilsukhnagar

Dynamic memory allocation:

As pointer variable are used to hold the address of a variable, Which is declared with the pointer variable during the variable declaration statement. So assigning of the address of variables to a pointer variable is one of the legal way of the initialization of pointer. This process is always dynamic.

In the dynamic memory allocation of the memory, the declaration of variable is no longer required. The job of memory allocation can be done by using the three functions.

These are malloc(), calloc() and realloc(). malloc():

The general syntax used for the declaration of this function is as follows: Void *malloc(unsigned size);

It allocates a block of size bytes of consuctive memor7y from the heap of memory. Ot returns starting address of the allocated bytes. Note that if sufficient memory is not available, then it

returns the Null value. A cast operator is used to cast the memory allocation pointer to the desired type as the returned pointer to the allocated memory is of generic type.

(49)

--- calloc():

The general syntax used is as: Void *calloc(xyz, unsigned size);

The calloc() function provides dynamic allocation of block of consecutive memory locations of size to xyz from trhe heap of the memory. It return a pointer to the newly allocated block. If enough memory is not available, then NULL value be returned. Like in the case of of malloc function the memory allocation pointer can be cast to the proper type.

realloc():

The general syntax used for this function is as: Void *realloc(void *block, unsigned size);

It adjust the preciously allocated block to the size bytes. I will allocate the increasing or decreasing the block to the new size. Here block refers to the original block already allocated by malloc() or calloc() function. It returns the address of the new reallocated block. Note that if it will unable to reallocate the block , then it will display and return the Null value. For example, the concept of allocation of dynamic memory can be explained by using the c program as below:

(50)

---

STRUCTURE :-

We know different data type of variables can be used for different purpose. C support such type of constructed data type, which is called Structure.

A structure having different type of data types in a single structure.

‚A structure is Heterogeneous collection of related fields. Here fields are structured member elements. A field has different data type‛.

For example, book having title, author, price, pages<<

Struct library { Char title[20]; Char author[20]; Int pages; Float price; }; Sysntax:- 1. Struct structre-tag { Datatype1 element1; Datatype2 element2; Datatype3 element3; --- --- Datatype n element n; }; Main() {

Structre-tag v1,v2<.vn; / / list of variables of stucture tag. Local variable declaration;

Executable statements; } 2. struct structre-tag { datatype1 element1;

(51)

--- datatype2 element2; datatype3 element3; --- --- datatype n element n; } v1,v2<.vn; main() { executable statements; } 3. main() { Struct structure-tag { datatype1 element1; datatype2 element2; datatype3 element3; --- --- datatype n element n; } Struct Structre-tag v1,v2<.vn; } Ex:- 1. Struct library { Char title[20]; Char author[20]; Int pages; Float price; }; main() {

Struct library book1,book2,book3; }

(52)

--- 2. Struct library { Char title[20]; Char author[20]; Int pages; Float price; } book1,book2,book3; main() { Local variables; Executable statements; } 3. Main() { Struct library { Char title[20]; Char author[20]; Int pages; Float price; };

Struct library book1,book2,book3; }

Assigning values to structure variables:-

We are assigning values to the variables using member operator ‚ .‛ which is called dot or period operator. This is creates a relationship between the variablename and structure elelment of the structure tag.

Ex:- Struct library { Char title[20]; Char author[20]; Int pages;

(53)

--- Float price;

} book1; main() {

printlf(‚enter the book details‛);

scanf(‚%s%s%d%f‛,&book1.title,&book1.author,&book1.pages,&book1.price); printf(‚\n the book title is = %s‛,book1.title);

printf(‚\n the book title is = %s‛,book1.author); printf(‚\n the book pages are = %d‛,book1.pages); printf(‚\n the book price is = %f‛,book1.price); getch();

}

Strucuter and array:-

Array play very important role with sturcture.Sturcture has two types of view with the array.

1.Array of Sturcture 2.Array within Sturcture

1. Array of Structure : An array structure 1D &2D are Declared by only changing the structure variables from fundamental type to an array type with no change in the structure declaration.

For 1D:

Sturct sturct-tag variable name[row size]; For 2D:

Sturct sturct-tag variable name[row size][column size]; For example Main() { Sturct student { int student1; int student2; int student3; }; Int I,n,total; Float av; Struct student st[20];

(54)

--- Scanf(‚%d‛,&n);

For(i=0, i<n; i++) {

Printf(‚ \ n Enter marks of three subjects of %d the student:‛i+1); total=0;

scnaf(‚%d %d %d‛, &s[i].subject1, &st[i]. subject2, &st[i]. subject3); total = st[i].subject1+st[i].subject2+st[i].subject3;

av = total / 3 ;

printf(‚\n AVERAGE Marks of %d the student is =% f‛ i+1,av); }

getche(); }

The Output be:

Enter the number of students 10

Enter marks if three subjects 1 the student: 20

35 45

AVERAGE Marks of 1 the student is =33.33 Enter marks of three subjects 2 the student: 10

30 20

AVERAGE Marks of 2 the student is =20.00 Enter marks of three subjects 10 th student: 22

38 30

AVERAGE Marks of 10 th student is = 30.00

2.Array within Sturcture :

Array are declared within the structure.

1D :-

Struct struct-tag {

data type1 element1; data type2 element[size];

(55)

--- }variable list;

2D ;-

Struct structre-tag {

data type1 element1;

data type2 element2[row][column]; }

Structure with in structure:

A structure can be embedded within another structure. In other words when a structure is declared and processed with in another structure, then it is called Nesting of structure or structure within structure.

Sturct tag 1 { element-1; --- etruct tag 2 { element-1; <<<<<. element –n; }v1; element-m; }v2; EX:- Struct student { int rollno; char name[20]; char address[30]; int phno; float fees; struct exam { float tel; float eng; float compu;

(56)

--- float tot; float avg; }ex[10]; Char dateofbirth[8]; }st[10];

The inner structure element can be linked with the outer structure variable by using the structure dot operator. This can be represented as:

st[i].ex[j].tel;

Structure and Function:-

Structure can be implemented with the function easily. For this process, passing of arguments takes place similar to the array and variable. This relationship of structure with the function can be viewed from three angle as;

i) Passing structure to a function ii) Function returning structure

iii) Passing array of structure to function.

1.Passing structure to a function:-

Similar to passing of array or variable, structure can be passed to the function as argument.

Syn:-

type specifier function-name (structure-variable); // as actual arguments type specifier function-name (structure variable) // as formal arguments struct tagname structurevariable;

{ --- --- } main() { Struct tagname { datatype1 ele1; ---

(57)

--- datatype-n ele n; }v1; --- --- function name(v1); --- getch(); }

Type function name(v2) Struct tag-name v2; {

--- --- }

2.Function Returning Structure:

All the values can be computed in the function programs and return a combined value of whole structure back. This can be explained with a simple problem to compute the net pay of an employee having structure as:

Main() { Sturct employee { char name [20]; float bp; float da; float hra; float netpay; }emp;

Sturct emp npay(emp y);

Printf(‚\n ENTER THE NAME, BASIC PAY,DA,HRA:‛);

Scanf(‚\n%s%f%f%f, emp.name, &emp.bp, &emp.ba, &emp.hra); Y = npay(y);

(58)

--- Getche(); } emp npay(emp Z) { Z =Z.bp +Z.hra; Return(Z); }

3.Passing array of Structure to function :

A complete complicated passing of an array of structure to the function is a difficult job, but the passing of array becomes very easy by using the passing of array as an individual element. For example, to compute the average marks of every student (there are five students in the class ), each having three subjects can be done by using the C program as below:

Main() {

Res m[100]; int n,I;

printf(‚\n How many students in the class:‛); scanf(‚\n %d‛,&n);

printf(‚\n Enter the data:‛); for( i=0; i < n; i++)

{ M[i] =input (m,n); } Display(m,n); getch(); }

res input (res m[],int i) {

int j; float tm =0;

printf (‚\n Enter Rollno andf marks :‛); scanf(‚\n %d‛, &m*i+.rn);

for (j =0;j<3;j++) {

(59)

--- Scanf(‚\n%d%*c‛,&m*i+.sub*j+); Tm =tm +m[i].sub[j]; } M[i].av =tm/3; J =0; Return m[i]; }

Void display (res m[],int n) {

int j,k;

printf(‚\n RESULT IS:‛);

printf(‚\n ROLLNO 1 2 3 Average of Marks‛); for(j =0; j<n; j++) { Printf(‚%5d‛,m*j+.sub*k+); Printf(‚%5d‛,m*j+.av); } } return; }

(60)

--- Structure And Pointer :-

Structure can be directly handled by its address by using the pointer with structure. we use pointer with structure through structure variable. Array of structure variable directly stands for the address of zero th element.

Struct tag { Type1 element1; <<<<<<<.. Type n element n; }v, *p;

Where v is structure variable and p is the pointer variable. Note that structure variable is a pointer and there are no pointer variable work as structure element. Also the structure variable is an array of pointer variable pointing to a structure.

Sturct employee { char name [20]; float bp; float da; float hra; }emp,*p;

Also the declaration of pointer variable p can be initialized as P=&emp; You can access the individual element by using,

(*p).bp; (*p).name; (*p).da; (*p).hra;

Don’t use like, *p.bp because user can’t access the element directly with the pointer initialization, so always avoid to use pointer with structure without the use of parenthesis. To solve such type of problem, user can use the arrow operator().

pbp; pname; pda; <..

(61)

--- <.. Ex:- main() { Struct student { Int rn; Float fees; }st[10],*p; int n,j;

printf(‚enter the no of students‛); scanf(‘%d‛,&n);

printf(‚\n enter the data‛); for(p=st;p<st+n;p++)

{

Scanf(‚%d\t%f‛, &prn,&pfees); }

p=st;

printf(‚entered dat is‛); while(p<st+n) { printf(‚%d\t%d‛,prn,pfees); p++; } getch(); }

(62)

---

UNION:-

A union is a variable that declares a set of multiple variables sharing the same memory area. The compiler allocates sufficient memory to hold the largest variable of the union.

All the members of union occupy the same memory locations called addresses. The old value of the already declared member will be destroyed and new value to the new member will be assigned in the memory by using the union concept.

Note :- union declaration has mote then one variable declaration, but only one can be used at a time. Also with the declaration of union, the turbo-c compiler will automatically allocates the memory locations to the variable which has the long data type member element I the union. Sys:- Union union-tag { Data-type 1 member-element 1; Data-type 2 member-element 2; <<<<<<<<<<<<<<<<<<.. Data-type n member-element n; }v1,v2<.vn; Note:- here union tag is optional Sys2:- Union { Data-type 1 member-element 1; Data-type 2 member-element 2; <<<<<<<<<<<<<<<<<<.. Data-type n member-element n; }v1,v2<.vn; Sys3:- Union union-tag { Data-type 1 member-element 1; Data-type 2 member-element 2; <<<<<<<<<<<<<<<<<<.. Data-type n member-element n; };

References

Related documents

Exports a data, where are scheduled tasks stored procedure is kept in the stored credential manager control the week field because of tasks are logged in the agents.. Version of

Ideal Logic HIUs incorporate one or two plate heat exchangers to transfer heat from a central boiler plant to individual heating and hot water systems within apartments. Ideal

The existing design of the security door lock employing mortise principle requires a definite key to be inserted while locking and unlocking it.. A major drawback of this

• Names and account numbers of all accounts you suspect are being fraudulently used. • Locations where fraudulent applications were presented. • Locations listed as home address

To determine whether the section 509(a)(1)/170(b)(1)(A)(vi) test is met, donor contributions are considered support from direct or indirect contributions from the general public only

Given the high prevalence of pediatric overweight and obesity and importance of physical activity in maintaining a healthy weight, it is essential that we better understand the

The purpose of this study was to examine the impact of test structures (unidimensional versus within-item multidimensional as modeled through a bifactor model), differences in

The impact of an increase in the shift is comparable to the change associated with a corresponding increase in the stated belief in treatment CTG/NI (0:46 versus 0:56, in