Вы находитесь на странице: 1из 143

Programming in C Index

Basic Concepts required for Introduction to C Introduction to C Operators in C Decision Control Structure If Statement If-Else Statement If-Else-If Statement Ternary Operator (ConditionalOperator) ASCII SwitchStatement Loop Control Structure While loop Do-While loop For-loop Functions Storage Classes in C Pointers Arrays Introduction to Arrays PassingArrayelementstoFunction Multidimensional Arrays Two Dimensional Arrays Three Dimensional Arrays String Functions Structures Union File Handling

2 4 20 23 24 25 34 36 42 43 50 52 65 79 81 87 91 97 100 102 110 116 119

Basic Concepts Required for Introduction to C

User language (English language)

System language (Language of 0s and 1s i.e. Binary language)

Interpreter OS (Mediator, which converts user language Into system language) Introduction to Number system There are two types of number system in a computer i.e. Decimal number system and Binary number system. Decimal Number System: The decimal number contains 10 natural numbers from 0 to 9, which are used by human being. Binary Number System: The binary number system contains only two numbers i.e. 0 and 1 which is used by compiler, because compiler cannot understand any other language except 0 and 1 in the form of electronic signals. 0 1 0 1 0 1 0 1 0 1

ASCII ASCII ranges from 0 to 255. A American S Standard C Code for I Information I Interchange In ASCII language, A 65 B 66 | | | Z 90

a 97 b 98 | | | z 122

Conversion of Decimal number in to Binary number system 2 2 2 2 2 2 65 32 16 8 4 2 1 1 0 0 0 0 0

In System language, A= 1000001 Two directories called <stdio.h> and <conio.h> are always included before starting the C program. These are included in the given way. #include<stdio.h> #include<conio.h> void main( ) { ------} printf To print on screen. scanf - To get value from keyboard/user. stdio.h standard input/output. header This directory is included because printf() and scanf() functions are present in this directory and if this directory is not included, printing and scanning is not possible. conio.h console input/output. header This directory is included because clrscr() and getch() functions are present in this directory. In C, semicolon (;) is used to terminate the statement. In C, = Represents assignment operator E.g. a=10 (here 10 is assigned to variable a. = = Represents equality E.g. a==b(here variable a and variable b represents equality)

Steps of C-program using flowchart Representation


START START

INPUT

a, b, c c=a+b Print c STOP

CALCULATE PRINT STOP


Datatype int

10,20,4,9

int a, b;

%d

int a;

10
float 18.84,20.54 float a, b; %f float a; a

18.84
char a, i, b char a; %c char a; a

c
string chester char a[20]; %s char a[7]; a

chester

Introduction to C
Dennis Ritchie developed the C language at AT & T Bells laboratory in 1972. It was originally written for programmes under the operating system UNIX. The early version written by Ken Thomson adopted in the form of a language by the initials BCPL which stands for Basic Combined Programming Language. To distinguish this language from BCPL, he termed it as B, the first character. When the language was modified and was improved to its present state, the second letter of BCPL, C was chosen to represent new version. There is no single compiler for C. Many different organizations have written and implemented C compiler. Power, Portability, Performance and flexibility are the most important results for C popularity. C combines the features of both high level language which is the functionality of the assembly language. Being a middle level language, it allows the manipulation of bits, bytes and the address directly make it more suitable for system programming and hence C is mostly used for writing interpreters, compilers, assembler editions, database management. Advantages of C

It is a structural programming language. C source code is portable. Being a middle level language suitable for commercial application. C is designed so that compiler can translate a program into efficient machine instructions.

For Normal language

Alphabets

Words

Sentences

Paragraphs

C consist of

Alphabets Digits Special symbols

Constants Variables Keywords

Instructions

Programs

Rules for C Program

C is a case sensitive.

All keywords have to be in lowercase. Keywords have fixed meaning and are reserved i.e. keyword if, int, char.

Instructions about C program C always start from main() [because C compiler starts compiling always from main() function. There should be {(opening brace) and }(closing brace) to indicate the start and the end of C program. For terminating the statements ;(semicolon) is used. For inputting the data from the keyboard, scanf() function is used. For output printf() function is used, where f is formatted input as well as for formatted output. C has no specific rules for the position at which a statement is to be written. Thats why it is often called a free-form language. Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword. Basic Structure of C program DOCUMENTATION SECTION. LINK SECTION. DEFINITION SECTION. GLOBAL DECLARATION SECTION. main() : FUNCTION SECTION { Declaration part Executable part } Subprogram section function1 function2 (User defined functions) | | | | function n. Syntax of scanf() statement scanf(control string,&variable1 ,&variable2 - - -); address Syntax of printf() statement printf(<format string>,<List of variables>) where format string can be %f, %d, %c. Format String %f : It is used for declaring float variables. %d : It is used for declaring integer variables.

%c : It is used for declaring character variables.

General Structure of C-program main() { declaration of variables/initialization scanf( _____ ); printf( _____ ); _______ _______ C-instructions _______

printf( _____ ); } Comments

Comments about the program should be enclosed within /* */ Any number of comments can be given at any place in the program. Comments cannot be nested. For example, /*Cal of SI /* Author sam date 01/01/90 */*/
is invalid. A comment can be split over more than one line, as in, /* This is a jazzy comment */ Comments should be used at any place where there is a possibility of confusion. Any program is nothing but a combination of functions. main() is one such function. Empty parentheses after main are necessary. The set of statements belonging to a function are enclosed within a pair of braces. For e.g. main() { statement 1; statement 2; statement 3; } Any variable used in the program must be declared before using it. // Program to calculate simple interest. main() { int p,n; float r,si; p=1000;

n=3; r=8.5; si=p*n*r/100; printf(%f,si); } In the above program we assumed the values of p, n and r to be 1000, 3 and 8.5. If we want to make a provision for supplying the values of p, n and r through the keyboard, scanf() function should be used. This is illustrated in the program shown below: main() { int p, n; float r, si; printf(\nEnter values of p, n, r:); scanf(%d %d %f,&p,&n,&r); si=p*n*r/100; printf(%f,si); } The 1st printf() statement outputs the message Enter values of p, n, r on the screen. Here we have not used any variables in printf(), which means that using variables in printf() is optional. Note that the ampersand (&) before the variables in the scanf() statement is a must. Also, note that the values for p, n and r to be supplied through the keyboard, must be separated by a blank, a tab or a newline. E.g. The three values separated by blank. 5 15.5 E.g. The three values separated by tab. 1000 5 15.5 E.g. The three values separated by newline. 1000 5 15.5 C-Character Set C-Character Set consists of alphabets, digits and special symbols. Alphabets: A---------Z a----------z Digits: 0--------9 Special symbols: +, -, =, {, }, [, ], ;, :, <, >, ?, /, \, @, #, *

Constants Constant is a quantity which does not change during the execution of program. This quantity can be stored as a location in the memory of computer.

Variables Variable are those which can change during the execution of program (compilation of program). Example of constants and variables: 2a+3b=23

Here a and b can vary but 2,3,23 cannot vary as those are values. Therefore, a &b are variables & 2,3,23 are constants.

//Program to convert Fahrenheit into celsius. #include<stdio.h> #include<conio.h> void main() { float f,c; clrscr(); printf("\nEnter the value of fahrenheit:"); scanf("%f",&f); c=5.0/9*(f-32); printf("%f",c); getch(); } *************************************************************************** //Program to convert Pound into Kgs. #include<stdio.h> #include<conio.h> void main() { float pound,kg; clrscr(); printf("\nEnter the pounds:"); scanf("%f",&pound); kg=pound/2.204; printf("Kg=%f",kg); getch(); } ******************************************************************************* //Program to calculate the area & volume of sphere #include<stdio.h> #include<conio.h> void main() { int radius; float volume,area; clrscr(); printf("\nEnter the radius of sphere:"); scanf("%d",&radius); volume=(4.0/3)*3.14*radius*radius*radius;

area=4*3.14*radius*radius; printf("Volume=%f Area=%f",volume,area); getch(); } ********************************************************************************

//Program to convert Km into m. #include<stdio.h> #include<conio.h> void main() { float km,m; clrscr(); printf("\nEnter the value of Km:"); scanf("%f",&km); m=(1.0/1000)*km; printf("%f",m); getch(); } ******************************************************************************* //Program to convert Byte into Bits, Kilobytes, Megabytes #include<stdio.h> #include<conio.h> void main() { float byte,bit,kb,mb; clrscr(); printf("\nEnter the bytes:"); scanf("%f",&byte); bit=1.0/8*byte; kb=byte*1000; mb=byte*1000000; printf("Bit=%f Kilobyte=%f Megabyte=%f",bit,kb,mb); getch(); } ******************************************************************************** //Program to calculate the sum of digits of three digit number //entered by user. #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,sum; clrscr(); printf("\nEnter any 3 digit number:");

10

scanf("%d",&num); n1=num%10; num=num/10; n2=num%10; num=num/10; sum=n1+n2+num; printf("\nSum of 3 digits=%d",sum); getch(); }

************************************************************************************ //Program to calculate the sum of 1st and last digit of four digit //number entered by user. #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,sum; clrscr(); printf("\nEnter any 4 digit number:"); scanf("%d",&num); n1=num%10; n2=num/1000; sum=n1+n2; printf("\nSum of 1st and last digit=%d",sum); getch(); } ************************************************************************************ //Program to find the reverse of a 3 digit number //entered by user. #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,rev; clrscr(); printf("\nEnter any 3 digit number:"); scanf("%d",&num); n1=num%10; num=num/10; n2=num%10; num=num/10; rev=n1*100+n2*10+num; printf("\nReverse of 3 digit number=%d",rev); getch(); } ***************************************************************************

11

Keywords
Keywords are the words whose meaning has been already explained to the C compiler. The keywords cannot be used as variables. There are 32 keywords in a C language. The keywords are also called reserve words. E.g. if, int, else, float, goto. The 32 keywords are as follows: auto double break case char const continue default Do else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Data Type Data type specifies the size and arrangement of memory storage for an object of that type. Variable Declaration Every variable must have a datatype. Use a type specifier, such as char, int, short or long to show the variables type. Syntax: type name[value]; Data Type in C

12

Character (char): 1 byte Integer (int): Positive 2 bytes Float (float): 4 bytes Data Type Modifiers

Signed/Unsigned type: Signed on integer in actual is redundant as the default integer assumes signed no. Signed is used to modify character (char), as character by default is unsigned. Unsigned can be applied to float. Long/Short type: Long or short are applied to basic types. They are used when an integer of shorter or longer length than its normal length is required. Short is 16 bits, long is 32 bits. E.g. int a, char p, float length, double area, long distance, short miles.

C-Tokens In a passage of text, individual words and punctuation marks are called as tokens. Similarly in a C-program, the smallest individual units are known as C-Tokens. C has 6 types of tokens.

C-Tokens

Keywords
E.g. float while if

Constants
E.g. 15.5 100

Identifier
E.g. max amount(amt)

Strings
E.g. ABC XYZ name

Operators
E.g. +, -, *, /

Special
E.g. { } [] s !

Symbol

Identifier Identifier refers to the names of variables, functions and arrays. These are user-defined names and consist of sequence of letters and digits with a letter as a first character. Both uppercase and lowercase letters are permitted and the underscore( _ ) is also permitted while defining the identifiers.

13

Types of C Constants C-Constants can be divided into two major categories: Primary Constants Secondary Constants These constants are further categorized as follows:

C- Constants

Primary Constants

Secondary Constants

Numeric Constants Integer Constants Real Constants

Character Constants

Arrays Pointers Structures Union

Character

String Constant

er Constants
they are as follows: Rules for Constructing Integer Constants

er Constants

For constructing these different types of constants certain rules have been laid down and

An integer constant must have at least one digit.

14

It must not have a decimal point. It could be either positive or negative. If no sign precedes an integer constant it is assumed to be positive. No commas or blanks are allowed within an integer constant. The allowable range for integer constants is 32768 to +32767 for 16-bit numbers. It is defined in a program as int. E.g. 426, +782, -8000, -7605 E.g. Invalid Valid 2_9 -15 -13m 2903 1.9 0

Rules For Constructing Real Constants Real Constants are often called Floating Point Constants. The real constants can be written in two forms, Fractional form and Exponential form. Rules for constructing real constants expressed in Fractional form: A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative. Default sign is positive. No commas or blanks are allowed within a real constant. E.g. +325.34, 426.0, -32.76, -48.5792 The exponential form of representation of real constant is usually used if the value of the constant is either too small or too large. In exponential form of representation, the real constant is represented in two parts. The part appearing before e is called mantissa, whereas the part following e is called exponent. Rules for constructing real constants expressed in exponential form:

The mantissa part and the exponential part should be separated by a letter e. The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive. The exponent must have at least one digit which must be a positive or negative integer. Default sign is positive. Range of real constants expressed in exponential form is 3.4e38 to 3.4e38. E.g. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5 Rules For Constructing Character Constants Rules for Constructing Single Character Constants A character constant is either a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, A is a valid character constant whereas A is not. The maximum length of a character constant can be 1 character. E.g. x, z, 9, = String Constants

15

String: It is a sequence of characters. Rules For Constructing String Constants It consists of multiple characters. It is represented in double quotation marks. E.g. Chester, x=ymg Variable Names Variable names are names given to locations in the memory of computer where different constants are stored. These locations can contain integer, real or character constants.

Rules For Constructing Variable Names It must begin with a letter. Some system permits underscore ( _ ) as a first character. It is a combination of 1 to 8 characters. Some compilers allow the length of 40 characters. No commas or blanks are allowed for constructing the variables. It should not be a keyword. No special symbol other than underscore can be used. It is case sensitive. E.g. Valid Invalid

x_y
Datatypes

x-y xy

It allows the programmer to select the type appropriate to the need of the application. It supports four classes. Primary Datatype User-Defined Datatype Derived Datatype Empty data set Primary Datatype There are 3 types of primary datatype. Integer (int) Real/Float (float) Character (char)

Integer (int)
int (16-bit) short int (8-bit) long int (32-bit) unsigned short int (32-bit) unsigned long int (64-bit)

16

Character (char)
Signed char Unsigned char

Float/Real (float)
Float Double Long double

Size and Ranges 1 byte=8 bits Datatype Range Char -128 to +127 Int -32768 to +32767 Float 3.4e-38 to 3.4e+38 Double 1.7e-308 to 1.7e+308 Declaration of Primary Data types Syntax: datatype a1, a2, a3 - - - - - - -an; E.g. int xyz; float val; char name[20]; float sal; User-Defined Datatype

Size 1 byte 2 bytes 4 bytes 8 bytes

User-Defined type declaration Syntax: typedef type identifier; Where, type refers to existing datatype and identifier refers to the new name given to datatype. E.g. typedef int xyz; typedef int sal; C-Instructions

Type Declaration Instruction Input/Output Instruction Arithmetic Instruction Control Instruction

Type Declaration Instruction This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. It is usually written at the beginning of the C-Program. E.g. int a; float amount;

17

Input/Output Instruction This instruction is used to perform the function of supplying input data to a program and obtaining the output results from it. E.g. printf( ), scanf( ) Arithmetic Instruction This instruction is used to perform arithmetic operations between constants and variables. E.g. c=a+2b; In this instruction one arithmetic operator is used and also one assignment operator is used. This instruction is divided into 3 types. Integer Mode: In this mode arithmetic integer variables and arithmetic integer constants are used. E.g. int i; i=i+2; Real Mode: In this mode real variables and real constants are used. E.g. float b; float c; c=3.2+b; Mixed Mode: In this mode some operands are integer and some operands are real. E.g. float b; int c; float a; a=b+c+3 Note: C allows the variables or constants with arithmetic operators on the left side of equation. In C language 3+a=b is an invalid expression whereas b=3+a is a valid expression. Control Instructions This instruction is used to control the sequence of execution of various statements. E.g. while, for

Integer and float conversions The rules that are used for the implicit conversion of floating point and integer values in C are as follows: An arithmetic operation between an integer and integer always yields an integer result. Operation between a real and real always yields a real result. Operation between an integer and real always yields a real result. E.g. Operation 5/2

Result 2

Operation 2/5

Result 0

18

5.0/2 5/2.0 5.0/2.0

2.5 2.5 2.5

2.0/5 2/5.0 2.0/5.0

0.4 0.4 0.4

Type Conversion in Assignments

It may happen that the type of the expression and the type of the variable on the left side of the assignment operator may not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variables on the left side of =. E.g. int i; float b; i=3.5; b=30; Here in the first assignment statement though the expressions value is a float(3.5) it cannot be stored in i since it is an integer. In such a case the float is demoted to an intege r and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value. Thus while storing the value the expression always takes the type of the variable into which its value is being stored. Consider the complex expression in the given program fragment: float a, b, c; int s; s=a*b*c/100+32/4-3*1.1; Here, in the assignment statement some operands are integers whereas others are floats. As we know during evaluation of the expression the integers would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an integer and then stored in s. E.g. k is an integer variable and a is a real variable. Arithmetic Instruction k=2/9 k=2.0/9 k=2/9.0 k=2.0/9.0 k=9/2 k=9.0/2 Result 0 0 0 0 4 4 Arithmetic Instruction a=2/9 a=2.0/9 a=2/9.0 a=2.0/9.0 a=9/2 a=9.0/2 Result 0.0 0.2222 0.2222 0.2222 4.0 4.5

19

k=9/2.0 k=9.0/2.0

4 4

a=9/2.0 a=9.0/2.0

4.5 4.5

Hierarchy of Operations

1st priority 2nd priority 3rd priority

*, /, % +, =

The priority or precedence in which the operations in an arithmetic statement are performed is called as Hierarchy of operations. The usage of operators in general is as follows:

In case of a tie between operations of same priority preference is given to the operator,
which occurs first. For example, consider the statement, z = a*b+c/d; Here, a*b will be performed before c/d even though * and / has same or equal priority. This is because * appears prior to the / operator. Also, if there are more than one set of parentheses, the operations within the innermost parentheses will be performed first, followed by the operations within the second innermost pair and so on. Always, a pair of parentheses should be used. Imbalance of the right and left parentheses is a common error. Q.1 Determine the hierarchy of operations and evaluate the following expression: i=2*3/4+4/4+82+5/8 Stepwise evaluation of this expression is shown below: i=2*3/4+4/4+82+5/8 i=6/4+4/4+82+5/8 Operation : * i=1+4/4+82+5/8 Operation : / i=1+1+82+5/8 Operation : / i=1+1+82+0 Operation : / i=2+82+0 Operation : + i = 10 2 + 0 Operation : + i=8+0 Operation : i=8 Operation : + Q.2 Determine the hierarchy of operations and evaluate the following expression: k=3/2*4+3/8+3 Stepwise evaluation of this expression is shown below: k=3/2*4+3/8+3 k=1*4+3/8+3 Operation : / k=4+3/8+3 Operation : * k=4+0+3 Operation : / k=4+3 Operation : + k=7 Operation : + 1) ab cd = a * b c * d

20

2) 3) 4)

(m + d) (x + y) = (m * d) * (x + y) 2x2 + 5x + 15 = 2 * xe2 + 5 * x + 15 x + y + z = ( x + y + z) / (b + c) b+c

5)

3xy y m+2 3(m+2) = (3* x*y)/(m+2) (y/3* (m+2))

Q.1 WAP to calculate the area of triangle. Q.2 WAP to calculate the area of square. Q.3 WAP to calculate the area and circumference of a circle. Q.4 WAP to calculate the area of a triangle when three sides of a triangle are given. Q.5 WAP to interchange two integer variables. With using 3rd variable. Without using 3rd variable. Q.6 WAP to convert Fahrenheit into Celsius. Q.7 WAP to convert Pound into kilograms. Q.8 WAP to calculate area and volume of a sphere. Q.9 WAP to convert Kilometers into meters. Q.10 WAP to convert Byte into bits, kilobytes, megabytes. Q.11 WAP to calculate the sum of digits of three-digit number entered by user. Q.12 WAP to calculate the sum of 1st and last digit of four-digit number. Q.13 WAP to find the reverse of three-digit number.

stdio.h

getchar() putchar() (For single character i/o)

gets() puts() (multiple character i/o including space)

printf() scanf() (multiple character i/o but in formatted manner without space)

21

**************************************************** ************************ //WAP to print a single character using getchar() and putchar() #include<stdio.h> #include<conio.h> void main() { char a; clrscr(); a=getchar(); putchar(a); getch(); } ********************************************************************** //WAP to print a string without space using printf() and scanf() #include<stdio.h> #include<conio.h> void main() { char username[20]; clrscr(); printf("\nEnter your name:"); scanf("%s",&username); printf("\nUsername=%s",username); getch(); } ********************************************************************************* //WAP to print a string including space using gets() and puts #include<stdio.h> #include<conio.h> void main() { char username[20]; clrscr(); printf("\nEnter your name:"); gets(username); printf("Username=");

22

puts(username); getch(); } *****************************************************************************

//WAP to print the name of the student using gets() and puts(), print //the marks of maths, science nad english and also print the total and //average of the student. #include<stdio.h> #include<conio.h> void main() { int maths, sci, eng; float total, avg; char sname[20]; clrscr(); printf("\nEnter the name of a student:"); gets(sname); printf("\nEnter the marks of maths, science and english:"); scanf("%d %d %d",&maths,&sci,&eng); total=maths+sci+eng; avg=total/3; clrscr(); printf("********************Student Details***********************"); printf("\nThe name of the student is:"); puts(sname); printf("The marks of Maths is:%d",maths); printf("\nThe marks of Science is:%d",sci); printf("\nThe marks of English is:%d",eng); printf("\nThe total marks of the student is:%f",total); printf("\nThe average of the student is:%f",avg); printf("\n**********************************************************"); getch(); } *********************************************************************** //WAP which prints the employee no, employee name and salary and using it //calculate its da, hra and total salary. #include<stdio.h> #include<conio.h> void main() {

23

int eno; float salary,da,hra,ts; char ename[20]; clrscr(); printf("\nEnter the name of the employee:"); gets(ename); printf("\nEnter the Employee id:"); scanf("%d",&eno); printf("\nEnter the salary of the employee:"); scanf("%f",&salary); da=0.35*salary; hra=0.11*salary; ts=da+hra+salary; clrscr(); printf("******************Employee Details***********************"); printf("\nThe name of the employee is:"); puts(ename); printf("The employee id is:%d",eno); printf("\nThe salary of the employee is:%f",salary); printf("\nDA:%f",da); printf("\nHRA:%f",hra); printf("\nTotal Salary of the employee is:%f",ts); printf("\n*********************************************************"); getch(); } ***********************************************************************

24

Operators in C
There are 8 types of operators in C and they are: Arithmetic Operators Relational Operators Logical Operators Conditional Operators Assignment Operators Increment and Decrement Operators Bitwise Operators Special type Operators. Arithmetic Operators Arithmetic Operators are +, -, *, /, %. OP1 int OP2 Int RESULT int

25

int float float

float int float

float float float

Relational Operators Relational Operators are > (greater than) < (less than) >= (greater than equal to) <= (less than equal to) = = (Equal to) != (Not Equal to) Assignment Operator (=) Syntax: Vop=Exp Where V: Variable, Op: Arithmetic Operator (+, -, *, /) =: Assignment Operator Exp: Any expression E.g. 1) a=a+2; Or a+=2 2) b=b+(89+c) Or b+=89+c 3) d=d%8+c Or d%=8+c 4) d=d/8%c Or d/=8%c Conditional Operator It consist of ?(Question mark) and :(colon) Syntax: Exp1 ? Exp2 : Exp3 True False E.g. a<b ? printf(T) : printf(F). Logical Operators

1) Logical AND (&&) 2) Logical OR ( || ) 3) Logical NOT ( ! )


Logical AND Expression1(Exp1) T T

Expression2(Exp2) T F

Result T F

26

F Logical OR Expression1(Exp1) T T F

Expression2(Exp2) T F F

Result T F F

Logical NOT Expression T F

Result F T

Increment and Decrement Operators + + : Increment Operator - - : Decrement Operator

Pre Increment: E.g. m=5 y=++m Post Increment: E.g. m=5 y=m++ The Increment or Decrement Operator, increases or decreases the value by 1 only. In Pre-Increment first the value will be incremented and then it will be assigned to variable. Therefore, y=6 m=6 In E.g. m=5 y=++m

27

the value of m is incremented first and then it will get assigned to the variable y and hence the output will be y=6, m=6 Post Increment Operator m=5; y=m++; Here the values of m will get assigned first to variable y and then it will be incremented by 1. Therefore, output is y=5, m=6 Similarly for Pre Decrement E.g. m=5; y=--m; will give the output y=4 m=4 and for Post Decrement E.g. m=5; y=m--; will give the output y=5 m=4 Note: In this Operator, increment or decrement is by 1 only. Bitwise Operator & - Bitwise AND | - Bitwise OR ^ - Bitwise X-OR >> - Bitwise Right Shift << - Bitwise Left Shift Special Operator & - address of sizeof(); . - Dot operator , - comma operator etc.

Decision Control Structure

Programming Techniques in C Sequential Programming Conditional Programming Looping Sequential Programming Sequence Control Structure is the one in which the various steps are executed sequentially, i.e. in the same order in which they appear in the program. By default the instructions in a program are executed sequentially. Conditional Programming Many times, it may be required that a set of instructions to be executed in one condition and an entirely different set of instructions to be executed in another condition. This kind of condition is used in C programs using a decision control instruction. Decision control instruction can be implemented in C using:

28

Switch-case statement. For checking the conditions in C program, if and else statement is used. Syntax: a) If(condition) Statement; b) If(condition) { statement 1; statement 2; statement 3; } if(condition) True statement; False else statement; if(condition) { statement 1; statement 2; } else { statement 1; statement 2; }

1) 2) 3) 4)

If statement. If-else statement. If-else-if statement.

If the condition in if statement is true then the C statements in if block are executed and if the condition in if statement is false then the C statements in else block are executed ignoring the C statements in if block.

START
INPUT

False if a>b B is greater

True A is greater

STOP 29

#include<stdio.h> #include<conio.h> void main() { int maths,sci,eng; float total,avg; char sname[20]; clrscr(); printf("\nEnter the name of the student:"); gets(sname); printf("\nEnter the marks of maths, science and english:"); scanf("%d %d %d",&maths,&sci,&eng); total=maths+sci+eng; avg=total/3; printf("\nStudent name is:"); puts(sname); if(avg<35) printf("\nResult is Fail"); else if(avg>=35 && avg<45) printf("\nResult is Third division"); else if(avg>=45 && avg<60) printf("\nResult is Second division"); else if(avg>=60 && avg<75) printf("\nResult is first division"); else if(avg>=75 && avg<101) printf("\nResult is Distinction"); getch(); } **********************************************************************

#include<stdio.h> #include<conio.h> void main() { int a,b,great; clrscr(); printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); //89 78 great=a; //89 if(a<b) great=b; //89 printf("\nThe greatest number is %d",great); getch(); } ***********************************************************************

30

If-else-statement:It is used to carry out a logical test and then take one of the two possible actions, depending on the outcome of the test(true or false). Syntax: if(expression) statement; else statement; If the if expression evaluates to true, the statement or block following the if is executed, otherwise statement block follows the else part. void main() { int a,b; clrscr(); printf(\nEnter any two numbers:); scanf(%d %d,&a,&b); if(a>b) printf(\nA is greatest); else printf(\nB is greatest); getch(); } Nested ifs If(exp1) { If(exp2) Statement 1; If(exp3) Statement 2; Else Statement 3; } Else Statement 4; OR If(condition) { If(condition) { _______ _______ } Else { _______ ________ } } Else { If(condition) { ______

31

_______ } Else { _____ _____ } } Example of Nested ifs ********************************************************************** #include<stdio.h> #include<conio.h> void main() { int x,y; x=y=0; clrscr(); printf("\nEnter choice(1-3):"); scanf("%d",&x); if(x==1) { printf("\nEnter value for y(1-5):"); scanf("%d",&y); if(y<=5) printf("\nThe value of y is %d",y); else printf("\nThe value of y exceeds 5"); } else printf("\nChoice entered was not one"); getch(); } ***********************************************************************

If-else-if Statement: Syntax: if(expression) statement; else if(expression) statement; else if(expression) statement; else statement; The conditions in this case are evaluated top to bottom. As soon as a true expression is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed. #include<stdio.h> #include<conio.h>

32

void main() { int x; x=0; clrscr(); printf("\nEnter choice(1-3):"); scanf("%d",&x); if(x==1) printf("\nChoice is 1"); else if(x==2) printf("\nChoice is 2"); else if(x==3) printf("\nChoice is 3"); else printf("\nInvalid Choice"); getch(); } ***********************************************************************

Switch Statement
The switch statement causes a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression that is included within the switch statement. E.g. switch(expression) statement; //WAP to check whether the entered number is even or odd.

33

#include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("\nEnter the number:"); scanf("%d",&num); //12 if(num%2==0) printf("\nNumber is even"); else printf("\nNumber is odd"); getch(); } *********************************************************************** //WAP to check whether an entered number is positive, negative or zero. #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); //13 if(num<0) printf("\nNumber is negative"); if(num>0) printf("\nNumber is positive"); if(num==0) printf("\nNumber is zero"); getch(); } *********************************************************************** //WAP to check whether a 3 digit entered number is pallindrome or not. //Pallindrome Number:When the reverse of a number is equal to the number //itself. Eg:121 #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,rev,orin; clrscr(); printf("\nEnter the number:"); scanf("%d",&num); orin=num; n1=num%10; num=num/10; n2=num%10; num=num/10; rev=n1*100+n2*10+num; if(rev==orin)

34

printf("\nNumber is pallindrome"); else printf("\nNumber is not pallindrome"); getch(); } ******************************************************************** //WAP to check whether an entered 3 digit number is armstrong or not. //If the sum of cube of each digit is equal to the number itself is called //armstrong Number. Eg:153 #include<stdio.h> #include<conio.h> void main() { int num,orin,n1,n2,sum; clrscr(); printf("\nEnter a 3 digit number:"); scanf("%d",&num); orin=num; n1=num%10; num=num/10; n2=num%10; num=num/10; sum=n1*n1*n1+n2*n2*n2+num*num*num; if(sum==orin) printf("\nNumber is Armstrong"); else printf("\nNumber is not Armstrong"); getch(); } ***********************************************************************

//WAP to calculate the roots of quadratic equation. //x1=(-b+sqrt(b2-4ac))/2a, x2=(-b-sqrt(b2-4ac))/2a //t<0:imaginary //t>0:real and different //t==0:real and equal #include<stdio.h> #include<conio.h>

35

#include<math.h> void main() { int a,b,c,t; float x1,x2; clrscr(); printf("\nEnter the values of a,b and c:"); scanf("%d %d %d",&a,&b,&c); t=b*b-4*a*c; if(t<0) printf("\nRoots are Imaginary"); if(t==0) { printf("\nRoots are real and equal"); x1=-b/(2*a); x2=x1; printf("\nRoots are %f %f",x1,x2); } if(t>0) { printf("\nRoots are real and distinct"); x1=-b+sqrt(t)/(2*a); x2=-b-sqrt(t)/(2*a); printf("\nRoots are %f %f",x1,x2); } getch(); } ********************************************************************** //WAP to calculate whether an entered number is perfect square or not. #include<stdio.h> #include<conio.h> #include<math.h> void main() { int num,n1; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); n1=sqrt(num); if(num==n1*n1) printf("\nNumber is a perfect square"); else printf("\nNumber is not a perfect square"); getch(); } *********************************************************************** //WAP to solve given 2 equations. //ax+by=m and cx+dy=n //where x=md-nb/ad-cd and y=na-mc/ad-cb //Calculate the value of x and y if ad-cb!=0 and print the appropriate result //if ad-cb=0. #include<stdio.h>

36

#include<conio.h> void main() { int a,x,b,y,m,c,d,n,t; clrscr(); printf("\nEnter the input:"); scanf("%d %d %d %d %d %d",&m,&n,&a,&b,&c,&d); t=a*d-c*b; if(t!=0) { x=m*d-n*b/t; y=n*a-m*c/t; printf("\nThe values for x and y are %d %d",x,y); } if(t==0) printf("\nInfinite Result"); getch(); } *********************************************************************** //WAP to find the largest number in 3 entered number. #include<stdio.h> #include<conio.h> void main() { int n1,n2,n3; clrscr(); printf("\nEnter 3 numbers:"); scanf("%d %d %d",&n1,&n2,&n3); if(n1>n2) { if(n1>n3) { printf("\nLargest number is n1"); } else printf("\nn3 is largest"); } else { if(n2>n3) printf("\nn2 is largest"); else printf("\nn3 is largest"); } getch();} *********************************************************************** //WAP which reads a marks of 5 subjects entered by student and check whether //the student has passed or fail. If passed calculate the percentage marks //of student and also print the division of the student. #include<stdio.h> #include<conio.h> void main()

37

{ int m1,m2,m3,m4,m5,per; clrscr(); printf("\nEnter the marks of 5 subjects:"); scanf("%d %d %d %d %d",&m1,&m2,&m3,&m4,&m5); if(m1>=40 && m2>=40 && m3>=40 && m4>=40 && m5>=40) { printf("\nStudent is passed"); per=(m1+m2+m3+m4+m5)/5; if(per>=75) printf("\nCongrats, U have got distinction"); if(per>=60 && per<=74) printf("\nFirst division"); if(per>=50 && per<=59) printf("\nSecond division"); if(per>=40 && per<=49) printf("\nThird division"); } else printf("\nSorry, U are fail"); getch(); } ********************************************************************** //WAP which reads a 4 digit number and check whether it is in the form //AABB, if found check whether it is a perfect square. #include<stdio.h> #include<conio.h> #include<math.h> void main() { int num,orin,d1,d2,d3,d4,a; clrscr(); printf("\nEnter a 4 digit number:"); scanf("%d",&num); orin=num; d1=num%10; num=num/10; d2=num%10; num=num/10; d3=num%10; num=num/10; d4=num; if(d1==d2 && d3==d4 && d2!=d3) { printf("\nNumber is in the form AABB"); a=sqrt(orin); if(a*a==orin) { printf("\nNumber is a perfect square"); } else printf("\nNumber is not a perfect square"); }

38

else printf("\nNumber is not in the form AABB"); getch(); } *********************************************************************** //WAP to accept 2 integers and divide bigger by smaller number. #include<stdio.h> #include<conio.h> void main() { float a,b,x; clrscr(); printf("\nEnter the values of a and b:"); scanf("%f %f",&a,&b); if((a>b) && (b!=0)) { x=a/b; printf("\n%f",x); } else if((b>a) && (a!=0)) { x=b/a; printf("\n%f",x); } getch(); } *********************************************************************** //WAP to find whether the entered year is a leap year or not. #include<stdio.h> #include<conio.h> void main() { int year; clrscr(); printf("\nEnter the year:"); scanf("%d",&year); if((year%4==0 && year%100!=0) || (year%400==0)) { printf("\nThe year is a leap year"); } else printf("\nThe year is not a leap year"); getch(); } *********************************************************************** //WAP for function of calculator which performs addition, subtraction, //multiplication and division. #include<stdio.h>

39

#include<conio.h> void main() { int x; float a,b,c; clrscr(); printf("\nMENU\n1.ADDITION\n2.SUBTRACTION\n3.MULTIPLICATION\n4.DIVISION \nEnter Choice"); scanf("%d",&x); printf("\nEnter 2 numbers:"); scanf("%f %f",&a,&b); if(x==1) { c=b+a; printf("\nThe result of addition is %f",c); } else { if(x==2) { c=a-b; printf("\nThe result of subtraction is %f",c); } else { if(x==3) { c=a*b; printf("\nThe result of multiplication is %f",c); } else { if(x==4) { c=a/b; printf("\nThe result of division is %f",c); } else { printf("\nInvalid Choice"); } } } } getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int age; clrscr(); printf("\nEnter your age:");

40

scanf("%d",&age); if(age<1) printf("\nMinor Category"); else if(age>=1 && age<18) printf("\nMedium Category"); else if(age>=18 && age<45) printf("\nMajor Category"); else if(age>=45 && age<70) printf("\nHighest Category"); else printf("\nWrong Age"); getch(); } ***********************************************************************

41

Ternary Operator or Conditional Operator(? :)


Syntax: e1?e2:e3

False True

condition
e1 is the logical expression depending on the evaluation of e1. The control will transfer to either e2 or e3. If e1 evaluates true then e2 is executed else e3. #include<stdio.h> #include<conio.h> void main() { int a,b,big; clrscr(); printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); big=(a>b?a:b); printf("\n%d is big",big); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int a,b,c,big; clrscr(); printf("\nEnter any three numbers:"); scanf("%d %d %d",&a,&b,&c); big=(a>b?(a>c?a:c):(b>c?b:c)); printf("\n%d is biggest",big); getch(); } *********************************************************************** ASCII (American Standard Code for Information Interchange) 0 48 | | | | | | 9 57

42

65 | | | 90 97 | | | 122

A | | | Z a | | | z

#include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); printf("\nEnter any character:"); scanf("%c",&ch); printf("\n%c",ch); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); printf("\nEnter any character:"); scanf("%c",&ch); printf("\n%d",ch); getch(); } ********************************************************************** #include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); printf("\nEnter any character:"); scanf("%c",&ch); if(ch>=48 && ch<=57) printf("\nThe character is a digit"); else if(ch>=65 && ch<=90) printf("\nThe character is in uppercase"); else if(ch>=97 && ch<=122) printf("\nThe character is in lowercase"); else printf("\nThe character is a special symbol");

43

getch(); } ***********************************************************************

Switch-case Statements
In switch case statements the switch statement causes a particular group of statements to be chosen from several available groups. Syntax: switch(choice) { case 1: statement 1; break; case 2: statement 2; break; case 3: statement 3; break; default: statement; }

Start

Yes Case 1 No Yes Case 2 No Yes Case 3 No Stop Statement 3 Statement 2

Statement 1

44

//WAP for addition,subtraction,multiplication,division and modular division //using switch case. #include<stdio.h> #include<conio.h> void main() { int a,b,c,d; clrscr(); printf("\nMENU\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.MOD"); printf("\nEnter your choice:"); scanf("%d",&d); printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); switch(d) { case 1: c=a+b; printf("\nThe result for addition is:%d",c); break; case 2: c=a-b; printf("\nThe result for subtraction is:%d",c); break; case 3: c=a*b; printf("\nThe result for multiplication is:%d",c); break; case 4: c=a/b; printf("\nThe result for division is:%d",c); break; case 5: c=a%b; printf("\nThe result for modular division is:%d",c); break; default:printf("\nInvalid Choice"); } getch(); } *********************************************************************** //WAP which prints the season according to the month entered //using switch case #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("\nEnter month number:"); scanf("%d",&n); switch(n) { case 12: case 1:

45

case 2: printf("\nWinter Season"); break; case 3: case 4: case 5: printf("\nSummer Season"); break; case 6: case 7: case 8: printf("\nRainy Season"); break; case 9: case 10: case 11: printf("\nSpring Season"); break; default: printf("\nInvalid month number"); } getch(); } *********************************************************************** Decisions Using Switch The control statement which allows to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They are as follows: switch(integer expression) { case constant 1: do this; case constant 2: do this; case constant 3: do this; default: do this; } Q. What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. E.g. main() { int i=2; clrscr(); switch(i) {

46

case 1: printf(I am in case 1\n); case 2: printf(I am in case 2\n); case 3: printf(I am in case 3\n); default: printf(I am in default\n); } getch(); } Output of the program: I am in case 2 I am in case 3 I am in default But the expected output of the above program was I am in case 2. This output can be achieved by getting out of the control structure then and there by using a break statement. Note that there is no need for a break statement after the default, since the control comes to the end anyway. It is as follows: main() { int i=2; clrscr(); switch(i) { case 1: printf(I am in case 1\n); break; case 2: printf(I am in case 2\n); break; case 3: printf(I am in case 3\n); break; default: printf(I am in default\n); } getch(); } Output: I am in case 2 Usage of Switch It is not necessary that only cases arranged in ascending order, 1, 2, 3 and default can be used. Cases can be written in any order we want. E.g. main() { int i=22; clrscr(); switch(i)

47

{ case 121: printf(I am in case 121\n); break; case 7: printf(I am in case 7\n); break; case 22: printf(I am in case 22\n); break; default: printf(I am in default\n); } getch(); } Output: I am in case 22 It is also allowed to use character values in case and switch. E.g. main() { char c=x; clrscr(); switch(c) { case v: printf(I am in case v\n); break; case a: printf(I am in case a\n); break; case x: printf(I am in case x\n); break; default: printf(I am in default\n); } getch(); } Integer and character constants can be mixed in different cases of a switch. E.g. main() { char c=3; clrscr(); switch(c) { case v: printf(I am in case v\n); break; case 3:

48

printf(I am in case 3\n); break; case 12: printf(I am in case 12\n); break; default: printf(I am in default\n); } getch(); } Sometimes there may not be any statement in some of the cases in switch, but still they might turn out to be useful.

E.g. //WAP to print the colours of the rainbow according to the alphabets entered //(uppercase or lowercase) using switch case. #include<stdio.h> #include<conio.h> void main() { char choice; clrscr(); printf("\nSelect rainbow colour VIBGYOR:"); scanf("%c",&choice); switch(choice) { case 'v': case 'V': printf("\nViolet"); break; case 'i': case 'I': printf("\nIndigo"); break; case 'b': case 'B': printf("\nBlue"); break; case 'g': case 'G': printf("\nGreen"); break; case 'y': case 'Y': printf("\nYellow"); break; case 'o': case 'O': printf("\nOrange"); break; case 'r': case 'R': printf("\nRed"); break; default: printf("\nWrong Colour Entered"); } getch(); } ****************************************************************

49

Loop Control Structure


The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control structure. If a block of statement is to be executed n number of times in a program then the loops are used. There are three methods by way of which we can repeat a part of a program. They are: Using a while statement Using a for statement Using a do-while statement. Using a while statement or using a while loop. It is possible to do certain job a fixed number of times using a while loop. E.g. To calculate gross salaries of 10 different persons or to convert temperature from centigrade to Fahrenheit for 15 different cities. Syntax: initialization; while(condition) { ______ ______ ______ updation; (increment/decrement) } OR while(expression) statement; Here statement can be either an empty statement, a single statement or a block of statements that repeat. The loop iterates while this condition is true and when the condition becomes false the program control is passed to the line after the loop code. The while loop is generally used in cases where number of iterations to be performed are not known. Like for loop, while loop checks the condition at the top of the loop which means the loop code is not executed if the condition is false at the start. The operation of the while loop is illustrated in the given flowchart:

50

START initialize
False

test
True

body of loop

STOP

increment
//WAP to calculate a simple interest for 3 sets of p,n, and r using//while loop and draw its flowchart representation. #include<stdio.h> #include<conio.h> void main() { int p,n,count; float r,si; clrscr(); count=1; while(count<=3) { printf("\nEnter values of p,n and r:"); scanf("%d %d %f",&p,&n,&r); si=p*n*r/100; printf("\nSimple Interest=Rs.%f",si); count=count+1; } getch(); }

51

START

count=1 NO

is count<=3

YES

STOP
INPUT

p, n, r si=p*n*r/100
PRINT

si

count=count+1
Rules for representation of while loop.

The statements within the while loop would keep on getting executed till the condition being
tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop. The condition being tested may use relational or logical operators as shown in the following examples: while(i<=10) while(i<=10 && j<=15) while(j>10 && (b<15 || c<20)) The statement within the loop may be a single line or a block of statements. In the first case the parentheses are optional. For E.g. while(i<=10) i=i+1; is same as while(i<=10) { i=i+1; } There are variety of operators which are frequently used with while. Consider a program wherein numbers from 1 to 10 are to be printed on the screen. The program for performing this task can be written using while in the following different ways: 1) main() {

52

int i=1; 2) 3) while(i<=10) { P rintf(%d\n,i); i=i+1; } } 4) main() { int i=1; while(i<=10) { printf(%d\n,i); i++; } } 5) main() { int i=1; while(i<=10) { printf(%d\n,i); i+=1; } } 6) main() { int i=0; while(i++<10) printf(%d\n,i); } 7) main() { int i=0; while(++i<=10) printf(%d\n,i); }

53

//WAP to print the numbers from 1 to 10. #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); while(i<=10) { printf("%d\n",i); i=i+1; } getch(); }

//i++;

//WAP to print the sum of 10 numbers #include<stdio.h> #include<conio.h> void main() { int i=1,s=0; clrscr(); while(i<=10) { s=s+i; i=i+1; } printf("The sum of 10 numbers is %d",s); getch(); } //WAP to find the sum of all the odd numbers in the range of 50 to 100. #include<stdio.h> #include<conio.h> void main() { int i=51,s=0; clrscr(); while(i<=100) { s=s+i; i=i+2; } printf("The sum of odd numbers in the range of 50 to 100 is %d",s); getch();

54

} //WAP to find the sum of all the even numbers from 1 to 100.

#include<stdio.h> #include<conio.h> void main() { int i=2,s=0; clrscr(); while(i<=100) { s=s+i; i=i+2; } printf("The sum of even numbers from 1 to 100 is %d",s); getch(); } *********************************************************************** //WAP to print the numbers from 1 to 30 which is divisible by 3. #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=1; while(i<=30) { i++; if(i%3==0) printf("%d\n",i); } getch(); } ********************************************************************** //WAP to print even numbers from 1 to 10. #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); while(i<=10) { i++; if(i%2==0) printf("%d\n",i); } getch(); }

55

********************************************************************** //WAP to print odd numbers from 11 to 20. #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=10; while(i<20) { i++; if(i%2==1) printf("%d\n",i); } getch(); } *********************************************************************** //WAP to print the ASCII value. #include<stdio.h> #include<conio.h> void main() { int a=65; clrscr(); while(a<=90) { printf("\nThe ASCII value of %c is %d",a,a); a++; } getch(); } //WAP which finds the sum of digits of any number entered by user. #include<stdio.h> #include<conio.h> void main() { int num,d,s=0; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); while(num!=0) { d=num%10; s=s+d; num=num/10; } printf("%d",s); getch();

56

} //WAP to find the reverse of a number entered by user. #include<stdio.h> #include<conio.h> void main() { int num,d,rev=0; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); while(num!=0) { d=num%10; rev=rev*10+d; num=num/10; } printf("%d",rev); getch(); } //WAP to check whether an entered number is pallindrome or not. #include<stdio.h> #include<conio.h> void main() { int num,d,rev=0,orin; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); orin=num; while(num!=0) { d=num%10; rev=rev*10+d; num=num/10; } if(rev==orin) printf("\nNumber is a pallindrome"); else printf("\nNumber is not pallindrome"); getch(); }

57

//WAP to check whether an entered number is armstrong or not. #include<stdio.h> #include<conio.h> void main() { int num,d,sum=0,orin; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); orin=num; while(num!=0) { d=num%10; sum=sum+d*d*d; num=num/10; } if(sum==orin) printf("\nNumber is armstrong"); else printf("\nNumber is not armstrong"); getch(); } ********************************************************************** //WAP which counts the number of digits in a number entered by user. #include<stdio.h> #include<conio.h> void main() { int num,d,count=0; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); while(num!=0) { count=count+1; //count++; num=num/10; } printf("\n%d",count); getch(); } ***********************************************************************

58

Using a do-while statement or using a do-while loop.


In do-while statement, C first executes the body of loop and then checks the condition. The main difference between while and do-while statement is that since the while loop, C first checks the condition, the body of loop can be ignored if condition is false whereas in case of do-while though the condition is false, C program executes atleast once. Syntax: do { statements; _________ _________ } while(this condition is true);

Flowchart representation of do-while loop.

START Initialize Body of loop increment test

STOP

59

//WAP to print numbers from 1 to 10. #include<stdio.h> #include<conio.h> void main() { int i; i=1; clrscr(); do { printf("%d\n",i); i++; }while(i<=10); getch(); } *********************************************************************** //WAP to print the numbers divisible by 3 from 1 to 30. #include<stdio.h> #include<conio.h> void main() { int i; i=1; clrscr(); do { i++; if(i%3==0) printf("%d\n",i); }while(i<=30); getch(); } ******************************************************************** //WAP to print even numbers from 1 to 10. #include<stdio.h> #include<conio.h> void main() { int i; i=1; clrscr(); do { i++; if(i%2==0) printf("%d\n",i); }while(i<=10);

60

getch(); } ********************************************************************** //WAP to print the odd numbers from 10 to 20. #include<stdio.h> #include<conio.h> void main() { int i; i=10; clrscr(); do { i++; if(i%2==1) printf("%d\n",i); }while(i<20); getch(); } **********************************************************************

FOR LOOP
The FOR statement includes an expression that specifies an initial value for an Index, another expression that determines whether or not to continue the loop (conditional test) and a third expression that allows the index to be modified at the end of each pass. Syntax: for(initialization; condition; updation) { ________ ________ C-statements ________ } The WHILE and FOR loop are same in terms of execution. They vary only in terms of their representation as the execution of both the loops are same, all the programs written as while loop can be successfully be written by FOR loop

Flowchart representation of FOR loop.

61

START
initialize
False

test
True

Body of loop
increment

START

//WAP to calculate the simple interest using FOR loop and also give the //flowchart representationof a program. /*Calculation of simple interest for 3 sets of p,n and r*/ #include<stdio.h> #include<conio.h> void main() { int p,n,count; float r,si; clrscr(); for(count=1;count<=3;count=count+1) { printf("\nEnter values of p,n and r:"); scanf("%d %d %f",&p,&n,&r); si=p*n*r/100; printf("\nSimple Interest=Rs.%f\n",si); } getch(); }

62

START
count=1 count=count+1
Yes

is count<=3

No

INPUT p,n,r

STOP

si=p*n*r/100

PRINT si

If this program is compared with the one written using while, it can be seen that the three stepsinitialization, testing and incrementation required for the loop construct have been incorporated in the FOR statement. FOR statement gets executed in the following way. When the FOR statement is executed for the first time, the value of count is set to an initial value 1. Now the condition count<=3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time. Upon reaching the closing brace of for, compiler sends the control back to the for statement, where the value of count gets incremented by 1. Again the test is performed to check whether the new value exceeds 3. If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again. The body of the for loop continues to get executed till count doesnt exceed the final value 3. When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for.

63

Q.1 WAP to print numbers from 1 to 10 in different ways using FOR loop. a) main() { int i; for(i=1;i<=10;i=i+1) printf(%d\n,i); } b) main() { int i; for(i=1;i<=10;) { printf(%d\n,i); i=i+1; } } c) main() { int i=1; for(;i<=10;i=i+1) printf(%d\n,i); }

d) main() { int i=1; for(;i<=10;) { printf(%d\n,i); i=i+1; } } e) { int i; for(i=0;i++<10;) printf(%d\n,i); } f) main() { int i; for(i=0;++i<10;) printf(%d\n,i); } main()

64

//WAP to check the number is divisible by 3. If yes, print from 1 to 30. #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for(i=1;i<=30;i++) { if(i%3==0) printf("%d\n",i); } getch(); } *********************************************************************** //WAP to print all odd numbers from 10 to 20. #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for(i=10;i<=20;i++) { if(i%2==1) printf("%d\n",i); } getch(); } **********************************************************************

Nesting of Loops The way if statements can be nested, similarly while loop and for loop can also be nested. A For loop is said to be nested when it occurs within another FOR. The code will be similar to for(i=1;i<max1;i++) { ________ ________ for(j=0;j<max2;j++) { _________ _________ } _________ _________ }

65

/*WAP 1 2 3 1 2 3 1 2 3 1 2 3 */

to print numbers 1 to 5, four times i.e the output should be 4 5 4 5 4 5 4 5

#include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=4;i++) { for(j=1;j<=5;j++) { printf("%d ",j); } printf("\n"); } getch(); } ********************************************************************* /*WAP A B C A B C A B C A B C A B C */ to print the output as D E F D E F D E F D E F D E F

#include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++) { for(j=65;j<=70;j++) { printf("%c ",j); } printf("\n"); } getch(); } ***********************************************************************

66

/*WAP to print the output as 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%d ",j); } printf("\n"); } getch(); } ******************************************************************** /*WAP to print the output as 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%d ",i); } printf("\n"); } getch(); } ***********************************************************************

67

/*WAP to print output as 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=5;i>=1;i--) { for(j=1;j<=i;j++) { printf("%d ",j); } printf("\n"); } getch(); } ********************************************************************* /*WAP to print output as * * * * * * * * * * */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=4;i++) { for(j=1;j<=i;j++) { printf("* "); } printf("\n"); } getch(); } ***********************************************************************

68

/*WAP to print the output as * * * * * * * * * * */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=4;i>=1;i--) { for(j=1;j<=i;j++) { printf("* "); } printf("\n"); } getch(); } *********************************************************************** /*WAP to print 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 */ #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=10;i++) { for(j=1;j<=10;j++) { printf("%d ",i*j); } printf("\n"); } getch();

69

} ***********************************************************************

Jump Statements
C has four statements that perform unconditional branch:


1) 2)

return goto break continue

return statement: It is used to return from a function. It causes execution to return to the point at which it returns to the calling routine. break statement: The break statement can be used either to terminate a case in a switch statement or to force an exit from a loop. When the keyword break is encountered inside any C loop, control automatically passes to the first statement after the loop. A break is usually associated with an if. When a break is encountered in a loop, it takes the control out of the loop in which it is defined. It is a statement which abnormally terminates the execution of loop.

#include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=0,j=0;i<=100;i++) { printf("\nEnter the value for j:"); scanf("%d",&j); if(j==50) break; } getch(); } ***********************************************************************

70

#include<stdio.h> #include<conio.h> void main() { int num,i; clrscr(); printf("\nEnter any number:"); scanf("%d",&num); for(i=2;i<=num;i++) { if(num%i==0) { printf("\nNumber %d is prime",num); break; } else if(num%i==1) { printf("\nNumber %d is not prime",num); break; } } if(num==1) printf("\nNumber %d is not prime",num); getch(); } 3) goto statement: This is an unstructured programming instruction which transfers program control to the statement whose prefix is label. General format is: goto label; goto statement allows jump in and out of blocks violating rules of a structured programming. The label is an identifier which must be preceded by a semicolon to mark the end of the goto statement.

#include<stdio.h> #include<conio.h> #include<math.h> void main() { int a; float sqr; stop: printf("\nEnter only positive numbers"); clrscr(); printf("\nEnter any number:"); scanf("%d",&a); if(a<0) goto stop; else { sqr=sqrt(a); printf("\nSquare root of a no=%f",sqr); }

71

getch();} *********************************************************************** #include<stdio.h> #include<conio.h> #include<math.h> void main() { int a; float sqr; clrscr(); printf("\nEnter any number:"); scanf("%d",&a); if(a<0) goto stop; else { sqr=sqrt(a); printf("\nSquare root of a no=%f",sqr); } stop: } 4) continue statement: The continue statement causes the next iteration of the enclosing loop to begin. When this statement is encountered in the program, the remaining statement in the body of the loop are skipped and the control is passed to the re-initialization step. For for loop continue causes the increment of the portion of loop and then the conditional test to execute whereas for, while and do-while loops, program control passes to the conditional tests. When the keyword continue is encountered inside any C loop, control automatically passes to the beginning of the loop. A continue is usually associated with an if. Note that when the value of i equals that of j, the continue statement takes the control to the for loop(inner) bypassing rest of the statements pending execution in the for loop.(inner). Usually continue is associated with if statement. It allows to take control beginning of the loop. Void main() { int i; for(i=1;i<=50;i++) { if(i%2==0) continue; printf(%d,i); } getch(); } printf("\nEnter positive numbers only"); getch();

72

Above program prints odd number from 1 to 50. Void main() { int i,j; for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { if(i==j) continue; printf(\n%d %d\n,i,j); } } getch(); } Output: 12 21

Exit( ) function This is a standard e-library function which is said to break out of the program and not just out of a loop. An exit() is generally used to check if a mandatory condition for a program is satisfied or not. The general form of exit() is exit(int return code); Zero is generally used as a return code to indicate normal program termination.

Odd loop The loop which is controlled by user is known as odd loop i.e. every execution of the loop is decided by user. While(1) loop This is a loop used for creating a infinite loop because here 1 is considered as a true value. So to terminate this loop exit(); function is used. This is a function which takes the control out of the program.

73

Q. Write a difference between break and exit(). Break The syntax of break is break; Break is a statement It takes the control out of the loop. Eg: main() { int i=1; for( ; ; ) { printf(%d,i); i++; break; } printf(\n abc); getch(); } Output: 1 abc Note: Exit() The syntax of exit is exit(); Exit is a function. It takes the control out of the program. Eg: main() { int i=1; for( ; ; ) { printf(%d,i); i++; exit(); } printf(\n abc); getch(); } Output: 1

The statement while(1) puts the entire logic in an indefinite loop. This is necessary since
the menu must keep reappearing on the screen once an item is selected and the appropriate action taken. Exit() is a standard library function. When it gets executed the program execution is immediately terminated. Note that a break would not have worked here because it would have taken the control only outside the switch and not outside the while.

74

//WAP for addition,subtraction,multiplication,division and modular division //using switch case. #include<stdio.h> #include<conio.h> void main() { int a,b,c,d; clrscr(); while(1) { printf("\nMENU\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.MOD\n6.exit"); printf("\nEnter your choice:"); scanf("%d",&d); if(d==6) goto e; else if(d>6) goto r; printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); switch(d) { case 1: c=a+b; printf("\nThe result for addition is:%d",c); break; case 2: c=a-b; printf("\nThe result for subtraction is:%d",c); break; case 3: c=a*b; printf("\nThe result for multiplication is:%d",c); break; case 4: c=a/b; printf("\nThe result for division is:%d",c); break; case 5: c=a%b; printf("\nThe result for modular division is:%d",c); break; e: case 6: exit(); break; r: default:printf("\nInvalid Choice"); } } getch(); } ***********************************************************************

75

Functions
#include<stdio.h> #include<conio.h> void main() { int n1,n2,s; clrscr(); printf("\nEnter 2 numbers:"); scanf("%d %d",&n1,&n2); s=add(n1,n2); printf("%d",s); getch(); } add(int x,int y) { int res; res=x+y; return(res); } Note: Return returns a single value and also passes the control from called function to calling function. *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int x,y; int sum=0; clrscr(); printf("\nEnter any two numbers:"); scanf("%d %d",&x,&y); sum=adder(x,y); printf("\nAddition of x & y is %d",sum); getch(); } adder(int a,int b) { int total; total=a+b; return(total); } **********************************************************************

76

#include<stdio.h> #include<conio.h> void main() { int rad; clrscr(); printf("\nEnter the value of radius:"); scanf("%d",&rad); areacir(rad); getch(); } areacir(int r1) { float area,cir; area=3.142*r1*r1; cir=2*3.142*r1; printf("%f %f",area,cir); } Note : In a function if we are not returning any value then we should write void instead of assigning value to the variable. If the values to be return are more than 1 then we cannot return the values from called function to calling function, because return can return only a single value so we have to print the results in called function itself without returning anything to calling function. As we are not returning anything to the calling function we have to write void in front of calling function. *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int a,b,c,sum; clrscr(); printf("\nEnter any 3 numbers:"); scanf("%d %d %d",&a,&b,&c); sum=calsum(a,b,c); printf("\nSum=%d",sum); getch(); } calsum(x,y,z) int x,y,z; { int d; d=x+y+z; return(d);

77

} ***********************************************************************

#include<stdio.h> #include<conio.h> void main() { int x,y,z,m; clrscr(); printf("\nEnter any three numbers:"); scanf("%d %d %d",&x,&y,&z); m=max(x,y,z); printf("%d",m); getch(); } max(int a,int b,int c) { int mx; mx=a; if(b>mx) mx=b; if(c>mx) mx=c; return(mx); } *********************************************************************** #include<stdio.h> #include<conio.h> #include<math.h> qroot(float,float,float); void main() { float a,b,c; clrscr(); printf("\nEnter the values of a,b and c:"); scanf("%f %f %f",&a,&b,&c); qroot(a,b,c); getch(); } qroot(float a,float b,float c) { float t,x1,x2; t=b*b-4*a*c; if(t<0) { printf("\nRoots are imaginary"); } if(t>0) { printf("\nRoots are real and distinct");

78

x1=-b+sqrt(t)/(2*a); x2=-b-sqrt(t)/(2*a); printf("%f %f",x1,x2); } if(t==0) { printf("\nRoots are real and equal"); x1=-b/(2*a); x2=x1; printf("%f %f",x1,x2); } } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int x,y; x=20; y=10; clrscr(); printf("\nValue assign in x=%d and in y=%d",x,y); swap(&x,&y); printf("\nAfter swapping value x=%d and y=%d",x,y); getch(); } swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; printf("\nOn swapping the values of x=%d and y=%d",*x,*y); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int x,y; x=20; y=10; clrscr(); printf("\nValue assign in x=%d and in y=%d",x,y); swap(x,y); printf("\nAfter swapping value x=%d and y=%d",x,y); getch(); } swap(int x,int y) { int temp;

79

temp=x; x=y; y=temp; printf("\nValue of x and y in swap function is x=%d and y=%d",x,y); } *********************************************************************** #include<stdio.h> #include<conio.h> square(float); void main() { float a=2.5,sq; clrscr(); sq=square(a); printf("%f",sq); getch(); } square(float n) { float s; s=n*n; return(s); } ********************************************************************** #include<stdio.h> #include<conio.h> void main() { float a=2.5,sq,square(float); clrscr(); sq=square(a); printf("%f",sq); getch(); } float square(float n) { float s; s=n*n; return(s); } ***********************************************************************

80

Functions

A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. Functions breaks large computing tasks into smaller ones. The specified tasks is repeated each time the program calls the function. When a function is called, the program execution is transferred to the first statement in the called function. General form of a function: function(arg1, arg2, arg3) type arg1, arg2, arg3; { Statement 1; Statement 2; Statement 3; Statement 4; } The function which calls the other function is called as Calling Function whereas the function which is being called is called as Called Function. The function name followed with pair of brackets and a semicolon is known as Calling Function whereas function name followed with pair of brackets without a semicolon is known as Called Function. Eg: void main() { message(); printf(\nC++ primer plus); getch(); } message() {

81

printf(\nC++ cout object); } Output of the program C++ cout object C++ Primer Plus Here, through main() we are calling the function message(). Thus, main() becomes the Calling Function, whereas message() becomes the Called Function. If the arguments are present, before beginning with the statements in the functions it is necessary to declare the type of the arguments through type declaration statements.

Calling More than One Function Eg: void main() { printf(\nPointers); c1( ); c2( ); c3( ); } c1( ) { printf(\nPointers 1); } c2( ) { printf(\nPointers 2); } c3( ) { printf(\nPointers 3); } Output: Pointers Pointers1 Pointers2 Pointers3 Conclusion: Any C program contains atleast one function. If a program contains only one function, it must be main(). In a C program if there are more than one functions present, then one (& only one) of these functions must be main(), because program execution always begins with main(). There is no limit on the number of functions that might be present in a C program. Each function in a program is called in the sequence specified by the function calls in main().

82

After each function has done its task, control returns to main(). When main() runs out of function calls, the program ends.

Eg: void main() { printf(\nPointers); c1( ); printf(\nPointers 1); getch(); } c1( ) { printf(\nPointers 2); c2( ); printf(\nPointers 3); } c2( ) { printf(\nPointers 4); c3( ); } c3( ) { printf(\n Pointers 5); } Output of the program: Pointers Pointers 2 Pointers 4 Pointers 5 Pointers 3 Pointers 1

There are 2 types of functions available in C language.

83

Library Function: The functions which are readily available in C compiler in their respective header files are called as library functions. Eg: sqrt(), clrscr(), pow(), getch() User-defined Function: The functions which are defined to the program for the specific task are known as user-defined functions.

Q.1 WAP to do the addition of 2 numbers. Without using function With using function. With using function: //fun_add.c Q.2 WAP which calculates the area and circumference of a circle using a function areacir(). //fun_area.c Q.3 Write a function max() to calculate the maximum number out of 3 numbers passed by the user. Print the maximum number in main(). //fun_max.c Q.4 WAP to find the square of value using function. //func_p1.c The output of the above program is 6.000000 instead of 6.25 because by default the function always returns an integer value. To return any value other than integer (float), the return type of function should be specified. So to get the exact output, the above program can be modified as below: //func_p2.c Q.5 WAP to calculate the roots of quadratic equation using function qroot(). //fun_quad.c Passing Values between Functions The mechanism used to convey information to the function is the argument. E.g. The arguments that are included in printf( ) and scanf( ) functions. The format string and the list of variables used inside the parentheses in these functions are arguments. The arguments are sometimes also called parameters. //fun_cals.c In this program, from the main(), the values of a, b and c are passed on to the function calsum(), by making a call to the function calsum() and mentioning a, b and c in the parentheses:

84

sum=calsum(a,b,c); In the calsum() function these values get collected in three variables x, y and z: calsum(x,y,z) int x, y, z; The variables a, b and c are called actual arguments, whereas the variables x, y and z are called formal arguments. Any number of arguments can be passed to a function being called. However, the type, order and number of the actual and formal arguments must always be same. Instead of using different variable names x, y, z; the same variable names a, b and c can also be used. But the compiler would still treat them as different variables since they are in different functions.

a)

There are two methods of declaring the formal arguments The method used in the program for the statements: calsum(x, y, z) int x, y, z; is known as Kernighan and Ritchie (or just K & R) method. Another method is: calsum(int x, int y, int z) Mostly in programs when the closing brace( } ) of the called function is encountered the control returns to the calling function. No separate return statement is required to send back the control. This will work, if the called function is not going to return any meaningful value to the calling function. In the above program, as the sum of x, y and z is to be returned, therefore it is necessary, to use the return statement. The return statement serves two purposes: On executing the return statement it immediately transfers the control back to the calling program. It returns the value present in the parentheses after return, to the calling program. In the above program the value of sum of 3 numbers is being returned. There is no restriction on the number of return statements that may be present in a function. Also, the return statement need not always be present at the end of the called function. E.g. fun( ) { char ch; clrscr(); printf(\n Enter any alphabet:); scanf(%c,&ch); if(ch>=65 && ch<=90) return(ch); else return(ch+32); getch(); } In this function different return statements will be executed depending on whether ch is capital or not.

b)

1) 2)

3)

85

c)

Whenever the control returns from a function some value is definitely returned. If a meaningful value is returned then it should be accepted in the calling program by equating the called to some variable. sum=calsum(a, b, c); The valid return statements are as follows: return(a); return(23); return(12.34); return; In the last statement a garbage value is returned to the calling function since we are not returning any specific value. Note that in this case the parentheses after return are dropped.

d)

e)

If it is required that a called function should not return any value, then the keyword void is written as below: void display( ) { printf(\n xyz - - ); printf(\n pqr - - ); getch( ); }

f)

A function can return only one value at a time. Thus, the given statements are invalid. return(a,b); return(x,12);

g)

If the value of a formal argument is changed in the called function, the corresponding change does not take place in the calling function. E.g. main( ) { int a=30; clrscr(); fun(a); printf(\n %d,a); getch(); } fun(int b) { b=60; printf(\n %d,b); } Output 60 30 Thus, even though the value of b is changed in fun( ), the value of a in main( ) remains unchanged. Function Declaration and Prototypes In some programming situations it may happen that a called function should not return any value. This is made possible by making use of the keyword void.

86

void main() { void gospel(); gospel(); } void gospel() { printf(\n xyz); printf(\n pqr); printf(\n abc); } Here, the gospel() function has been defined to return void; means it would return nothing. Therefore, it would just flash the three messages and return the control back to the main function.

Call by Value and Call by Reference

Whenever a function is called and something is passed to it, always values (of variables) are passed for the variables to the called function. Such function calls are called Call by value. This means that on calling a function we are passing values of variables to it. Example of call by value is as shown below: sum=calsum(a,b,c); Also, it is known that variables are stored somewhere in memory. So, instead of the value of the variable, the location number(also called address) of the variable can also be passed to the function which is called as Call by reference. Consider the function with arguments and no return value. //fun_swap.c Q.7 WAP which uses function with arguments and returning value i.e., by using call by value. //fun_adde.c Q.8 WAP which uses function with address as arguments and return value. //fun_rswp.c

Recursion

A function is called recursive if a statement within the body of a function calls the same function. Recursive function can be effectively used in application in which the solution to a program can be expressed in terms of successively applying the same solution to subsets of program. Recursion means a function call to itself.

Q.9 WAP which computes the factorial value of an integer. Without using recursive function. //precur.c

87

Using recursive function. //prec1.c Factorial of number 5 using recursion: rec(5) returns (5 times rec(4), which returns (4 times rec(3), which returns (3 times rec(2), which returns (2 times rec(1), which returns (1))))).

#include<stdio.h> #include<conio.h> rec(int); main() { int a, fact; clrscr(); printf("\nEnter any number"); scanf("%d", &a); fact= rec(a); printf("factorial value = %d", fact); getch(); } rec(x) int x; { int f; if(x==1) return(1); else f=x*rec(x-1); return(f); } *********************************************************************** #include<stdio.h> #include<conio.h> factorial(int); main() { int a, fact;

88

clrscr(); printf("\nEnter any number"); scanf("%d", &a); //3 fact= factorial(a); printf("factorial value = %d", fact); getch(); } factorial(int x) { int f=1,i; for(i=x; i>=1; i--) f=f*i; //6 return(f); } ***********************************************************************

//stclass1.c #include<stdio.h> #include<conio.h> void main() { auto int i,j; clrscr(); printf("\n%d %d",i,j); getch(); } /*****************************OUTPUT********************************** -28701 12803 **********************************************************************/ //stclass2.c #include<stdio.h> #include<conio.h> void main() { auto int i=1; clrscr(); { { { printf("\n%d ",i); } printf("%d ",i); } printf("%d ",i); } getch(); } /*****************************OUTPUT******************************* 1 1 1

89

*******************************************************************/

//stclass3.c
#include<stdio.h> #include<conio.h> void main() { auto int i=1; clrscr(); { auto int i=2; { auto int i=3; printf("\n%d ",i); } printf("%d ",i); } printf("%d ",i); getch();} /**************************OUTPUT*********************************** 3 2 1 ********************************************************************/ //stclass4.c #include<stdio.h> #include<conio.h> void main() { register int i; clrscr(); for(i=1;i<=10;i++) printf("\n%d",i); getch(); } ******************************************************************** //stclass5.c #include<stdio.h> #include<conio.h> void main() { clrscr(); increment(); increment(); increment(); getch(); } increment() { auto int i=1; printf("%d\n",i); i=i+1; } /****************************OUTPUT*********************** 1 1

90

1 **********************************************************/ //stclass6.c #include<stdio.h> #include<conio.h> void main() { clrscr(); increment(); increment(); increment(); getch(); } increment() { static int i=1; printf("%d\n",i); i=i+1; } /*******************************OUTPUT************************* 1 //Stclass7.c #include<stdio.h> #include<conio.h> int i; void main() { clrscr(); printf("\ni=%d",i); increment(); increment(); decrement(); decrement(); getch(); } increment() { i=i+1; printf("\nOn incrementing i=%d",i); } decrement() { i=i-1; printf("\nOn decrementing i=%d",i); } /************************OUTPUT********************************* i=0 On incrementing i=1 On incrementing i=2 On decrementing i=1 On decrementing i=0

91

****************************************************************/ //stclass8.c #include<stdio.h> #include<conio.h> int x=21; void main() { extern int x; clrscr(); printf("\n%d",x); getch(); } *****************************************************************

//stclass9.c #include<stdio.h> #include<conio.h> int x=10; void main() { int x=20; clrscr(); printf("\n%d",x); display(); getch(); } display() { printf("\n%d",x); } /*****************************OUTPUT************************* 20 10 *************************************************************/

92

Storage Classes in C
From C compilers point of view, a variable name identifies some physical location within the computer where the string of bits representing the variables value is stored. There are basically two kinds of locations in a computer where such a value may be kept: Memory and CPU registers. It is the variables storage class which determines in which of these two locations the value is stored. Moreover, a variables storage class represents that Where the variable would be stored? What will be the initial value of the variable, if the initial value is not specifically assigned? (i.e. the default initial value) What is the scope of the variable i.e. in which functions the value of the variable would be available. What is the life of the variable i.e. how long would the variable exist. There are four storage classes in C. Automatic storage class Register storage class

93

Static storage class External storage class.

Automatic Storage Class: The features of a variable defined to have an automatic storage class are as follows: Storage : Memory Default initial value : An unpredictable value, which is often called a garbage value. Scope : Local to the block in which the variable is defined. Life : Till the control remains within the block in which the variable is defined. An automatic storage class variable is declared as below and the fact that if the variable is not initialized it contains a garbage value. //stclass1.c Output 1211 221 which is the garbage value since automatic variables are required to initialize properly. Scope and life of an automatic variable is illustrated as follows: //stclass2.c Output of the program is 111 Since all printf( ) statements occur within the outermost block. When the control comes out of the block in which the variable is defined, the variable and its value is irretrievably lost. E.g. //stclass3.c Note that the compiler treats the three is as totally different variables, since they are defined in different blocks.

Register Storage Class: Storage : CPU registers Default initial value : Garbage value Scope : Local to the block in which the variable is defined. Life : Till the control remains within the block in which the variable is defined. A value stored in a CPU register can always be accessed faster than the one which is stored in memory. Therefore if a variable is used at many places it is better to declare its storage class as register. Example of frequently used variables are loop counters. Storage class is named as register. //stclass4.c Here, even though the storage class of i is declared as register, it is not necessary that the value of i would be stored in a CPU register. Because the number of CPU registers are limited (14 in case of a micro-computer), and they are busy doing some other task. Then the variable works as if its storage class is automatic. Register storage class cannot be used for all types of variables. E.g. register float q; register double a; register long c;

94

These declarations are wrong because the CPU registers in a microcomputer are usually 16 bit registers and therefore cannot hold a float value or a double value, which require 4 and 8 bytes respectively for storing a value. For the above declarations error messages are not displayed, only the compiler treats the variables to be of automatic storage class. Static Storage Class: Storage : Memory Default initial value : zero Scope : Local to the block in which the variable is defined. Life : Value of the variable persists between different function calls. Consider the comparison of automatic storage class and static storage class using the given program. //stclass5.c //stclass6.c Like auto variables, static variables are also local to the block in which they are declared. The difference between them is that static variables dont disappear when the function is no longer active. Their values persist. If the control comes back to the same function again the static variables have the same values they had last time around. External Storage Class Storage: Memory Default initial value: zero Scope: Global Life: As long as the programs execution doesnt come to an end. External variables are declared outside all functions, yet are available to all functions that use them. E.g: stclass7.c i is available to the functions increment() and decrement() since i has been declared outside all functions. The function that uses an external variable should declare that variable external i.e., the keyword extern, as shown below: //stclass8.c The use of extern inside a function is optional as long as it is declared outside and above that function in the same source code file. Consider the given program: //stclass9.c Here, the local variable gets preference over the global variable hence for the printf(), present in main() output is 20. When display() is called and control reaches the printf(), the value of the global x i.e., 10 is printed.

95

96

Pointers
A Pointer is a variable that represents the location (address) of a variable, within the computer memory. Also, Pointers are special type of variables which stores the address of some another variable. Consider the declaration, int i=3; This declaration indicates the C compiler to:

Reserve space in memory to hold the integer value. Associate the name i with this memory location. Store the value 3 at this location.
is location in memory is represented by following memory map. location name i value at location

65524

location number (address)

From the above description, it is seen that the compiler has selected memory location 65524 as the place to store value 3. The location number 65524 is not a number to be relied upon, because some other time the compiler may choose a different location for storing value 3. The important point is is address in memory is 65524. The following program can print address number: #include<stdio.h> #include<conio.h> void main() { int i=3; clrscr(); printf("\nAddress of i=%u", &i); printf("\nValue of i=%d", i); getch(); } /****************************OUTPUT******************************** Address of i=65524 Value of i=3 *******************************************************************/

97

#include<stdio.h> #include<conio.h> void main() { int i=3; clrscr(); printf("\nAddress of i=%u", &i); printf("\nValue of i=%d",i); printf("\nValue of i=%d",*(&i)); getch(); } /*******************************OUTPUT******************************** Address of i=65524 Value of i=3 Value of i=3 **********************************************************************/ #include<stdio.h> #include<conio.h> void main() { int i=3; clrscr(); printf("\nAddress of i=%u", &i); printf("\nValue of i=%d", i); getch(); } /****************************OUTPUT******************************** Address of i=65524 Value of i=3 *******************************************************************/

& is Cs address of operator. The address is printed out using %u which is a format specifier for printing an unsigned integer and since 65524 represents an address, there is no question of sign being associated with it. The other pointer operator available in C is *, called value at address operator. It gives the value stored at a particular address. The value at address operator is also called indirection operator. E.g. hv

98

#include<conio.h> void main() { int i=3; clrscr(); printf("\nAddress of i=%u", &i); printf("\nValue of i=%d",i); printf("\nValue of i=%d",*(&i)); getch(); } /*******************************OUTPUT******************************** Address of i=65524 Value of i=3 Value of i=3 **********************************************************************/ The expression &i gives the address of the variable i. This address can be collected in a variable, by j=&i; j is a variable which contains the address of other variable. (i in this case) i j

3
65524 is value is 3 and js value is is address.

65524
65522

Since j is a variable which contains the address of i, it is declared as, int *j; This declaration means that j will be used to store the address of an integer value. Also, * stands for value at address. Thus int *j also means that the value at the address contained in j is an integer.

99

************************************************************************ #include<stdio.h> #include<conio.h> void main() { int i=3; int *j; j=&i; clrscr(); printf("\nAddress of i=%u",&i); printf("\nAddress of i=%u",j); printf("\nAddress of j=%u",&j); printf("\nValue of j=%u",j); printf("\nValue of i=%d",i); printf("\nValue of i=%d",*(&i)); printf("\nValue of i=%d",*j); getch(); } /********************************OUTPUT******************************* Address of i=65524 Address of i=65524 Address of j=65522 Value of j=65524 Value of i=3 Value of i=3 Value of i=3 **********************************************************************/ Consider the declarations, int *alpha; char *ch; float *s; Here alpha, ch and s are declared as pointer variables i.e., variables capable of holding addresses. Addresses are always going to be whole numbers, therefore pointers always contain whole numbers. *s means s is going to contain the address of a floating point value. Similarly char *ch Is going to contain the address of a char value or in other words, the value at address stored in ch is going to be a character. Pointer is a variable which contains address of another variable. This variable itself might be another pointer. Thus pointer may contain, another pointers address. This concept is explained in the example given below:

100

*********************************************************************** #include<stdio.h> #include<conio.h> main() { int i=3, *j, **k; j=&i; k=&j; clrscr(); printf("\nAddress of i=%u", &i); //65524 printf("\nAddress of i=%u", j); //65524 printf("\nAddress of i=%u", *k); //65524 printf("\nAddress of j=%u", &j); // 65522 printf("\nAddress of j=%u", k); //65522 printf("\nAddress of k=%u", &k); //65520 printf("\nValue of j=%u", &j); //65522 printf("\nValue of j=%u", &k); //65520 printf("\nValue of j=%u", j); //65524 printf("\nValue of k=%u", k); //65522 printf("\nValue of i=%d", i); //3 printf("\nValue of i=%d", *(&i)); //3 printf("\nValue of i=%d",*j); //3 printf("\nValue of i=%d",**k); //3 getch(); } *********************************************************************** i j k 65524

65522

65524 65520

65522

Variables j and k are declared as: int i, *j, **k; Here i is an ordinary int, j is a pointer to an int (also called an integer pointer) whereas k is a pointer to an integer pointer. Consider an example, i j k

259
6328 l m

6328
9123

9123
5926

5926 2222
2223

2222
5555

101

************************************************ #include<stdio.h> #include<conio.h> main() { int i=3, ****m = & l; int *j = &i,**k=&j, ***l= &k; clrscr(); printf("\n%u", &i); //65524 printf("\n%d", *(&i)); //3 printf("\n%d", **k); //3 printf("\n%u", **m); //5133 printf("\n%u", ***(&l)); //61 printf("\n%u", *(&j)); //12803 printf("\n%d", ****m); //3 printf("\n%u", **(&m)); //767 printf("\n%u", ***(&m)); //5133 getch(); } ********************************************************************** &i=6328 *(&i)=*6328=259 **k=**9123=*6328=259 **m=**2222=*5926=9123 ***(&l)=***2222=**5926=*9123=6328 *(&j)=*9123=6328 ****m=****2222=***5926=**9123=*6328=259 **&m=**5555=*2222=5926 ***&m=***5555=**2222=*5926=912 *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("\nEnter a and b:"); scanf("%d %d",&a,&b); swap(&a,&b); printf("\nThe result after swapping is:%d %d",a,b); getch(); } swap(int *a1, int *b1) { int c; c=*a1; *a1=*b1;

102

*b1=c; } ************************************************ #include<stdio.h> #include<conio.h> areacir(float ,float *, float *); main() { float r, area,cir; clrscr(); printf("\nEnter radius"); scanf("%f",&r); areacir(r,&area,&cir); printf("\nThe Area:%f, The circumference:%f",area,cir); getch(); } areacir(float r1, float *a, float *c) { *a= 3.142*r1*r1; *c=2*3.142*r1; } *********************************************** #include<stdio.h> #include<conio.h> sum(int,int,int,int *, float *); main() { int a,b, c, s; float avg; clrscr(); printf("\nEnter the values of a,b,c"); scanf("%d%d%d", &a,&b,&c); sum(a,b,c, &s, &avg); printf("the sum :%d, the avg :%f", s,avg); getch(); } sum(int a1,int a2, int a3, int *s1, float *a) { *s1=a1+a2+a3; *a=*s1/3.0; }

103

Arrays

An array is defined as a set of homogenous data item.Sometimes it can be required to assign different values to the variables store only one value at a time that is last value so because of this drawback arrays are used to store more than one value at the same memory location. Array is a collection of similar elements where similar elements can be all integers or all characters or all floats. It is a collection of similar datatypes arranged in a contigeous memory location. Syntax: Datatype int float

Name of the array A X

[Dimension of the array] [5]; [10];

The variable having only one subscript is a single subscripted variable or also known as one dimensional array. Example: Suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case we have two options to store there marks in memory. 1. Construct 100 variables to store percentage marks obtained by 100 different student i.e., each variable containing one students marks. 2. Construct one variable (called array or subscripted variable) capable of storing or holding all hundred values. Definition of array in other words An array is a collective name given to a group of similar quantities that could be percentage marks of 100 students or salaries of 300 employee usually array of character is called a string

Defining Arrays

int a[5];
a[0] a[1] a[2] a[3] a[4]

int a[10] 200 202 204 a[0] a[1] a[2]

104

206 208 210 212 214 216 218

a[3] a[4] a[5] a[6] a[7] a[8] a[9]

#include<stdio.h> #include<conio.h> void main() { int a[10],i; clrscr(); for(i=0;i<=9;i++) { printf("\nEnter the element:"); scanf("%d",&a[i]); } for(i=0;i<=9;i++) { printf("\n%d",a[i]); } getch(); } /**************************OUTPUT********************************* Enter the element:1 Enter the element:2 Enter the element:3 Enter the element:4 Enter the element:5 Enter the element:6 Enter the element:7 Enter the element:8 Enter the element:9 Enter the element:10 1 2 3 4

105

5 6 7 8 9 10 ********************************************************************/

#include<stdio.h> #include<conio.h> void main() { float avg,sum=0; int i; int marks[30]; /*array declaration*/ clrscr(); for(i=0;i<=29;i++) { printf("\nEnter marks:"); scanf("%d",&marks[i]); /*store data in array*/ } for(i=0;i<=29;i++) sum=sum+marks[i]; /*read data from an array*/ avg=sum/30; printf("\nAverage marks=%f",avg); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int number[10]; int great,i; clrscr(); printf("\nEnter any ten numbers:"); for(i=0;i<10;i++) { scanf("%d",&number[i]); } great=number[0]; for(i=1;i<10;i++) { if(great<number[i]) great=number[i]; } printf("\nThe greatest number is %d",great); getch(); } /*******************************OUTPUT********************************* Enter any ten numbers:90

106

89 78 67 56 98 45 64 34 23 The greatest number is 98 ***********************************************************************/ #include<stdio.h> #include<conio.h> void main() { int i,pcount=0,ncount=0; int zcount=0,a[20]; clrscr(); for(i=0;i<=19;i++) { printf("\nEnter the element:"); scanf("%d",&a[i]); } for(i=0;i<=19;i++) { if(a[i]<0) ncount++; if(a[i]>0) pcount++; if(a[i]==0) zcount++; } printf("%d %d %d",ncount,pcount,zcount); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { float x[20],ele; int i,c=0; clrscr(); printf("\nEnter the 20 elements:"); for(i=0;i<=19;i++) { scanf("%f",&x[i]); } printf("\nEnter the element for count:"); scanf("%f",&ele); for(i=0;i<=19;i++) {

107

if(ele==x[i]) { c++; } } printf("\n%d",c); getch(); } *************************************************

Boundary Checking In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply in be placed memory outside the array; probably on top of other data, or on the program itself. This will lead to unpredictable results, their will be no error message that array size has been exceeded. *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int num[40],i; clrscr(); for(i=0;i<=100;i++) num[i]=i; getch(); } ****************************************************** Passing Array Elements to a Function Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. ****************************************************** #include<stdio.h> #include<conio.h> void main() { int i; int marks[]={55,65,75,56,78,78,90}; clrscr(); for(i=0;i<=6;i++) display(marks[i]); getch(); } display(int m) { printf("%d ",m); } /****************************OUTPUT********************************* 55 65 75 56 78 78 90

108

********************************************************************/

#include<stdio.h> #include<conio.h> void main() { int i; int marks[]={55,65,75,56,78,78,90}; clrscr(); for(i=0;i<=6;i++) display(&marks[i]); getch(); } display(int *n) { printf("%d ",*n); } /*****************************OUTPUT*********************************** 55 65 75 56 78 78 90 ***********************************************************************/ ****************************************************** Pointers and Arrays Eg: #include<stdio.h> #include<conio.h> void main() { int i=3,*x; float j=1.5,*y; char k='c',*z; clrscr(); printf("\nValue of printf("\nValue of printf("\nValue of x=&i; y=&j; z=&k; printf("\nOriginal printf("\nOriginal printf("\nOriginal x++; y++;

i=%d",i); j=%f",j); k=%c",k);

address in x=%u",x); address in y=%u",y); address in z=%u",z);

109

z++; printf("\nNew address in x=%u",x); printf("\nNew address in y=%u",y); printf("\nNew address in z=%u",z); getch(); } /*****************************OUTPUT********************************* Value of i=3 Value of j=1.500000 Value of k=c Original address in x=65524 Original address in y=65520 Original address in z=65519 New address in x=65526 New address in y=65524 New address in z=65520 *********************************************************************/ Rules for Initialization int mark[5]={88,90,67}; it will be stored as int mark[5]={88,90,67,0,0}; For character initialization char name[6]=Sneha; char name[6]={S,N,E,H,A,\0}; The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus, the following operations can be performed on a pointer: a) Addition of a number to a pointer. E.g.: int i=4,*j,*k; j=&i; j=j+1; j=j+9; k=j+3; b) Subtraction of a number from a pointer. E.g.: int i=4, *j,*k; j=&i; j=j-2; j=j-5; k=j-6; c) Subtraction of one pointer from another. One pointer variable can be subtracted from another provided both variables point to elements of the same array. The resulting value indicates the number of bytes separating the corresponding array elements. E.g.: main() { int arr[]={10,20,30,45,67,56,74}; int *i,*j; i=&arr[1]; j=&arr[5];

110

printf(%d %d,j-i,*j-*i); } Here i and j have been declared as integer pointers holding addresses of first and fifth element of the array respectively. Suppose the array begins at location 4002, then the elements arr[1] and arr[5] would be present at locations 4004 and 4012 respectively, since each integer in the array occupies two bytes in memory. The expression j-i would print a value 4 and not 8. This is because j and i are pointing to locations which are 4 integers apart. The result of the expression *j-*i is 36 since *j and *i return the values present at addresses contained in the pointers j and i. Comparison of two pointer variables. Pointer variables can be compared provided both variables point to objects of the same data type. Such comparisons can be useful when both pointer variables point to elements of the same array. The comparison can test for either equality or inequality. Moreover a pointer variable can be compared with zero (usually expressed as NULL). E.g.: main() { int arr[]={10,20,36,72,45,36}; int *j,*k; j=&arr[4]; k=(arr+4); if(j==k) printf(\nThe two pointers point to the same location); else printf(\nThe two pointers do not point to the same location); }

Correlation between two facts. a) Array elements are always stored in contiguous memory locations. b) A pointer when incremented always points to an immediately next location of its type. Consider an array num[]={24,34,12,44,56,17} The following figure shows how this array is located in memory. 24 34 12 44 56 17 4001 4003 4005 4007 4009 4011

#include<stdio.h> #include<conio.h> void main() { int num[]={24,34,12,44,56,17}; int i; clrscr(); for(i=0;i<=5;i++) { printf("\nElement no:%d",i); printf(" Address:%u",&num[i]); } getch();

111

/*************************OUTPUT********************************** Element no:0 Address:65514 Element no:1 Address:65516 Element no:2 Address:65518 Element no:3 Address:65520 Element no:4 Address:65522 Element no:5 Address:65524 ******************************************************************/ Note that the array elements are stored in contiguous memory locations, each element occupying two bytes, since it is an integer array. Each address will be 2 bytes greater than its immediate predecessor. ******************************************************************** #include<stdio.h> #include<conio.h> void main() { int num[]={24,34,12,44,56,17}; int i; clrscr(); for(i=0;i<=5;i++) { printf("\nAddress:%u",&num[i]); printf(" Element:%d",num[i]); } getch(); } /****************************OUTPUT********************************** Address:65514 Element:24 Address:65516 Element:34 Address:65518 Element:12 Address:65520 Element:44 Address:65522 Element:56 Address:65524 Element:17 *********************************************************************/ *************************************************** #include<stdio.h> #include<conio.h> void main() { int num[]={24,34,12,44,56,17}; int i,*j; clrscr(); j=&num[0]; /*assign address of zeroeth element */ for(i=0;i<=5;i++) { printf("\nAddress:%u",j); printf(" Element:%d",*j); j++; /*increment pointer to point to next location*/ } getch();

112

/*****************************OUTPUT******************************* Address:65514 Element:24 Address:65516 Element:34 Address:65518 Element:12 Address:65520 Element:44 Address:65522 Element:56 Address:65524 Element:17 ********************************************************************/ #include<stdio.h> #include<conio.h> void main() { int num[]={24,34,12,44,56,17}; clrscr(); display(&num[0],6); getch(); } display(int *j,int n) { int i; for(i=0;i<=n-1;i++) { printf("\nElement:%d",*j); j++; /*increment pointer to point to next location*/ } } /***************************OUTPUT***************************** Element:24 Element:34 Element:12 Element:44 Element:56 Element:17 ***************************************************************/ *********************************************************************** Note that the address of the zeroth element(many a times called the base address) can also be passed by just passing the name of the array. Thus, the following two function calls are same: display(&num[0],6); display(num,6); Consider the following array. 24 34 12 4001 4003 4005 4007

44 4009

56 4011

17

The above array is declared in C as: int num[]={24,34,12,44,56,17}; On mentioning the name of the array we get its base address. Thus, by *num, we can refer to the zeroth element of the array, that is, 24. i.e. *num and *(num+0) both refer to 24.

113

Similarly, *(num+1) refer to the first element of the array i.e. 34. For num[i], the C compiler internally converts it to *(num+i). All the following notations are same: num[i] *(num+i) *(i+num) i[num]

****************************************************** #include<stdio.h> #include<conio.h> void main() { int num[]={24,34,12,44,56,17}; int i; clrscr(); for(i=0;i<=5;i++) { printf("\nAddress:%u",&num[i]); printf(" Element:%d %d",num[i],*(num+i)); printf(" %d %d",*(i+num),i[num]); } getch(); } /********************************OUTPUT********************************* Address:65514 Element:24 24 24 24 Address:65516 Element:34 34 34 34 Address:65518 Element:12 12 12 12 Address:65520 Element:44 44 44 44 Address:65522 Element:56 56 56 56 Address:65524 Element:17 17 17 17 *********************************************************************** More than one dimension Multidimensional Arrays Two Dimensional Arrays The two dimensional array is also called a matrix. int student[4][2] ;

rows
Col 0

columns
col 1

114

ro r1 r2 r3

1 3
Total Total No. Of

4 6 8
No of elements =total No. Of Rows * Columns = 4 * 2 =8

5 7

***********************************************************************

#include<stdio.h> #include<conio.h> void main() { int stud[4][2]; int i,j; clrscr(); for(i=0;i<=3;i++) { printf("\nEnter rollno and marks:"); scanf("%d %d",&stud[i][0],&stud[i][1]); } for(i=0;i<=3;i++) printf("\n%d %d",stud[i][0],stud[i][1]); getch(); }

/******************************OUTPUT************************** Enter rollno and marks:01 89 Enter rollno and marks:02 78 Enter rollno and marks:03 67 Enter rollno and marks:04 65 1 89 2 78 3 67 4 65 *****************************************************************/

115

col.no 0

col.no 1

1234 1212 1434 1312


Fig. a.

56 33 80 78

row no. 0 row no. 1 row no. 2

row no. 3

Initializing a 2-Dimensional Array int stud[4][2]={ {1234,56}, {1212,33}, {1434,80}, {1312,78} }; OR int stud[4][2]={1234,56,1212,33,1434,80,1312,78}; It is important to note that while initializing an array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional. Thus the declarations, int arr[2][3]={12,34,23,45,56,45}; int arr[ ][3]={12,34,23,45,56,45}; are valid. whereas, int arr[2][ ]={12,34,23,45,56,45}; int arr[ ][ ]={12,34,23,45,56,45}; are invalid. Memory Map of a 2-Dimensional Array The arrangement shown in Fig. a is only conceptually true. This is because memory doesnt contain rows and columns, In memory whether it is a one-dimensional or a two-dimensional array, the array elements are stored in one continuous chain. The arrangement of array elements of a 2-dimensional array in memory is shown below: s[0][0] 1234 s[0][1] 56 s[1][0] 1212 s[1][1] 33 s[2][0] 1434 s[2][1] 80 s[3][0] 1312 5014 s[3][1] 78 5016

5002 5004 5006 5008 5010 5012 printf(Marks of 3rd student=%d,stud[2][1]);

116

will refer to the 3rd student.

Pointers & 2-Dimensional Arrays

2-D array is an array of arrays. #include<stdio.h> #include<conio.h> void main() { int s[4][2]={ {1234,56}, {1212,33}, {1434,80}, {1312,78}, }; int i,j; clrscr(); for(i=0;i<=3;i++) printf("\nAddress of %dth 1-D array=%u",i,s[i]); getch(); } /**************************OUTPUT************************************ Address of 0th 1-D array=65510 Address of 1th 1-D array=65514 Address of 2th 1-D array=65518 Address of 3th 1-D array=65522 *********************************************************************/ Here, 5 is an integer array. So each element of this array occupies 2 bytes. There are 2 elements in each row, so each row takes 4 bytes. The following expressions refer to the same element. s[2][1] *(s[2]+1) *(*(s+2)+1) ************************************************* #include<stdio.h> #include<conio.h> void main()

117

{ int s[4][2]={ {1234,56}, {1212,33}, {1434,80}, {1312,78}, }; int i,j; clrscr(); for(i=0;i<=3;i++) { printf("\n"); for(j=0;j<=1;j++) printf("%d ",*(*(s+i)+j)); } getch(); } /******************************OUTPUT******************************** 1234 56 1212 33 1434 80 1312 78 *********************************************************************/

Three Dimensional Array Initializing a 3 dimensional array int arr[3][4][2]={ { {2,4}, {7,8}, {3,4}, {5,6} }, { {7,6}, {3,4}, {5,3},

2
{2,3} }, { {8,9}, {7,2}, {3,4}, {5,1}

4 8 4 6

4 3 3

4 1

7 3 5

118

}; }; A 3-dimensional array can be thought of as an array of arrays of arrays. 2nd 2-D Array 1st 2-D Array 8 0th 2-D Array In memory the same array elements are stored as

0th 2-D Array


2 4 7 8 3 4 5 6 7 6

1st 2-D Array


3 4 5 3 2 3 8

2nd 2-D Array


9 7 2 3 4 5 1

Following expressions refer to the same element in the 3-D array. arr[2][3][1] *(*(*(arr+2)+3)+1).

Array of Pointers The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer variable always contains an address, an array of pointers would be nothing but a collection of addresses. *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int *arr[4]; int i=31,j=5,k=19,l=71,m; clrscr(); arr[0]=&i; arr[1]=&j; arr[2]=&k; arr[3]=&l; for(m=0;m<=3;m++) printf("%d ",*(arr[m])); getch(); } /*************************OUTPUT********************************* 31 5 19 71 ***************************************************/

31

19 119

71

4008

5116

6010

7118

arr[0] 4008 7602

arr[1] 5116 7604

arr[2] 6010 7606

arr[3] 7118 7608

An array of pointers can even contain the addresses of other arrays. main() { int a[]={0,1,2,3,4}; int *p[]={a,a+1,a+2,a+3,a+4}; printf(\n%u %u %d,p,*p,*(*p)); }

Printing of string #include<stdio.h> #include<conio.h> void main() { char name[]="Klinsman"; int i=0; clrscr(); while(i<=7) { printf("%c",name[i]); i++; } getch(); }

/***************************OUTPUT****************************** Klinsman ****************************************************************/ Here we have initialized a character array, & then printed out the elements of the array within a while loop.

120

String Functions
A string constant is a one dimensional array of characters terminated by a null( \0). For E.g.: char name[]={H,A,E,S,L,E,R,\0}; Each character in the array occupies one byte of memory and the last character is always \0. The terminating null(\0) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a \0 is not really a string, but merely a collection of characters. H 4001 A 4002 E 4003 S 4004 L 4005 E 4006 R 4007 \0 4008

The above string can also be initialized as:

121

char name[]=HAESLER; Here C inserts the null character automatically so; in this declaration \0 is not necessary. Each character array always ends with a \0 so program can be written w ithout using the final value (7) in while loop. *********************************************************************** #include<stdio.h> #include<conio.h> void main() { char name[]="Klinsman"; int i=0; clrscr(); while(name[i]!='\0') { printf("%c",name[i]); i++; } getch(); } /****************************OUTPUT********************************** Klinsman *********************************************************************/

Pointer to access the array elements. #include<stdio.h> #include<conio.h> void main() { char name[]="Klinsman"; char *ptr; clrscr(); ptr=name; /*store base address of string*/ while(*ptr!='\0') { printf("%c",*ptr); ptr++; }

122

getch(); } ****************************************************** A large set of useful string handling library functions are provided to every C compiler. From this, the most commonly used string functions are strlen(), strcpy(), strcat() and strcmp().

1) Strlen():
This function counts the number of characters present in a string. It is used to find length of string i.e. it returns number of character. *************************************************** #include<stdio.h> #include<conio.h> #include<string.h> void main() { char arr[]="Nagpur"; int len1,len2; clrscr(); len1=strlen(arr); len2=strlen("Humpty Dumpty"); printf("\nString=%s length=%d",arr,len1); printf("\nString=%s length=%d","Humpty Dumpty",len2); getch(); } /****************************OUTPUT************************************ String=Nagpur length=6 String=Humpty Dumpty length=13 ***********************************************************************/

Using function xstrlen() i.e. by removing the standard library function strlen(), the same program can be written as: ****************************************************** #include<stdio.h> #include<conio.h> #include<string.h> void main() { char arr[]="Nagpur"; int len1,len2; clrscr(); len1=xstrlen(arr); len2=xstrlen("Humpty Dumpty"); printf("\nString=%s length=%d",arr,len1);

123

printf("\nString=%s length=%d","Humpty Dumpty",len2); getch(); } xstrlen(char *s) { int length=0; while(*s!='\0') { length++; s++; } return(length); }

/*******************************OUTPUT******************************* String=Nagpur length=6 String=Humpty Dumpty length=13 *********************************************************************/ Here, the function xstrlen keep counting characters till the pointer S doesnt point to \0.

This function copies the contents of one string into another. The base addresses of the source & target strings should be supplied to this function. If the target string has value then it will be overwritten. ***************************************************** #include<stdio.h> #include<conio.h> #include<string.h> void main() { char source[]="Nagpur"; char target[20]; clrscr(); strcpy(target,source); printf("\nSource String=%s",source); printf("\nTarget String=%s",target);

2) Strcpy():

124

getch(); } /***************************OUTPUT************************************ Source String=Nagpur Target String=Nagpur **********************************************************************/ ****************************************************** //Program using function xstrcpy(). #include<stdio.h> #include<conio.h> void main() { char source[]="Nagpur"; char target[20]; clrscr(); xstrcpy(target,source); printf("\nSource String=%s",source); printf("\nTarget String=%s",target); getch(); } xstrcpy(char *t,char *s) { while(*s!='\0') { *t=*s; s++; t++; } *t='\0'; } /*******************************OUTPUT********************************* Source String=Nagpur Target String=Nagpur ***********************************************************************/

3) Strcat(): This function concatenates the source string at the end of the target string.
****************************************************** #include<stdio.h> #include<conio.h> #include<string.h> void main() { char source[]="Bombay"; char target[30]="Nagpur"; clrscr(); strcat(target,source); printf("\nSource String=%s",source); printf("\nTarget String=%s",target);

125

getch(); }

/***************************OUTPUT*********************************** Source String=Bombay Target String=NagpurBombay *********************************************************************/

4) Strcmp():
different.

This is a function which compares two strings to find out whether they are same or

#include<stdio.h> #include<conio.h> #include<string.h> void main() { char string1[10], string2[10]; int x; clrscr(); printf("\nEnter a word:"); scanf("%s",&string1); printf("\nEnter a word to be compared:"); scanf("%s",&string2); x=strcmp(string1,string2); if(x==0) printf("\nThey are similar words"); else printf("\nThey are not similar words"); getch(); } *********************************************************************

/Program to input a string and

print into uppercase and lowercase.

#include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[20]; clrscr(); printf("\nEnter first string:"); gets(a); printf("\nString in uppercase:%s",strupr(a)); printf("\nString in lowercase:%s",strlwr(a)); getch(); }

126

/******************************OUTPUT********************************* Enter first string:Kanchan String in uppercase:KANCHAN String in lowercase:kanchan *********************************************************************** //Program to enter a string and count no.of times 'a' occurs in a string #include<stdio.h> #include<conio.h> #include<string.h> void main() { int n,i,count=0; char a[20]; clrscr(); printf("\nEnter a string:"); gets(a); n=strlen(a); for(i=0;i<n;i++) if(a[i]=='a') count++; printf("\nNo. of times 'a' occurs=%d",count); getch(); } /**************************OUTPUT******************************* Enter a string:Kanchan No. of times 'a' occurs=2 ***********************************************************************

/*Enter the string in uppercase and convert it into lowercase without using any string function.*/ #include<stdio.h> #include<conio.h> void main() { char a[50]; int i; clrscr(); printf("\nEnter a string in uppercase:"); gets(a); while(a[i]!='\0') { if(a[i]>='A' && a[i]<='Z')

127

{ a[i]+=32; i++; } } printf("\nString in lowercase is \n%s",a); getch(); } Two Dimensional Array of Characters #include<stdio.h> #include<conio.h> #define FOUND 1 #define NOTFOUND 0 void main() { char masterlist[6][10]={ "reena", "akshay", "girish", "mandeep", "srinivas", "shikha" }; int i,flag,a; char yourname[10]; clrscr(); printf("\nEnter your name:"); scanf("%s",&yourname); flag=NOTFOUND; for(i=0;i<=5;i++) { a=strcmp(&masterlist[i][0],yourname); if(a==0) { printf("Welcome you can enter the palace"); flag=FOUND; break; } } if(flag==NOTFOUND) printf("Sorry, you are a trespasser"); getch(); } /*****************************OUTPUT******************************* Enter your name:dinesh Sorry, you are a trespasser Enter your name:mandeep Welcome you can enter the palace *******************************************************************/

128

r a g

e e n a \0 k s h a y \0 i r i s h \0 p \0 \0

1001 1011 1021 1031 1041 1051 1060(last location)

m a n d e e s s

Here, 1001, 1011, 1021 etc are the base addresses of successive names, some of the names do not occupy all the bytes reserved for them. For E.g., even though 10 bytes are reserved for storing the name reena, it occupies only 6 bytes. Thus, 4 bytes go waste. Similarly, for each na me there is some amount of wastage. In fact, more the number of names, more would be the wastage. This is avoided by array pointers.

r i n i v a s h i k h a \0

Array of Pointers to Strings Array of pointers is to make a more efficient use of available memory, to obtain greater ease in manipulation of the strings.

****************************************************** #include<stdio.h> #include<conio.h> void main() { char names[][10]={ "reena", "akshay", "girish", "mandeep", "srinivas", "shikha" }; int i;

129

char t; clrscr(); printf("\nOriginal:%s %s",&names[2][0],&names[3][0]); for(i=0;i<=9;i++) { t=names[2][i]; names[2][i]=names[3][i]; names[3][i]=t; } printf("\nNew:%s %s",&names[2][0],&names[3][0]); getch(); } /*****************************OUTPUT************************************* Original:girish mandeep New:mandeep girish *************************************************************************/

In the above program, 10 exchanges are needed to interchange two names as exchange is corresponding characters of the two names. This can be reduced by using an array of pointers to strings.

****************************************************** #include<stdio.h> #include<conio.h> void main() { char *names[]={ "reena", "akshay", "girish", "mandeep", "srinivas", "shikha" }; char *temp;

130

clrscr(); printf("\nOriginal:%s %s",names[2],names[3]); temp=names[2]; names[2]=names[3]; names[3]=temp; printf("\nNew:%s %s",names[2],names[3]); getch(); } /**************************OUTPUT***************************** Original:girish mandeep New:mandeep girish **************************************************************/ Here, exchange of addresses (of the names) stored in the array of pointers takes place instead of names themselves.

Structures
Structure can be defined as a data structure whose individual elements differ in types. Thus, a single structure might contain integer elements, floating points & characters, pointer, array and other structure can be included as elements within a structure. In other words, a structure is a collection of one or more variables, possibly of different data types grouped together under a single name for convenient handling. Syntax: struct name { member 1 member 2 };

131

e.g. struct student { char name[20]; int rollno; float marks; }student1, student2; If data about 3 books is to be stored, then we can follow two approaches: Construct individual arrays, one for storing names, another for storing prices & still another for storing number of pages. Use a structure variable.

A structure contains a number of data types grouped together. These data types may or may not be of the same type.

Declaration of the structure type and the structure variables. E.g. struct book { char name; float price; int pages; }; struct book b1,b2,b3; is same as struct book { char name;

132

float price; int pages; }b1,b2,b3; OR struct { char name; float price; int pages; }b1,b2,b3; Like primary variables and arrays, structure variables can also be initialized where they are declared. struct book { char name[10]; float price; int pages; }; struct book b1={Basic,130.00,550}; struct book b2={Physics,150.80,800}; Structure Elements are stored as below: #include<stdio.h> #include<conio.h> void main() { struct book { char name; float price; int pages; }; struct book b1={'B',130.00,550}; clrscr(); printf("\nAddress of name=%u",&b1.name); printf("\nAddress of price=%u",&b1.price); printf("\nAddress of pages=%u",&b1.pages); printf("\nName=%c Price=%f Pages=%d",b1.name,b1.price,b1.pages); getch(); } *********************************************************************** Structure elements are stored in memory as: b1.name b1.price

b1.pages

130.00

550

Array of Structures Like an ordinary integer variable, float variable we can have array of structure #include<stdio.h>

133

#include<conio.h> #include<string.h> void main() { struct employee { char name[10]; int age; float salary; }; struct employee e[3]; int i clrscr(); printf(\nenter name\tage and salary of employee); for(i=0;i<3;i++) scanf(%s %d %f,&e[i].name,&e[i].age,&e[i].salary); printf(\nthe details of employee are); for(i=0;i<3;i++) { printf(\nname=%s age=%d,e[i].name,e[i].age); printf(\nsalary=%f,e[i].salary); } getch(); } /****************************OUTPUT*********************************** Enter name age and salary of employee Sanjay 30 12000.26 Nikhil 31 13000.55 Nitesh 28 14000.22 the details of employee are Name=Sanjay age =30 salary =12000.259999 Name=Nikhil age =31 salary =13000.549999 Name=Nitesh age =28 salary =14000.219999 **********************************************************************/

Additional features of Structures

a) The values of a structure variable can be assigned to another structure variable of the same type
using the assignment operator. #include<stdio.h> #include<conio.h> #include<string.h> void main() { struct employee { char name[10];

134

int age; float salary; }; struct employee e1={"Sanjay",30,20000.50}; struct employee e2,e3; clrscr(); strcpy(e2.name,e1.name); e2.age=e1.age; e2.salary=e1.salary; e3=e2; printf("\n%s %d %f",e1.name,e1.age,e1.salary); printf("\n%s %d %f",e2.name,e2.age,e2.salary); printf("\n%s %d %f",e3.name,e3.age,e3.salary); getch(); } /****************************OUTPUT*********************************** Sanjay 30 20000.500000 Sanjay 30 20000.500000 Sanjay 30 20000.500000 **********************************************************************/

b) One structure can be nested within another structure. Using this, complex data types can be created.
#include<stdio.h> #include<conio.h> void main() { struct address { char phone[15]; char city[25]; int pin; }; struct emp { char name[25]; struct address a; }; struct emp e={"Akshay","531046","Nagpur",10}; clrscr(); printf("\nName=%s Phone=%s",e.name,e.a.phone); printf("\nCity=%s Pin=%d",e.a.city,e.a.pin); getch(); } /****************************OUTPUT******************************* Name=Akshay Phone=531046 City=Nagpur Pin=10 ******************************************************************/

c) A structure variable can also be passed to a function like an ordinary variable. 135

#include<stdio.h> #include<conio.h> void main() { struct book { char name[25]; char author[25]; int callno; }; struct book b1={"Let Us C","YPK",101}; clrscr(); display(b1.name,b1.author,b1.callno); getch(); } display(char *s,char *t,int n) { printf("\n%s\t%s\t%d",s,t,n); } /*****************************OUTPUT****************************** Let Us C YPK 101 ******************************************************************/ Here, instead of passing individual elements entire structure can be passed at a time. #include<stdio.h> #include<conio.h> struct book { char name[25]; char author[25]; int callno; }; void main() { struct book b1={"Let Us C","YPK",101}; clrscr(); display(b1); getch(); } display(struct book b) { printf("\n%s\t%s\t%d",b.name,b.author,b.callno); } /************************OUTPUT********************************* Let Us C YPK 101 ****************************************************************/ Pointers pointing to struct are called as Structure pointers. #include<stdio.h>

136

#include<conio.h> void main() { struct book { char name[25]; char author[25]; int callno; }; struct book b1={"Let Us C","YPK",101}; struct book *ptr; clrscr(); ptr=&b1; printf("\n%s %s %d",b1.name,b1.author,b1.callno); printf("\n%s %s %d",ptr->name,ptr->author,ptr->callno); getch(); } /**************************OUTPUT****************************** Let Us C YPK 101 Let Us C YPK 101 ***************************************************************/

b1.name Let Us C 4001 ptr

b1.author YPK 4026

b1.callno 101 4051

4001

137

/*Passing address of a structure variable*/ #include<stdio.h> #include<conio.h> struct book { char name[25]; char author[25]; int callno; }; void main() { struct book b1={"Let Us C","YPK",101}; clrscr(); display(&b1); getch(); } display(struct book *b) { printf("\n%s %s %d",b->name,b->author,b->callno); } /*************************OUTPUT******************************* Let Us C YPK 101 ***************************************************************/ Unions Both structures and unions are used to group a number of different variables together, But while a structure allows to treat a number of different variables stored at different places in memory, a union allows to treat the same space in memory as a number of different variables. #include<stdio.h> #include<conio.h> void main() { union a { int i; char ch[2]; }; union a key; clrscr(); key.i=512; printf("\nkey.i=%d",key.i); printf("\nkey.ch[0]=%d",key.ch[0]); printf("\nkey.ch[1]=%d",key.ch[1]); getch();

138

/**************************OUTPUT******************************* key.i=512 key.ch[0]=0 key.ch[1]=2 ****************************************************************/ Consider struct a { int i; char ch[2]; }; struct a key; The data type would occupy 4 bytes in memory, 2 for key.i and 1 each for key.ch[0] and key.ch[1] as shown: key.i 1002 Consider union a { int i; char ch[2]; }; union a key; This data type in memory is represented as shown: Key.i 1003 key.ch[0] 1004 key.ch[1] 1005

key.ch[0]

key.ch[1]

The union occupies only 2 bytes in memory. o/p key.i=512 key.ch[0]=0 key.ch[1]=2 512 is an integer, a 2 byte number. Its binary equivalent will be 0000 0010 0000 0000. When stored in memory. key.i 0 0

0 0 0 high byte key.ch[0]

0 0 low byte key.ch[1]

139

When a two byte number is stored in memory, the low byte is stored before the high byte. It means 512 would be stored in memory as: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 Therefore, the value of key.ch[0] is printed as 0 and value of key.ch[1] is printed as 2. We cant assign different values to the different union elements at the same time. #include<stdio.h> #include<conio.h> void main() { union a { int i; char ch[2]; }; union a key; clrscr(); key.i=512; printf("\nkey.i=%d",key.i); printf("\nkey.ch[0]=%d",key.ch[0]); printf("\nkey.ch[1]=%d",key.ch[1]); key.ch[0]=50; printf("\nkey.i=%d",key.i); printf("\nkey.ch[0]=%d",key.ch[0]); printf("\nkey.ch[1]=%d",key.ch[1]); getch(); } /*****************************OUTPUT************************************ key.i=512 key.ch[0]=0 key.ch[1]=2 key.i=562 key.ch[0]=50 key.ch[1]=2 *************************************************************************/

Union of Structures
Union can be nested in another union or a structure in a union. #include<stdio.h> #include<conio.h> void main() { struct a { int i; char c[2];

140

}; struct b { int j; char d[2]; }; union z { struct a key; struct b data; }; union z strange; strange.key.i=512; strange.data.d[0]=0; strange.data.d[1]=32; clrscr(); printf("\n%d",strange.key.i); printf("\n%d",strange.data.j); printf("\n%d",strange.key.c[0]); printf("\n%d",strange.data.d[0]); printf("\n%d",strange.key.c[1]); printf("\n%d",strange.data.d[1]); getch(); } /****************************OUTPUT********************************* 512 512 0 0 32 32 ********************************************************************/

File Handling
File handling is about How new lines (\n) are stored. How end of file is indicated. How numbers are stored in the file. Mode in which a file should be opened for input is determined by the above characteristics of a file. File I/O in high level, unformatted, text mode is as follows: Given program reads a file and count, how many characters, spaces, tabs and new lines are present in the file. /*Count characters, spaces, tabs and newlines in a file*/

141

#include<stdio.h> #include<conio.h> void main() { FILE *fp; char ch; int nol=0, not=0, nob=0, noc=0; fp=fopen("struct7.c","r"); while(1) { ch=fgetc(fp); if(ch==EOF) break; noc++; if(ch==' ') nob++; if(ch=='\n') nol++; if(ch=='\t') not++; } fclose(fp); printf("\nNumber of characters=%d",noc); printf("\nNumber of blanks=%d",nob); printf("\nNumber of tabs=%d",not); printf("\nNumber of lines=%d",nol); getch(); } /*****************************OUTPUT********************************** Number of characters=4313 Number of blanks=3840 Number of tabs=14 Number of lines=71 **********************************************************************/ Before we can write information to a file on a disk or read it, we must open the file. The link between the program and the operating system is a structure called FILE which has been defined in the header file stdio.h declaration before opening the file is FILE *fp; fopen() will open a file struct7.c in read mode. Reading from a file. ch=fgetc(fp); Trouble in Opening a file #include<stdio.h> void main() { FILE *fp; fp=fopen(PR1.c,r); if(fp==NULL) { puts(Cannot open file);

142

exit(); } } Closing the file fclose(fp); A File-Copy Program Function fgetc() reads the characters from a file, fputc() writes the characters to a file. Given program takes the contents of a text file and copy them into another text file, character by character. #include<stdio.h> #include<conio.h> void main() { FILE *fs,*ft; char ch; clrscr(); fs=fopen("struct7.c","r"); if(fs==NULL) { puts("Cannot open source file"); exit(); } ft=fopen("nagpur.c","w"); if(ft==NULL) { puts("Cannot open target file"); fclose(fs); exit(); } while(1) { ch=fgetc(fs); if(ch==EOF) break; else fputc(ch,ft); } fclose(fs); fclose(ft); getch(); } *********************************************************************

143