Sunteți pe pagina 1din 56

Basics of C

History of C In 1960s a first high level language called as ALGOL 60 was developed for the application of structure programming to the computer science community but this language was not accepted because it was very large. Ken Thompson developing a compiler for a new high level language called B based on the earlier BCPL language developed by Martin Richard. This was small but not sufficient to handle all programming application. In 1972 Kernighan and Dennis Richie was developed language called as C. The language C uses the ideas from B and BCPL both. This language has become very popular world wide. C recently been standardized by the American National Standards Institute (ANSI).
BCPL B C

1967 developed by Martin Richards 1970 developed by Ken Thompson 1972 developed by Dennis Richie

Why C is called middle level language There are two mainly types of languages, which are known as low level language and high level language. Low level language interacts with the computer hardware. E.g. Assembly language interacts with the machine hardware which is the form of 0 and 1. High level language is human understandable language like English C which is easy to used to different developer. C programming language is also called as middle level language programming both machine efficiency and program efficiency. Features of C 1. In C along with the basic data types (char, int, float) secondary data types (long, double) with allowed modifiers (signed, unsigned) can be used. 2. The input and output formatted can be used. 3. C has powerful debugging tools which make testing and fault finding easy. 4. C has compiler. So, it is fast and finds all the errors and warnings are displayed at the same time. 5. C is middle level language programming and hence it has both machine efficiency and program efficiency. 6. C has structured programming this makes easy to read and understand. 7. C supports modular programming approach. 8. C has provides many standard library function. 9. C program accept the command line arguments. 10. C is collection of functions that are supported by the C library. Importance of C or Advantages of C 1. C is portable; it means that c programs written for one computer can be run on another computer easily. 2. C language is well structured programming; it means user can write a program in modules or blocks. Naresh Shende 1 9890379983

3. 4. 5. 6.

Several standard library function and operators are used to write a complex program. Programs written in C are efficient, fast, reliable, simple and easy to use. The basic concept and programming skills of C are used in C++, C# and Java. C provides close interaction to the hardware.

Drawbacks of C 1. C does not allow multiprogramming, parallel operations 2. Making a menu driven program with good graphic interface is not very easy. 3. No operations are possible to deal directly with composite such as characters, strings, and set of array. Steps in learning C 1. 2. 3. 4. C is simple English language which is used alphabets, number (digits) and special symbols. C is used constant, variable and keywords. Collections of instruction are the commands given to the machine for doing actions. After the instructions to form the program. Fig shows the learning process for C language.
Alphabets, digits and special symbols Constants, variables keywords Instructions Program

Fig. learning process of C What is a C token? In individual words and punctuation marks are called tokens or the smallest individual marks are called as C tokens. C program written using these tokens and the syntax of the language.
CTokens Tokens C Keywords Keywords Identifiers Constants Strings Special Symbols Special Symbols Operators

Fig. C token C Character Set The character denotes in alphabets, digits or special symbols used to represent the data or information. Alphabets: A, B, C . . . Z or a, b, c . . . z Digits: 0,1,2,3,4,5,6,7,8,9 Special Symbols: <, >, ?, /, , , ; , :, {, }, [, ], |, \, =, +, (,) , *, &, ^, %, $, #, @, !, ~, ` What is Keywords Keywords are predefined words in C programming language with specific meaning and these meaning can not be changed. All keywords must be written in lowercase. Keywords can not be used as a variable name. There are 32 keywords available in C programming. auto double int struct break else long switch case enum register typedef char extern return uninon const float short unsigned continue for signed void default goto sizeof volatile do if satic while

Naresh Shende

9890379983

Define Identifier and Rule for identifiers Identifier refers to the names of variables, functions and arrays. These are user defined names and consist of a sequence of letters and digits with a letter as a first character uppercase or lowercase letters are permitted. The underscore (_) character is also permitted identifiers. Rules for Identifiers 1. 2. 3. 4. 5. First character must be an alphabet or underscore. It must be consist of only letters, digits or underscore. Only first 31 characters are significant. Cannot use a keyword. Must not contain white space.

Define Constants Constant in C refer to fixed valued that do not change during the execution of a program. Several types of constant in programming C.
Constants

Numeric Constant

Character Constant

Integer

Real/Float

Single Character

String

Fig. the basic types of constant Declaration of constant: Syntax: Example: const datatype identifier = value; const float pi = 3.14;

The keyword const used to denote that the value represented by identifier is a constant and that it can not be changed the identifier is assigned the value in the declaration only. Define the Variable and write the rules for constructing variable A variable is a data name that may be used to store data value. The values can be changed during the execution of the program. Example: sum, total, roll_no Rules for constructing variable name 1. 2. 3. 4. 5. The variable name must begin with letters. The variable name is formed with letters and digits. The special character are not allowed e.g. comma, white space. The underscore ( _ ) is the only special character which is allow. The lowercase and uppercase do defer while forming variable names. Hence a and A are two different variable. 6. The underscore is considered as letter. The variable name can start with underscore. But usually while forming the variable names underscore is used in between.

Example: Valid variables: marks, roll_no, x1, Marks, max_value Invalid variables: 123, 1abc, %per, max marks, 1to4 etc. Naresh Shende 3 9890379983

Declaration and initialization of variables with example The variables are declared before they are use. The general syntax of declaring the variables is as follows. datatype variable_name; datatype variable1, variable2. . . variable n; int x, y; float per; char name; Initialization of variables The variables can be initializing with specific values at the time of the declaration. Consider the following example. int x, y, z = 10; The above example x and y are uninitialized and z is initialized with 10. If we want to initialize all of them with 10 then it can be done as follows. int x=10, y=10, z=10; float a=2.4, b=3.8, c; char name=p, d=A; In the above example a, b and c are floating type variables. The variable a and b are initialized with values 2.4 and 3.8 respectively and c is uninitialized. 2) The variable name and d are character data type variable. The variable name is initialized with p and variable d is initialized with A. Syntax: Or Example:

Data Types used in C language


Data type is a tool which is used for mathematical presentation of a data in computer memory. All C compilers support a variety of data types. A data type indicates which type of data is stored in variables. According to type of data memory is allocated for those data values. Integer data type ( int ) An integer is a number which is formed with a sequence of digit. Following are the rules followed by constructing integer data type. 1. 2. 3. 4. 5. It can not be use decimal point or exponent sign. It can be prcised by sign i.e. + or If the number is not prcised by sign, it is assume to be always +ve. Format specifier for integer data type is %d. An integer requires 2 bytes means 16 bits for storage. Integer quantity is represented number of form (range) -32768 to +32767.

The following table shows the range of the integer with different qualifier along with the storage space. Format Data type with qualifier %d Short int %d Signed short int %u Unsigned short int %d Int %d signed int %u Unsigned int %ld Long int %ld Signed long int %lu Unsigned long int Naresh Shende Storage space in byte 1 1 1 2 2 2 4 4 4 4 Range of value -128 to +127 -128 to +127 0 to 255 -32768 to +32767 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 2147483648 to +2147483647 0 to 4294967295 9890379983

Float or Real and Double data type Rules for constructing float data type. 1. 2. 3. 4. 5. 6. The float and double numbers will either include decimal point or exponent sign or both. The numbers can also be preceded by sign. If the numbers are not preceded by a sign they are assumed to be +ve. The float number will require 4 byte for storage and double will require 8 byte for storage. Range of float data type is 3.4e-38 to 3.4e+37 and double range is 1.7e308 to 1.7e307. Floating format string is %f and double float format string is %lf.

Character data type (char) 1. Format string for character data type is %c. 2. The character type data require 1 byte for storage. 3. The ASCII character set has got 128 different symbols and the extended ASCII character set will involved 256 symbols. 4. The single character constant is enclosed within single quote A e.g. a ,2

Formatted Input and Output Statement


1. Formatted output printf( ) printf( ) function is used in order to display the contents of a variable on the screen or to simply print the contents as it is on the screen. This function can be accessed from anywhere within a program simply by writing the function name followed by a list of arguments enclosed in parenthesis. The arguments represent data items that are sent to the function. The printf( ) and scanf( ) function is supplied by <stdio.h>. This file is <stdio.h> is called header file. The general form of printf( ) is printf(<format string>, <list of variable>); Example: printf(%d %d, a, b); it will print the value of a and b. <Format string> consist of character to be display with following specifiers %c %d %f %s %o %x %u 2. Formatted Input scanf( ) Input is entered into the computer from a standard input device by using scanf( ) function. This function can be used to enter any combination of numerical values. Single characters & is used to store and create location or address for the variable values. The general form of scanf( ) is scanf(<format string>,&<variable>,&<variable>, . . .); Example: scanf(%d %d, &a, &b); it will be read the value of a and b from the keyboard. Naresh Shende 5 9890379983 Read/Write a single character Read/Write a integer value Read/Write a floating value Read/Write a string Read/Write an octal value Read/Write a hexadecimal value Read / Write a unsigned decimal integer

First program of C /* sample program of C */ #include<stdio.h> void main( ) { printf(\n welcome to C programming); } Output: Welcome to C programming //include the header files // function name // start of program // print the message // end of the program

The lines beginning with /* and ending with */ are known as comment lines. These are used in a program to enhance its readability and understanding. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. Also comment indicated using // for single lines. In the above program only one statement is used within main function. Every C program must have at least one function called as main. The word void indicates that the main function should not return any value. The opening curly {is used to indicate start of the main function. The closing curly braces } is used to indicate end of the main function. The printf( ) is function and it is available in a library file called as stdio.h (standard input output header file). To use the printf file must be include as shown. In the printf statement whatever is written within double quote (.) will be printed as it is. The back slash (\n) is called as newline character and it will take the cursor in newline and hence output will be as follows. Welcome to C programming The main( ) function The main() is part of every C program. C permits different forms of main statement. Following forms are allowed. main( ) int main( ) void main( ) main(void) void main(void) int main(void) The empty pair of parenthesis indicates that the function has no arguments. This may be explicitly indicated by using the keyword void inside the parenthesis. We may also specify the keyword int or void before the word main. The keyword void means that the function does not return any information to the operating system and int means that the function returns an integer value to the operating system. When int is specified the last statement in the program must be return 0.

Preprocessor Directive
The commonly used preprocessor directives are: 1) #include 1. #include These preprocessor directive is used to include specifies files in the program for example to used printf and scanf function we require #include<stdio.h>. Similarly, if we want to function square root we Naresh Shende 6 9890379983 2) #define

have to write #include<math.h> in the program. When we have to take the input data through the keyboard or using console then write the preprocessor directive #include<conio.h> 2. #define The #define preprocessor directives is used two different processor. i) Define constant Example: #define PI=3.1459 The above example defines PI as a symbolic constant with values 3.14159 one PI is define as a constant it can be only used inside the program but its value can not be changed symbolic constants are often written with capital letters but its not a rule. #define macros will similar to function in certain aspects. However there is difference between 2. When a function is called the stack will come in picture internally. When macro is called stack will not coming in picture. Consider the following program #include<stdio.h> #define add (a, b) a + b void main( ) { int x=7, y=5; float z=3.1, w=4.5; printf(%d \n, add(x, y)); printf(%f \n, add(z, w)); } In the above program add us define as macro that accepts two parameter a and b and macro definition is a + b. As the above program the data type is not specified by macro parameters. Hence, same macro can be used as 2 integers and 2 float and one integer and one float this is advantage of macro. The call add(x, y) will be replaced by x + y and add (z, w) is replaced by z + w stack will not coming picture.

C Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. 1. Arithmetic Operators Operator + * / % Meaning Addition or unary plus Subtraction or unary minus Multiplication Division Modulus division x * y = 21 x/y=2 x%y=1

For example value of x=7 and y=3 x + y = 10 xy=4

2. Logical Operators It is used to form compound conditions by combining two or more relations. E.g. a > b && x==10. && Logical AND || Logical OR ! Logical NOT The logical operators && and || are used when we want to test more than one condition and make decision. Example: (a > b) && (x==10) Naresh Shende 7 9890379983

The logical expression given above is true only if a>b is true and x==10 is true. If either of them is false the expression is false. According to the truth table shown in table. Op1 0 0 1 1 3. Relational Operators We often compare two quantities these comparisons can be done with the help of relational operators. Operators < <= > >= == != 4. Assignment Operators These are special operators that are used to assign the result of an expression to a variable. The use of shorthand operators for 1. Left hand side operator is the short hand operators and right hand side operator is simple assignment operator. 2. The statement is easier to read. 3. The statement is more efficient. Shorthand operator a+=1 b-=2 c*=3 d/=4 e%=5 z*=x + y The sizeof operator The sizeof operator returns the number of bytes the operand occupies in memory. The operand may be a variable, constant data type qualifier. Example: m=sizeof(sum); n=sizeof(long int); k= sizeof(235L); The sizeof operator is normally used to determine the lengths of arrays and structure when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variable during execution of a program. Naresh Shende 8 9890379983 Simple assignment operator a=a+1 b=b-2 c=c*3 d=d/4 e=e%5 z=z*(x + y) Meaning is less than is less than or equal to is greater than is greater than or equal to is equal to is not equal to Op2 0 1 0 1 Value of the expression Op1 && Op2 Op1 || Op2 0 0 0 1 0 1 1 1

Increment and Decrement Operator The operator ++ adds 1 to the operand, while - - subtracts 1. Both are unary operators and take the following form. Example: a++ or a- The above example is post ++ or - - is used with a variable in an expression, the expression is evaluated first using the original value of the variable and then the variable is incremented or decremented by 1. Example: ++a or - -a The above is pre ++ or - - is used with a variable in an expression, the variable is incremented or decremented first and then the expression is evaluated using the new value of the variable. Increment operator (++) The increment operator is used either as pre increment operator or it can be used as post increment. Consider the following example. The increment is used to increment the variable by 1. e.g. x = 4; x = 4; ++x; x++; The value of x will become 5. The value of x will become 5. The above two example indicates that the value of x will become 5 in both the cases. Hence, it is since like there is no different between pre increment and post increment. It is true of above example but not always. Consider the above example. x = 4; x = 4; y = ++x; y = x++; In above statement y = ++x two jobs are to be done assignment and increment. x = 4 and y = ++x since, it is pre increment operator x is incremented first and then incremented value is assign to y. Therefore y=5 and x=5. y = ++x is equivalent to following statement x=x+1and y=x. x = 4; y = x++; The statement y = x++ has two job assignment and increment. Since, it is post increment operator first assign and then increment is done. Hence, the original value of x. i.e. 4 is assign to y and then x is increment by 1 and hence x will become 5. y = x++ is equivalent to y=x after x=x+1 means x=5 and y=4. Decrement operator The decrement operator is used to decrement the value of variable by one. Consider the following example. x = 4; x = 4; y = - - x; y = x- -; Output: y=3 Output: y = 4 x=3 x=3 Bitwise Operator C supports special operators known as bitwise operators for manipulation of data at bit level. These operators as used for testing the bits or shifting them right or left. Bitwise operators may not be applied to float or double. Naresh Shende 9 9890379983

Operator ~ & | ^ << >> &= ^= |= Example:

Function Bitwise NOT Bitwise AND Bitwise OR Bitwise XOR Left shift Right shift Assign bitwise AND Assign bitwise XOR Assign bitwise OR 1000 0000 1111 1111 & ---------------------1000 0000

Use ~exp expr1 & expr2 expr1 | expr2 expr1^ expr2 expr1 << expr2 expr1 >> expr2 expr1 &= expr2 expr1 ^= expr2 expr1 |= expr2

Bitwise AND Operator

1000 0000 1111 1111 | ------------------------Bitwise OR Operator 0111 1111 00=0 11=0 0111 1111 ~

1000 0000 1111 1111 ^ ----------------------Bitwise XOR Operator 0111 1111

-----------------------Bitwise NOT Operator 1000 0000

0111 1111 0111 1111 << 7 shift 7 bits left >> 6 shift 6 bits right ----------------------------------------------Bitwise left shift Operator 1000 0000 Bitwise right shift Operator 0000 0001

Precedence of Arithmetic Operator


Arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. These are two distinct priority levels if arithmetic operators. High priority *, /, % Low priority +, The basic evaluation procedure includes two left to right passes through the expression. High priority operators are applied first and low priority operators are second. Just executed the following expression. x= a b / 3 + c * 2 -1 When a = 9, b = 12 and c = 3 the statement becomes Step 1 9-4+3*21 Step 2 94+61 Step 3 5 + 6 -1 Step 4 11 1 Step 5 10 Same expression are evaluated the numbers inside parenthesis 9 -12 / (3 + 3) * (2 1) Whenever parenthesis are used the expression within parenthesis are assume to be highest priority. The expression on contained in the left most set is evaluated first and the rightmost in the last. Naresh Shende 10 9890379983

Given below the steps. Step 1 9 12 / 6 * (2 1) Step 2 9 12 / 6 *1 Step 3 9-2*1 Step 4 92 Step 5 7 The procedure consists of three left to right passes. When parentheses may be nested in such cases evaluation of the expression will proceed outward from the inner most set of parentheses. Every opening parenthesis has matching closing parentheses. 9 (12 / (3 + 3) * 2) 1 9 (12 / 6 * 2) 1 9 (2 * 2) 1 9-41 4 Rules for evaluation of expression. 1. Parenthesized expression from left to right is evaluated. 2. If parentheses are nested the evaluation begins with the innermost sub expression. 3. The precedence rule is applied in determining the order of application of expressions of operators in evaluating sub expression. Conditional or Ternary Operator (? : ) Two character use in condition operator ? and :. This is also called as ternary operator pair ? : Syntax: condition ? expression2 : expression3;

In the above syntax, C compiler first checks the condition. If condition is true then value of expression1 will be evaluated otherwise the value of expression3 will be evaluated. Example: Output: a = 10, b = 15; x = (a > b) ? a : b; x = 15

Handling Octal, Hexadecimal and Decimal number. The integer number can be expressed in the three different format. Octal number: the octal number can be used digit from 0 to 7. The octal number must be preceded by zero. It can not have any special characters as blank space, comma etc. following are few valid octal numbers 0426, 0367, 014 are the valid octal numbers. The numbers are preceded by 0 to differentiate them from decimal numbers. Following are few invalid octal numbers 437, 0429, 0183 since the numbers 437 is not preceded by 0. Consider as decimal 0429, 0183 here 8 and 9 is not allow in order. The format string for octal number is %o printf statement. Hexadecimal number: The hexadecimal number is used the digit from 0 to 9 and the character a to f and A to F. The hexadecimal number will be preceded by 0X or 0x. Special character such as blank space are not allowed. Following are few valid hexadecimal numbers 0x1223e, 0xabcd3, 0XFFF, 0xA43CD. The format string for hexadecimal is %x in printf statement. Naresh Shende 11 9890379983

Consider the following program. #include<stdio.h> #include<conio.h> void main ( ) { int x=28, y=076, z=0x1ab; printf(\n %d in decimal printf(\n %d in decimal printf(\n %d in decimal getch (); } Output 28d in decimal 76 in decimal 427 in decimal 34 in octal 62 in octal 653 in octal 1c in hexadecimal 3c in hexadecimal 1ab in hexadecimal

%o in octal %o in octal %o in octal

%x in hexadecimal \n, x, x, x); %x in hexadecimal \n, y, y, y); %x in hexadecimal \n, z, z, z);

Write a program that will read two integers and print there addition, subtraction, multiplication and division. #include<stdio.h> #include<conio.h> void main() { int x, y, add, sub, mul, div; printf(\n Enter the two integers); scanf(%d %d, &x, &y); add = x + y; /*= is assignment operator*/ sub = x - y; mul = x * y; div = x / y; printf(\n Addition of two integers = %d , add); printf(\n Subtraction of two integers = %d , sub); printf(\n Multiplication of two integers = %d , mul); printf(\n Division of two integers = %d , div); getch (); } OR The above program also modify as follows. #include<stdio.h> #include<conio.h> void main() { int x, y; printf(\n Enter the two integers); scanf(%d %d, &x, &y); printf(\n %d + %d = %d , x, y, x + y); printf(\n %d - %d = %d , x, y, x - y); printf(\n %d * %d = %d , x, y, x * y); printf(\n %d / %d = %d , x, y, x / y); getch (); } Naresh Shende 12 9890379983

Problem solving technique: Algorithm and Flowchart


Problem solving with computers involves several steps: 1. 2. 3. 4. 5. 6. 7. 8. Clearly define the problem. Analyze the problem and formulate a method to solve it (validation). Describe the solution in the form of an algorithm. Draw a flowchart of the algorithm. Write the computer program. Compile and run the program (debugging). Test the program (debugging) (verification). Interpretation of results.

Algorithm: The logical sequence of operations described in concise and precise form is called algorithm. It is to be prepared before writing a program. It is machine and language independent. Flowchart: It is diagrammatic representation that shows the flow of execution of a program. Flow of procedure is from left to right and top to bottom. Arrows are used to indicate the flow. The standard symbols used for drawing flowcharts are:

Connector Magnetic Tape Magnetic Drum Magnetic disk

Naresh Shende

13

9890379983

Decision Making
Introduction
Decision Control Structure is a structure which executes a set of instructions depending on certain conditions. Generally instructions are executed sequentially. In some cases it becomes necessary to alter the sequence of executions based on certain conditions. The execution skips a part of the program are decision control structure. The different decision control structures are: 1. If 2. If else 3. Nested If else. 4. If - else - if ladder 1. If statement The general syntax of the if statement as follows. if (expression) { Statement1; } Statement2; If the value of the expression is true then Statement1 block will be executed and if the value of the expression is false then statement1 block will be skipped and the execution will jump to Statement2. The statement can be any valid statement of C. Example: if (m<40) printf (fail\n); If the above e.g. if the value of m is less than 40 then the massage fail will be executed. If the value of m is 40 or above then the expression will result is false and hence the statement part will not executed at all. Write a program that will read marks of one subject out of 100 and will display the class. 1) 2) 3) 4) 5) if m > 70 then class is distinguish. if m > 60 and < 70 then first class. if m > 50 and < 60 then second class. if m > 40 and < 50 then pass class. if m < 40 then fail. #include<stdio.h> #include<conio.h> void main ( ) { int m; printf(\n Enter Makes out of 100= ); scanf(%d, &m); Naresh Shende 14 9890379983 Syntax: -

if(m >= 70) printf(Distinction \n); if (m >= 60 && m < 70) printf(First class \n); if(m >= 50 && m < 60) printf(Second class \n); if(m >= 40 && m < 50) printf(pass \n); if( m< 40) printf(fail \n); getch( ); } 2. If-else statement The general syntax of if-else statement is as follows. if(expression) { Statement1; } else { Statement2; } It is conditional statement. When the value of expression is true it performs one action by executing a Staement1 or a set of statement. When value of expression is false it skips the part of if statement and executes statement inside the else part i.e. statement2. That is when two choices of action are required if else statement is useful. Consider the following example. if (m<40) { printf(fail\n); } else { printf(pass\n); } If value of m is less than 40 then the massage fail will be display and value of m is 40 or more then message pass will be displayed. 3. Nested if-else statement If one if is used inside the other if or multiple ifs are used one inside the other, the program structure looks like nested. Therefore, such if statement are called nested if statement.

Naresh Shende

15

9890379983

The general syntax of Nested if-else statement is as follows. if(condition1) { if(condition2) { Statement1; } else { Statement2; } } else { Statement3; } Statement-x; If condition 1 and condition2 is true, Statement1 will get executed. If condition1 is true and condition2 is false, Statement2 will get executed. if condition1 is false then Statement3 will get executed, and then the control is transferred to the statement-x. 4. If-else-if ladder When multiple decisions are involved, a multiple decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general from. if (codition1) Statement1; else if (condition 2) Statement 2; else if (condition n) Statement-n ; else default statement; Statement-x; This construct is known as the else if ladder. The condition are evaluated from the top (of the ladder), to downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the default statement will be executed. Write a program that will read marks of one subject out of 100 and will display the class. 1. 2. 3. 4. 5. if m >70 then class is distinguish. if m > 60 and < 70 then first class. if m > 50 and < 60 then second class. if m > 40 and < 50 then pass class. if m > 40 then fail. 16 9890379983

Naresh Shende

#include<stdio.h> #include<conio.h> void main () { int m; printf(\nEnter Makes out of 100= ); scanf(%d, &m); if(m >= 70) printf(Distinction \n); else if(m.>=60 && m < 70) printf(first class \n); else if(m >= 50 && m < 60) printf(second class \n); else if(m > 40 && m < 50) printf(pass class \n); else printf(fail \n); getch (); } Switch statement The switch statement causes a particular group of statement to be chosen from several available groups. The selection is based upon the current value of an expression, which is including within switch statement. It is multi decisional entry test statement. It consists of several case values, which will compared with a single expression value. If expression value and case value matches, statements in the case are executed. It is also called as menu driven program. The general from of switch statement shown below. switch (expression) { case expression 1: statement 1; : break; case expression 2: statement 2; : break; case expression n: statement 1; : break; default : statement ; } statement x; Naresh Shende 17 9890379983

Write a program to perform addition, subtraction, multiplication, division according to user choice using switch statement. #include<stdio.h> #include<conio.h> void main () { int no1, no2, choice; clrscr( ); printf(\n 1. Addition); printf(\n 2. Subtraction); printf(|n 3. Multiplication); printf(\n 4. Divition); printf(Enter two number: ); scanf(%d %d, &no1, &no2); printf(\n Enter choice: ); scanf(%d, &choice); switch(choice) //passing choice to check its values { case 1: //checks if 1 is entered as a choice printf(\n Addition is %d, no1+no2); break; //case will get break if executed case 2: printf(\n Subtraction is %d, no 1- no 2); break; case 3: printf(\n Multiplication is %d ,no1*no2); break; case 4: printf(\n Division is %d, no1/no2); break; default: printf(\n Invalid value entered); // other than 1,2,3or4 break; getch (); } Goto statement.(Jump Any Where in a Program) The goto statement to branch unconditionally from one point to another in the program. The go to statement requires label in order to identify the place where the branch is to be made. A label is any valid variable name and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The label can be any where in the program either before or after the go to label statement. Syntaxgoto label; statement 1; statement 2; label: statement; The goto breaks a normal sequential execution of the program. If the label; is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as Naresh Shende 18 9890379983

a backward jump. On the other hand, if the label; is placed after the goto label; some statements will be skipped and the jump is known as a forward jump. Consider the following program. /* program for controlling flow of data using goto */ #include<stdio.h> void main ( ) { float x, y; read: scanf(%f, &x); if(x < 0) goto read; y = sqrt (x); printf(%f %f \n, x, y); getch( ); } This program is written to evaluate the square root of a series of number read from the terminal. The program use goto statement, to skip any computation when the number is negative. Break statement (Jumping Out of Loop) The break is supported by loop. Break statement throws the control outside the loop and skip part of loop below it and transfers control to the statement very next to loop. This statement is also used in switch statement to break the particular case body. Irrespective of condition I.e.in a premature condition break statement is supported by loop only. The break statement can be used in the format given below. Any loop statement { Statement 1; if(expression) break; Statement 2; } Statement x; In above loop, test expression is evaluated, if the true, break will be executed and loop will be terminated without executing statement 2. After the loop termination, the statement x is executed. Consider the following example. for(i=1; i<100; i++) if(i >10) break; else printf(%d\t, i); In the above program from all the values i from 1 to 10 the condition i >10 will be false hence, control will go in else part and number from 1 to 10 will be printed when i will become 11 will greater than 10 true the break statement will be executed and control will come out of the for loop. The above example the break statement can be avoided by modifying as follows. for(i=1; i<10; i++) printf(%d\t, i); Naresh Shende 19 9890379983

Accept 5 numbers from user and sum them, if user enters 100 exit the program #include<stdio.h> #include<conio.h> void main ( ) { int no=0, i=1, sum=0; clrscr(); while(i<=5) //condition for accepting five numbers i.e. till becomes 5 { printf(\n Enter number: ); scanf(%d, &no); if(no ==100) //if accepted number is 100. { break; //the control gets break and it comes out of loop } sum=sum + no; i++; } printf(The sum of is %d, sum); //the final sum of all the numbers. getch(); } Continue statement(Skip part of the Loop) The continue statement allows to skip the part of the loop (below the continue statement) after it is encounter in the loop and mares execution to start from beginning part of the loop Any loop statement { statement 1; if(expression) continue; statement 2; } Every time conditional statement is executed, if it is true, continue statement is executed. This skips statement2 and starts from the first statement in the loop. Consider the following program Program to display only the numbers divisible by 7 #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for( i=1; i<=100; i++) { if(i%7!=0) continue; printf(%d\n, i); } getch(); } Naresh Shende 20 9890379983

In the above example all the value of i from 1 to 6. i % 7!=0 and continue statement will be executed and control of execution will keep on continue the next iteration. When i will become 7, 7%7 will go false and printf will executed and 7 will be executed for the value of i from 8 to 13 continue statement will be executed and the 14 will be printed. Thus, we can conclude that all the multiplies of 7 which are less than or equal to 100 will be printed. For the above example continue can be avoided and modifying logic can be written as follows. for(i=1; i<100; i++) if(i%7 == 0) printf(%d\t i); Program to demonstrate use of continue statement #include<stdio.h> #include<conio.h> void main() { inti=0, j=0; for(i=1; i<=2; i++) { for(j=1; j<=2; j++) { if(i==j) continue; printf(\n %d %d, i, j); } } getch(); } Difference between if statement and switch statement If 1. If is used to check multiple conditions at a time. 2. If is complicated to understand if number of conditions are more. 3. If provides a facility to use the nesting of the loop. 4. If uses AND, OR, NOT operator to verify or check the condition. Switch 1. Switch checks a single condition at a time. 2. Switch is easy to understand even if number of condition is more. 3. Nested Switch is not popular as If else nested loop. 4. Switch generally checks unique i.e. single character or single integer values as its cases.

Loops
When a certain statement or groups of statement are executed repeatedly then it from loop. In C there is different types of loops. 1. for loop 2. while loop 3. do-while loop Naresh Shende 21 9890379983

for loop The for loop is entry controlled loop that provides a more concise loop structure. The general syntax of for loop is as follows. for(expression 1; expression 2; expression 3) { statement; } Where expression1 is used to initialize the control variable, expression2 is used to check the condition and expression3 is used to for increment/decrement or modifying. 1. for(i=1; i<=5; i++) printf(%d\t, i); Output- 1 3. 2 3 4 2. for(i=1; i<=4; i=i) printf(%d\t, i); Output-111111.is printed is infinite loop

for(i=5; i<=4; i++) printf(%d\n, i); No output display

Description of for loop expression1-: The expression 1 is called as initialization expression it is executed only once. expression2-: The expression2 is called as conditional expression depending on the result of this condition the statement is executed or not executed. expression3-: The expression3 is called as modifying expression it is used to modifying the value of variable used in expression2. While loop The general form of while loop is initialization; while ( test condition) { Body of the loop; } The while loop is an entry controlled loop statement. The test condition is evaluated and if the condition is true then the body of the loop is executed. This process is repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. Do-while loop The general form of do-while loop is initialization; do { Body of the loop; } while (test condition); In do-while loop first evaluate the body of the loop. At the end of the loop, test condition is evaluated in while statement. If the condition is true, the program continues to evaluate the body of the loop upto the condition is true. When condition is false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Naresh Shende 22 9890379983

Difference between while loop and do-while loop While loop In while loop checks the condition at the beginning of loop. It is more accurate as compare to do while loop. If condition is false it can not execute the statement body of the loop. Syntax of while loop while ( test condition) { Body of the loop; } Do while loop Do while loop checks the condition at the end of the loop. It is not accurate as compare to while loop. It can be execute all the statement body of the loop at least once. Syntax of do while loop do { Body of the loop; } while (test condition);

Write a program that accepts that one positive integer and prints whether the number is even or odd. #include<stdio.h> #include<conio.h> void main() { int num; clrscr( ); printf(\n Enter the one positive integer number: ); scanf(%d, &num); if(num%2 == 0) // if num % 2 is zero then number is divisible by 2 so it is even { printf(\n %d is even number, num); } else { printf(\n %d is odd number, num); // non zero then number is odd } getch(); } Write a program to find the greater number between two numbers. #include<stdio.h> #include<conio.h> void main( ) { int num1, num2; printf(\n Enter two numbers:); scanf(%d %d, &num1, &num2); if(num1 > num2) //Checking condition if num1 > num2 { printf(\n The greater number is:%d,num1); } else { printf(\n The greater number is: %d, num2); } getch(); } Naresh Shende 23 9890379983

Arrays and Strings


Arrays Array is collection of similar data type of elements, where all the data elements share the same name. OR An array is a data form that can hold several values all of same type. Each value is stored in a separate array element and computer stores all the elements sequentially or consecutively in memory. The array may consist of integers, characters, floating point values, or other data types present in C. Arrays are classified in the three types as follows. 1) One dimensional array 2) Two dimensional array 3) Multidimensional array Dimension defines the number of rows and columns of the array, i.e. dimension specifies how many rows and columns are available to store the data. 1. One dimensional array Single dimensional array is collection of multiple elements of the same data type. A list of items having same variable name and they are stored in continuous memory location. Declaration of one dimensional array Syntax: Example: data_type array_name[max_size]; int a[5];

The above example a is group of 5 integers and a is group name but to access individual element. We will have to specify the position of that element. This position is called subscript or index. This array element will be stored as

a[0]

a[1]

a[2]

a[3]

a[4]

The above example indicates that a is array of 5 integers and subscripts values ranges from 0 to 4. In general, if the array is of n elements then the subscript ranges from 0 to n-1. Initialization of one dimensional array The single dimensional array is initializing as follows. int a[5] ={10, 20, 30, 40, 50,}; Then it will be store this data as 10 a[0] a[0]=10 a[1]=20 a[2]=30 a[3]=40 a[4]=50 Naresh Shende 20 a[1] 30 a[2] 40 a[3] 50 a[4]

24

9890379983

Example:

int b[5]={10, 20};

10 b[0]

20 b[1]

0 b[2]

0 b[3]

0 b[4]

Example: int c[5]; c[0] c[1] c[2] c[3] c[4]

Example: float val[5] ={1.2, 2.1, 11.1, 2.20, 13.4}; 1.2 val[0] Example: char name[9]=WEL COME; name[0] name[1] name[2] name[3] name[4] name[5] name[6] name[7] name[8] W E L C O M `E \0 2.1 val[1] 11.1 val[2] 2.20 val[3] 13.4 val[4]

In the above example when we assign a character value then it is given the single quotation marks. When each character is placed in the location then some locations may left empty. Remaining locations are empty then immediately after last character \0 value is placed. This is called as NULL. Null means nothing not even zero. Null indicates the end of the string. Reading elements of an array The first element in the array is numbered 0, so the last element is less than the size of the array. Example, to read the elements in an array the C code will be int a[10]; for( i=0; i<9; i++) { printf(\n%d, a[i]); } Storing element in to array int a[10], i; for( i=0; i<9; i++) { scanf(%d, &a[i]); } Naresh Shende 25 9890379983

Write a program to print the contents of the array using for loop #include<stdio.h> #include<conio.h> void main( )
{

int arr[5] ={10, 15, 78, 90, 100}; //Declaration and initialization of array int i; for (i=0; i<=4; i++) // for loop is used to count the location from 0 to 4 { printf(\n%d, &arr[i]); //printing values of ith location of an array } getch ( ); } Write a program to accept 5 elements store them in an array and display result. #include<stdio.h> #include<conio.h> void main( ) { int number[5]; //Declaring integer array number of 5 elements. int i; // i is used for repetition as well as for accessing location. clrscr ( ); printf (\n Enter the elements: ); for (i=0; i<=4; i++) { scanf (%d, & number [i]); } for (i=0; i<=4; i++) // for loop to print the values from array. { printf (\n %d is stored at %d location of array, number[i], i); } getch ( ); } 2. Two Dimensional Arrays Two dimensional arrays require two pairs of square brackets. The value within the first brackets indicates of number of rows and value within the second bracket indicates number of columns. Initialization of two dimensional arrays during declaration is done as Syntax: Example: data_type array_name[row_size][column_size]; int arr[3][3]={1,2,3,4,5,6,7,8,9};

The result of this initial assignment is as follows arr[0][0]=1 arr[0][1]=2 arr[0][2]=3 arr[1][0]=4 arr[1][1]=5 arr[1][2]=6 arr[2][0]=7 arr[2][1]=8 arr[2][2]=9 Row 0 Row 1 Row 2 Col 1 1 4 7 Col 2 2 5 8 Col 3 3 6 9

The natural order in which the initial values are assigned can be altered by forming group of initial values enclosed within braces i.e. {.} Naresh Shende 26 9890379983

int arr[3] [3]={ {1, 2, 3}; {4, 5, 6}; {7, 8, 9}; }; Accessing two dimensional array elements. The element is of a two dimensional array can be accessed by following expression arr[i][j] Where [i] refers to the row number and [j] refers to the column number. The c code will be as for(i=0; i<3; j++) { for(j=0; j<3; j++) { printf(\n%d, arr[i][j]); } } Write a program to read two dimensional matrixes and print it. #include<stdio.h> #include<conio.h> void main ( ) { int i, j, m[3][3]; printf(\n Enter the element in matrix); for ( i=0; i < =2; i++) { for (j=0; j<=2; j++) { scanf (%d, &m[i][j]); } printf(\n); } printf(\n Display two dimensional matrix ); for(i=0; i<=2; i++) { for(j=0; j<=2; j++) { printf(\t.%d, m[i][j]); } printf (\n); } getch ( ); }

Strings
String is collection of characters. When we write a word or sentence, it is treated as a string. e.g. Welcome to Home is called as string. Arrays can be used to store character string. Each location of character array stores each string character from string. Naresh Shende 27 9890379983

Declaration of Strings Syntax: char array_name[size];

Example: char name[20]; If we would like to store Welcome to Home to name variable then memory representation of string name would be as follows. 0 W 1 e 2 l 3 c 4 o 5 m 6 e 7 8 t 9 o 10 11 H 12 o 13 m 14 e 15 \0

Where 0, 1, 2,..15 are location number of string.\0 is called as null value. Null means end of the string. After entering string by user null value is stored after the last character entered. Null value can be represented as \0 as well as Null. Initializing String String can be initialized in two way as follows. char name[25] = Welcome to Home; or char name[25] ={W, e, l, c, o, m, e, , t, o, , H, o, m, e, \0}; In the above example the string will be filling with Welcome to Home and after that it will place \0 i.e. null remaining location. Write a program to display the contents of the string. #include<stdio.h> #include<conio.h> void main ( ) { char str[25]=Welcome to World of C ; int i=0; printf(\n Entered string is %s, str); printf(\n Values stored at each location are: \n); for(i=0; i<=25; i++) { printf(str[%d]=%c\n, i, str[i] ); } getch( ); } Write a program to accept string from user and display message. #include<stdio.h> void main () { char name[20]; clrscr( ); printf(\n Enter name:); scanf(%s, name); printf(Welcome %s you are running C program, name); getch( ); } Naresh Shende 28 9890379983

Table of String When we need the lists of character string, such as a list of the name of students in a class, list of the names of employees in an organization, list of places, etc. a list of names can be treated as a table of string and a two, dimensional character array can be used to store the entire list. A character array student [30] [15] may be used to store a list of 30 name, each of length not more than 15 character. For example following program store the 5 city name and maximum length character is not more than 10. #include<stdio.h> #include<conio.h> void main( ) { char city[5] [10] ={

Mum,bai, Pune, Nasik, Aurangabad, Kolhapur

}; int i=0; for(i=0; i<=4; i++) { printf(\n %s, city[i] ); } getch( ); }

String handling (library) function


String is nothing but a sequence of character. The string is to be terminated with null character \0. There are different standards function are available with string for reading, writing the string, copying the strings. The mostly commonly used string functions are. 1. strlen(string): This function counts and returns the number of characters in the string. Syntax n = strlen(string);

Where n is an integer variable which receives the value of the length string. String is any character string or a constant string. The counting ends of the first null characters. 2. strcat(string1, string2): This function is used to join to string together. Syntax strcat (string1, string2); Where string1 and string2 are separate arrays. When function strcat( ) is executed string2 gets appended to string1 and the null character at the end of string is removed. 3. strcmp (string1, string2):

This function is used to compares two strings and return value 0 if they are equal. If they are not equal it returns the numeric difference between the first non matching characters in the string. i. e. numeric between the ASCll values. Syntax strcmp (string1, string2);

Where string1 and string2 are character arrays.

Naresh Shende

29

9890379983

4. strcpy (string1, string2): This function copies the content of one string to other string. Syntax strcpy (string1, string2);

Where string1 and string2 are character arrays. The content of string2 gets copied to string1. The length of string should be enough large to receive the contents of the string. Program for standard library functions. #include<stdio.h> #include<conio.h> #include<string.h> void main( ) { char str1[20] =Computer; char str2[10] =World; clrscr( ); printf(\n String length of % s is %d, str1, strlen(str1)); printf(\n String length of %s is %d, str2, strlen(str2)); if (strcmp(str1, str2)!=0) { printf(\n %s and %s are not equal, str1, str2); } strcat(str1, str2); printf(\n After concatenation str1 is %s, str1); strcpy(str1,str2); printf(\n After copying str1=%s str2=%s, str1, str2); getch( ); }

Naresh Shende

30

9890379983

Functions and Structures


Introduction to functions Every C program contents at least one function and that function is named as main. A program can have two or more function and one of them must have the name main. A function is a self contained block of statements that perform a particular task. Every C program can be designed using a collection of functions. Types of Function 1. Library function: These are predefined functions are not required to be written by us. E.g. printf(), 2. User defined function: User defined functions are developed by the user at the time of writing a program. When a certain type of operations or calculations are repeated many time in the program, one way to repeat the statements where they are required. Another way is to design a function that can be called and use whenever required which saves both time and space. Need of function / Advantages of functions. 1. 2. 3. 4. 5. It avoids rewriting the same code again and again. Using function it becomes easier to write programs and keep track of what they are doing. The length of source program can be reduced using function. It is easy to locate and isolated a faulty function. We can use the function in many programs.

Elements of user - defined function In order to make use of a user- defined function, we need to establish three elements that are related to functions. 1. function definition. 2. function call. 3. function declaration. The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as the function call. The program (or a function) that calls the function is referred to as the calling program or calling function. The calling program should declare any function (like declaration of a variable) that is to be used later in the program. This is known as the function declaration or function prototype. 1. Definition of function A function definition, also known as function implementation shall include the following element. function type; function name; list of parameters; local variable declaration; function statement; return statement. Naresh Shende 31 9890379983

All the six element are grouped into two part, namely, function header (first three element); and function body (second three element). A general format of a function definition to implement these two parts is given below: function_type function_name (parameter list) { local variable declaration; executable statement 1; return statement; } The first line function_type function_name(parameter list) is known as function as the function header and the statements within the opening and closing braces constitute the function body, which is a compound statement. Return values and their type Function may or may not send back any value to the calling function. If it dose, it is done through the return statement. While it is possible to pass to the called function any number of values, the called function can function can only return one value per call, at the most. The return statement can task one of the following forms: return; or return(expression); The first, the plain return dose not returns any value; it acts much as the closing brace of the function. When a return is encountered, the control is immediately passed back to the calling function. An example of the use of a simple return is as follows: if(error) return; The second from of return with as expression returns the value of the expression. For example, the function. int mul (int x, int y) { int p; p=x*y; return (p); } Returns the value of p which is the product of the value of x and y. the last two statements can be combined into one statement as follows: return (x*y); A function may have more than one return statement. This situation arises when the value returned is based on certain condition. For example if(x <=0) return(0); else return(1); Naresh Shende 32 9890379983

2. Function calls A function can be called by simply using the function name followed by a list of actual parameters (or arguments), if any, enclosed in parentheses. Example: main( ) { int y; y = mul (10, 5); /* Function call */ printf(%d \n, y); } When the compiler encounters a function call, the control is transferred to the function mul( ). This function is then executed line by line as described and value is returned when a return statement is encountered. This value is assigned to y. this value is assigned to y. this is illustrated below: #include<stdio.h> void main( ) { int y; y = mul (10, 5); // function call printf(\n multiplication = %d, y); } int mul (int x, int y) { int p; /* local variable */ p=x*y; /* x=10, y=5 */ return (p); } The function call sends two integer values 10, and 5 to the function. 3. Function declaration Like variable, all function in a C program must be declared, before they are invoked. A function declaration (also known as function prototype) consists of four parts. Function (return type). Function name. Parameter list. Terminating semicolon. They are coded in the following format: Function_type Function_name (parameter list); This is very similar to the function header line except the terminating semicolon. For example, mul function. int mul (int m, int n); /* Function prototype */ Category of functions A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: Category 1: Functions with no arguments and no return values. Category 2: Functions with arguments and no return values. Category 3: Functions with arguments and one return values. Category 4: Functions with no arguments but return a values. Category 5: Function that return multiple values. Naresh Shende 33

9890379983

1. Functions with no arguments and no return values When a function has no arguments, it dose not receive any data from the calling function. Similarly, when it dose not return a value, the calling function dose not receive any data from the called function. In effect, there is no data transfer between the calling function and the called function. The dotted lines indicate that there is only a transfer of control but not data. control function1 ( ) { No input -----------------------------------------No output function2 ( ) ---------------------------------control } Figure 1 function2 ( )
{

------------------------------------}

No data communication between function

Write a program to add two numbers using user defined functions that do not communicate any data between them. #include<stdio.h> #include<conio.h> void add (void); void main( ) { clrscr( ); add ( ); getch( ); } void add ( ) { int a, b; printf(\n Enter first number:); scanf(%d, &a); printf(\n Enter second number:); scanf(%d, &b); printf(\n The addition of %d+%d=%d, a, b, a+b); } 2. Function with Arguments but no return values In functions with no arguments and no return values has no control over the way the functions receive input data. In this case function will print the same line each time. We could make the calling function to read data from the terminal and pass it on the called function. This approach calling function can check for the validity of data, if necessary, before it is handed over to the called function. The nature of data communication between the calling function and the called function with arguments but no return values is called one way data communication. function1 ( ) { ------------------function2 (a) ---------} Naresh Shende Value of arguments function2 (f)
{

No return values ----------------------------

------------------------------------} 9890379983

Figure 2: One way data communication 34

PARAMETERS The parameters are also known as arguments used to communicate between function. The parameters are used in function definition, function declaration (prototype) and function definition. Parameters are two types. 1. Actual parameters. 2. Formal parameters. 1. Actual parameters: The parameters which are enclosed in a function call is called actual parameters. Actual parameters used in a calling statement may be simple constants, variable or expression. 2. Formal parameters: The parameters used in prototypes and function definitions are called formal parameters. main( ) { Function call Called function function1(a1, a2, a3,..am); } function2(f1, f2, f3, .fn); { }

Arguments matching between the function call and the called function Write a c program to print fibonacci series using functions #include<stdio.h> #include<conio.h> void fib(int,int,int,int); void main() { int n,i=0,j=0,s=1; clrscr( ); printf(Enter a value:\n); scanf(%d,&n); printf(Fibonacci series is:\n); fib(n,i,j,s); getch(); } void fib(int n,int i,int j,int s) { if(n>0) { printf(%d,,s); i=j; j=s; s=i+j; fib(n-1,i,j,s); } }

Naresh Shende

35

9890379983

3. No arguments and return values The function which does not accept arguments the values is function without arguments and returning values. Following are the demonstrate the same category. function1 ( ) { ------------------function2 ( ) ---------} No arguments ---------------------------Function result } function2 (f)
{

---------------------------return (e)

Figure 3 One way data communication Write a program to calculate the string length using function. #include<stdio.h> #include<conio.h> int str_len ( ); void main( ) { int length; length=str_len ( ); printf(\n string length=%d, length); getch ( ); } int str_len ( ) { int i=0; char str[10]; printf(\n Enter string); scanf(%s, str); while (str[i]!=\0) { i++; } return i; } 4. Arguments with return values In this category functions may have one or more than one arguments with in which can be different data types and also return values of required data type. A self contained and independent function should behave like a black box that receives a predefined from of input and outputs a desired value. Such functions will have two way data communication between calling and the called function. function1 ( ) { ------------------function2 (a) ---------} Values of arguments function2 (f)
{

function result }

---------------------------return(e)

Naresh Shende

Figure 4 Two way data communication between functions 36 9890379983

Write a program to find out factorial of number using function. #include<stdio.h> #include<conio.h> long int fact(int); void main( ) { int no=1; printf(\n Enter number:); scanf(%d, &no); printf(\n The factorial of number %ld, fact(no)); } long int fact(int n) { int no=1; long int fact=1, i; for(i=1; i<=n; i++) { fact =fact*i; } return fact; }

Recursion
When a function calls itself the process is called as recursion and such a function is called as recursive function. Recursion is suitable for the problems which can be express in terms of itself. Recursion always gives partial solution. All partial solution is to be combined to get the final solution. The recursive process must be return in such way that by same condition it should stop. Otherwise it will lead to an infinite process. Write a recursive function that accepts one integer and finds out its factorial. #include<stdio.h> #include<conio.h> long int fact(int); void main( ) { int no=1; printf(\n Enter number:); scanf(%d, &no); printf(Factorial of number=%ld, fact(no)); getch() ; } long int fact(int n) { long int f; if(n==1) return 1; else { f=n*fact(n-1); return(f); } } Naresh Shende 37 9890379983

Enter number: 4 Factorial of number=24 In the above program the multiplication of factorial of number will take place as follows. f=4*fact(3) f=4*3fact(2) f=4*3*2fact(1) f=4*3*2*1 f=24 In the above process fact (3) is to invoke of the fact function called from main. As the process shows function calls fact (2) which is invoke of the same function and the function invokes will keep n calling new invoke and it will returned the value 1 and then the come back process will start. Call by value In this method while calling function the arguments are passed to function by value. In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. Write a function to exchange the values of two variables. #include<stdio.h> #include<conio.h> void swap(int, int); void main( ) { int a=10, b=20; clrscr( ); printf(\n Before swapping); printf(\n a=%d, b=%d, a, b); swap(a, b); getch (); } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; printf(\n After swapping); printf(\n a=%d, b=%d, a, b); } Call by reference Call by reference means calling the function by passing the address of the variables, rather than copies are sent to the called function. In this case, the called function directly works on the data in the calling function and the changed values are available in the calling function for its use. Write a pointers function to exchange the values two variables. #include<stdio.h> void swap(int *a, int *b); void main( ) { int a =10, b=20; printf(\nBefore swapping\n); Naresh Shende 38 9890379983

printf(\n a =%d, b=%d, a , b); swap(&a , &b); getch ( ); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; printf(\n After swapping\n); printf(\n a =%d, b=%d, *a , *b); }

Scope, Visibility and Lifetime of Variable


Scope the region of program in which a variable is available for use. Visibility is the programs ability to access a variable from the memory. The lifetime of variable is the duration of time in which a variable exists in the memory during execution. Rules of use 1. The scope of global variable is the entire program file. 2. The scope of local variable begins at point of declaration and ends at the end of the block or function in which it is declared. 3. The scope of a formal function argument is its own function. 4. The lifetime of an auto variable declared in main is the entire program execution time, although its scope is only the main function. 5. The life of an auto variable declared in a function ends when the function is exited. 6. A static local variable, although its scope is limited to its function, its lifetime extends till the end of program execution. 7. All variable have visibility in their scope, provided they are not declared again. 8. If a variable is redeclared within its scope again, it loses its visibility in the scope of the redeclared variable.

Storage classes (short notes on storage classes)


The storage classes are used the area within the program in which variable are going to be recognized. Storage class is also called as type qualifiers which can be used while declaring the variable. There are four types of variables used in storage classes. 1. Auto: Auto variable use inside the function or block in which it is declared. Default is auto and life of this variable is until the end of function. 2. Static: Static variable is declared in external or internal. External static variable before all function in a file. This variable active only in that file and this is global variable. Internal static variable inside a function and only in that function. 3. Extern: Global variable which is declared before all the functions in a file and used files where variable is declared. 4. Register: local variable which is stored in the resister memory. 1. Auto variable Automatic variable declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name Naresh Shende 39 9890379983

automatic. Automatic variables are therefore private to the function in which they are declared. Automatic variables are also referred as local or internal variable. An automatic variable is that their value cannot be changed accidentally by what happens in some other function in the program. This assures that we may declare and use the same variable name in different functions in the same program without any confusion to the complier. Consider the following program to study auto variables. #include<stdio.h> void main ( ) { auto int i; void fun ( ); for(i=1; i<=5; i++) fun (); } void fun () { auto int x=1; printf(%d\n, x); x++; } In above program the function fun is defined. It accepts nothing and returns nothing. The function is called from the loop five times. When function is called at the first time the variable x with storage class auto will come in existence inside the memory and it will be initialized with 1 and then its value will be printed. After printing the value is incremented by 1. So it will become 2. Then the function fun is finished. Since the storage class of x is auto it will also get finished. The control will go back to main and fun is called again. When it is called for the second time the x will come in existence again. It will reinitialize with 1 then it is printed and then it is incremented and as function gets finished x gets finished. The purpose will be repeated 5 times and 1 is printed 5 times. 2. Static variable The value of static variable persists until the end of the program. The variable can be declared static using the keyword static like. static int x; static float y; A static variable may be either an internal type or an external type depending on the place of declaration. Internal static variable are those in which are declared inside a function. The scope of internal static variable extends up to the end of the function in which they are defined. Internal static variable are similar to auto variable, except that they remain in existence throughout the remainder of the program. Consider the following program to study static variables. #include<stdio.h> void main( ) { auto int i; void fun ( ); for(i=1; i<=5; i++) Naresh Shende 40 9890379983

fun ( ); } void fun ( ) { static int x=1; printf(%d\n, x); x++; } In above program the variable x is defined with storage class static. Everything is same at that of program of auto variable. When the function is called for the first time the x will come in existence inside the memory and its initialize with 1. Its value is printed the function is finished but x will not be finished. It will remain in the memory along with its value. When the fun is called second time it will not be reinitialized. Hence the value of x i.e.2 is printed and x is incremented by 1. So that it will become 3 and the process will continue 5 times and output will be printed as 1 2 3 4 5. When the main function is finished and x will also be finished. 3. External variable Variable that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. External variables are declared outside a function. External variables declared with extern keyword. Extern declaration does not allocate storage space for variables. Consider the following example. #include<stdio.h> void main ( ) { extern int x; int y=12; printf(%d \n %d \n, x, y); } int x=10; Output 10 12 In the above program the statement extern int x it informs compiler x available some where external to the main function. Since x is define externally and initialize with 10. The value printed will be 10, 12. Global variable: The variable which is defined out side of any of the function is called as Global variable. Local variable: The variable which is defined with in a function is called as called as local variable of that function.

Extern variables with multiple programs


Multiple source files can share a variable provided it is declared as an external variable appropriately. Variable that is shared by two or more files global variables and therefore we must declare them accordingly in one file and then explicitly define them with extern in other files. Naresh Shende 41 9890379983

Consider the following example. #include<stdio.h> #include<pqr.dat> void main ( ) { extern int x; int y=12; printf(%d %d \n, x, y); } Output 10 12

pqr.dat int x=10

The above example is the multi file programming example. The file pqr.dat defines only one variable x and it is initialized with 10. In file abc.c with in a main function the x is declared as external variable. When compiler in stdio.h and x will not be found it. Then it will declare in pqr.dat and it will found. Therefore output will be 10, 12. 4. Register variable Whenever, a storage class of variable is register then it will be stored inside one of the general purpose register inside the memory (microprocessor). (Auto and static are stored in RAM). However if any register inside the microprocessor is not free then the register variable will be stored in main memory only just like auto and static. Wherever that register variable is stored its life span is just like auto. Since a register access is much faster than a memory access, keeping the frequently accessed variables. register int x; Consider the following declaration: #include<stdio.h> void main( ) { register int i=1; for(i=1; i<=3; i++) { printf(\n Welcome to C programming); } getch( ); } Output Welcome to C programming Welcome to C programming Welcome to C programming

Structure
Structure is a user defined data type which is collection of different data elements or collection of data types is a according to the requirement of user. The general syntax of structure template as follows. Syntax struct structure_name { data_type member_name 1; data_type member_name 2; ------------data_type member_name n; }; Naresh Shende 42 9890379983

Example

struct student { int roll_no; char name name[20]; int percent; };

Where struct is the keyword used to declare the structures. Structure name is the identifier for structure and the block of the structure contains fields which can be of dissimilar data types. Each of the fields is known as the member or the element of the structure. In the above example student is a structure template and roll_no, name and percent are all members of the structure template. One can create any number of variables of type student. Thus above example the members are different type. To create a variable of type student write the following statement. struct student S1; roll_no name percent S1 2 bytes 20 bytes 4 bytes Give the general from of structure and define a structure student having member variables as roll_no, name, dob. struct student { int roll_no; char name[20]; int dob; }; Declaring structure variables Example struct book { char name[20]; float price; int pages; }b1,b2,b3; struct book { char name[20]; float price; int pages; }; struct book b1,b2,b3;

OR

Accessing Members of the Structure Individual member of structure are accessed through the use of the dot (.) operator. The general form for accessing a member of a structure is structure_variable . member_name; Consider the following example. Example struct book { char name[20]; float price; int pages; }b1;

The individuals members for variables b1 can be access as b1.name, b1.price and b1.pages. The above examples indicate how to access the individual fields or members of this structure. Naresh Shende 43 9890379983

Array of Structure
Array is collection of same type of elements. Same as structure is collection of different data types of elements. When we would like to store more than one record in the memory, we can use array of structure. This array gets store continuously in the memory. Due to continuous storage, access to this array becomes easy. This is similar for loop can be used to access the structure elements. Declaration of array of structure can be done as follows. Example struct book { char name[20]; OR float price; int pages; }; struct book b[3]; In the above case b is the structure variable. b[3] is an array which can store three records of the student details. b[0].name b[0].price b[0].pages b[1].name b[1].price b[1].pages b[2].name b[2].price b[2].pages Nested structure of structure within a structure or embedded structure Consider the following example struct date { int dd, mm, yy; }; struct student { int roll_no; int marks; struct date birthdate; }; struct student s1;
s1 roll_no marks birthdate dd mm yy

struct book { char name[20]; float price; int pages; }b[3];

The member of s1 can be access as s1.roll_no, s1.marks and to access the complete birthdate it will be done as s1.birthdate. To access the individual member of the birthdate from s1. We can write s1.birthdate.dd, s1.birthdate.mm, s1.birthdate.yy therefore the general syntax that can be used to with nested structure to access the members as follows. struct_variable_name . member_name . submember_name Naresh Shende 44 9890379983

Assignment with structure variable consider the following example struct date { int dd, mm, yy; }; struct date d1,d2; void main( ) { d2.dd=18; d2.mm=3; d2.yy=2002; d1=d2; }

i.e d1.dd=d2.dd; d1.mm=d2.mm; d1.yy=d2.yy;

Declare a structure emp having data member employee number, name, salary. Accept this data for one variable and display accepted result. #include<stdio.h> #include<conio.h> void main( ) { struct emp { int emp_no; char emp_name[10]; float emp_sal; }e; struct emp e={101,Ashish, 5250.50}; printf(\n employee number=%d,e.emp_no); printf(\n employee name=%s, e.emp_name); printf( \n employee salary=%f, e.emp_sal); getch( ); } Declare a structure Book having data member title, author, price. Accept this data for one variable and display accepted result. #include<stdio.h> #include<conio.h> struct book { char title[20]; char author[20]; float price; }b1; void main() { printf(\n Enter book title ); scanf(%s, b.title); printf(\n Enter book-name: ); scanf(%s, b.author); printf(\n Enter book price: ); scanf(%f, &b.price); printf(\n book title=%s\t book author=%s \t book price=%f \t, b.title, b.author, b.price); getch( ); } Naresh Shende 45 9890379983

Pointers
Introduction to pointers Pointer is derived data type in C. Pointer contain memory addresses as their values. Since these memory addresses are the locations in the computer memory where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory. Need of Pointers Pointers are one of the most exciting features of C language. It has power and flexibility to the language. 1. Pointers are more efficient in handling arrays and data tables. 2. Pointers can be used to return multiple values from a function via function arguments. 3. Pointers permit references to functions and facilitating passing of function as arguments to other functions. 4. The use of pointer arrays to character string result in saving of data storage space in memory. 5. Pointers allow C to support dynamic memory management. 6. Pointers provide an efficient tool for structure, linked lists, queues, stacks and trees. 7. Pointers reduce the length and complexity of programs. 8. They increase the execution speed and thus reduce the program execution time. Concepts of Pointers A pointer is a variable that represents the address of a data item i.e. location of data item in the computer memory. The computer memory is a sequential collection of storage cells, each cell commonly known as byte, has a number called address associated with it. Whenever we declare a variable, the system allocates somewhere in the computer memory, an appropriate location to hold the value of the variable. Since, every byte has a unique address number this location will have its own address number. Consider the following example int quantity=179; quantity 179 5000 Variable Value Address

During execution of the program system always associates the name quantity with the address 5000. We have access to the value 179 by using either the name quantity or the address 5000. Since memory addresses are simply numbers, they can be assigned to some variables that can be stored in memory, like any other variable. Such variables that hold memory addresses are called pointer variables. A pointer variable is nothing but a variable that contains an address, which is a location of another variable in memory. Declaring pointer variable Pointer variable contain addresses that belong to a separate data type, they must be declared pointers before use them. Declaration of pointer variable is as follows. data_type * pointer_name; This tells the complier three things about the variable pointer_name Naresh Shende 46 9890379983

1. The asterisk (*) tells that the variable pointer_name is a pointer variable. 2. Pointer_name needs a memory location. 3. Pointer_name points to a variable of type data_type. Example int *p;

The above example means that p is pointer variable which is integer data type. In other words p will be used to store address of integer. Consider the following example. int *p, *b, r; float *d; The above example p and b is pointer to integer and r is integer variable. In next statement d is pointer of float data type. Accessing the address of variable The address (&) of operators is used to get the address of a particular variable, The operator & immediately preceding a variable returns the address of the variable associated with it. Consider the following statement. int p=&quantity; This statement address 5000(the location of quantity) to the variable p. The & operator can be remembered as address of. Initialization of pointer variables The process of assigning of a variable to a pointer variable is known as initialization. The in directional operator operates an address and use the value stored at the address. Example int quantity=7; int *p; p=&quantity; //declaration of pointer variable // initialization of dres

In the above example quantity is integer variable which is initialize with 7 and p is defined as pointer to integer. The statement p=&quantity; stores the address of quantity into p. in other words p will act as a pointer to quantity. Pointers are flexible same pointer to different data variable in different statement. int x, y, z, *p; p=&x; p=&y p=&z; p x y z

Also use different pointer to point to the same date variable. int x; int *p1=&x; int *p2=&x; int *p3=&x; Naresh Shende x 47 9890379983 p1 p2 p3

Write the output following program. #include<stdio.h> #include<conio.h> void main () { int x=7; int *y; y=&x; printf(%d is stored at %u \n, x, y,); printf(%d is stored at %u \n, x, &x); printf(%d is stored at %u \n,*y, &x); printf(%d is stored at %u \n, *y, &x); } Output 7 is stored at 1000 7 is stored at 1000 7 is stored at 1000 7 is stored at 1000 Chain of Pointers In this case the pointer to point to another pointer. Thus creating a chain of pointers as shown. p1 address 2 p2 address 1 variable value Variable name x y value 7 1000 address 1000 1002

Here, the pointer variable p2 contains the address of the pointer variable p1. This point to the location that contains the desired value. This is known as multiple indirections. A variable that is pointer to a pointer must be declared using additional indirections operator symbols in front of the name. Example int **p2;

This type of declaration tells the complier that p2 is a pointer of int type. Remember, the pointer p2 is not a pointer to an integer, but rather pointer to an integer pointer. int x; int *y; int **z; In the above example x is integer variable y is pointer to integer and z is pointer to pointer to integer. Write the output of the following program. #include<stdio.h> #include<conio.h> void main ( ) { int x=7; int *y; Naresh Shende 48 9890379983 Consider the following example

int **z; y=&x; z=&y; printf(%d is stored at %u \n, *y, y); printf(%d is stored at %u \n, *z, z); printf(%d is stored at %u \n, **z, *z); } Output 7 is stored at 1000 7 is stored at 1000 7 is stored at 1000 7 is stored at 1000 Variable name x y z value 7 1000 1002 address 1000 1002 1004

Write a program to accept number from the user and print it with it address with pointer and without pointers. #include<stdio.h> #include<conio.h> void main ( ) { int number=0; int *ptr; printf(\n Enter number:); scanf(%d, &number); ptr=&number; printf(\n %d is stored at %u, number, ptr); getch ( ); } Write a program to find out the product two numbers using pointers. #include<stdio.h> #include<conio.h> void main( ) { int no1=0, no2=0; int*pt1,*pt2; printf(\n Enter two number:); scanf(%d%d, &no1,&no2); pt1=&no1; pt2=&no2; printf(\n %d * %d=%d, *pt1, *pt2, (*pt1)*(*pt2)); getch( ); } Pointer and arrays VIMP - Explain the concept array of pointers with example.

Array of pointers is nothing but a collection of address of same type of elements. Here, we store addresses of variable for which we have to declare an array as a pointer. When array is declared, the complier allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory location. The base address is the location of the first element of the array. Naresh Shende 49 9890379983

int x[5]={10,20,30,40,50}; Suppose the base address of x is 1000 and assuming that each integer requires two bytes the five elements will be stored as follows. Array element Value Address x[0] 10 1000 x[1] 20 1002 x[2] 30 1004 x[3] 40 1006 x[4] 50 1008

The name x is defined as a constant pointer pointing to the first element. x[0] and therefore the value of x is 1000, the location where x[0] is stored. That is, x = &x [0] =1000 If we declare p as an integer pointer then we can make the pointer p to point to the array x by the following assignment. int *p; p=x; This is equivalent to p = &x[0]; Now we can access the value of x using p++ to move from one element to another. The relationship between p and x is shown as. p=&x[0] p+1=&x[1] p+2=&x[2] p+4=&x[3] p+6=&x[4] (=1000) (=1002) (=1004) (=1006) (=1008)

That the address of an element is calculated using its index and the scale factor of the data type. For instance, address of x[3] = base address + (3 scale factor of int) = 1000 + (3 2) = 1006 When handling array, instead of using array indexing, we can use pointers to access array elements. That *(p+3) give the value of x[3]. The pointer accessing method is much faster than array indexing. See following example. #include<stdio.h> #include<conio.h> void main ( ) { int *arrp[3]; int arr1[3]={10,20,30}, k; clrscr( ); for(k=0; k<3; k++) arrp[k]=arr1+k; printf(\n \t address element \n); for(k=0; k<3; k++) { printf(\t %u, arrp[k]); printf(\t %7d \n,*(arrp[k])); } getch ( ); } Naresh Shende 50 9890379983

Write the output of the following program. #include<stdio.h> void main ( ) { static int a[5]={10,20,30,40,50}; int *y, i; y=a; for(i=0; i<5; i++) { printf(%d is stored at %u \n, *y, y); y=y+1; } } a[0] a[1] a[2] a[3] a[4] 10 1000 20 1002 30 1004 40 1006 50 1008

When array name return without subscript it acts as pointer to be 0th element of array or its stored address of the 0th element of array. a = &a[0] Give to the statement y=a the address of a[0] that is in this example is stored in y. 10 is stored at 1000 20 is stored at 1002 30 is stored at 1004 40 is stored at 1006 50 is stored at 1008 a[0] 10 1000 a[1] 20 1002 a[2] 30 1004 a[3] 40 1006 a[4] 50 1008 1000

Give the statement y=a, y is initialize with 1000 i.e. address of a[0]. Therefore first message is 10 is stored at 1000 give to the statement y=y+1; 1000+1 is calculated and it will result into 1002 i.e. pointer plus integer and second message is 20 is stored at 1002 and so on. Write the output of the following program. #include <stdio.h> void main ( ) { static int a[5]={10,20,30,40,50}; int *y1, *y2; y1=&a[0]; y2=y1 + 3; printf(%d is stored at %u \n, *y1, y1); printf(%d is stored at %u \n, *y2, y2); printf(%d is stored %d position to part from %d \n, *y2, y2, y1, *y1); } 10 is stored at 1000 40 is stored at 1006 40 is stored at 3 position to part from 10

Output

Give to the statement y1=&a[0] y1 point a[0] i.e. it will become 1000. Consider the statement y2=y1+3. Since y1 is1000. 1000+3=1006 Naresh Shende 51 9890379983

Pointers and Character Strings


String is treated like character arrays and therefore, they are declared and initialized as follows. char str[5]=good; The complier automatically inserts the null character \0 at the end of the string. C supports an alternative method to create strings using pointer variables of type char. Example char *str=good; This creates a string for the literal and then stores its address in the pointer variable str. The pointer str now points to the first character of the string pointer good as. Also use runtime assignment for giving values to a string pointer. Example char *string1; string1=good; To print the content of the string string1 using either printf or puts functions as follows. printf(%s, string1); puts(string1); string1 is a pointer to the string, it is also the name of the string1. Therefore, we do not need to use indirection operator*. Write a program using pointers to determine the length of the characters string. #include<stdio.h> #include<conio.h> void main ( ) { char name[5], *ptr; int count=0; ptr=name; printf(\n Enter the String); scanf(%s, name); while(*ptr!=\0) { count = count+1; ptr++; } printf(\n Length of the string= %d \n, count); getch ( ); } Output DELHI Length of the string=5

Table of Strings Pointers The use of pointers is handling of a table of strings. Consider the following array of string. char name[3] [25]; This says that the name is a table containing the names, each with a maximum length of 25 characters (including null characters). The total storage requirements for the name table are 75 bytes. char *name[3]={ NEW ZELAND, AUSTRALIA, INDIA }; Naresh Shende 52 9890379983

Declares name to the array of three pointers to character, each pointer pointing to a particular name as: name[0] = NEW ZEALAND name[1] = AUSTRALIA name[3] = INDIA This declaration allocates only 28 bytes, sufficient to hold all the characters as shown. N A I E U N W S D T I Z R A E A \0 A L L I A A N \0 D \0

The following statement would print out all the three names for(i=0; i<=2; i++) printf(%s \n, name[i]); To access the jth character in the ith name, we may write as *(name[i] + j).The access the jth character in the rows of varying length are called ragged arrays and are batter handled by pointers. Write a program array of pointer using table of stings #include<stdio.h> #include<conio.h> void main ( ) { char *str[5]={Mumbai, Nashik, Pune, Nagpur, Aurangabad }; int i=0; for(i=0; i<=4; i++) { printf(\n %d element=%s, i, str[i]); } getch ( ); }

Pointers Arithmetic

(VIMP - Explain the concept of pointer arithmetic operations example)

Pointer arithmetic is concern with the arithmetic operations with the pointers. Like basic operation +, -, * and / can be done using pointer notation. As * pointer indicates the value whose address is stored in pointer. Increase, decrease, prefix and postfix operation can be performed with the help of pointers. Data type int i=2 char c=x float f=2.2 Initial Address 4046 4053 4058 Operation ++ ++ ++ ++ Address after operation 4048 4054 4062 4064 Required Bytes 2 1 4 4

long int l=2 4060

From above table we can observe that on increase of the pointer variable for integers the address is increased by two. i.e. 4046 is original address and on increase its value will be 4048 because integers require two bytes.

Naresh Shende

53

9890379983

Pointer arithmetic #include<stdio.h> #include<conio.h> void main ( ) { int a=0, b=0; int *p1, *p2; printf(\n Enter the two number:); scanf(%d%d, &a,&b); p1=&a; p2=&b; printf(\n %d is at %u and %d is at %u, a, p1, b, p2); printf(\n *p1-*p2=%d,*p1 - *p2); printf(\n*p1+*p2=%d,*p1 + *p20; printf(\n*p1*p2=%d, *p1 * *p2); printf(\n*p1/*p2=%d,*p1 / *p2); printf(\n*p1%*p2=%d,*p1%*p2); printf(\np1++ =%u,++p1); getch (); } Pointers with Function (Call By Reference) When pointers i.e. address is passed to the function as an argument instead of values then function is said to the call by reference. Following is the example for the same type. Write a pointers function for exchanging the values of integers variables. #include<stdio.h> void swap(int *p, int *q); void main ( ) { int p=10,p=20; printf(Before swapping\n); printf(p=%d and q=%d, p, q); swap(&p, &q); getch ( ); } void swap (int*p, int*q) { int temp; temp=*p; *p=*q; *q=temp; printf(After swapping\n); printf(p=%d, q=%d, p, q); }

Naresh Shende

54

9890379983

Functions Returning Pointers Function can return a single value by its name or return multiple values through pointer parameters. Since pointers are a data type in C. we can also force a function to return a pointer to the calling function, Consider the following example Write a program to find the larger number between two number using function pointers. #include<stdio.h> int larger(int *x, int *y); void main( ) { int a=10, b=20; int *p; p=larger(&a,&b); printf(%d, *p); getch(); } int larger(int *x, int *y) { if(*x>*y) return(x); else return(y); } Pointer and Structures We can declare pointer to whole structure arrow operator (->) also known as members selection operator and is made up of minus sign and greater than sign. The general from of declaring pointer to the structure is as follows. Consider the following example struct date { int dd, mm, yy; }; struct date d, *p;

The above example date is structure type. It has 3 integer data member as dd, mm, and yy. Define with d as structure variable and p as pointer variable to struct date. Consider the following example #include<stdio.h> #include<conio.h> struct date { int dd, mm, yy; }; void main( ) { struct date d; struct date *p; p=&d; printf(\n Enter date in dd/mm/yy format); scanf(%d %d%d, &p->dd, &p->mm, &p->yy); printf(\n the same date in mm/dd/yy format is as follows \n); printf(%d/ %d/%d, p->mm, p->dd, p->yy); getch ( ); } Naresh Shende 55

9890379983

In the above programd is defined as structure variable and *p is pointer variable. p=&d this statement indicates p stores the address of the structure variabled. To read the data and display the data to pointer structure to use the expression p->dd. This expression refers a data member dd of that structure which is to be pointed by p. This expression most effectively than refers d.dd. Similar explanation can be applied p->mm and p->yy. The field dd of d can also be represented with one more method and that will be given as (*p).dd. Write a program to perform sum and average of all elements of array using pointer. #include<stdio.h> #include<conio.h> void main ( ) { int arr[5], i, sum=0, avg=0; int *j; for(i=0; i<=4; i++) { printf(\n Enter number:); scanf(%d, &arr[i]); } j = &arr[0]; for(i=0; i<=4; i++) { sum=sum + *j; j=j+1; } avg= sum/5; printf(\n Sum = %d,sum); printf(\n Average = %d,avg); getch ( ); } Write the output of the following program. #include<stdio.h> #include<conio.h> void main( ) { int i=5, *ptr; ptr=&i; clrscr(); printf("%d \t",*ptr); *ptr++; printf("%d\t",*ptr); ++*ptr; printf("%d\t",*ptr); *++ptr; printf("%d\t",*ptr); getch( ); } Output 5 0 1 344 56 9890379983

Naresh Shende

S-ar putea să vă placă și