You are on page 1of 134

C Programming Chapter 1 2 3 4 5 6 7 8 9 10 11 Topic BASICS OF C PROGRAM VARIBLES IN C KEYWORDS IN C OPERATORS CONDITIONAL CONSTRUCTS FUNCTION IN C ARRAY STRUCTURE POINTER File

HANDLING PROGRAMS FOR PRACTICE Page No. 2 4 7 8 17 35 41 46 52 59 66

Institute for Design of Electrical Measuring Instruments

-1-

C++ Programming

Chapter 1 2 3 4 5 6

Topic C++ FUNDAMENTALS BASIC DATA TYPES IN C++ VARIABLES IN C++ OPERATORS CLASS AND OBJECTS CONSTRUCTORS AND DESTRUCTORS FUNCTION AND OPERATOR OVERLOADING INHERITANCE FILE HANDLING WITH STREAM PROGRAMS FOR PRACTICE

Page No. 77 82 85 86 89 103

7 8 9 10

112 121 127 129

Institute for Design of Electrical Measuring Instruments

-2-

Chapter 1 BASICS OF C PROGRAM The standard library of C contains header files that have many built-in functions used for common tasks, such as performing input and output operations, converting characters to uppercase and lowercase, and calculating the length of words. The library functions can be included in C programs using the preprocessor directive # include<name.h>, where name.h is the header file. All the functions written in this header file are included in a program. A C program has the main() function that is mandatory for all programs. The execution of a program starts from the main() function. The statements within all functions, including main(), are enclosed in curly brackets { }. The syntax of using the main() function is: # include<stdio.h> void main() { /* Logic of the program to be written here */ } In the above statements, the stdio.h file is included so that standard input/output library can be used, and the main() function is defined. PRINTF () AND COMMENT STATEMENT Introduction to printf() statement Consider a sample program void main() { printf(" printf through "); } The above program will display printing through printf function on the terminal. The name print, meaning .display. Displays the message written in printf statement on the terminal. printf() is a precompiled library function. supplied with turbo Curly braces({ }) that display formatted(hence the f in printf) strings of characters on standard output device, which for the moment simply means monitor screen. Unlike other high level languages C has on in out/output statement such as printf. Instead, all input/output is done by library function such as printf. Details about the printf function is written in stdio.h file means standard input out header file when the program contains the printf function, then program should include stdio.h file eg. #include<stdio.h> void main() { printf(hello!); } While execting the program, it will look through stdio.h file for printf function. According to file. statement information printf function will work. This means it will display string written in pritnf function on the terminal. Suppose, some one waned to display hello in quote marks then, to avoid confusion between the messages quote mark and the printf function.s quote mark program would be written in the following manner

Institute for Design of Electrical Measuring Instruments

-3-

# include<stdio.h> void main() { printf(.hello!.); } which display .hello!. when, you want to display a string containing real quotes In printf(.hello! . how are you?. .); Turbo Curly braces({ }) would take the second . as an end to the string. i.e it will print only hello! then what to do? for this the scape character\. for the internal double quotes as in printf(Hello!. how are you .); Which will display Hello!. how are you. The escape character is used to solve the problem of inserting nonprintable control code or difficult characters into a string Example After printing hello through printf statement, cursor resides after hello! if you want control to transfer on to the new line through printf statement then, printf statement would be printf(hello! \n); to get a true new line you type the escape character\n Example printf(good morning\n); It can be written as printf(good); printf(morning); printf(\n); The first statement displays good and leaves the cursor sitting after the space waiting for something to happen. .The morning is displayed and finally printf(\n); provides a new line on the screen.and you will get output good morning Use of comment statement in a C program In the above program, additional statement are the comment statement comments are enclosed in /* */ these pairs comments are remarks written in a program to make the program more readable. These remarks are often used to give more information about the program or about the instruction in a program. Comments are not instructions, but are very useful to get a good understanding of the program. A comment is declared by forward slash followed by *(/*) at the starting and a star followed by forward slash (*/) at the end. so anything in between these 2 signs is taken as a comment Example /* these are the comment statement */ this is how a comment is to be declared

Institute for Design of Electrical Measuring Instruments

-4-

Chapter 2 VARIBLES IN C Consider the same example from the previous session. The example of adding two numbers. The first step is to accept a number from the terminal. The number which is accepted should be stored in the memory, so that it is possible to perform a certain process on this number. Any part of memory which stores the data should be given a unique name. These names help in identifying any, memory location and in turn in locating the data. So any time the data is required just the name of the location is mentioned. The value/data in this location can keep on changing and is therefore called as variables. A variables name should begin with a letter but it may include digits also. Different types of variables An entity whose value keeps on changing is called a variable. The value taken from the terminal should be stored in a variable. A program to add two integers will require two variables to hold these integer values. The type of data that a variable store decides the type of variable. For example an integer variable is supposed to hold integer values. Whereas in the second example the type of variable is string. So as to store a set of characters. Turbo C supports three major types. Integer A number without fractional part. A range of number that an integer variable can store is -32768 to -32767 Float It is real number. A variable of this type can store values from 3.4E -38 to 3.4 E +38 Char A variable of this type can store a single character -128 to 127 range of this data type. How to declare these variables Every variable in a program should have a unique name. The type of the variable and how to declare such a variable is listed below Type of variable How to name Integer e.g variable i stores integer value.So it is to be declared as int initialisation; float e.g variable j stores float value so it is to be declared as float j; How to assign values to variables A Variable either stores values taken from the user or it is assigned values through program itself. Consider program which will store value 0 in an integer variable i. This value is to be stored through the program. That is the variable initialization will be assigned the value 0. The = sign/operator is used to assign values to variables. e.g. int len =10; /*declare int variable and initialize it */ This facility is available only in c Language. float pi= 3.14 ;/*declare floating point variable*/ char alpha =.a.;/*is declare and initialize*/

Institute for Design of Electrical Measuring Instruments

-5-

Different types of type Qualifiers When we use variables the system needs same prior warning as to which data type we intend. Each data type has predetermined memory requirements and an associated range of legal values. This advanced warning is known as a data type declaration. Three basic data type (int, float and char) are already discussed in earlier session. Associated with these data type there are different type specifies. These are short, long for integers and double for float. All these could be along with signed and unsigned. Basic difference is that, signed (variable) data type means +ve as well as -ve values. Unsigned (variable) data type means only positive values. By declaring int sum; Maximum value that can be held by sum variable is from -32768 to +32767. In some cases, a variable may have a value greater than the above mentioned range. Then, it is necessary to declare as a long int. C officially recognizes a third integer data type called short int (or short) The rules for the three integer types can be expressed informally as long int = short where = means 'bit size greater than or equal to' Short and int are have same size i.e. 16bit. If you come across short or short int while reading a C program, make a mental note that for some systems it may be smaller than int. In the big, wide world of C the choice of integer data types can affect program portability. The keywords as short, int, long are known as type specifies. The optional specifies unsigned can proceed and modify these specifies as shown in the syntax. [unsigned] type-specifies identifies, where the brackets around unsigned indicate that it is optional. Signed is assumed in the absence of unsigned. In short various type specifies can be listed as shown below Table : Ranges of Data Types Type Range char -.128 to 127 int -32768 to 32767 short -32768 to 32767 long 2,147,483,648 to 2,147,483,647 unsigned char 0 to 255 unsigned int 0 to 65535 unsigned short 0 to 65535 unsigned long 0 to 4,294,967,295 float 3.4E + 38 double 1.7E + 308 The floating point variables are declared with the keywords float or double. The floating point type (float) occupies four bytes of storage, upto six digits of precision. The double precision floating point type (double) occupies eigth bytes of storage. A double precision floating point type has upto fifteen digits of precision. Constants A constant declares a fixed value for an integer, a character, floating point, and a string. Integer constants represent an integer number that specifies in the decimal, octal, or hexadecimal formats. A character constant is the numeric value of the C character set and a

Institute for Design of Electrical Measuring Instruments

-6-

floating point constant is a decimal point number or an exponential number. The rules set for the float data type also apply to floating point constants. String constants are a list of characters. A string constant is declared within double inverted commas or quotation marks. For example "hello", "9+2=11", and "MY NAME IS XYZ" are valid strings.

Institute for Design of Electrical Measuring Instruments

-7-

Chapter 3 KEYWORDS IN C Reserved words or keywords have a predefined meaning in the C programming language. Keywords cannot be used as identifiers. C has a set of 32 keywords specified always in lowercase. If used in uppercase, they are not recognized as keywords. Table lists the various keywords in the C programming language: Keywords in C auto break case char else enum void const extern float goto long if struct volatile default register switch continue int do union short for static signed return double while typedef sizeof unsigned

Institute for Design of Electrical Measuring Instruments

-8-

Chapter 4 OPERATORS Comparing to other languages, C language also have set of operations. In this area, C is very rich. It has many set of operators. (nearly upto 30 different operators) . An operator specifies how the operands in an expression are to be evaluated. C contains a full set of operations covering everything from basic arithmetic operations to logical and bitwise operations. Arithmetic operator The C arithmetic operators closely resemble the arithmetic expressions. Operator Action + Addition e.g. A = B + 1; The + operator will add 1 and value of B and result will be assigned ,to A. Subtraction e.g. B = 5 - 2; the number 2 is subtracted from 5 and result is stored in B * Multiplication e.g. A =3* 2; B =A* 2; / Division e.g. A = B/2; C = A/B; % (int. remainder) e.g. A=B%2 ;B will be divided by 2 and remainder of this expression will be stored in A. Program to find Simple Interest #include<stdio.h> void main() { float p,n,r,si; clrscr(); printf("Enter the Amount\n"); scanf("%f",&p); printf("Enter the Duration\n"); scanf("%f",&n); printf("Enter the Interest\n"); scanf("%f",&r); si=(p*n*r)/100; printf("Simple Interest is %f",si); getch(); }

Institute for Design of Electrical Measuring Instruments

-9-

Relational operator Relational operator evaluate the relationship between two expression, returning true or false result in terms of 1 & 0 Operator Action < Less than e.g. 3 < 2 returns false (0 value) > Greater than e.g. 4 > 2 returns true (1 value) <= Less than or equal to e.g. A < = B if value of A is less than or equal to B then it returns true value >= Greater than or equal to e.g. 4 > = 4 returns true == Equality e.g. 4 = = 4 returns true != Not equal to e.g. 2! = 3 returns true. Assignment operator The "=" operator is used to assign values to variables. e.g. i = 10; At the time of declaration only we can assign the value like int i = 0; Suppose more than one variable has got same value, then compound Assignment is possible. e.g. int i; int j; i = j = 5; /* i & j have value equal to 5 */ Comma operator Comma can separate multiple function arguments or multiple variable declarations. In such cases the comma is not an operator in the formal sense but merely punctuation. Like the semicolon that ends a statement. e.g. int j, k, m; All variables having same datatype (i.e. int) The comma is also an operator. When it separates multiple expressions the comma

Institute for Design of Electrical Measuring Instruments

- 10 -

operator determines the order used to evaluate the expressions and the type and value of the result that is returned. Following program illustrate how the comma operator is used. /* comma C demonstrate comma operator */ #include<stdio.h> main() { int val = 5 , k = 50 , temp; temp = val, val = k, k = temp; printf("val = %d k = %d\n", val, k); } Output val =50 k =5 The comma operator causes expressions to be evaluated from left to right.

Logical operator C has three logical operators OR AND NOT OR, AND often are used to combine logical tests in a conditional statement. Operator Action && Logical AND e.g. if (( A > 10) && (B > 1 0)) printf(true condition"); if value of A & B are greater than 10 then only it print true condition || Logical OR e.g. if ( (A > 0) || (B > 0) printf("values may be positive"); either A > 0 or B > 0 then it will print the message values may be positive. ! Logical NOT e.g. int val = 0; if (!val) printf("Val is zero"); if(!val) is equivalent to if(val = = 0)

Institute for Design of Electrical Measuring Instruments

- 11 -

Introducing the increment and decrement operators Incrementing (and decrementing) by 1 is a very common computing statement. C offers several shorthand methods of above type of assignment. Examples total =sum + +; /* set total to sum, then increment sum by 1*/ total =sum - -; /* set total to sum, then decrement sum by 1*/ total =+ + sum; /* set sum to sum+ 1, then set total to new */ total = - - sum; /* set sum to sum-1, then set total to new sum */ The symbols + + and -- after the variable sum are called the post increment and post decrement operator respectively. They imply that sum is increased or decreased by 1 after the assignment total. The general terms post fix is used for such operators. Similarly, the prefix operator + + and -- appearing before sum are known as pre increment and pre decrement operators. With these, the increment or decrement by 1 is performed on sum before the assignment to total is made. Assignments Single Assignment To illustrate above operations, consider the following statements. int sum, total; /* declaration*/ total = 5; sum = 3; /* initialize*/ total = sum + +; /* total now =3 & sum =4 post increment */ total = + + sum; /* total now= 5 & sum= 5 pre increment */ total= sum --; /* total now = 5 & sum = 4 post dec*/ total = --sum; /* total now = 3 & sum = 3 pre dec*/ If you just want to increment or decrement without any assignment, the postfix & prefix methods are as sum sum++; /* set sum to sum + 1 */ + +sum; /* set sum to sum + 1*/ sum--; /* set sum to sum - 1 */ --sum; /* set sum to sum . 1*/ sum++ cannot be used on the left side of an assignment. e.g. sum + + = total is not allowed.

Compound Assignment The postfix and prefix operators can be used with variables other than integers. The increment or decrement can be made other than 1. Such as, total = total + sum; This statement can be written as total + =sum; /* increase total by sum*/ /* i.e. total + sum */ total - =sum; /* decrease total by sum*/ /* i.e total = total . sum*/

Institute for Design of Electrical Measuring Instruments

- 12 -

These are two forms of a compound Assignment. The operator + = & - = use to form a compound Assignment. Along with these operators, compound Assignment can be done using *= . / = % these operators. Examples: sum =sum * factor; /* multiply */ sum * = factor; total-sum = total-sum / factor; /* divide */ rem = rem % divisor; /* integer remainder*/ rem% = divisor; If the left value is long (as in the above example), the notation of compound assignment saves much typing. This is one of the C's popular features. Sample program /* Program using assignment statements using increment & decrement operators */ #include<stdio.h> void main() { int i,j,sum; i=5; j=sum=0; clrscr(); printf("i =%d\n",i++); printf("i =%d\n",i); printf("i =%d\n",--i); j=++i; printf("j =%d\n",j); sum=--j; printf("j= %d\tsum =%d\n",j,sum); i+=j; j=sum++; sum*=j; printf("i= %d\tj = %d\tsum = %d",i,j, sum); } Output i =5 i =6 i =5 j =6 j =5, sum = 5 i =11 j = 5 , sum = 30 FORMAT CONTROL STRINGS Printing through format control strings Untill now printf has been used with a single string constant as an argument.

Institute for Design of Electrical Measuring Instruments

- 13 -

e.g. printf("how are you."); printf has two argument, separated by a comma. e.g. printf("Entered value is %d", i); "Entered value is %d" represents a format control string, the function of which is to control the conversion and formatting of the following argument. Above string contains : Plain characters such as familiar text means ("Entered value is") Conversion specification such as %d. These are not displayed as a text but act as a format for the following arguments of a %d is a format for decimal int.

considering above example, value of I is displayed as a int. value, because %d is used in 1st argument of printf. Suppose value of i is 5 then output of above printf will be Entered value is 5. %d will be replaced by value of i Use of format control string Each conversion specification must start with a (%) percent sign. This tells the compiler where and how to display an argument. e.g. printf("i = % d, j = % d, i,j); In above example, value of i will be displayed in place of first % d. Value of j will be displayed in place of second % d. Suppose value of i, j are 7, 8 respectively. Output will be i=7,j=8 This concept is similar to the PRINT USING STR$ found in BASIC language Format for all type Qualifiers There are many control string, along with %d. %s for any matching string argument. %c for any matching character argument. %u for unsigned int. %f for real (float) value. %ld for decimal long (signed) %lu for decimal unsigned long. Likewise for each type Qualifier, these is a separate format control string or conversion specification. /* Program to display values of various variables*/ /* using various format control string*/

Institute for Design of Electrical Measuring Instruments

- 14 -

#include<stdio.h> void main() { int i=-5,j=10; unsigned int k=12; long m=64546; clrscr(); printf("The value of i is %d\n", i); printf("Sum of i + j is %d\n",i+j); printf("Sum of i + j + k is %d\n",i+j+k); printf("Square of m is %ld\n",m*m); getch(); } First printf displays The value of i is -5 %d interprets as, i is a signed int next printf(), printf("Sum of i + j is %d", i+ j); This interprets how second argument can be a arithmetical expression. % d is replaced by i + j sum of i + j is 5 next printf() printf("Sum of i + j +k is %d", i+ j+k); This interprets how third argument can be a arithmetical expression. % d is replaced by i + j+k sum of i + j+k is 17 next printf() printf("Square of m is %Id", m * m); % id long signed int conversion. The display will be square of m is ----------

All conditions using relational operators #include<stdio.h> /*program to demonstrate the relational operator*/ main() { int a, b; scanf(.% d % d" & a, & b); /*keyboard input*/ printf("True = 1 and false = 0") ; printf("\n Is a > b ? = %d, a > b) ; printf("\n Is a = b ?= %d, a = b); printf("\n Is a < b ? = %d, a < b); } The above program illustrates the concept of relational operator. A relational operator returns a value, in terms of whether the condition is true or false. If the condition is true, it returns 1 and if false it returns 0. Introduction to scanf To read the value of a, b from input device, scanf() is used. scanf("%d %d", &a, &b);

Institute for Design of Electrical Measuring Instruments

- 15 -

Interpreted as, how the elements can be read from input and where they will be stored. For a & b, values read by program, are 4, 5 respectively. Resulting value of a is stored at the same address of a, namely &a. The same is true for b. The display of the above program will be (a=4, b=5) True = 1 and false = 0 Is a > b ? = 0 Is a = b ? = 0 Is a < b ? = 1 /* Sample.c demonstrate the printf with the various format*/ #include<stdio.h> void main() { int i,j,k; // declaration float m,n; char cp,ch; clrscr(); printf("Enter two integer values"); scanf("%d %d",&i,&j); /* keyboard input*/ printf("\nEnter one float value"); scanf("%f",&m); printf("\nenter a characters\n"); /* display on a new line */ scanf("\n%c",&cp); k=i+j; /* assigning the values*/ n=m*m; ch=cp; printf("\n\n the value stored using scanf display"); printf("\n There are % d integer values, as follows",3); printf("\n%d i = %d",1,i); printf("\n%d j = %d",2,j); printf("\n%d (i+j)=k = %d",3,k); printf("\n There are % d float values, as follows", 2); printf("\n%d m = %f",1,m); printf("\n%d (m*m)=n = %f",2,n); printf("\n There are % d character values, as follows", 2); printf("\n%d cp = % c",1,cp) ; printf("\n%d (cp=ch)ch = % c",2,ch); printf("\n End of the program"); getch(); } /* end of main */ While printing those values on the terminal printf statement is used in various ways. All statements, will be printed on a new line because of \n. (Escape character for new line i.e line feed) Here, in some printf statement % d format has been used to display constant value. i.e printf ("\n % d i = % d", 1, i); The first % d, will be replaced by 1 and the next % d will be replaced by value of variable i. In place of % c, ft prints respective value of a character variable. If you execute the above program, output of the program will be as follows Enter the integer values 20 30 Enter one float value

Institute for Design of Electrical Measuring Instruments

- 16 -

10.20 Enter a character a The value's display There are 3 integer values, as follows i=20 j=30 (i+j)k= 50 There are 2 float values, as follows m= 10.20 (m*m)=n= 20.40

There are 2 character values, as follows cp= a (cp=ch)=ch= a End of the program

Institute for Design of Electrical Measuring Instruments

- 17 -

Chapter 5 CONDITIONAL CONSTRUCTS C has built-in instructions for making decisions. These instructions alter the sequence of execution of a program by choosing one of the various possibilities and continuing program execution from there onwards. The instructions that help make decisions in the C programming language are called conditional constructs. Introduction to IF statement More generally, we can say that the syntax of an if statement is: if( expression ) statement; where expression is any expression and statement is any statement. What if you have a series of statements, all of which should be executed together or not at all depending on whether some condition is true? The answer is that you enclose them in braces: if( expression ) { statement1; statement2; statement3; } As a general rule, anywhere the syntax of C calls for a statement, you may write a series of statements enclosed by braces. (You do not need to, and should not, put a semicolon after the closing brace, because the series of statements enclosed by braces is not itself a simple expression statement.) Statements discussed until now are Assignment statement Declaration statement Functional statement etc.

Examples of Assignment statements are, i=i+1; sum += 5; Declarative statements are, int i; float k; functional statements are printf ("We are learning C"); scanf ("%d", & i); Like any other language C language also has IF statement Example: if (marks < 45) printf("student has failed");

Institute for Design of Electrical Measuring Instruments

- 18 -

In the above example a simple form of 'if' statement is considered. This statement at first evaluates conditions and if the condition is true, the statements following the condition are executed and control is then passed to next sentence after IF. If the condition is false, the control is transferred directly to the next statement without executing the statements following the condition. The condition is shown above is known as a relational condition. The if statement is known as a conditional statement. Example: if A is greater than o then A is a positive number. Related C statements are if (A > 0) printf("It is a positive number"); In above example if A's values is less than zero an alternative action can be considered optionally. For the above situation the modified version of previous program is, if (A > 0) printf("It is a positive number"); else printf("it is a negative number"); When the condition is a false condition then the statements following the else are executed. Like any other C statement, all statements are terminated by a semicolon within a if, block of statements should be enclosed in curly brackets ({ }) Example: if (A > 0) { printf ("it is a true condition.); printf ("\n it is a positive number:.); } else { printf ("it is a false condition"); printf ("\n it is a negative number.); }

PROGRAM:

In a company an employee is paid as under: If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary. /* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ;

Institute for Design of Electrical Measuring Instruments

- 19 -

} else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; } Flow Control statement C provides and very potentially dangerous construct viz the goto statement. The syntax for this statement is goto label; The goto label statement transfers control directly to the statement specified by the label name. Formally the goto is never necessary and code can be written without it. goto's are to be used as a last measure, such as when disaster strikes and processing is to be abandoned inside a deeply nested structure. In such cases some recovery measures have to be undertaken and this code is written from the statement containing the label. e.g while (......) for (.......){ if (disaster) goto recovery; } recovery initiate recovery steps It should be noted that goto is an unstructured construct and can lead to many problems if not properly used. Is advisable to use it very sparingly if at all. if marks. Example: /* multiple if statement*/ #include<stdio.h> void main() { int a,j=0; clrscr(); abc: if(j<10) { printf("Enter Any Number\n"); scanf("%d",&a); if(a>0) { printf("it is a positive number.\n"); j++; } else {

Institute for Design of Electrical Measuring Instruments

- 20 -

printf ("it is a negative number.\n"); j++; } goto abc; } else { printf("Program executes for 10 times."); } getch(); } /* end is the name of label*/ Program to use Two goto statement #include<stdio.h> void main() { float r,area; char ch; clrscr(); start: printf("\nEnter the radius of a circle\n"); scanf("%f",&r); area=3.14*r*r; printf("\nArea of a circle is %f",area); printf("\n\nDo you want to continue?..."); top: printf("\nIf YES then press 'y' OR 'Y'\n"); scanf("%s",&ch); if(ch=='y'|| ch=='Y') { goto start; } else if(ch=='n' || ch=='N') { exit(); } else { printf("\nInvalid key\n"); printf("\nIf You want to quit?...\n"); printf("press n"); goto top; } getch(); }

Institute for Design of Electrical Measuring Instruments

- 21 -

Switch Statement if and if-else statements have already been discussed in earlier session. But one disadvantage of these statements are, they allow only one condition per statement. To perform more complex tests, program have to use more ff and if- else statements. The switch statement offers an elegant solution in situations that require multiple conditions. It tests a single expression that can have several values. For each value may be different action is required. /* switch.c demonstrate switch statement*/ #include<stdio.h> void main() { char c; clrscr(); printf("Press the b key to hear a bell \n"); c=getchar(); switch(c) { case 'b': // first condition { printf("Beep! \a \n"); break; } case 'n': // second condition { printf("What a boring selection ... \n"); break; } default: { printf("Bye bye."); /* Default case */ break; } } /* end of switch */ getch(); } // end of main In the above program, variable c's value is accepted from the terminal. Through the test expression switch(c) program the checks for various conditions. When C is equal to "b. then through '\a', it returns a bell. Use of break statement in each case is to exit a case statement. Otherwise, control will fall through each & every case statement. The statement under default label are executed ff none of the case constant expressions matches the value of the test expression. In short, the switch s helps to control complex conditional and branching operations. No two constants within the same switch can have the same value. /* Program to calculate no. of tabs, spaces or any other special character. */ #include<stdio.h> #include<conio.h> void main()

Institute for Design of Electrical Measuring Instruments

- 22 -

{ int i=0,t,s,o; char str[40]; o=t=s=0; /* multiple assignment*/ clrscr(); puts("Enter any Name"); gets(str); /* accepting string values from terminal*/ while(str[i++]!='\0') { switch(str[i]) { case '\t': /* for tab character*/ { t++; break; } case 32 :/* for space character*/ { s++; break; } default: /* for rest characters*/ { o++; } }/* end of switch*/ }/* end of while*/ printf ("\n\nwithin a %s string \nno.of tab characters %d \nno.of spaces = %d \nalbhabets = %d",str,t,s,o); getch(); } /* end of main */ In the above program, user accepts a string though gets 0 function. For this special program, user can't use scanf() function, because scanf() function treats space character as a terminating character. Through while loop it extracts each and every character from a string. That is checked by switch statement. According to its value proper counter is incremented. This means that if character is equal to space character, s variable's value will increment. /*Program to remove spaces from a string.*/ #include<stdio.h> void main() { int i=0; char str[20]; printf("Enter your Name\n"); gets(str); while(str[i]!='\0') { if(str[i]!=32) { printf("%c",str[i]); } i++; } // end of while

Institute for Design of Electrical Measuring Instruments

- 23 -

getch(); } // end of main Program reads each character from the string. If that character is not equal to space then program prints it the terminal. It gives the effect as if, the string's contents are without spaces. Here were assuming that between any two letters, there is a only one space. If there is more than one space between any two characters then what to do? It is explained in following program. #include<stdio.h> void main() { int i=0; char str[20]; clrscr(); printf("Enter your name\n"); gets(str); while(str[i]) { if(str[i]==32) { while(str[i]==32) { i++; } } printf("%c",str[i]); i++; } getch(); } In above program, it is followed by while statement. Because if current character is equal to spaces. Then program will remain in while loop until the next character is other than space. This means that when current character is other than space character then only control will come out of the while loop. Result of the program will be, It will remove all spaces from the string & print rest characters on the terminal. Suppose, input of the program (String's value) ABC DEF GHI Output will be ABCDEFGHI Program to calculate the no. of words from the string What is a word? It can be defined as set of characters separated by space/spaces are called as a word. There may be one character in a word or more than one character in a word. e.g. .a" "are" "***. "123ab" *. all are valid words.

Institute for Design of Electrical Measuring Instruments

- 24 -

Program to calculate the number of words from a string. /* Program to calculate no. of words*/ #include<stdio.h> void main() { int i,count; char str[50]; i=count=0; /* initialization*/ clrscr(); puts("Enter your name"); gets(str); /* accepting value of the string from terminal*/ while(str[i]) { if((str[i]==32)&&(str[i+1]!=32)) { count++; /* incrementing word counter*/ } i++; } printf("In a %s String\n,No.of words are %d",str,++count); getch(); } In the above program, assumption is that, there may be one or more than one spaces between any two words. According to this, when the current character is a space (ASCII code 32) and the next character is other than space then only then is the word counter increased. (Because first word ends) For the last word, As lastword is not followed by spaces. Counter is incremented by one. That's why, in a printf statement ++count is taken the place of count. Example Input to a Program like abc ^ ^ ^ def ^ xyz^ ^^*** Output will be In a abc^ ^ ^ def ^ xyz ^ ^^ *** String no. of words are 4 (^ - indication of a space character) Programs based on string and while loop Program to count how many times any character is appearing in the string. #include<stdio.h> void main() { int i,count; char str[50]; i=count=0; clrscr(); puts("Enter any String"); gets(str);

Institute for Design of Electrical Measuring Instruments

- 25 -

while(str[i]) /* while string is having any character*/ { if(str[i]=='a' || str[i]=='A') /* check for occurance of 'a' or 'A' alphabet (||-OR operator)*/ { count++; } i++; } /* end of while*/ printf("\nIn '%s' string\n 'a'or 'A' character occurs %d times",str,count); getch(); } /* end of main */ Above program checks how many times character 'a' repeats in a string. Program checks string's each character with character's', if it equals then incrementing counter value is incremented by one and likewise checking upto last character. Finally, printf statement displays value of counter. Input to the program Enter any String Abcadea Output will be In Abcadea string, a or A character occurs 3 times. Above program is finding occurrence of only a character in a given string. When we want, program should find any character's occurrence within a given string . It is illustrated in following program. #include<stdio.h> void main() { int i=0,count=0; char cp,str[30]; clrscr(); printf("Enter a string without a blank space\n"); scanf("%s",str); printf("\nwhich character occurance you want to find\n"); scanf("\n%c",&cp); while(str[i]) { if(str[i]==cp) { count++; } i++; }/* end of while*/ printf("Occurrence of '%c' character within '%s' string is %d times",cp,str,count); getch(); } /* end of main*/ */ Output will be, Enter a string without a blank space Incremented which character occurance you want to find

Institute for Design of Electrical Measuring Instruments

- 26 -

e Occurrence of e' character within 'incremented ' string is 3 times Program to concatinate any two strings #include<stdio.h> void main() { int i,j,k; char str1[50],str2[50]; /* declaration of two string*/ i=j=0; clrscr(); printf("Enter the first string \n"); scanf("%s",&str1); printf("Enter the second string \n"); scanf("%s",&str2); while(str1[i++]); /* finding the length of str1*/ while(str2[j++]); /* finding the length of str2*/ i--; /* last position is a NULL character*/ for(k=0;k<j;k++) { str1[i+k]=str2[k]; } printf("Final string is % s",str1); getch(); } /* end of main */ Output will be Enter the first string Software Enter the second string programming Final string is software programming In this program, first string does not have its original value. If user wants to retain the value of both strings the contents of both strings should be copied in to a third string. That can be a resultant string. Program will display how to copy one string's contents into another string. #include<stdio.h> void main() { int i; char str1[50],str2[50]; i=0; clrscr(); printf("Enter the string\n"); scanf("%s",&str1); while(str1[i]!='\0') { str2[i]=str1[i]; /* copying the content of first string into another string*/ i++; /* incrementing first string's index value*/

Institute for Design of Electrical Measuring Instruments

- 27 -

} str2[i++]='\0'; printf("first string %s",str1); printf("\ncopied string %s",str2); getch(); } /*end of main*/

Introduction to 'for' loop statement


As in BASIC the for statement in C is often used to repeat a statement statements number of times. A for statement is more complex than the while statement. In that its parentheses can contain three expressions separated by semicolon like for (i = 0; i < 10; i + +) First part is an initializing expression. Second, ft is a test expression that states how long the loop continues. Third part is a modifying expression. Like the test expression in a while statement, the test expression in a for statement is a continuous condition. The loop continues as long as the test expression is evaluated as true. Execution of for loop will be clear from the following example. /* for,c demonstration of for loop*/ #include<stdio.h> void main() { int i; for (i = 0; i < 10;i++) printf("value of i is %d", i) } Output will be value of i is = 0 value of i is = 1 value of i is = 9 In the above program, Value of i gets initialized as 0. Then statements written in the for loop will execute. According to this program it will print value of variable i. Then statement written in modifying expression will execute. i.e i + + ; It will increase the value of i by one. After evaluating modifying expression, if condition remains as a true condition then statements written within the for loop will execute for second time and so on. This process will continue till terminating condition is true. After that control will transfer to the next statement after the for statement.

Institute for Design of Electrical Measuring Instruments

- 28 -

Various forms of for statement In the above program, Suppose statements are for (i = 9; i < 10; i + +) printf(value of i = %d", i); It will print only one statement i.e value of i = 9 Because for statement is followed by semicolon R treats as one single statement.(statement terminator) Blank for loop will execute and what is last value of I variable that is used in the printf() statement. This logic is used, when delay is required while executing the program. All expressions in for loop are optional. Example #include<stdio.h> main() { int i=0; for (; i < 10; i + +) printf( value of i = %d, i); } In the above program, value of i is initialized while declaration. Then for statement can be without first part. Suppose, a program omits terminating condition then there is no limitation on execution for loop. This can be treated as infinite loop. Example #include<stdio.h> void main() { Int i; for( i = 10;; i + +) printf(Value of i = %d", i); getch(); } Above program will print the values of 'i' variable infinitely. Another form of infinite loop is, #include<stdio.h> void main() { for(;;) printf ("Hi ! how are you?); getch(); }

Institute for Design of Electrical Measuring Instruments

- 29 -

The program will repeatedly print above message. This is same as main() { while (1) ; printf("Hi ! how are you,?); } Using more than one variable In a for statement. The for statement allows for plenty of flexibility in that ft may contain multiple expression for initializing expression or modifying expression. /* Demonstrate multiple expressions */ #include<stdio.h> void main() { int i, j; for (i = 10, j= 5; i < 100; i+ = 10, j* =2) printf (i = %d j=%d \n", i, j); } Output will be i i i i i i i i i = = = = = = = = = 10 20 30 40 50 60 70 80 90 j= j= j= j= j= j= j= j= j= 5 10 20 40 80 160 320 640 1280

Here comma that separate the extra expressions in the for statement, are operators Here terminating condition is a single condition. In some cases we can use multiple terminating condition connected by I and' or 'or' operator. Above program uses compound terminating condition, #include<stdio.h> void main() { int I,j; for(i =10, j = 5; ((i < 100) && (j < 100)); i+ =10, j*=2) printf("i = %d, i = %d \n, i, j) ; } Output i i i i i = = = = = 10 20 30 40 50 j j j j j = = = = = 5 10 20 40 80

Institute for Design of Electrical Measuring Instruments

- 30 -

Since the terminating condition is (( i < 100) and (j< 100) if one of conditions fails, control will come and of the loop. The for statement is flexible enough to be used in many different ways. To understand how nested loops work, look at the program given below: /* Demonstration of nested loops */ #include<stdio.h> void main( ) { int r, c, sum ; for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ { for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ { sum = r + c ; printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ; } } getch(); } When you run this r = 1 c = 1 sum = r = 1 c = 2 sum = r = 2 c = 1 sum = r = 2 c = 2 sum = r = 3 c = 1 sum = r = 3 c = 2 sum = program you will get the following output: 2 3 3 4 4 5

Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop.terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3. As you can see, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand. Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying: printf ( "r = %d c = %d sum = %d\n", r, c, r + c ) ; Introduction to do-while loop A normal while loop is only entered if the leading condition turns out to b true. It is useful to have another type like (REPEAT .... UNTIL) in other languages in which the loop condition is tested out the end of the loop. A do loop always executes its loop body at least once. Example /* demonstrate the do loop */ #include<stdio.h> void main() { int i = 20; do

Institute for Design of Electrical Measuring Instruments

- 31 -

{ printf(i = % d,i); i - = 5; } while (i > 0); getch(); } Output i i i i = = = = 20 15 10 5

Here do loop executes its loop body before evaluating its test expression. First, blankly it performs the loop and then it checks for condition. If condition fails control will come out of the loop. That's why at least do-while loop executes one time. Example 1. Program #include<stdio.h> void main() { int i = 0; do { printf ("value of i= % d", i), } while (i > 0); getch(); } /* end of main */ 2. The above same program using while statement would be #include<stdio.h> void main() { int i = 0; while(i > 0) { printf("value of i = %d,i); } } /* end of main */ Output of 1st Program will be value of i = 0 In case of second program, there will be no output. Because of while loop first checks the condition. In this Program condition' fails the first time itself, so loop body will not execute. In case of the1st program, (using do statement) irrespective of condition, program will execute the loop.

Institute for Design of Electrical Measuring Instruments

- 32 -

So output is value of i= 0. Then Program will check the condition. (i =0) as in 1st Program condition fails (as i value is zero) for first time only so control will come out the loop. But output is value of i = 0, because of do statement's bottom line condition. After execution, Program will check the condition.

Menu driven Program


Consider a hotel menu card where different options (menus) are written. Example The main menu in the menu card can be continental, Chinese, Punjabi, Desserts, Drinks etc. Each of these menu is further divided. This is quite similar to the tree structure. To select an option under punjabi, one must choose the punjabi menu and then the respective suboption. Same structure applies for C program. In a C program, after executing selected option again Program should display same menu structure. In this Program, this menu must be established at least once and then possibly repeated. That's why in a menu driven Program do-while statement (loop) is very useful. Example #include<stdio.h> void main() { int choice; int i=0; do { clrscr(); puts("1. print the (1 to 10) values using while loop"); puts("2. print the (1 to 10) values using for loop."); puts("3. Exit from the system"); puts("Enter menu item (1 or 2) OR (3 to exit) "); scanf("%d",&choice); if(choice==1) { while(i<=10) { printf("value of i =%d\n",i++); } break; /* control goes to while statement */ } /* end of first condition*/ if(choice==2) { for(i=1;i<=10;i++) { printf("value of i =%d\n",i); } break ; } /* end of second condition*/ }

Institute for Design of Electrical Measuring Instruments

- 33 -

while(choice >0 && choice<3); getch(); } In the above program, based on the choice's value, statements will execute, i-e When user enters choice value as 1-, as per stated in menu statement, Program will print values from one to ten using while loop. Likewise for the second option. In the above program, all conditions are based on various values of choice variable. To check one variable's various value. Switch() statement is more useful than multiple if-else statement. Program to display result same as calculator. #include<stdio.h> #include<conio.h> void main() { int a,b,choice; do { clrscr(); /* to clear the screen*/ puts("1. Add two numbers"); puts("2. subtract two numbers"); puts("3. multiply two numbers"); puts("4. Divide two numbers"); puts("5. Exit from the system"); puts("Enter Your choice"); scanf("\n%d",&choice); switch(choice) { case 1: { printf("Enter values for two variables for Addition\n"); scanf("%d%d",&a,&b); printf("Addition of %d & %d is %d",a,b,a+b); break; } case 2: { printf("Enter the values for two variables for Subtraction\n"); scanf("\n%d%d",&a,&b); printf("\nsubtraction of %d & %d is %d",a,b,a-b); break; } case 3: { printf("Enter the values for two variable for Multiplication\n"); scanf("\n%d%d",&a,&b); printf("\nMultiplication of %d & %d is % d",a,b,a*b); break; } case 4: { printf("Enter the values for two variable for Divison\n");

Institute for Design of Electrical Measuring Instruments

- 34 -

scanf("\n%d%d",&a,&b); printf("\nDivision of % d by %d is %d",a,b,a/b); break; } case 5: { exit(0); /* terminate the Program*/ } default: { printf("Wrong choice"); break; } } /* end of switch statement*/ getch(); }while(1); /* indication of infinite loop*/ } /* end of main */ After executing selected option, Program should display menu statements on the blank screen. That's why within a if statement clrscr() is the first statement. After selecting any option. (such as add, subtract, multiply, divide.) Each option should run for new values, for that Program introduced scanf() statement in each case statement. Every time we want menu as a active menu, For that in a Program do-while loop with infinite time executions, this logic is used. While (1) every time condition is a true condition. When user select 5th option, to terminate the program or to exit from the infinite loop. provision made in switch statement by exit(0) function. exit(0) terminates the Program, returns the code of successful compition of the Program.

Institute for Design of Electrical Measuring Instruments

- 35 -

Chapter 6 FUNCTION IN C Introduction to function What is a function? A collection of declarations and statements that has a unique name and can return a value. Example #include<stdio.h> void main() { int i=5; int a; a=cube(i); /* cube(i) is called function */ printf("cube of %d is %d",i,a); getch(); } cube(n) int n ;/* function declaration*/ { return (n * n * n); } /* value returned to main program*/ A C program consists of a series of functions. in C the word function is used in a wider sense than in most other languages. C function can be treated as subroutine and procedure. With C almost any block of statements can be together a function, to which a unique name is assigned. When that name is written anywhere in a program, the function is called or invoked and the statements used to define the function are obeying-, One function, may contain the reference Of other function or the same function . Functions are therefore the heart and soul of C. The function main() has a unique role to play in all C programs. Since a C program consists of sequences of functions, it is the one fires up first. The answer is that main(). Every complete C program must have just one main() somewhere, and this is where C starts off when executing the compiled / linked code.

Placement of function within C program. The place of a function within a C program is after main progam. i.e main() { msg(); /* called function*/ } /* end of main */ msg( )/* place of a function*/ printf(.Control is in a function.); /* details about function*/ } In above program,

Institute for Design of Electrical Measuring Instruments

- 36 -

msg() is a called function with in a main program. Control will transfer to the msg function, just like subroutine. It will execute statements written in function. Control goes back to main program after execution of function. It will execute statements after called function. Totally, result is , program will print a message written in the printf statement. Instead of writing all details in the main program, R can be written through different functions. It will give the effect as a structural programming. Within a one glance only, any one can know about the flow of the program, logic of the program. Example #include<stdio.h> void main() { int a,b,c; clrscr(); printf("Enter the value of a\n"); scanf("%d",&a); /* accepting the value from terminal*/ printf("Enter the value of b\n"); scanf("%d",&b); printf("Enter the value of c\n"); scanf("%d",&c); print_num(a); /* function is called to print the value of a*/ print_num(b); print_num(c); getch(); }/* end of main*/ print_num(x)//called function declaration int x; { printf("Values are = %d\n",x); return 0; } /* end of print-num function*/ In the above program, it is printing various variables value through same function. For same task, program is calling same function more than one time. After accepting the values for a,b,c variables from terminal. Control transfers to print_num(a) function to print the value of a variable. After executing the function, control transfers back to main program. Next statement is print_num(b); again function is called to print the value of b variable. Same case with C variable. This means that whenever a function is called, it will execute statements after function name. Control is transferred within a program depending on called function. Different types of functions What is a function ? placement of functions, like the things related to the functions have already been discussed in the earlier session. /* Program to find factororial of Number using functions*/ #include<stdio.h> long factor(int p);/*declaring function's return type*/ void main()

Institute for Design of Electrical Measuring Instruments

- 37 -

{ int num; long result ; /* declarations*/ /* Display a prompt*/ printf("Enter a number :"); /* Input a numeric value, assign to num */ scanf("\n%d",&num); /* \n %d clears the buffer to scanf*/ result=factor(num); /* assigning function value to result*/ printf("Factorial of %d is %ld\n",num,result); getch(); } /* end of main program */ long factor(int p) /*function starts*/ { long value =1; while(p>1) { value=value*p; p=p-1; /* or p--*/ } /* end of while */ return(value); }/* end of a function */ Output Enter a number 5 Factorial of 5 is 120 Above program is the example of function passed by a value. Consider the above program, before starting the program with main function. there is a declaration of a function. Until now, we seen the declaration of data type. Declaration of a function means, declaration of a function's return value type. long factor (int p) means factor is a function. Its Return type is of long. int p is a parameter passed to a function having integer type. p is called as a argument to factor function. Argument means value passed to a function. From a main program, it will accept a value from terminal. To calculate its factorial value. here scanf() function is used as scanf(" \n%d", & num); It clears previous buffer & from the new line it reads a value for num variable. Next statement is result = factor (num); Here factor is a function called with num as a argument. Control transfers to where details about factor function is written. long factor (int p).It is a function header with p is a parameter. It will take a value of num variable, which is already passed from main (function) program. Just

Institute for Design of Electrical Measuring Instruments

- 38 -

like main program, functional statements also enclosed in a pair of curly braces. After functional header and before opening curly traces, there is a declaration of parameters data type. long factor (p) int p; function contains a while loop. This int repeats while the condition p > 1 is true. Value of value variable is nothing but the factorial value. That value will returned in a main program. That will assigned to the result variable. So, data type of result variable, (from main program) function's value variable & (factor function) are same as long (long int) function's return type finally program will print a variable & its factorial value.

/* one more example to demonstrate passing values to function */ #include<stdio.h> void print_num(int p); void main() { int a,b,c; clrscr(); printf("Enter the three numbers"); scanf("\n%d %d %d",&a,&b,&c); /* enter three values separated by spaces*/ print_num(a); print_num(b); print_num(c); getch(); } /* end of main*/ void print_num(p) int p; { printf("entered value = %d\n",p); } /* end of the function */ Passing more than one values to function The above program can be written as #include<stdio.h> void print_num(int p,int q,int r);//print_num function with three parameters void main() { int a,b,c; printf("Enter three values"); scanf("\n%d %d %d",&a,&b,&c); print_num(a,b,c); /* function call with scant argument*/ getch(); } /* end of main */ void print_num(p,q,r) int p,q,r;

Institute for Design of Electrical Measuring Instruments

- 39 -

{ printf("First value = %d",p); printf("\nSecond value = %d",q); printf ("\nThird value = %d",r); } /* end of function */ In the above program, function is containing more than one arguments all having integer data type. Value of argument is assigned to the parameter. Variables value is assigned to the p variable likewise for variables q and Function can have one argument or more than one arguments to execute Function's type is dependent on its return value. When function is not returning any value to main program that function is called as a void function. In above program, function is printing only parameters value. Void concept A function that does not return any value to main can be declared as a void function, In other case, if a function doesn't except any parameters, like void beep (void); in place of a parameter list, void can be written. The void inside parentheses shows that the beep function doesn't take any parameters. /*program to find out maximum variable from accepted variables*/ #include<stdio.h> int max(int a,int b); void main() { int x,y,max_num; printf("Enter two numbers"); scanf("\n%d %d",&x,&y); max_num=max(x,y); printf("Maximum number from %d & %d is %d",x,y,max_num); getch(); } /* end of main */ int max(int a,int b) { if(a>b) return(a); else return(b); } /* end of function*/ The void preceding the function name shows that beep doesn't return any value either. Based on the condition (a > b) function will return the value either a or b as maximum value in a main program. Program to find Largest among three numbers using function #include<stdio.h> #include<conio.h>

Institute for Design of Electrical Measuring Instruments

- 40 -

int big(int,int,int); int main() { int a,b,c; clrscr(); printf("Enter Three Numbers\n"); scanf("%d\n%d\n%d",&a,&b,&c); big(a,b,c); printf("Largest Number is %d",big(a,b,c)); getch(); return(0); } big(int x,int y,int z) { int max; max=x; if(y>max) { max=y; } if(z>max) { max=z; } return(max); }

Institute for Design of Electrical Measuring Instruments

- 41 -

chapter 7 ARRAY The C language provides a capability that enables the user to define a set of ordered data items known as an array. Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number. In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a number called as index number or subscript. Declaration of arrays: Like any other variable arrays must be declared before they are used. The general form of declaration is: type variable-name[50]; The type specifies the type of the elements that will be contained in the array, such as int float or char and the size indicates the maximum number of elements that can be stored inside the array for ex: float height[50]; Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid. In C the array elements index or subscript begins with number zero. So height [0] refers to the first element of the array. (For this reason, it is easier to think of it as referring to element number zero, rather than as referring to the first element). As individual array element can be used anywhere that a normal variable with a statement such as G = grade [50]; The statement assigns the value stored in the 50th index of the array to the variable g. More generally if I is declared to be an integer variable, then the statement g=grades [I]; Will take the value contained in the element number I of the grades array to assign it to g. so if I were equal to 7 when the above statement is executed, then the value of grades [7] would get assigned to g. A value stored into an element in the array simply by specifying the array element on the left hand side of the equals sign. In the statement grades [100]=95; The value 95 is stored into the element number 100 of the grades array. The ability to represent a collection of related data items by a single array enables us to develop concise and efficient programs. For example we can very easily sequence through the elements in the array by varying the value of the variable that is used as a subscript into the array. So the for loop

Institute for Design of Electrical Measuring Instruments

- 42 -

for(i=0;i < 100;++i); sum = sum + grades [i]; Will sequence through the first 100 elements of the array grades (elements 0 to 99) and will add the values of each grade into sum. When the for loop is finished, the variable sum will then contain the total of first 100 values of the grades array (Assuming sum were set to zero before the loop was entered) In addition to integer constants, integer valued expressions can also be inside the brackets to reference a particular element of the array. So if low and high were defined as integer variables, then the statement next_value=sorted_data[(low+high)/2]; would assign to the variable next_value indexed by evaluating the expression (low+high)/2. If low is equal to 1 and high were equal to 9, then the value of sorted_data[5] would be assigned to the next_value and if low were equal to 1 and high were equal to 10 then the value of sorted_data[5] would also be referenced. Just as variables arrays must also be declared before they are used. The declaration of an array involves the type of the element that will be contained in the array such as int, float, char as well as maximum number of elements that will be stored inside the array. The C system needs this latter information in order to determine how much memory space to reserve for the particular array. The declaration int values[10]; would reserve enough space for an array called values that could hold up to 10 integers. Refer to the below given picture to conceptualize the reserved storage space. values[0] values[1] values[2] values[3] values[4] values[5] values[6] values[7] values[8] values[9] The array values stored in the memory.

Initialization of arrays: We can initialize the elements in the array in the same way as the ordinary variables when they are declared. The general form of initialization off arrays is:

Institute for Design of Electrical Measuring Instruments

- 43 -

type array_name[size]={list of values}; The values in the list care separated by commas, for example the statement int number[3]={0,0,0}; Will declare the array size as a array of size 3 and will assign zero to each element if the number of values in the list is less than the number of elements, then only that many elements are initialized. The remaining elements will be set to zero automatically. In the declaration of an array the size may be omitted, in such cases the compiler allocates enough space for all initialized elements. For example the statement int counter[]={1,1,1,1}; Will declare the array to contain four elements with initial values 1. this approach works fine as long as we initialize every element in the array. The initialization of arrays in c suffers two draw backs There is no convenient way to initialize only selected elements. There is no shortcut method to initialize large number of elements. /* Program to count the no of positive and negative numbers*/ #include<stdio.h> void main() { int a[50],n,count_neg=0,count_pos=0,i; printf("Enter the size of the array\n"); scanf("%d",&n); printf("Enter the elements of the array\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { if(a[i]<0) count_neg++; else count_pos++; } printf("There are %d negative numbers in the array\n",count_neg); printf("There are %d positive numbers in the array\n",count_pos); getch(); }

Multi dimensional Arrays:

Institute for Design of Electrical Measuring Instruments

- 44 -

Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row & the other the column. The declaration of two dimension arrays is as follows: data_type array_name[row_size][column_size]; int m[10][20] ; Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19] Elements of multi dimension arrays: A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on. marks [0][0] 35.5 Marks [0][1] 40.5 Marks [0][2] 45.5 marks [1][0] 50.5 Marks [1][1] 55.5 Marks [1][2] 60.5 marks [2][0] Marks [2][1] Marks [2][2] marks [3][0] Marks [3][1] Marks [3][2] Initialization of multidimensional arrays: Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces Example:

Institute for Design of Electrical Measuring Instruments

- 45 -

int table[2][3]={0,0,01,1,1}; Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as int table[2][3]={{0,0,0},{1,1,1}} Program to show use of Multidimensional Array #include<stdio.h> void main() { int stud[5][2]; int i,j; clrscr(); for(i=0;i<=4;i++) { printf("Enter roll number and Marks\n"); scanf("%d %d",&stud[i][0],&stud[i][1]); } printf("\nROLL_NO\tMARKS"); for(i=0;i<=4;i++) { printf("\n%d\t%d",stud[i][0],stud[i][1]); } getch(); } Program to print Multiplication Table using Multidimensional Array #include<stdio.h> void main() { int r,c,row=0,col=0; int prod[5][5]; clrscr(); for(r=0;r<=4;r++) { row=r+1; for(c=0;c<=4;c++) { col=c+1; prod[r][c]=row*col; printf("%d\t",prod[r][c]); } printf("\n"); } getch(); }

Institute for Design of Electrical Measuring Instruments

- 46 -

Chapter 8 STRUCTURE Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types. structure definition: general format: struct tag_name { data type member1; data type member2; } Example: struct lib_books { char title[20]; char author[15]; int pages; float price; }; the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name any where in the program. For example the statement, struct lib_books book1,book2,book3; declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price;

Institute for Design of Electrical Measuring Instruments

- 47 -

}; struct lib_books, book1, book2, book3; structures do not occupy any memory until it is associated with the structure variable such as book1. the template is terminated with a semicolon. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. The tag name such as lib_books can be used to declare structure variables of its data type later in the program. We can also combine both template declaration and variables declaration in one statement, the declaration struct lib_books { char title[20]; char author[15]; int pages; float price; } book1,book2,book3; is valid. The use of tag name is optional for example struct { } book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. Giving values to members: As mentioned earlier the members themselves are not variables they should be linked to structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator . Which is known as dot operator or period operator. For example: Book1.price Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like scanf(%s,&book1.file); scanf(%d,& book1.pages); Or we can assign variables to the members of book1

Institute for Design of Electrical Measuring Instruments

- 48 -

strcpy(book1.title,basic); strcpy(book1.author,Balagurusamy); book1.pages=250; book1.price=28.50; /* Example program for using a structure*/ #include<stdio.h> #include<conio.h> struct name { int id_no; char name[20]; char address[20]; char qualification[30]; int age; }newstudent; void main() { clrscr(); printf("Enter the student information"); printf("\nNow Enter the student id_no"); scanf("%d",&newstudent.id_no); printf("Enter the name of the student"); scanf("%s",&newstudent.name); printf("Enter the address of the student"); scanf("%s",&newstudent.address); printf("Enter the qualification of the student"); scanf("%s",&newstudent.qualification); printf("Enter the age of the student"); scanf("%d",&newstudent.age); printf("\n\nStudent information\n"); printf("student id_number=%d\n",newstudent.id_no); printf("student name=%s\n",newstudent.name); printf("student Address=%s\n",newstudent.address); printf("students qualification=%s\n",newstudent.qualification); printf("Age of student=%d\n",newstudent.age); getch(); } Functions and structures: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we dont effect its corresponding argument. Passing indvisual structure elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> void main()

Institute for Design of Electrical Measuring Instruments

- 49 -

{ struct employee { int emp_id; char name[25]; char department[10]; float salary; }; static struct employee emp1={125,"sampath","operator",7500.00}; /* pass only emp_id and name to display function*/ display(emp1.emp_id,&emp1.name); } /* function to display structure variables*/ display(int e_no,char *e_name) { clrscr(); printf("%d\t%s",e_no,e_name); return 0; } in the declaration of structure type, emp_id and name have been declared as integer and character array. When we call the function display() using display(emp1.emp_id,emp1.name); we are sending the emp_id and name to function display(0); it can be immediately realized that to pass individual elements would become more tedious as the number of structure elements go on increasing a better way would be to pass the entire structure variable at a time. Passing entire structure elements to functions: In case of structures having to having numerous structure elements passing these individual elements would be a tedious task. In such cases we may pass whole structure to a function as shown below: #include<stdio.h> struct employee { int emp_id; char name[25]; char department[10]; float salary; }; void main() { static struct employee emp1= { 12, "sadanand", "computer", 7500.00 }; /*sending entire employee structure*/

Institute for Design of Electrical Measuring Instruments

- 50 -

display(emp1); } /*function to pass entire structure variable*/ display(struct employee empf) { clrscr(); printf("%d\t%s\t%s\t%f", empf.emp_id,empf.name,empf.department,empf.salary); return 0; } Arrays of structure: It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example: structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100]; An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> #include<conio.h> void main() { struct info { int id_no; char name[30]; char address[30]; char qualification[30]; int age; }std[100]; int I; clrscr(); for(I=0;I<=99;I++) { printf("Enter Id_no,Name,Address,Qualification and age of a Student\n"); scanf("%d%s%s%s %d",&std[I].id_no,&std[I].name,&std[I].address,&std[I].qualification,&std[I].age); } printf("\n\nStudent information\n"); printf("Id_no\t\tName\t\tAddress\t\tEducation\tAge\n");

Institute for Design of Electrical Measuring Instruments

- 51 -

for(I=0;I<=99;I++) { printf("%d\t\t%s\t\t%s\t\t%s\t\t %d\n",std[I].id_no,std[I].name,std[I].address,std[I].qualification,std[I].age); } getch(); } Structure within a structure: A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures. #include<stdio.h> #include<conio.h> struct date { int dd,mm,yy; }; struct stud { int roll_no; char name[20]; struct date bd; int marks; }; void main() { struct stud st; clrscr(); printf("Enter the Roll No\n"); scanf("%d",&st.roll_no); printf("Enter Your NAME\n"); scanf("%s",&st.name); printf("Enter the Marks\n"); scanf("%d",&st.marks); printf("Enter your Birth date(DD/MM/YY)\n"); scanf("%d%d%d",&st.bd.dd,&st.bd.mm,&st.bd.yy); printf("\nROLL No=%d",st.roll_no); printf("\nNAME=%s",st.name); printf("\nMARKS=%d",st.marks); printf("\nBIRTH DATE={%d/%d/%d}",st.bd.dd,st.bd.mm,st.bd.yy); getch(); } the sturucture student constains another structure date as its one of its members.

Institute for Design of Electrical Measuring Instruments

- 52 -

Chapter 9 POINTER Introduction: In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name ; Example: int *ptr; float *string; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260. /* A program to illustrate pointer declaration*/ void main() { int *ptr; int sum; sum=45; ptr=&sum; printf (\n Sum is %d\n, sum); printf (\n The sum pointer is %d, ptr); } we will get the same result by assigning the address of num to a regular(non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 21260 but in the value stored in that memory location. While the value of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in *ptr=45. This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer contains the address 21260 the value 45 is placed in that memory location. And since

Institute for Design of Electrical Measuring Instruments

- 53 -

this is the location of the variable num the value also becomes 45. This shows how we can change the value of pointer directly using a pointer and the indirection pointer. /* Program to display the contents of the variable and their respective address using pointer variable*/ #include<stdio.h> void main() { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch='k'; intptr = &num; cptr = &ch; floptr = &x; printf("Number %d stored at address %u\n",num,intptr); printf("float number %f stored at address %u\n",x,floptr); printf("Character %c stored at address %u\n",ch,cptr); getch(); } Pointer expressions & pointer arithmetic: we can perform following actions with pointer 1.Addition of a number to pointer:int i=4,*j,*k; j=&i; j=j+4; 2.Subtraction of a number from pointer:int i=4,*j,*k; j=&i; j=j-2; 3.Subtraction of one pointer from Another:It is done if only both variables (pointer) points to the elements to same array.Resulting value indicates no of bytes separating corresponding array element #include<stdio.h>

Institute for Design of Electrical Measuring Instruments

- 54 -

Void main() { int arr[]={10,20,30,40,50,60}; int *I,*j; i=&arr[1]; i=&arr[4]; printf(%d%d,j-I,*j-*i); getch(); } OUTPUT:j-i would be 4 because j and I are pointing to locations which are 5 integers apart and *j-*I would be 30 ,since it returns values present at addresses in pointer j and i. 4.Comparison of Two pointer variables:It is done if both pointer variables point to objects of same type.it is useful when both pointers point to elements of same array.it test for either equality or inequality

#include<stdio.h> Void main() { int arr[]={10,20,30,40,50,60}; int *I,*j; i=&arr[4]; j=(arr+4); if(i==j) printf(Two pointer points to same Locations); else printf(Two pointer do not point to same Locations); }

Institute for Design of Electrical Measuring Instruments

- 55 -

Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include<stdio.h> void main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30,b=6; clrscr(); ptr1=&a; ptr2=&b; x=(*ptr1+*ptr2)/6; y=((*ptr1)*(*ptr2))+30; printf("\nAddress of a is %u",ptr1); printf("\nAddress of b is %u",ptr2); printf("\na=%d\tb=%d",a,b); printf("\nx=%d\ty=%d",x,y); *ptr1=*ptr1+70; *ptr2=++(*ptr2); printf("\na=%d\tb=%d",*ptr1,*ptr2); getch(); } Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference :2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters. #include<stdio.h> void main()

Institute for Design of Electrical Measuring Instruments

- 56 -

{ int a,b; a=20; b=30; printf("\n Value of a and b before function call =%d %d",a,b); fncn(a,b); printf("\n Value of a and b after function call =%d %d",a,b); getch(); } fncn(p,q) int p,q; { p=p+p; q=q+q; printf("\n Value of p and q after function call =%d %d",p,q); return 0; } Call by Reference: When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*/ #include<stdio.h> void main() { int x,y; x=20; y=30; printf("\n Value of a and b before function call =%d %d",x,y); fncn(&x,&y); printf("\n Value of a and b after function call =%d %d",x,y); getch(); } fncn(p,q) int *p,*q; { *p=*p+*p; *q=*q+*q; printf("\n Value of p and p after function call =%d %d",*p,*q); return 0; } Program to swap the two number using call by value #include<stdio.h> #include<conio.h> int swapv(int,int); int main()

Institute for Design of Electrical Measuring Instruments

- 57 -

{ int a,b; clrscr(); printf("Enter Any Two Number\n"); scanf("%d\t%d",&a,&b); printf("\nBefore Swapping\ta=%d\tb=%d",a,b); swapv(a,b); printf("\nAfter Swapping\ta=%d\tb=%d",a,b); getch(); return 0; } swapv(int x,int y) { int z; z=x; x=y; y=z; printf("\nAfter Swapping\tx=%d\ty=%d",x,y); return(0); } In above program value of a and b does not change when control goes back to main function after executing function swapv in which x holding value of a and y holding value of b gets swaped.This is because in call by Value ,we only send the copy of values of Variable.so any changes made to them in called function does not affect values of variable in calling function Program to swap the two number using call by Reference #include<stdio.h> #include<conio.h> int swapr(int *,int *); void main() { int a,b; clrscr(); printf("Enter Any Two Number\n"); scanf("%d%d",&a,&b); printf("\nBefore Swapping\ta=%d\tb=%d",a,b); swapr(&a,&b); printf("\nAfter Swapping\ta=%d\tb=%d",a,b); getch(); } swapr(int *x,int *y) { int z; z=*x; *x=*y; *y=z; printf("\nAfter Swapping\tx=%d\ty=%d",*x,*y); return(0); } In above program values of a and b also changes when control goes back to main function after executing function swapr in which x holding value of a and y holding value of b gets swaped.This is because in call by Reference,we send the Address of Variable.and ,if we get

Institute for Design of Electrical Measuring Instruments

- 58 -

address of any variable we can change its value.so,in program changes made to variables in called function also affects values of variable in calling function Pointer to arrays: An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator. /* A program to display the contents of array with address using pointer*/ #include<stdio.h> void main() { int a[100],*ptr; int i,j=0,n; clrscr(); printf("\nEnter the size of the array\n"); scanf("%d",&n); printf("Enter the array elements\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Array element are\n"); { for(ptr=a;ptr<(a+n);ptr++) printf("Value of a[%d]=%d stored at address %u\n",j++,*ptr,ptr); } getch(); }

Institute for Design of Electrical Measuring Instruments

- 59 -

Chapter 10 File HANDLING What is a File? Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage. Essentially there are two kinds of files that programmers deal with text files and binary files. These two classes of files will be discussed in the following sections. ASCII Text files A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Similarly, since text files only process characters, they can only read or write data one character at a time. (In C Programming Language, Functions are provided that deal with lines of text, but these still essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signalled the intention to process a text file. Binary files A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences. 1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. 2. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.

Institute for Design of Electrical Measuring Instruments

- 60 -

Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files they a generally processed using read and write operations simultaneously. For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files. Creating a Text file and output some data We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type. #include <stdio.h> void main( ) { FILE *fp; char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line.");/*copying string into stuff*/ for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %d\n", stuff, index);/*printing message in TENLINES.TXT file*/ fclose(fp); /* close the file before ending program */ getch(); } The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. The definition of C contains the requirement for a pointer to a FILE, and as usual, the name can be any valid variable name. Program:Another program to create a file and enter some data in it at Run Time /* Program to create a file and write some data the file */ #include<stdio.h>

Institute for Design of Electrical Measuring Instruments

- 61 -

#include<conio.h> void main() { FILE *fp; char c[100]; clrscr(); fp=fopen("hello.txt","w");/* open for writing */ printf("\nPlease enter a word : \n"); scanf("%s", &c); fprintf(fp,"\n%s",c); /*printing message in hello.txt file*/ fclose(fp);/* close the file before ending program */ getch(); } In above program we are Opening file hello.txt for writing by statement fp=fopen("hello.txt","w"); Here we can create any File by giving extension. ie:- hello.doc or hello.xls or hello.ppt for word file, Excel file and

Powerpoint file respectively. Opening a file Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type.

Institute for Design of Electrical Measuring Instruments

- 62 -

The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with this name, you should change its name or move it because when we execute this program, its contents will be erased. If you dont have a file by this name, that is good because we will create one and put some data into it. You are permitted to include a directory with the file name.The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character \ must be written twice. For example, if the file is to be stored in the \PROJECTS sub directory then the file name should be entered as \\PROJECTS\\TENLINES.TXT Reading (r) The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case. When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program. Writing (w) When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. Appending (a) When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. Outputting to the file The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.

Institute for Design of Electrical Measuring Instruments

- 63 -

Closing a file To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program. You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesnt generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in some of the other examples in this section. Reading from a text file Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it.

#include <stdio.h> void main( ) { FILE *funny; char c; funny = fopen("TENLINES.TXT", "r"); if (funny == NULL) { printf("File doesn't exist\n"); } else { do { c = getc(funny); /* get one character from the file */ putchar(c); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF (end of file) */ } fclose(funny); getch(); }

Institute for Design of Electrical Measuring Instruments

- 64 -

In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesnt, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated. At this point, we have the potential for one of the most common and most perplexing problems of programming in C. The variable returned from the getc function is a character, so we can use a char variable for this purpose. There is a problem that could develop here if we happened to use an unsigned char however, because C usually returns a minus one for an EOF - which an unsigned char type variable is not capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that. After you compile and run this program and are satisfied with the results, it would be a good exercise to change the name of TENLINES.TXT and run the program again to see that the NULL test actually works as stated. Be sure to change the name back because we are still not finished with TENLINES.TXT.

PROGRAM:-Another program to read the contents of the file #include<stdio.h> #include<conio.h> void main() { FILE *fp; char ch; clrscr(); fp=fopen("hello.txt","r");

Institute for Design of Electrical Measuring Instruments

- 65 -

if (fp == NULL) { printf("File doesn't exist\n"); } else { do { ch=fgetc(fp); /* get one character from the file */ printf("%c",ch); /* display it on the monitor */ }while(ch!=EOF); /* repeat until EOF (end of file) */ } fclose(fp); getch(); }

Institute for Design of Electrical Measuring Instruments

- 66 -

PROGRAMS for Practice:1.While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses
/* Calculation of total expenses */ main( ) { int qty, dis = 0 ; float rate, tot ; printf ( "Enter quantity and rate " ) ; scanf ( "%d %f", &qty, &rate) ; if ( qty > 1000 ) dis = 10 ; tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf ( "Total expenses = Rs. %f", tot ) ; }

2.The current year and the year in which the employee joined the organization are entered through the keyboard. If the number of years for which the employee has served the organization is greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of service are not greater than 3, then the program should do nothing.
/* Calculation of bonus */ main( ) { int bonus, cy, yoj, yr_of_ser ; printf ( "Enter current year and year of joining " ) ; scanf ( "%d %d", &cy, &yoj ) ; yr_of_ser = cy - yoj ; if ( yr_of_ser > 3 ) { bonus = 2500 ; printf ( "Bonus = Rs. %d", bonus ) ; } }

3.A company insures its drivers in the following cases: a..Driver is married. b.Driver is an unmarried male above 30 years of age. c.Driver is an unmarried female above 25 years of age.
/* Insurance of driver - using logical operators */ main( ) { char sex, ms ; int age ;

Institute for Design of Electrical Measuring Instruments

- 67 -

printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c" &age, &sex, &ms ) ; if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) || ( ms == 'U' && sex == 'F' && age > 25 ) ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; }

4.WAP to enter a number and find whether that Number is Palindrome or not
#include<stdio.h> void main() { int no,pal=0,i,x; clrscr(); printf("Enter any Number"); scanf("%d",&no); i=no; while(no!=0) { x=no%10; pal=(pal*10)+x; no=no/10; } if(i==pal) { printf("%d is a Palindrome Number",i); } else { printf("%d is not a Palindrome Number",i); } getch(); }

5.WAP to enter a number and find whether that Number is Armstrong or not
#include<stdio.h> void main() { int no,arm=0,i,x; clrscr(); printf("Enter any Number\n"); scanf("%d",&no); i=no; while(no!=0) { x=no%10; arm=arm+(x*x*x); no=no/10; }

Institute for Design of Electrical Measuring Instruments

- 68 -

if(i==arm) { printf("%d is an Armstrong Number",i); } else { printf("%d is not an Armstrong Number",i); } getch(); }

6.WAP to show String Pyramid using for loop:#include<stdio.h> #include<string.h> void main() { char n[]="cprograming"; int i,j; clrscr(); for(i=0;i<=n[i];i++) { for(j=0;j<=i;j++) { printf("%c",n[j]); } printf("\n"); } for(i==n[i];i>=0;i--) { for(j=0;j<=i;j++) { printf("%c",n[j]); } printf("\n"); } getch(); }

7.WAP to calculate Gross salary.da is 40%,hra is 20% of bs.


#include<stdio.h> void main() { float bs,da,hra,gs; clrscr();

Institute for Design of Electrical Measuring Instruments

- 69 -

printf("Enter the Basic Salary Of Ramesh\n"); scanf("%f",&bs); da=(40*bs)/100; hra=(20*bs)/100; gs=bs+da+hra; printf("Gross salry is %f",gs); getch(); }

8.WAP, to enter distance in KM.convert it into meter,cm,inch and ft


#include<stdio.h> void main() { long km,m,ft,inch,cm; clrscr(); printf("enter the distance between two cities\n"); scanf("%ld",&km); m=km*1000; cm=m*100; inch=cm/2.45; ft=inch/12; printf("\nDistance in meters %ld",m); printf("\nDistance in centimeters %ld",cm); printf("\nDistance in inches %ld",inch); printf("\nDistance in feet %ld",ft); getch(); }

Institute for Design of Electrical Measuring Instruments

- 70 -

PROGRAMS On ARRAY:1.WAP,to Sort Array Elements in Ascending Order


//Sorting Array #include<conio.h> #include<stdio.h> void main() { int i,j,n; int a[50],temp; clrscr(); printf("Enter the size of array"); scanf("%d",&n); printf("Array elements:\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf("\nElement in ascending order\n"); for(i=0;i<n;i++) { printf("%d\t",a[i]); } getch();

2.WAP,to find a Number from Array Elements


#include<stdio.h> void main() { int a[10],b,i,count=0; clrscr(); printf("Enter TEN numbers in an Array\n"); for(i=0;i<=9;i++) {

Institute for Design of Electrical Measuring Instruments

- 71 -

scanf("%d",&a[i]); } printf("Enter the number to be searched\n"); scanf("%d",&b); for(i=0;i<=9;i++) { if(b==a[i]) count++; } printf("\nnumber of searching %d",count); if(count==0) { printf("\n\nThis no is not present in array"); } getch(); }

PROGRAMS On STRUCTURE:1. program of Array of Structure


struct marks { int sub1; int sub2; int sub3; int total; }; void main() { int i; struct marks student[3]={{45,55,65},{56,78,63},{89,62,66}}; struct marks total; for(i=0;i<=2;i++) { student[i].total =student[i].sub1+student[i].sub2+student[i].sub3; } printf("Student\tTotal\n\n"); for(i=0;i<=2;i++) { printf("student[%d]\t%d\n",i+1,student[i].total); } getch(); }

Institute for Design of Electrical Measuring Instruments

- 72 -

2.Nesting of Structure:#include<stdio.h> #include<conio.h> struct employee { char name[20]; char post[25]; int salary; }; struct worker { int age; struct employee e; }; struct worker w={22,Albert Fernandis,Manager,35000}; void main() { clrscr(); printf(AGE=%d\nNAME=%s\nPOST=%s\nSALARY=%d,w.age,w.e.name,w.e.post,w.e.salary); getch(); }

3.Structure with Function:#include<stdio.h> #include<conio.h> display(char *,char *,float); struct book { char book_name[30]; char author[30]; float price; }; struct book b={LET US C,Y KANETKAR,150.50}; void main() { clrscr(); display(b.book_name,b.author,b.price); printf(\n\nTO STUDY C LANGUAGE PLZ REFER FOLLOWING BOOK); printf(\nBOOK NAME= %s\nAUTHOR NAME=%s\nPRICE OF BOOK= %f,b.book_name,b.author,b.price); getch(); } display(char*a,char*b,float c) { printf(\n%s\n%s\n%f,a,b,c); return 0;

Institute for Design of Electrical Measuring Instruments

- 73 -

4.Copy Elements of objects of Structure:#include<stdio.h> #include<conio.h> struct employee { char name[20]; int age; float salary; }; struct employee e1={"sushant",22,25000.00}; struct employee e2,e3; void main() { /* piece meal copying*/ strcpy(e2.name,e1.name); e2.age=e1.age; e2.salary=e1.salary; /* copying all elements at one go*/ e3=e2; clrscr(); printf("%s %d %f\n",e1.name,e1.age,e1.salary); printf("%s %d %f\n",e2.name,e2.age,e2.salary); printf("%s %d %f\n",e3.name,e3.age,e3.salary); getch(); }

PROGRAM to place Numbers at different Locations


#include<stdio.h> void main() { int n; n=12345; clrscr(); printf("\n"); printf("%ld\n",n); printf("%5.6ld\n",n); printf("%-7.2ld\n",n); printf("%9.4ld\n",n); printf("%11.11ld\n",n); printf("%18.3ld\n",n); getch(); }

PROGRAM to place String at different Locations


#include<stdio.h> void main() {

Institute for Design of Electrical Measuring Instruments

- 74 -

int i; char n[22]="C PROGRAMMING LANGUAGE"; //char mm; clrscr(); printf("\n"); printf("%-22.5s\n",n); printf("%2.3s\n",n); printf("%3.8s\n",n); printf("%2.13s\n",n); printf("%-20.1s\n",n); printf("%s\n",n); printf("%-24.10s\n",n); printf("%15.10s\n",n); printf("%4.4s\n",n); printf("%10.10s\n",n); printf("%s\n",n); getch(); }

PROGRAMS On POINTER:1.WAP,to show Various forms of Pointers


#include<stdio.h> void main() { int a,b,*p1,*p2,x,y; a=4; b=6; p1=&a; p2=&b; clrscr(); x=*p1 + *p2; y=*p2 - *p1; printf("\na is %d",a); printf("\nAddress of a is :%u",p1); printf("\nb is %d",b); printf("\nAddress of b is :%u",p2); printf("\nAddress of p1 is :%u",&p1); printf("\nAddress of p2 is :%u",&p2); printf("\nAddress of a is :%u",&a); printf("\na is %d",*p1); printf("\nAddress of b is :%u",&b); printf("\nb is %d",*p2); printf("\nx is %d",x); printf("\ny is %d",y); x = *p1 * *p2;

Institute for Design of Electrical Measuring Instruments

- 75 -

printf("\nx is %d",x); *p2 = *p2+5; *p1 = *p2+50; printf("\nNow b is :%d",b); printf("\nNow a is :%d",a); getch(); }

2.WAP ,to show use of Pointer with string


/*Pointer with String*/ #include<stdio.h> #include<conio.h> void main() { char n[30],*c; clrscr(); printf("Enter a String : "); gets(n); c=n; while(*c!='\0') //\0 means null { printf("%c\t%u\n",*c,c); //%u used for unsigned integer c++; } getch(); }

Institute for Design of Electrical Measuring Instruments

- 76 -

C++ Programming

Institute for Design of Electrical Measuring Instruments

- 77 -

Chapter 1 C++ FUNDAMENTALS

OBJECT ORIENTED PROGRAMMING PARADIGM Object oriented programming (oops) treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the function that operate on it, and protect it form modification from outside functions. oops allows decomposition of a problem into a number of entities called objects and then builds data and functions around those objects. The organization of data and functions in object oriented program is shown as

Data

Data

Functions

Functions

Functions

Data

Fig. 1.1 Organization of data & functions in oops Some of the features of oops are Emphasis is on data rather than procedure. Programs are divided into what are known as objects. Data structures are designed such that they characterize the objects. Functions that operate on the data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be easily added wherever necessary. Follows bottom up approach in program design.

Institute for Design of Electrical Measuring Instruments

- 78 -

BASIC CONCEPT IN OOPs Some important concept in oops are Objects Classes Data abstraction & Encapsulation. Inheritance Dynamic binding. Message passing. Objects Object is the basic run-time entities in an object-oriented system. They may represent a person, a place a bank account, a table of data or any item that the program has to handle. Programming problem is analyzed in terms of objects and the nature of communication between them. Objects take up space in the memory & have an associated address like structure in c. When a program executes, the object interacts by sending messages to one another. Ex. If there are two objects customer and account then the customer object may send a message to account object requesting for the bank balance. Thus each object contains data, and code to manipulate the data.

Object - Student Data - Name Roll No. Marks

Functions : Total average Display


Fig. 1.2 Student Object Classes The entire set of data and code of an object can be made a user-defined data type with the help of a class. Objects are actually variable of the type class. Once a class has been defined, we can create any number of objects belonging to that class. Thus a class is collection of objects of similar type. Classes are user defined data types and behaves like the built in type of a programming language. The syntax for defining class is class class-name { -------------------------------

Institute for Design of Electrical Measuring Instruments

- 79 -

} Data abstraction and Encapsulation The wrapping up of data and functions into a single unit called class is known as encapsulation. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide the interface between the objects data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and coast, and functions to operate on these attributes. Inheritance Inheritance is the process by which object of one class acquire the properties of objects of another class. In OOPs, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have combined features of both the classes. Polymorphism Polymorphism is important oops concept. It means ability to take more than one form. In polymorphism operations may shows different behavior in different instances. The behavior depends upon the type of data used in the operation. For Ex- Operation of addition for two numbers will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to show different behavior in different instance is called as operator overloading. C++ support operator overloading.

Shape Draw ()

Circle Draw (Circle)

Box Draw (Box)

Triangle Draw (Triangle)

Fig 1.3 Polymorphism The above figure shows concept of function overloading. Function overloading means using a single function name to perform different types of tasks.

Institute for Design of Electrical Measuring Instruments

- 80 -

Dynamic Binding Binding referes to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time.

Message Passing OOPs consist of a set of objects that communicate with each other. Message passing involves following stepsCreating classes that define objects and their behavior Creating objects from class definitions and Establishing communication among objects. A message for an object is a request for execution of a procedure & therefore will invoke a function in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function i.e. message and the information to be sent. Excustomer. balance(account no) object message information

BENEFITS OF OOPs OOP offers several benefits to both the program designer and the user. The principal advantages are. Through inheritance, we can eliminate redundant code and extend the use of existing classes We can build program from the standard working module that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. The principal of data hiding helps the programmer to build secure programs that cannot be invaded by code in other part of the program. It is possible to have multiple instance of an object to co-exist without any interference It is easy to partition the work in a project, based on objects. Object oriented systems can be easily upgraded from small to large systems. Message passing techniques for communication between objects makes the interface description with external systems much simpler. Software complexity can be easily managed.

WHAT IS C++ C++ is an object oriented programming language developed by Biarne stroustrup at AT & T Bell laboratories.

Institute for Design of Electrical Measuring Instruments

- 81 -

C++ is an extension of c with a major addition of the class construct feature.

A SIMPLE C++ PROGRAM # include<iostream.h> int main() { cout<<Hello Wold; return 0; } C++ program is a collection of functions. Every C++ program must have a main() function. The iostream file:The header file iostream should be included at the beginning of all programs that uses one output statement. Input / Output operator Input Operator cin :- The identifier cin is a predefined object in c++ that corresponds to the standard input stream. Here this stream represents keyboard. Syntax:- cin>>variable; The operator >> is known as extraction or get from operator & assigns it to the variable on its right. Output operator cout :-The identifier cout is predefined object that represents the standard output stream in c++. Here standard output stream represents the screen. Syntax:- cout<<string; The operator << is called the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left. Return type of main():- In C++, main returns an integer type value to the operating system. So return type for main() is explicitly specified as int. Therefore every main() in c+ + should end with a return 0 statement.

Institute for Design of Electrical Measuring Instruments

- 82 -

Chapter 2 BASIC DATA TYPES IN C++ C++ Data Types

User defined type Structure Union Class Enumeration

Built in type

Derived type Array Function Pointer reference

Integral Type int Built-in-type char

void

Floating type Float double

Integral type The data types in this type are int and char. The modifiers signed, unsigned, long & short may be applied to character & integer basic data type. The size of int is 2 bytes and char is 1 byte. void void is used for To specify the return type of a function when it is not returning any value. To indicate an empty argument list to a function. Ex- Void function1(void) In the declaration of generic pointers. EX- void *gp A generic pointer can be assigned a pointer value of any basic data type. Ex int *ip // this is int pointer gp = ip //assign int pointer to void. A void pointer cannot be directly assigned to their type pointers in c++ we need to use cast operator. Ex Void * ptr1; Char * ptr2;

Institute for Design of Electrical Measuring Instruments

- 83 -

ptr2 = ptr1; is allowed in c but not in c++ ptr2 = (char *)ptr1 is the correct statement Floating type: The data types in this are float & double. The size of the float is 4 byte and double is 8 byte. The modifier long can be applied to double & the size of long double is 10 byte. User-defined type The user-defined data type structure and union are same as that of C. Classes Class is a user defined data type which can be used just like any other basic data type once declared. The class variables are known as objects. EnumerationAn enumerated data type is another user defined type which provides a way of attaching names to numbers to increase simplicity of the code. It uses enum keyword which automatically enumerates a list of words by assigning them values 0, 1, 2,.etc. Syntax:enum shape { circle, square, triangle } Now shape become a new type name & we can declare new variables of this type. EX shape oval; In C++, enumerated data type has its own separate type. Therefore c++ does not permit an int value to be automatically converted to an Ex. shape shapes1 = triangle, // is allowed shape shape1 = 2; // Error in c++ shape shape1 = (shape)2; //ok By default, enumerators are assigned integer values starting with 0, but we can over-ride the default value by assigning some other value. EX:enum colour {red, blue, pink = 3}; it will assign red to o, blue to 1, & pink to 3 or enum colour {red = 5, blue, green}; it will assign red to 5, blue to 6 & green to 7. Derived Data types

Institute for Design of Electrical Measuring Instruments

- 84 -

Arrays An array in c++ is similar to that in c, the only difference is the way character arrays are initialized. In c++, the size should be one larger than the number of character in the string where in c, it is exact same as the length of string constant. Ex char string1[3] = ab; // in c++ char string1[2] = ab; // in c.

Functions Functions in c++ are different than in c there is lots of modification in functions in c++ due to object orientated concepts in c++. Pointers Pointers are declared & initialized as in c. Ex- int * ip; // int pointer ip = &x; //address of x through indirection c++ adds the concept of constant pointer & pointer to a constant pointer. char const *p2 = HELLO; // constant pointer

Institute for Design of Electrical Measuring Instruments

- 85 -

Chapter 3 VARIABLES IN C++ Declaration of variables C requires all the variables to be defined at the beginning of a scope. But c++ allows the declaration of variable anywhere in the scope. That means a variable can be declared right at the place of its first use. It makes the program easier to understand. Dynamic initialization of variables In c++, a variable can be initialized at run time using expressions at the place of declaration. This is refereed to as dynamic initialization. Ex.- int m = 10; Here variable m is declared and initialized at the same time. Reference variables A reference variable provides an alias for a previously defined variable. Example:- If we make the variable sum a reference to the variable total, them sum & total can be used interchangeably to represent that variable. Reference variable is created as:data type & reference name = variable name. Ex:int sum = 200; int &total = sum; Here total is the alternative name declared to represent the variable sum. Both variable refer to the same data object in memory. A reference variable must be initialized at the time of declaration. C++ assigns additional meaning to the symbol &.Here & is not an address operation. The notation int & means reference to int. A major application of reference variable is in passing arguments to functions. Ex. void fun (int &x) // uses reference { x = x + 10; // x increment, so x also incremented. } int main( ) { int n = 10; fun(n); // function call }

When the function call fun(n) is executed, it will assign x to n i.e. int &x = n; Therefore x and n are aliases & when function increments x. n is also incremented. This type of function call is called call by reference.

Institute for Design of Electrical Measuring Instruments

- 86 -

Chapter 4 OPERATORS IN C++ C++ have rich set of operators. Some of the new operators in c++ are :: - Scope resolution operators. ::* - pointer to member decelerator. *-pointer to member operator. .* - pointer to member operator. delete memory release operator. endl Line feed operator new Memory allocation operator. stew Field width operator. Scope resolution Operator

C++ is a block Structured language. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. Consider following program. . { int x = 1; === } ===== { int x = 2; } ===== The two declaration of x refer to two different memory locations containing different values. Blocks in c++ are often nested. Declaration in a inner block hides a declaration of the same variable in an outer block. In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope resolution operator (::), because this operator allows access to the global version of a variable. Consider following program. #include<iostream.h> #include<conio.h> int m=10; void main() { int m=20; { int k = m; int m = 30; clrscr(); cout<<"K = " <<k<<endl; cout<<"m = "<<m<<endl; cout<<"::m = "<<::m<<endl;

Institute for Design of Electrical Measuring Instruments

- 87 -

} cout<<"m = "<<m<<endl; cout<<"::m = "<<::m<<endl; getch(); } The output of program is k = 20 m = 30 :: m = 10 m = 20 :: m =10 In the above program m is declared at three places. And ::m will always refer to global m. A major application of the scope resolution operator is in the classes to identify the class to which a member functions belongs. Member dereferencing operators C++ permits us to define a class containing various types of data & functions as members. C++ also permits us to access the class members through pointers. C++ provides a set of three pointer. C++ provides a set of three pointers to member operators. 1) ::* - To access a pointer to a member of a class. 2) .* - To access a member using object name & a pointer to that member. 3) * - To access a member using a pointer in the object & a pointer to the member. Memory management operators We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. C++ supports two unary operators new and delete that perform the task of allocating & freeing the memory. An object can be created by using new and destroyed by using delete. A data object created inside a block with new, will remain existence until it is explicitly destroyed by using delete. It takes following form. variable = new data type The new operator allocated sufficient memory to hold a data object of type data-type & returns the address of the object. EX - p = new int. Where p is a pointer of type int. Here p must have already been declared as pointer of appropriate types. New can be used to create a memory space for any data type including user defined type such all array, classes etc. Ex- int * p = new int [10] Creates a memory space for an array of 10 integers. When a data object is no longer needed, it is destroyed to release the memory space for reuse. The general form is delete variable. If we want to free a dynamically allocated array, we must use following form. delete [size] variable. The size specifies the no of elements in the array to be freed. The new operator has following advantages over the function malloc() in c -.

Institute for Design of Electrical Measuring Instruments

- 88 -

It automatically computes the size of the data object. No need to use sizeOf() If automatically returns the correct pointer type, so that there is no need to use a type cast. new and delete operators can be overloaded. It is possible to initialize the object while creating the memory space. Manipulators Manipulators are operators that are used to format the data display. There are two important manipulators. 1) endl 2) stew 1) endl : - This manipulator is used to insert a linefeed into an output. It has same effect as using \n for newline. Ex- cout<< a << a << endl <<n= <<n; << endl<<p=<<p<<endl; The output is a = 2568 n = 34 p = 275 2) Setw : With the stew, we can specify a common field width for all the numbers and force them to print with right alignment. EX cout<<stew (5) <<sum<<endl; The manipulator setw(5) specifies a field width of 5 for printing the value of variable sum the value is right justified. 3 5 6

Type cast operator. C++ permits explicit type conversion of variables or expressions using the type cast operator. Syntax type name (expression) Ex avg = sum/float(i) Here a type name behaves as if it is a function for converting values to a designated type.

Institute for Design of Electrical Measuring Instruments

- 89 -

Chapter 5 CLASSES AND OBJECTS SPECIFYING A CLASS Class A class is a user defined data type which binds data and its associated functions together. It allows the data and functions to be hidden, if necessary from external use. Generally, a class specification has two parts. Class declaration: it describes the type & scope of its members. Class function definitions: It describes how the class functions are implemented. Class declaration. The general form of a class is class class-name { private: variable declaration; function declaration; public: variable declaration; function declaration; }; The class keyword specifies that what follows is an abstract data of type class name. The body of a class is enclosed within braces & terminated by semicolon. The class body consists of declaration of variables & functions which are called as members & they are grouped under two sections i.e. private & public. Private and public are known as visibility labels, where private can be accessed only from within the class where public members can be accessed from outside the class also. By default, members of a class are private. The variable declared inside the class are known as data members & functions are known as member functions. Only the member function can have access to the private data members & private functions. However the public members can be accessed from outside the class. Simple class example class item { int number; variable float cost; declaration public : void getdata (int a, float b); void putdata (void);

function declaration

In above class class-name is item. These class data members are private by default while both the functions are public by declaration. The function getdata() can be used to assign values to the member variable number & cost, and putdata() for displaying their values. These functions provide the only access to data members of the class.

Institute for Design of Electrical Measuring Instruments

- 90 -

Creating objects

Object is an instance or variable of the class. Once a class has been declared. We can create variables of that type by using the class name. Ex item x; Here class variables are known as object therefore, x is called an object of type item and necessary memory space is allocated to an object. Accessing class Members Private data of a class can be accessed by the member function. The following is the format for calling member function. Object-name.function-name(actual argument) Ex x.getdata (10, 20.3); This statement assign value 10 to number & 20.3 to cost of the object x. By implementing the getdata() function similarly, the statement. x.putdata(); would display the value of data member. If the member variable is declared as private then it cannot be accessible by object. It can only be accessed by a member function. Whereas, if a variable is declared as public it can be accessed by the object directly. Ex class abc { int x, y; public : int z; }; main() { abc m ; m.x = 100; // error x is private m.z=50; // ok ,z is public The above example shows concept of data hiding. DEFINING MEMBER FUNCTIONS Member functions can be defined in two ways. Outside the class definition Inside the class definition Outside the class definition Member function that is declared inside a class has to be defined separately outside the class. These member functions associate a membership identify label in the header. This

Institute for Design of Electrical Measuring Instruments

- 91 -

label tells the compiler which class the function belongs to. The general format of a member function definition is. Return type class name:: function-name(argument declaration) { Function body } The membership label class-name:: tells the compiler that the function function-name belongs to the class-name. The symbol :: is called as scope resolution operator. Ex- the function getdata is coded as void item:: getdata(int a, float b) { number = a; cost = b; } The member function have some special characteristics :i) ii) iii) Several different classes can use the same function name the membership label will resolve their scope. Member function can access the private data of the class. A non member function cannot do so. A member function can call another member function directly, without using the dot operator.

Inside the class definition In this method the function declaration inside the class is replaced by actual function definition. For Exclass item { int number; float cost; pubic : void getdata (int a float b); //declaration void putdata (void) { cout << number << endl; cout << cost << endl; }

} Remember only small functions can be defined inside the class. C++ PROGRAM WITH CLASS #include<iostream.h> #include<conio.h> class item // class declaration

Institute for Design of Electrical Measuring Instruments

- 92 -

int number; // private by default float cost; public : void getdata(int a,float b); void putdata(void) // function defined here { clrscr(); cout<<"number "<<number<<"\n"; cout<<"cost: "<<cost<<"\n"; } }; // member functions definition void item::getdata(int a, float b) { number = a; cost = b; } // main program void main() { item x; // create object x x.getdata(100,20.3); x.putdata(); getch(); } In the above program we have shown that one member functions is inline and other is external member function. Here is the output of program. number : 100 cost : 20.3 MAKING AN OUTSIDE FUNCTION INLINE We can define a member function outside the class definition and still make it inline by just using the qualifier inline in the header line of function definition Ex class item { ------public : void getdata(int a, float b); } inline void item ::getdata (int a, float b) { number = a; cost = b; } NESTING OF MEMBER FUNCTION

Institute for Design of Electrical Measuring Instruments

- 93 -

When a member function can be called by using its name inside another member function of the same class, it is known as nesting of member function. Ex #include<iostream.h> #include<conio.h> class set { int m,n; public: void input(void); void display(void); int largest(void); }; int set::largest(void) { if(m > n) return(m); else return(n); } void set::input(void) { cout<<"input values of m & n:\n"; cin>>m>>n; } void set::display(void) { cout<<"largest value = "<<largest(); } void main() { set a; clrscr(); a.input(); a.display(); getch(); } PRIVATE MEMBER FUNCTION Although we place all data items in a private section and all the functions in public, some situation may require certain function to be hidden from the outside calls. We can place these functions in the private section. A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot operator. Consider following class: class sample { int m; void read(void); public: void update(void); void write(void);

Institute for Design of Electrical Measuring Instruments

- 94 -

}; If s1 is an object of sample then s1.read(); // will not work , object cannot access private data. read() can be called by the function update() to update the value of m. void sample :: update (void) { read(); // a simple call } MEMORY ALLOCATION FOR OBJECTS The member functions are created & place in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions no separate space is allocated for member functions when the objects are created only space for member variables is allocated separately for each object.

common for all object


member function1 member function 2

memory created when function defined object 3 mem.function 1 mem.funct2

object 1 mem.function 1 mem.funct2

object 2 mem.function 1 mem.funct2

Fig. Object in memory STATIC DATA MEMBERS A data member of a class can be qualified as static. A static member variable has certain special characteristics these are. It is initialized to zero when the first object of its class is crated. No other initialization is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to the entire class for Ex - A static data member can be used as a counter that records the occurrences of all the objects. #include<iostream.h> #include<conio.h> class item { static int count;

Institute for Design of Electrical Measuring Instruments

- 95 -

int number; public: void getdata(int a) { number=a; count++; } void getcount(void) { cout<<"count :"; cout<<count<<"\n"; } }; int item::count; void main( ) { item a,b,c; clrscr(); a.getcount(); b.getcount(); c.getcount(); a.getdata(100); b.getdata(200); c.getdata(300); cout<<"After reading data\n"; a.getcount(); b.getcount(); c.getcount(); getch(); } the output would be count : 0 count : 0 count : 0 After reading data count : 3 count : 3 count : 3 The static variable count is initialized to zero when the objects are created. The count is incremented whenever the data is read into an object. Since the data is read into objects three times, variable count is incremented three times. Static variables are like non inline member functions in that they are declared in a class declaration & defined in the source file. Now use this code instead of above code written in main().and check output a.getcount(); b.getcount(); c.getcount(); a.getdata(100); a.getcount(); b.getdata(200); a.getcount(); c.getdata(300); a.getcount();

Institute for Design of Electrical Measuring Instruments

- 96 -

cout<<"After reading data\n"; a.getcount(); b.getcount(); c.getcount(); STATIC MEMBER FUNCITON A static member function has following properties. A static function can have access to only other static members declared in the same class. A static member function can be called using the class name as follows: classname:: functionname; Following program illustrates the implementation of these characteristics. #include<iostream.h> #include<conio.h> class test { int code; static int count; public: void setcode(void) { code =++count; } void showcode(void) { cout<<"object No "<<code<<endl; } static void showcount(void) { cout<<"count : "<<count<<endl; } }; int test::count; void main() { clrscr(); test t1,t2; t1.setcode(); t2.setcode(); test::showcount(); test t3; t3.setcode(); test::showcount(); t1.showcode() ; t2.showcode(); t3.showcode(); getch(); } Output of the program count : 2

Institute for Design of Electrical Measuring Instruments

- 97 -

count : 3 object No : 1 object No : 2 object No : 3 The static function showcount displays the number of objects created till that moment. A count of number of objects created is maintained by the static variable count. OBJECTS AS FUNTIONS ARGUMENTS An object may be used as function arguments in two ways : A copy of the entire object is passed to the function. Only the address of the object is transferred to the function. Pass-by-value Since a copy of the object is passed to the function, any change made to the object inside the function do not effect the object used to call the function. Pass-by-reference when an address of the object is passed the called function works directly on the actual object used in the call. This means that any changes made to the object inside the function will reflect in the actual object. Example -Following program illustrates the use of object as function arguments. It performs the addition of time in the hour & minute format. #include<iostream.h> #include<conio.h> class time { int hours; int minutes; public: void gettime(int h,int m) { hours=h; minutes=m; } void puttime(void) { cout<<hours<<" hours: "; cout<<minutes<<" minutes "<<"\n"; } void sum(time,time); }; void time::sum(time t1,time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours=t1.hours+t2.hours; }

Institute for Design of Electrical Measuring Instruments

- 98 -

void main() { time T1,T2,T3; clrscr(); T1.gettime(2,30); T2.gettime(3,45); T3.sum(T1,T2); cout<<" T1 = "; T1.puttime(); cout<<" T2 = "; T2.puttime(); cout<<" T3 = "; T3.puttime(); getch(); } An object can also be passed as argument to a non-member function but, such functions can have access to the public member function only through the object passed as arguments to it. FRIENDLY FUNCTIONS A non member function cannot have an access to the private data of a class. However there could be situation where we would like two classes to share a particular function. In such situation, c++ allows the common function to be made friendly with both the classes, thereby allowing the function to have access to the private data of these classes such a function need not be a member of any of these classes. The syntax for friend function is class ABC { ======= public: ======= friend void function1(void); } The function is declared with friend keyword. But while defining friend function. It does not use either keyword friend or :: operator. A friend function, although not a member function, has full access right to the private member of the class. A friend, function has following characteristics. It is not in the scope of the class to which it has been declared as friend. A friend function cannot be called using the object of that class. If can be invoked like a normal function without help of any object. It cannot access the member variables directly & has to use an object name dot membership operator with member name. It can be declared either in the public or the private part of a class without affecting its meaning. Usually, it has the object as arguments. Ex-

Institute for Design of Electrical Measuring Instruments

- 99 -

#include<iostream.h> #include<conio.h> class sample { int a,b; public: void setvalue() { a=25; b=40; } friend float mean(sample s); }; float mean(sample s) { return float(s.a+s.b)/2.0; } void main() { sample x ; clrscr(); x.setvalue(); cout<<"Mean Value = "<<mean(x); getch(); } output Mean value = 32.5

Member function of one class can be friend functions of another class. In such cases they are defined using the scope resolution operator. EX class x { ------------int fun(); // member function of x }; class y {-----------------friend int x : : fun() }; --------We can declare all the member functions of one class as the friend functions of another class by declaring that class as a friend class. Ex class z { --------------friend class x ; {;

Institute for Design of Electrical Measuring Instruments

- 100 -

A friend function work as a bridge between the classes. Ex #include<iostream.h> #include<conio.h> class ABC; //forward declaration class XYZ { int x; public: void setvalue(int i) { x = i; } friend void max(XYZ,ABC); }; class ABC { int a; public : void setvalue(int i) { a=i; } friend void max(XYZ,ABC); }; void max(XYZ m, ABC n) // definition of friend. { if(m.x >= n.a) cout<<m.x; else cout<<n.a; } void main() { ABC k; k.setvalue(20); XYZ l; l.setvalue(40); max(l,k); getch(); } output :40 A friend function can be called by reference. In this local copies of the object are not made. Instead, a pointer to the address of the object is passed and the called function directly works on the actual object used in the call. Ex-following program shows how to use a common friend function to exchange private value of two classes. #include<iostream.h>

Institute for Design of Electrical Measuring Instruments

- 101 -

#include<conio.h> class c2; class c1 { int value1; public: void indata(int a) { value1 = a; } void display(void) { cout<<endl<<value1<<endl; } friend void exchange(c1 &,c2 &); }; class c2 { int value2; public: void indata(int a) { value2 = a; } void display(void) { cout<<value2<<endl; } friend void exchange(c1 &,c2 &); }; void exchange(c1 &x,c2 &y) { int temp = x.value1; x.value1 = y.value2; y.value2 = temp; } void main() { c1 co1; c2 co2; clrscr(); co1.indata(10); co2.indata(20); cout<<"Values before exchange"; co1.display(); co2.display(); exchange(co1,co2); cout<<"Values after exchange"; co1.display(); co2.display(); getch(); }

Institute for Design of Electrical Measuring Instruments

- 102 -

output of the program Values before exchange 10 20 Values after exchange 20 10 RETURNING OBJECTS A function can not only receive objects as arguments but also can return them. Ex. #include<iostream.h> #include<conio.h> class complex { float x,y; public: void input(float real,float image) { x = real; y = image; } friend complex sum(complex,complex); void show(complex); }; complex sum(complex c1,complex c2) { complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return(c3); } void complex::show(complex c) { cout<<c.x<<"\t"<<+j<<c.y<<"\n"; } void main() { complex A,B,C; clrscr(); A.input(3.1,5.65); B.input(2.75,1.2); C=sum(A,B); cout<<"A= "; A.show(A); cout<<"B= "; B.show(B); cout<<"C= "; C.show(C); getch(); } output of the program A = 3.1 +j5 65

Institute for Design of Electrical Measuring Instruments

- 103 -

B = 2.75 C = 5.85

+j1.2 +j6.85 Chapter 6 CONSTRUCTORS AND DESTRUCTORS

INTRODUCTION We have seen, so far, a few examples of classes being implemented. In all the cases, we have used member functions such as putdata() and setvalue() to provide initial values to the private member variables. For example, the following statement. a.input(); invoke the member function input() which assigns the initial values to the data items of object A. Similarly, the statement. x.getdata (100, 299.95); passes the initial values as arguments to the function getdata() where these values are assigned to the private variables of object x. All these function call statements are used with the appropriate objects that have already been created. These functions cannot be used to initialize the member variables at the time of creation of their objects. Providing the initial values as described above does not confirm with the philosophy of C++ language. We stated earlier that one of the aims of C++ is to create user-defined data types such as class, that behave very similar to the built-in types. This means that we should be able to initialize a class type variable (object) when it is declared, much the same way as initialization of an ordinary variable. For example. int m = 20; Float x = 5.75; Are valid initialization statements for basic data types. Similarly, when a variable of built-in-type goes out of scope, the compiler automatically destroys the variable. But it has not happened with the objects we have so farstudied. It is therefore clear that some more features of classes need to be explored that would enable us to initialize the object when they are created and destroy them when their presence is no longer necessary. C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. This is known as automatic initialization of objects. It also provides another member function called the destructor that destroys the objects when they are no longer required. CONSTRUCTORS

Institute for Design of Electrical Measuring Instruments

- 104 -

A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it construct the value data members of the class. //class with a constructor class Integer { int m, n; public: Integer(void); //constructor declared . . }; Integer :: Integer(void) // constructor defined { m = 0; n = 0; } }; When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialized automatically. For example, the declaration. Integer int1; // object int1 created not only creates the object int1 of type Integer but also initializes its data members m and n to 0.There is no need to write any statement to invoke the constructor function. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A(). If no such constructor is defined the compiler suppliers default constructor. Therefore a statement such as A a; invokes the default constructor of the compiler to create the object a. The constructor functions have some special characteristics They should be declared in the public section. They are invoked automatically when the objects are created. They do not have return types, not even void and therefore, they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, they can have default arguments. Constructors cannot be virtual. We cannot refer to their addresses. An object with a constructor (or destructor) cannot be used as a member of a union. They make implicit calls to the operations new and delete when memory allocation is required. Remember, when a constructor is declared for a class initialization of the class objects become mandatory.

PARAMETERIZED CONSTRUCTORS

Institute for Design of Electrical Measuring Instruments

- 105 -

The constructor Integer(), defined above, initialized the data members of all the objects to zero. However in practice it may be necessary to initialize the various data elements of different objects with different values when they are created. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors. The constructor integer() may be modified to take arguments as shown below : class integer { int m, n; public: integer (int x, int y); //parameterized constructor .. .. }; integer : : integer (int x, int y) { m = x; n = y; } When a constructor has been parameterized, the object declaration statement such as integer int1; may not work. We must pass the initial values as arguments to the constructor function when an object is declared. This can be done in two ways; By calling the constructor explicitly. By calling the constructor implicitly. Integer Int1 = Integer (0, 100); //explicit call This statement creates in integer object int1 and passes the values 0 and 100 to it. The second is implemented as follows : Integer int1 (0, 100); //implicit call. This method sometimes called the shorthand method, is used very often as it is shorter, looks better and is easy to implement. Remember, when the constructor is parameterized, we must provide arguments for the constructor. Program 3.1 demonstrates the passing of arguments to the constructor functions. [CLASS WITH CONSTRUCTORS] #include<iostream.h> #include<conio.h> class integer { int m,n; public: integer(int,int) ; // constructor declared void display(void)

Institute for Design of Electrical Measuring Instruments

- 106 -

{ } };

cout<<"m = "<<m<<"\n"; cout<<"n = "<<n<<"\n";

integer::integer(int x,int y) // constructor defined { m = x; n=y; } void main() { integer int1(0,100); //IMPLICIT call integer int2=integer(25,75); // EXPLICIT call clrscr(); cout<<"\nOBJECT1"<<"\n"; int1.display(); cout<<"\nOBJECT2"<<"\n"; int2.display(); getch(); } Program 3.1 displays the following output : OBJECT1 m=0 n = 100 OBJECT2 m = 25 n = 75 The constructor functions can also be defined as inline functions. Example: class integer { int m, n; public: integer (int x, int y) //inline constructor { m = x; y = n; } .. .. }; The parameters of a constructor can be of any type except that of the class to which it belongs. For example, class A { .. .. public: A(A);

Institute for Design of Electrical Measuring Instruments

- 107 -

}; is illegal However a constructor can accept a reference to its own class as a parameter. That is, Class A {

.. .. public: A(A&); };

is valid. In such cases, the constructor is called the copy constructor.

MULTIPLE CONSTRUCTORS IN A CLASS So far we have used two kinds of constructors. They are; integer(); // No arguments integer(int, int); // Two arguments In the first case, the constructor itself supplies the data values and no values are passed by the calling program. In the second case, the function call passes the appropriate values from main ( ). C++ permits us to use both these constructors in the same class. For example, we could define a class as follows : class integer { int m, n; public: integer ( ) {m = 0; n = 0;) integer (int a, int b) {m = a; n = b;) integer (integer & i) {m = i.m; n = i.n;) };

// constructor 1 // constructor 2 // constructor 3

This declared three constructors for an integer object. The first constructor receives no arguments, the second receives two integer arguments and the third receives one integer object as an argument. For example, the declaration. Integer I1; would automatically invoke the first constructor and set both m and n of I1 to zero. The statement integer I2 (20, 40); would call the second constructor which will initialize the data members m and n I2 to 20 and 40 respectively. Finally, the statement.

Institute for Design of Electrical Measuring Instruments

- 108 -

Integer I3(I2); would invoke the third constructor which copies the values of I2 into I3. That is, it sets the value of every data element of I2 to the value of the corresponding data element of I3. As mentioned earlier, such a constructor is called the copy constructor. The process of sharing the same name by two or more functions is referred to as function overloading. Similarly, when more than one constructor is overloaded, it is called constructor overloading. Program 3.2 shows the use of overloaded constructors. [ OVERLOAED CONSTRUCTORS ] #include<iostream.h> #include<conio.h> class complex { float x,y; public: complex() // constructor with no arg { } complex(float a) // constructor with one arg { x = y = a; } complex(float real, float imag) // constructor with two args { x =real; y =imag; } friend complex sum(complex,complex); friend void show(complex); }; complex sum(complex c1, complex c2) // friend { complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return(c3); } void show(complex c) // friend { cout<<c.x<<"+j"<<c.y<<"\n"; } void main() { complex A(2.7,3.5); complex B(1.6) ; complex C; //define C=sum(A,B);//sum() is a friend cout<<"A = "; show(A); //show() is also friend cout<<"B = ";

//define & initialize //define & initialize

Institute for Design of Electrical Measuring Instruments

- 109 -

show(B); cout<<"C = "; show(C); // Another way to give initial values (second method) complex P,Q,R; // define P, Q and R P=complex(2.5,3.9); // initialize P Q=complex(1.6,2.5); // initialize Q R=sum(P,Q); cout<<"\n"; cout<<"P = "; show(P); cout<<"Q = "; show(Q); cout<<"R = "; show(R); getch();

} output A = 2.7 + j3.5 B = 1.6 + J1.6 C = 4.3 + j5.1 P = 2.5 + j3.9 Q = 1.6 + j2.5 R = 4.1 + j6.4

There are three constructors in the class complex. The first, which takes no arguments, is used to create objects which are not initialized. The second , which takes one argument, is used to create objects and initialize them. The third constructor, which takes two arguments, is also used to create objects and initialize them to specific values. Note that the second method of initializing values looks better. Let us look at the first constructor again. complex ( ) { } It contains the empty body and does not do anything. We just stated that, this is used to create objects without any initial values. Remember, we have defined objects in the earlier examples without using such a constructor. Why do we need this constructor now? As pointed out earlier, C++ compiler has an implicit constructor which creates objects, even though it was not defined in the class. This works fine as long as we do not use any other constructors in the class. However, once we defined a constructor, we must also define the do-nothing implicit constructor. This constructor will not do anything and is defined just to satisfy the compiler. DESTRUCTORS A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, it is a member function whose name is the same as the class name but is preceded by a tilde, For example, the destructor for the class integer can be defined as shown below: ~ integer ( ) { }

Institute for Design of Electrical Measuring Instruments

- 110 -

A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or block or function as the case may be) to clean up storage that is no longer accessible. It is good practice to declare destructors in a program since it release memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. For example the destructor for the matrix class discussed above may be defined as follows. matrix :: ~ matrix ( ) { for (int i = 0: j < d1;i++) delete p[i]; delete p; } This is required because when the pointers to object go out of scope, a destructor is not called implicitly. The example below illustrates that the destructor has been implicitly by the compiler. #include<iostream.h> #include<conio.h> int count=0; class alpha { public: alpha() { count++; cout<<"\nNo.of object created"<<count; } ~alpha() { cout<<"\nNo.of object destroyed"<<count; count--; } }; void main() { clrscr(); cout<<"Enter MAIN"; alpha A1,A2,A3,A4; { cout<<"\n\nEnter Block\n"; alpha A5; } { cout<<"\n\nEnter Block2\n"; alpha A6; } cout<<"\nRE-ENTER MAIN\n";

Institute for Design of Electrical Measuring Instruments

- 111 -

getch(); } output ENTER MAIN No. No. No. No. of of of of object object object object created created created created 1 2 3 4

ENTER BLOCK 1 No. of object created 5 No. of object destroyed 5 ENTER BLOCK 2 No. of object created 5 No. of object destroyed 5 RE-ENTER MAIN No. No. No. No. of of of of object object object object destroyed destroyed destroyed destroyed 4 3 3 1

As the objects are created and destroyed they increase and decrease the count. Notice that after the first group of objects is created. A5 is created and then destroyed. A6 is created, and then destroyed. Finally, the rest of the objects are also destroyed. When the closing brace of scope is encountered, the destructors for each object in the scope are called. Note that the objects are destroyed in the reverse order of creation. void main() { cout<<"Enter MAIN"; alpha A1,A2,A3,A4; cout<<"\n\nEnter Block\n"; alpha A5; cout<<"\n\nEnter Block2\n"; alpha A6; cout<<"\nRE-ENTER MAIN\n"; } now use this code instead of above in main() and check output

Institute for Design of Electrical Measuring Instruments

- 112 -

Chapter 7 FUNCTION AND OPERATOR OVERLOADING FUNCITON OVERLOADING Overloading refers to the use of the same thing for different purposes. This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOPs. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number & type of the arguments but not on the function type. Example// declarations int add(int a, int b); //declaration1 int add(int a, int b, int c); //declaration2 double add (double x, double y); //declaration3 double add (int p, double q); //declaration4 // function calls cout << add (5, 10); // uses declaration1 cout << add (5, 10.3); // uses declaration4 cout << add (2, 3, 4); // uses declaration2 cout << add (2.3, 5.4); // uses declaration3 A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. The function selection involves following steps. The compiler first tries to find an exact match in which the types of actual arguments are the same & use that function. If an exact match is not found, the compiler uses the integral promotions to the actual argument, such as. char to int float to double to find a match. When either of them fails, the compiler tries to use built in conversions to the actual arguments & then uses the functions whose match is unique. If the conversion is possible to have multiple matches, then the compiler will generate an error. Ex long add(long n) double add(double m) A function call such as. add(20) will cause an error because int argument can be converted either long or double. For example

Institute for Design of Electrical Measuring Instruments

- 113 -

following program Illustrates function overloading. #include<iostream.h> #include<conio.h> int volume(int); double volume(double,int); long volume(long,int,int); void main() { clrscr(); cout<<volume(10)<<"\n"; cout<<volume(2.5,8)<<"\n"; cout<<volume(100L,75,15); getch(); } int volume(int s) { return(s*s*s); } double volume(double r,int h) { return(3.14*r*r*h); } long volume(long l,int b,int h) { return(l*b*h); } The output of program 1000 157.2595 112500 FUNCTION WITH DEFAULT ARGUMENTS The function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses & alerts the program for possible default values. For examplefloat amount (float principal, int period. float rate = 0.15); declares a default value to argument rate A function call like Value = amount (4000, 8); Passes the value of 4000 to principal and 8 to period and then lets the function use default value of 0.15 for rate. The call value = amount (3000, 5, 0, 12); passes an explicit value of 0.12 to rate. A default argument is checked for type at the time of call. Only the trailing arguments can have default values. We must add defaults from right to left we cannot provide a default value to a particular argument in the middle of an argument list.

Institute for Design of Electrical Measuring Instruments

- 114 -

For example#include<iostream.h> #include<conio.h> float value(float,int,float r=0.15); void printline(char ch='*',int len=10); void main() { float amount; clrscr(); amount=value(4000,8); cout<<"Final Value :"<<amount<<endl; printline(); cout<<endl; printline('='); getch(); } float value(float p,int n,float r) { int year=1; float sum=p; while(year<=n) { sum=sum*(1+ r); year=year+1; } return(sum); } void printline(char ch,int len) { for(int i=1;i<len;i++) cout<<ch; }

The output is
Final Value :12236.091797 ********* =========

INLINE FUNCITON Every time a function is called, it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack & returning to the calling function. When a function is small, lot of execution time may be spent in such overhead. Solution to this problem is to use macro definition, but because macros are not function, usual error checking does not occur during compilation.

Institute for Design of Electrical Measuring Instruments

- 115 -

To eliminate the cost of calls to small functions, c++ introduces inline function. When inline function is called, the compiler replaces the function call with corresponding function code. Syntax is inline function header { function body } Ex inline int cube (int a) { return (a * a * a); } this function can be called as c = cube(5); All inline functions must be defined before they are called. The speed benefits of inline functions decreases as function grows in size. Therefore functions are made inline when they are small enough to be defined in one or two lines. Following are situations where inline expansion may not works are: For functions returning values, if a loop, a switch, or a goto exists. For functions not returning values, if a return statement exists. If function contains static variables. If inline functions are recursive.

Example of inline function #include<iostream.h> inline int add(int x,int y) { return(x + y); } inline int subtract(int a,int b) { return(a-b); } void main() { int p=15; int q=10; cout<<add(p,q)<<"\n"; cout<<subtract(p,q)<<"\n"; } output of program. 25 5 OPERATOR OVERLOADING DEFINITION:

Institute for Design of Electrical Measuring Instruments

- 116 -

Overloading means assigning different meaning to an operation depending on the context. C++ permits overloading of operators, thus allowing us to assign multiple meanings to the operators. Example:The input/output operators << and >> are good examples of operator overloading although the built in definition of the << operator is for shifting of bits. It is also used for displaying the values of various data types. We can overload all the C++ operators except the following, Class member access operators (., . *) Scope resolution operator (: :) Size operator (sizeOf) Conditional operator (?:)

Defining operator overloading To define an additional task to an operator, operator function is used. The general form is Return type classname :: operator op (anglist) { } Where return type is the type of value returned by the specified operation and op is the operator being overloaded. Operator op is the function name. Operator functions must be either member functions or friend function. The difference is a friend function will have only one argument for unary operators and two for binary operators. While a member function has no arguments for unary operators and only one for binary operators. This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function. This is not case with friend function, because arguments may be passed either by value or by reference. Example Vector operator ( ) ; // unary minus Vector operator + (vector); // vector addition Friend vector operator + (vector, vector) // vector addition Friend vector operator (vector); // unary minus Vector operator (vector & a); // subtraction Int operator == (vector); // comparision Friend int operator == (vector,vector) //comparision The process of overloading involves Function body //task defined

Institute for Design of Electrical Measuring Instruments

- 117 -

Create a class that defines the data type that is to be used in the overloading operation. Declare the operator function operator op () in the public part of the class. It may be either a member or friend function. Define the operator function to implement the required operation.

Overloaded operator functions can be invoked by expressions such as. Op x or x op For unary operators and x op y for binary operators. And op x would be interpreted as operator op (x) for friend functions and x op y would be interpreted as x.operator op (y) in member function and operator op (x,y) in friend function. UNARY OPERATOR OVER LOADING In overloading unary operator, a friend function will have only one argument, while a member function will have no arguments. Let us consider the unary minus operator. A minus operator, when used as a unary takes just one operand. This operator changes the sign of an operand when applied to a basic data item. Following example shows how to overload this operator so that it can be applied to an object in much the same way as is applied to an int or float variables. #include<iostream.h> #include<conio.h> class unary { int x,y,z; public: void getdata(int a,int b,int c); void display(void); void operator -(); // overload unary minus. }; void unary::getdata(int a,int b,int c) { x=a; y=b; z=c; } void unary::display(void) { cout<<"\t"<<x<<"\t"<<y<<"\t"<<z<<"\n";

Institute for Design of Electrical Measuring Instruments

- 118 -

} void unary::operator -() { x=-x; y=-y; z=-z; } void main() { unary u; clrscr(); u.getdata(20,-30,40); cout<<"u :"; u.display(); -u; cout<<"u :"; u.display(); getch(); } output: u: u: 20 -20 -30 30 40 -40

The function operator ( ) takes no argument because this function is a member function of the same class, it can directly access the member of the object which activated it. It is possible to overload a unary minus operator using a friend function as follows : Friend void operator (unary & u); Void operator (unary & u) { u.x = -u.x; u.y = -u.y; u.z = -u.z; } The argument is passed by reference. It will not work if we pass argument by value because only a copy of the object that activated the call is passed to operator(). Therefore changes made inside the operator function will not reflect in the called object. BINARY OPERATOR OVERLOADING:In overloading binary operator, a friend function will have two arguments, while a member function will have one argument. Following example shows how to overload + operator to add 2 complex number #include<iostream.h> class complex { float x,y; public: complex() {

Institute for Design of Electrical Measuring Instruments

- 119 -

} complex(float real,float imag) { x=real; y=imag; } complex operator+(complex); void display(void); }; complex complex::operator+(complex c) { complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex::display(void) { cout<<x<<" +j"<<y<<"\n"; } void main() { complex c1,c2,c3; c1=complex(2.5,3.5); c2=complex(1.6,2.7); c3=c1+c2; cout<<"c1 = "; c1.display(); cout<<"c2 = "; c2.display(); cout<<"c3 = "; c3.display(); } output: c1 = 2.5 +j3.5 c2 = 1.6 +j2.7 c3 = 4.1 +j6.2 In the above program, the function operator +, is expected to add two complex values and return a complex value as a result but receives only one value as argument. The function is executed by the statement c3 = c1 + c2 Here, the object c1 is used to invoke the function and c2 plays the role of an argument that is passed to the function. The above statement is equivalent to c3 = c1.operator +(c2) Here, in the operator +() function, the data members of c1 are accessed directly and the data member of c2 are accessed using the dot operator. Thus in overloading binary operators, the left-hand operand is used to invoke the operator function and the right-hand operand is passed as an argument.

Institute for Design of Electrical Measuring Instruments

- 120 -

RULES FOR OVERLOADING OPERATORS Only existing operators can be overloaded. New operators cannot created. The overloaded operator must have at least one operand that is of user-defined type. We cannot change the basic meaning of an operator. That is, we cannot redefine the plus (+) operator to subtract one value from the other. Overloaded operators follow the syntax rules of the original operators. There are some operators that cannot be overloaded. We cannot use friend functions to overload certain operator. Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values. But, those overloaded by means of a friend return (din); function take one reference argument. Binary operators overloaded through a member function take one explicit argument and those which one overloaded through a friend function take two explicit arguments. When using binary operators overloaded through a member function, the left-hand operand must be an object of the relevant class.

Binary arithmetic operators such as +, - *, and / must explicitly return a value. They must not attempt to change their own arguments.

Institute for Design of Electrical Measuring Instruments

- 121 -

Chapter 8 INHERITANCE INTRODUCTION C++ supports the concept of reusability once a class has been written and tested, it can be adapted by other programmers to suit their requirements. This is basically done by creating new classes, reusing the properties of the existing ones. The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as base class or super class. And the new one is called as derived class or subclass. Types of Inheritance: Single Inheritance A derived class with only one base class, is called Single Inheritance.

B
Multiple Inheritance A derived class with several base classes, is called multiple Inheritance.

Institute for Design of Electrical Measuring Instruments

- 122 -

Hierarchical Inheritance The properties of one class may be inherited by more than one class is called hierarchical Inheritance.

Multilevel Inheritance The mechanism of deriving a class from another derived class is known as multilevel Inheritance.

BASE CLASS B INTERMEDIATE BASE CLASS

DERIVED CLASS

Hybrid Inheritance The hybrid Inheritance is a combination of all types of Inheritance.

DERIVED AND BASE CLASS Base class: -

Institute for Design of Electrical Measuring Instruments

- 123 -

A base class can be defined as a normal C++ class, which may consist of some data and functions. Ex Class Base { ::::: } Derived Class: A class which acquires properties from base class is called derived class. A derived class can be defined by class in addition to its own detail. The general form is Class derived-class-name: visibility-mode base-class-name { } The colon indicates that the derived class name is derived from the base-class-name. The visibility-mode is optional and if present it is either private or public. PUBLIC INHERITANCE When the visibility-mode is public the base class is publicly inherited. In public inheritance, the public members of the base class become public members of the derived class and therefore they are accessible to the objects of the derived class. Syntax is class ABC : public PQR { }; Where PQR is a base class illustrate public inheritance. Let us consider a simple example to illustrate public inheritance . #include<iostream.h> class Base { int no1; public: int no2; void getdata(); int getno1(); void showno1(); }; members of ABC :::::

Institute for Design of Electrical Measuring Instruments

- 124 -

class Derived:public Base // public derivation. { int no3; public: void add(); void display(); }; void Base::getdata() { no1=10; no2=20; } int Base::getno1() { return(no1); } void Base::showno1() { cout<<"Number1 ="<<no1<<"\n"; } void Derived::add() { no3=no2+getno1(); // no1 is private } void Derived::display() { cout<<"Number1 = "<<getno1()<<"\n"; cout<<"Number2 = "<<no2<<"\n"; cout<<"Sum = "<<no3<<"\n"; } void main() { Derived d; d.getdata(); d.add(); d.showno1(); d.display(); d.no2=100; d.add(); d.display(); } The output of the program is Number1 = 10 Number1 = 10 Number2 = 20 Sum = 30 Number1 = 10

Institute for Design of Electrical Measuring Instruments

- 125 -

Number2 = 100 Sum = 110 In the above program class Derived is public derivation of the base class Base. Thus a public member of the base class Base is also public member of the derived class Derived. PRIVATE INHERITANCE When the visibility mode is private, the base class is privately inherited. When a base class is privately inherited by a derived class, public members of the base class becomes private members of the derived class and therefore the public members of the base class can only be accessed by the member functions of the derived class. They are inaccessible to the objects of the derived class. Public member of a class can be accessed by its own objects using the dot operator. So in private Inheritance, no member of the base class is accessible to the objects of the derived class. Syntax is class ABC: private PQR { member of ABC } Let us consider a simple example to illustrate private inheritance. #include<iostream.h> class Base { int x; public: int y; void getxy() ; int get_x(void) ; void show_x(void) ; }; void Base::getxy(void) { cout<<"Enter Values for x and y : "; cin>>x>>y; } int Base::get_x() { return x; } void Base::show_x() { cout<<"x = "<<x<<"\n"; } class Derived:public Base { public: int z;

Institute for Design of Electrical Measuring Instruments

- 126 -

void mul(); void display(); }; void Derived::mul() { getxy(); z=y*get_x(); } void Derived::display() { show_x(); cout<<"y = "<<y<<"\n"; cout<<"z = "<<z<<"\n"; } void main() { Derived d; d. mul(); d.display() ; //d.x=4;// won't work x has become private. d.mul(); d.display(); } Output: Enter values for x and y: 510 X=5 Y = 10 Z = 50 Enter values for x and y:1220 X = 12 Class derived Y = 20 Z = 240

sectionis shown in following figure, The membership of the derived Private class derived

z y getxy() get_x() show_x() Public section

Inherited from Base

Institute for Design of Electrical Measuring Instruments

mul()

- 127 -

display()

File Handling in C++


stream:C++ Handles file Operations which uses file streams as an Interface between Program and Files. The stream that Supplies data to program is known as input stream and one that receives data from program is known as output stream.In other words Input stream reads data from file and output stream inserts data or writes data to file

Classes:1. ifstream:Provides Input Operation.Contains open() with default input mode.It inherits functions get(),getline(),read() from iostream 2. fstream:Provides support for simultaneous input and output operations contain open() with default input mode.Inherits all functions from istream and ostream classes through iostream. 3. ofstream:Provides output operations contains open() with default output mode.Inherits put(),write(),write() function from ostream. PROGRAM:#include<iostream.h> #include<conio.h> #include<fstream.h> void main() { ofstream fout; fout.open("countr"); fout<<"United state of america\n"; fout<<"United kingdom\n"; fout<<"South africa\n"; fout.close(); fout.open("capita");

Institute for Design of Electrical Measuring Instruments

- 128 -

fout<<"Washington\n"; fout<<"Landon\n"; fout<<"seoul\n"; fout.close(); const int N=80; char line[N]; ifstream fin; fin.open("countr"); cout<<"\nContent of country file\n"; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); fin.open("capita"); cout<<"\nContent of capital file\n"; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); getch(); }

2.WAP to show use of arithmetic Operation with use of File


#include<iostream.h> #include<fstream.h> #include<conio.h> void main() { clrscr(); ofstream outf("d:\\calculation.txt"); int a,b,c; cout<<"enter the value of a & b"; cin>>a>>b; outf<<"value of a"<<a<<"\nvalue of b"<<b<<"\n"; c=a+b; cout<<"Addition of a & b "<<c; outf<<"Additiion of a& b "<<c; outf.close(); ifstream inf("d:\\calculation.txt"); inf>>a>>b; inf>>c; cout<<"\nValue of a "<<a<<"\nvalue of b "<<b; cout<<"\nAddition of a & b "<<c; inf.close();

Institute for Design of Electrical Measuring Instruments

- 129 -

getch(); }

PROGRAMS FOR PRACTICE


1.wap to find square of first ten numbers and addition of that squares using pow math operator #include<iostream.h> #include<conio.h> #include<math.h> void main() { int i,s=0; clrscr(); i=1; do { s=s+pow(i,2); i++; } while(i<=10); cout<<"sum="<<s<<endl; getch(); }

2.WAP to show how access private members.


#include<iostream.h> #include<conio.h> class sample { int m; void read(); public: void update(); void write(); }; void sample::read() {

Institute for Design of Electrical Measuring Instruments

- 130 -

cout<<"Enter value of m"; cin>>m; } void sample::update(void) { read(); m=m*m; } void sample::write(void) { cout<<"Square of m"<<m; } void main() { clrscr(); sample s; s.update(); s.write(); getch(); }

3.WAP to show use of Function Overloading


#include<iostream.h> #include<conio.h> int vol(int); double vol(double,double); long vol(long,int,int); void main() { clrscr(); cout<<"Volume of cube = "<<vol(10)<<"cm"<<endl; cout<<"Volume of cylinder = "<<vol(4.5,2.5)<<"cm"<<endl; cout<<"Volume of box = "<<vol(100,75,15)<<"cm"; getch(); } int vol(int s) { return(s*s*s); } double vol(double r,double h) { return(3.14*r*r*h); } long vol(long l,int b,int h) { return(l*b*h); }

4.WAP to show use of array


#include<iostream.h>

Institute for Design of Electrical Measuring Instruments

- 131 -

#include<conio.h> void main() { int items[4]={10,8,12,15}; int cost[4]={75,100,60,99}; clrscr(); cout<<"items\t"; cout<<"cost\t"; cout<<"total value"<<"\n"; int sum =0; for(int i=0;i<4;i++) { cout<<items[i]<<"\t"; cout<<cost[i]<<"\t"; int value=items[i]*cost[i]; cout<<value<<endl; sum =sum+value; } cout<<"\nGrand total\t"; cout<<sum<<"\n"; getch(); }

5.WAP ,To show use of class with private and public members
//to print average marks of students #include<iostream.h> #include<conio.h> #include<stdlib.h> class student { int roll_no,m1,m2,m3; char name[30]; float avg,per; public: void store() { clrscr(); cout<<"Enter the roll no of student\n"; cin>>roll_no; cout<<"Enter the name of student\n"; cin>>name; cout<<"Enter the marks1,marks2 and marks3 of student\n"; cin>>m1>>m2>>m3; } void calculate() { avg=(m1+m2+m3)/3; per=(m1+m2+m3)/3;

Institute for Design of Electrical Measuring Instruments

- 132 -

} void print() { cout<<"\nRoll no of student is "<<roll_no; cout<<"\nName of student is "<<name; cout<<"\nmarks1 marks2 marks3 of student are "<<"\t"<<m1<<"\t"<<m2<<"\t"<<m3; cout<<"\nAverage marks of the student is "<<avg<<endl; cout<<"Percentage of the student is "<<per; } };

void main() { student stud; stud.store(); stud.calculate(); stud.print(); getch(); }

6.WAP to create objects with two different forms


#include<iostream.h> #include<conio.h> class student { int id,per; public: student(int,int); void display() { clrscr(); cout<<"ID NO OF A STUDENT : "<<id; cout<<"\nPERCENTAGE OF A STUDENT : "<<per; } }; student::student(int x,int y) { id=x; per=y; } void main() { student stud(1,87); cout<<"\nFIRST OBJECT"<<endl; stud.display(); /*student stud2=student(4,5); cout<<"\nSECOND OBJECT\n"; stud2.display();*/

Institute for Design of Electrical Measuring Instruments

- 133 -

getch(); }

Institute for Design of Electrical Measuring Instruments

- 134 -

You might also like