Anda di halaman 1dari 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

C, C++ Fundamentals

Compiled by H.Srimathi

Page 1 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Computer Basics 1. Program Development Life cycle Define the problem: Examine the problem until you understand it thoroughly. Outline the solution: Analyze the problem. Expand the outline of the solution into an algorithm: Write a step-by-step procedure that leads to the solution. Test the algorithm for correctness: Provide test data and try to work out the problem as the computer would. This is a critical step but one that programmers often forget. Convert the algorithm into a program: Translate the instructions in the algorithm into a computer program using any programming language. Document the program clearly: Describe each line of instruction or at least some important portions in the program. This will make the program easy to follow when accessed later for corrections or changes. Run the program: Instruct the computer to execute the program. The process of running the program differs from language to language. Debug the program: Make sure that the program runs correctly without any errors or bugs as they are called in computer terminology. Finding the errors and fixing them is called debugging. Dont get depressed when bugs are found. Think of it as a way to learn.

2. Algorithm An algorithm is a sequence of steps to complete the task. An algorithm is a step by step list of directions that need to be followed to solve a problem. The instructions should be simple enough so that each step can be done without thinking about it Example: To find sum of n natural numbers 1. Let sum = 0 2. Let i = 1 3. While i n do the following: a. Add i to sum b. Add 1 to i 4. Output sum

3. Flowchart A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a process.

Compiled by H.Srimathi

Page 2 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example 1: Find sum of first 50 natural numbers

Example 2: Find largest of 3 Numbers

Compiled by H.Srimathi

Page 3 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example 3: Find factorial of N

Compiled by H.Srimathi

Page 4 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

C Programming Fundamentals

Compiled by H.Srimathi

Page 5 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 1: Use scanf() and printf() functions

4. Introduction to C Language C is a general purpose, flexible, high-level, Structured Programming Language. C is developed by Dennis Ritchie. 5. Structure of C Program A C program is a collection of one or more functions. A function name is followed by a pair of parentheses (). Every program must have a special function named main(). This function can be located anywhere in the program. However the program starts execution from main function only. Statements within any function are always enclosed within a pair of curly brackets. The closing bracket } of the main function is signals the end of the program. 6. Simple C program # include <stdio.h.> void main() { printf( C welcomes you \n); } Explanation 1. # symbol implies that a preprocessor directive is invoked. include is a statement to include the header/source file. <stdio.h> is name of the standard input-output header file. This file contains several functions to perform input and output and display error messages. 2. main() is a function that tells the computer where the main body of the C program begins. In program, this main() may be preceded by several other functions. The compiler always seeks out the main() function and starts execution from there. 3. The curly {} bracket contain the block of statements. 4. printf() is a C function included in the stdio.h file to display the control string to the VDU. Executing a C program 1. Create the program 2. Compile the program 3. Link the program with functions that are needed from the C library 4. Execute the program

Compiled by H.Srimathi

Page 6 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

7. C Character Set The characters in C are grouped into the following categories: Letters: Upper case AZ, Lowercase aZ Digits: 09 Special characters: , . : ; ? ! ~ | \ / < > # $ % ^ & * ( ) { } [ ] + - _ = White spaces: Blank space, Horizontal tab, Carriage return, New line, Formfeed 8. Tokens in C In C program the smallest individual units are known as C tokens. They are: Identifiers, Keywords, Constants, Strings, Special Symbols and Operators Tokens Definition Example: Identifiers assigns names to files, Valid Identifiers: name, street, mark1, test1, functions, variables etc., product123, emp_name Invalid Identifiers: 1Prg, 2.4, A.B, A$B Keywords Reserved words that have auto, break, case, char, const, continue, default, standard, predefined do, double, else, enum, extern, float, for, goto, meanings in C if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while

9. Data types Data is used in a program to get information. C supports several different types of data, each of which may be represented differently within the computers. Different classes of data types are a) b) c) d) Primary data types User-defined data types: enumerated Derived data types: arrays, functions, structures and pointers Empty data set: void

There are basically 4 primary data types in C. Data type int Char Float Double Description Integer quantity Character value Number containing decimal point or exponent Double precision floating point numbers for more significant digits Size 2 bytes 1 byte 4 bytes 8 bytes Range of Value -32768 to 32767 ASCII character set 3.4E-38 to 3.4 E+38 1.7E-308 to 1.7E+308

Compiled by H.Srimathi

Page 7 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

10. Constants Constants are fixed values that do not change during the execution of a program. Integer constants It refers to a sequence of digits. Decimal Integers consist of a set of digits 0 thru 9, preceded by optional + /- sign. Example: 123, -321, 0, 45678,+71 Real constants / Floating point numbers Numbers with fractional part:23.4, -123.56 Numbers in exponential notation:2.1234e2 Single character constants It contains only a single character enclosed within a pair of single quote marks. Example: 5, x, : String Constants A group of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Example: 5678, a345,(sfsf)5+3 Backslash character constants These special characters are used in output functions . Each one of them represents one character, although they consist of two characters. These character combinations are known as escape sequences. Example: \n 11. Variables A variable is a data name that may be used to store a data value. A variable may take different values at different times during execution. Name of the variable must be a valid identifier. Declaration of the variables: int x; float y; char z; double b=45.6; /* declaration as well initialization */ char a[20]; /* to store string */ New line

Compiled by H.Srimathi

Page 8 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

12. Input / Output functions: scanf() and printf() a) scanf(): This function is used to get the value from the keyboard at run time. Example: scanf(%d, &test1); scanf(%f, &price); scanf(%c,&choice);

Variable Type int unsigned int Long unsigned long float character string Floating point numbers in the exponential form

Conversion Factor %d %u %ld %lu %f %c %s %e

b) printf(): This function is used to print the value on the console monitor. Example: printf(enter name \n); printf(price of the product = %d,price); 13. Comments in C Program: Comments (remarks) may appear anywhere within a program, as long as they are placed within delimiters /* and */. Example : /* sample program to demonstrate the input and output functions */

Compiled by H.Srimathi

Page 9 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 2: Arithmetic expressions

14. Operators and Expressions An operator is a symbol that is used for mathematical or logical manipulations. Operators can be classified into Arithmetic b) Relational c) Logical d) Assignment a) Arithmetic operators The arithmetic operators are divided into two types, namely the unary and the binary. (i) The binary arithmetic operators are: Binary Arithmetic Operator + * / % Evaluation of the expression: Integer Arithmetic Consider a is integer data type Instruction Result a=5+3 8 a=5-3 2 a=5*3 15 a=5/3 1 a= 5 % 3 2 Real or mixed mode arithmetic Consider a is real data type Instruction Result a=5+3 8.0 a= 5/3 1.0 a = 5.0 / 3 1.666667 a = 5.0 / 3.0 1.666667 The operator % cannot be used with real operands Meaning Addition Subtraction Multiplication Division Modulo Division Example a+b ab a* b a/b a% b

(ii) The unary operators are: Unary Arithmetic Operator + ++ -Meaning Unary + Unary Increment Decrement Example +a -a ++a (or) a++ --a (or) a--

Compiled by H.Srimathi

Page 10 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Pre Increment & Decrement: Increment or decrement done before using the values of the variables Instruction Equivalent Result Pre Instruction i =10; i =10; i = 11 i = i+1; x = ++i x = 11 x=i i =25; i = i-1; x=i i =25; x = --i; i = 24; x = 24;

Post Increment and Decrement: Increment or decrements are done after using the values of the variables. Instruction Equivalent Result Post instruction i =10; i =10; x = 10 x=i x = i++; i = 11; i = i+1; i =25; x = i; i = i-1; i =25; x = i--; x = 25; i =24;

(iii) Hierarchy of arithmetic operators: 1. 2. 3. 4. 5. 6. 7. 8. ( ) parenthesis ++ increment (____fix) -- decrement (____fix) ++ increment (____fix) -- decrement (____fix) + unary plus unary minus (negation) *, /, % multiplication, division and modulo in the order in which they occur from left to right 9. +, - plus and minus in the order they occur from left to right Example: Determine the hierarchy of operations and evaluate the expressions: i = 2* 3 / 4 + 4 /4 + 8-2 + 5 / 8 Stepwise evaluation of this expression i = 2* 3 / 4 + 4 /4 + 8-2 + 5 / 8 i = 6 / 4 + 4 /4 + 8-2 + 5 / 8 i = 1 + 4 /4 + 8-2 + 5 / 8 i = 1 + 1 + 8-2 + 5 / 8 i = 1 + 1 + 8-2 + 0 i = 2 + 8-2 + 0 i = 10-2 + 0 i=8+0 i=8

Compiled by H.Srimathi

Page 11 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(iv) Mixed Mode Operands and type conversion Automatic type conversion: Normally, statements and arithmetic expressions use variables and constants of only one type. However, if mixed mode operands in an expression, the result of the operation can have only one type. C uses a set of rules to make the type conversions automatically. Reading from left to right, the ranking types from lowest to highest is as given below, char < int < long < float < double < long double Example: int i = 2; float x = 3.5; x = x + i; Stepwise evaluation of the expression is as follows x=3.5 + 2 x = 3.5 + 2.0 /* automatic type conversion */ x = 5.5

Simple Program: Program to find area of circle #include<stdio.h> #include<conio.h> void main() { float radius, area; clrscr(); printf("Enter the radius of a circle=>"); scanf("%f",&radius); area=3.14159*radius*radius; printf("\nArea = %f",area); getch(); }

Compiled by H.Srimathi

Page 12 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 3: Conditional Statements

15. Types of Control Statements Real life application programs do not merely consist of simple multiplication or addition. They are written for solving complex problems. Depending on the occurrence of a particular situation, the program follows different paths of execution. The control statements available in C are: Conditional statements: a) Simple If statement b) If-Else statement c) Switch statement d) Goto statement Looping statements: e) While statement f) Do-while statement g) For statement

16. Relational operators There are 6 relational operators are used to compare the expression. The result of comparison is true or false. But there are no such logical constants or Boolean values in C. Therefore, any non-zero value (positive or negative) is taken to be true or 0 value is taken to false. Relational Operator == < <= > >= != Explanation Equal to Less than Less than or equal to Greater than Greater than or equal to Not equal to Example Expression Result 4==4 Non-zero 4<3 0 5 <= 4 0 5>4 Non-zero 5 >= 5 Non-zero 4 != 4 0

Compiled by H.Srimathi

Page 13 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

17. Logical Operators The logical operators are used to combine two relational expressions. Logical Explanation Operator && Logical AND || ! Logical OR Logical NOT Example OP 1 OP 2 Non- Nonzero zero Non- Zero Zero Nonzero

Expression 2 < 3 && 4 < 5 2 < 3 || 6 < 5 ! (2 < 3)

Result Non-zero Non-Zero Zero

18. Simple If statement

The if statement allows decision to be made by evaluating a given expression is true or false. The general form is as follows: if (expression) statement 1; statement 2; False Statement 2 True
expression

Statement 1

The if statement first evaluates the expression. If the result is true (a non-zero value), then the body of C statement 1 that immediately follow the if is executed, followed by statement 2. If the result is false(zero value) the statement 2 is executed. When several statements are to be executed, they are grouped into a block within curly brackets { }.

Compiled by H.Srimathi

Page 14 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example: # include <stdio.h> # include <conio.h> void main() { int deduction, purchase, amount; clrscr(); printf(enter the product purchased :); scanf(%d, &purchase); deduction =0; if (purchase > 5000) deduction = 400; amount = purchase deduction; printf( purchased amount = %d , amount); }

19. If-else Statement The general form is as follows: if (expression) statement 1; Statement 2 else statement 2; statement 3; Statement 3 The if statement first evaluates the expression. If the result is true (a non-zero value), then the body of C statement 1 that immediately follow the if is executed, followed by statement 3. If the result is false(zero value) the statement 2 is executed, followed by statement 3. Example # include <stdio.h> # include <conio.h> void main() { int mark; clrscr(); printf(enter your mark : ); scanf(%d, &mark); if (mark >=50) printf( \n grade = pass ); else printf( \n grade = fail); } Compiled by H.Srimathi Page 15 of 83 False
expression

True Statement 1

SRM

Univesity

C & C++ Fundamentals for non-computer science students

20. Nested If statement The statement following an if or else can be another if-else series of statements. Since the else clause is optional, the number of if and the else statements need not be equal. An else statement is paired with the most recent if statement which lacks an else.

if (expression1) if (expression2) statement 1; else statement 2; else statement 3; Example: # include <stdio.h> # include <conio.h> void main() { int mark; clrscr(); printf(enter your mark : ); scanf(%d, &mark); if (mark >=80) printf( grade = Distinction,); else if (mark >= 60) printf( grade = First class); else if (mark >=50) printf( grade = Second class); else printf( grade = fail); }

Compiled by H.Srimathi

Page 16 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

21. Use of logical operators in if statement Expressions in the if condition can be compound by using one or more logical operators. There are three logical operators. a) && - Logical AND The if statement first evaluates both the expression. If both the expression returns nonzero value, then the statement immediately follow if statement is executed. Example: # include <stdio.h> # include <conio.h> void main() { int a,b,c; clrscr(); printf(enter the numbers : ); scanf(%d%d%d, &a, &b,&c); if ((a >b) && (a > c)) printf(a is maximum); else if ((b>a) && (b >c)) printf(b is maximum); else printf (c is maximum); } b) || - Logical OR The if statement first evaluates both the expression. If any one of the expression returns non-zero value, then the statement immediately follow if statement is executed. Example: # include <stdio.h> # include <conio.h> void main() { int score1, score2; clrscr(); printf(enter the scores : ); scanf(%d%d, &score1, &score2); if ((score1 > 70) || (score2 > 70)) printf(\n eligible for final); else printf(\n not eligible for final); } Compiled by H.Srimathi Page 17 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(c ) ! Logical Negation. The ! operator is used to toggle the value of the evaluated expression. (ie) If the value of the expression is Non-zero, then ! operator negates it to zero and vice-versa. Example: # include <stdio.h> # include <conio.h> void main() { int score; clrscr(); printf(enter the scores : ); scanf(%d, &score); if ( ! ( score < 25)) printf (\n eligible for final exam) else printf(\n not eligible for final exam); } 22. Switch Statement The switch statement is used to check a single variable against multiple discrete values. The general form of switch statement is: switch(expression) { case value1: case value2: statement2: break; case valuen: statementn; break; default: statementn1; } The switch statement evaluates the expression that follows it and then transfers control to the statement following the case statement whose value equals the result of the switch expression, if no match is found and a default statement is present in the statement body, the control transfers to the statement following the default statement. If no match is found and there is no default statement, then the control transfers to the next statement Compiled by H.Srimathi Page 18 of 83

statement1; break;

SRM

Univesity

C & C++ Fundamentals for non-computer science students

following the switch statement body. Suppose the control finds a match with case value2, after executing the statements in the case value2, the control will go to the next case body unless there is a transfer of control. So it is necessary to put a break statement at the end of every case body to prevent this running on. The break statement will take the control out of the switch body. Example:

# include <stdio.h> # include <conio.h> void main() { int a=10, b=5,c; char choice; clrscr(); printf(enter your choice : ); scanf(%c, &choice); switch(choice) { case +: case -: c= a-b; break; default: printf(wrong choice \n); } printf(value of c = %d,c);

c= a+b; break;

Compiled by H.Srimathi

Page 19 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 4: Looping Statements 23. While statement The while statement is a loop statement that allow its body of its instruction to be executed as long as the expression returns non-zero value. Prior to each execution of the loop body, expression will be checked. If the loop body contains only one statement the curly bracket is not required. The general form is while (expression) { /* looping statements; */ }

Example: # include <stdio.h> # include <conio.h> void main() { int i, product; clrscr(); i =1; printf(multiplication table of 5\n); while (i <=10) { product = i * 5; printf( %d x 5 = %d \n, i, product); ++i; }

24. DoWhile statement The Do..while statement is a loop statement that allows its body of instructions in a do..while loop always execute atleast once. Since the expression checked only after executing the loop body. The loop body continues to be executed repeatedly as long as the expression is non-zero.The general form is: do { /* looping statements; */ } while (expression);

Compiled by H.Srimathi

Page 20 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Note: the semicolon is used at the end of while(expression) to terminate the dowhile statement. Example # include <stdio.h> # include <conio.h> void main() { int i=1; do { product = i * 5; printf( %d x 5 = %d \n, i, product); ++i; } while(i <=10); }

25. For statement The for statement is a loop statement that provides an initialization part, an expression evaluation for terminating the loop and apart to prepare for the next iteration of the loop. The general form is for( initial counter; test counter; increment counter) { /* looping statements */ } Example: To evaluate 1+2+3+.+10 # include <stdio.h> # include <conio.h> void main() { int i, sum; clrscr(); sum =0; for(i=1;i<=10;i++) { sum += i; } printf( sum of the series = %d, sum);

Compiled by H.Srimathi

Page 21 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

26. Nested For statement The for loops can be nested. It is essential that one loop completely embedded within the other there can be no overlap. Also each loop must be controlled by a different index. Example

# include <stdio.h> # include <conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf(%d\t , j); } printf(\n); }

Compiled by H.Srimathi

Page 22 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 5: One dimensional Array 27. Array An array is a group of data items of the same type that share a common name and differentiated from one another by their positions within the array. The position of each of these numbers is indicated by subscripts, which are integers and enclosed in square brackets. Such variables are called subscripted variables. Arrays can be one, two, three and even multidimensional. A one dimensional array of say 10 integers by name x is declared as int x[10]; The above declaration reserves 10 locations in the memory with names x[0], x[1], x[2]x[9] placed continuously. The first elements always starts from the subscript 0. The data type can be any of the predefined or even user defined data types. The first element of the array is accessed by calling x[0]. The second by x[1] and so on.

A one dimensional array can be initialized by putting the values inside the curly brackets. For example an integer array of 5 elements can be initialized as int y[5] = { 10,5,5,6,25 }

Compiled by H.Srimathi

Page 23 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example Program: #include <stdio.h> int main(void) { int numbers[10]; int count = 10; long sum = 0; float average = 0; printf("\nEnter the 10 numbers:\n"); int i; for(i = 0; i < count; i ++) { scanf("%d", &numbers[i]); sum += numbers[i]; }

average = (float)sum/count; printf("\nAverage of the ten numbers entered is: %f\n", average); return 0; }

Compiled by H.Srimathi

Page 24 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 6: Two dimensional Array 28. Two Dimensional Array In a two dimensional array, the data items are visualized to be arranged in a matrix form. A two dimensional array of integers by name a with 5 rows and 6 columns is declared as int a[5][6]; This declaration will reserve 30 locations in the main memory continuously with names a[0][0].a[0][5], a[1][0]a[1][5],.a[4][0]..a[4][5]. The first subscript refers to the row and the second subscript refers to the column.

Program to add and subtract matrix:

#include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],d[10][10],m, n, i, j; clrscr(); printf("enter the row and column size of matrix 1: m, n"); scanf("%d%d",&m,&n); printf("enter the matrix1"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } }

printf("\n\n enter the matrix2"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&b[i][j]); } }

Compiled by H.Srimathi

Page 25 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

/* matrix addition and subtraction */ for(i=0;i<m;i++) { for(j=0;j<n;j++) { c[i][j]=a[i][j]+b[i][j]; d[i][j]=a[i][j]-b[i][j]; } } printf("\n The resultant matrix(addition) is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) {printf("\t%d",c[i][j]); } printf("\n"); } printf("\n The resultant matrix of subtraction is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) {printf("\t%d",d[i][j]); } printf("\n"); } getch(); }

Program to multiply two matrices:

#include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],m, n, p, i, j, k; clrscr(); printf("enter the row and column size of matrix 1, m, n"); scanf("%d%d", &m, &n);

Compiled by H.Srimathi

Page 26 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

printf("enter the matrix1"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } printf("enter the matrix2"); printf("enter the row and column size of matrix 2, n, p"); for(i=0;i<n;i++) { for(j=0;j<p;j++) { scanf("%d",&b[i][j]); } }

/* matrix multiplication */ for(i=0;i<m;i++) { for(j=0;j<p;j++) { c[i][j]=0; for(k=0; k<n;k++) c[i][j] = c[i][j] + a[i][k]* b[k][j]; } } printf("\n The resultant matrix(addition) is:\n"); for(i=0;i<m;i++) { for(j=0;j<p;j++) {printf("\t%d",c[i][j]); } printf("\n"); } getch(); }

Compiled by H.Srimathi

Page 27 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 7: Functions 29. Library or predefined functions A library function is a predefined program built in the language. Such functions are automatically computed whenever they are invoked in a program using appropriate arguments. The corresponding header file must be included to make use of library function. a) Mathematical functions: Header file: math.h Function abs(i) ceil(d) floor(d) Type int double double Purpose returns the absolute value of i returns the smallest integer that is greater than or equal to d returns the highest integer that is less than or equal to d Example abs(-10) ceil(45.6) ceil(-43.4) floor(42.5) floor(-43.6) Result

b) string functions: Header file: string.h Function Type Purpose strlen(x) int Finds length of the string Strlwr string Converts a string to lowercase Strupr string Converts a string to uppercase Strcat string Appends one string at the end of another c)general functions header file: conio.h Function clrscr() getch(); getchar(); putchar(c ) Purpose to clear the content displayed in vdu read a single character read a single character write character one at a time to the terminal.

Example

Result

30. User Defined functions The most important reason to define the user defined function is to modularize the program with smaller reusable components. It reduces the program size. The function code appears only in one place in memory, but the function is executed many times in a course of the program.

Compiled by H.Srimathi

Page 28 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

All functions have the form return data_type function-name(argument list) { local variable declaration; statements; return(expression); } Example for Function Declaration: # include<stdio.h> int sum(int a, int b) {return(a+b); } void main() { int x, y,z; /* passing constant arguments to the function */ x = sum(4,5); printf(sum is %d\n, x); /* passing variables to the function */ printf(enter values for y and z\n); scanf(%d%d,&y,&z); x = sum(4,5); printf(sum is %d\n, x); } 31. Call by Value and Call by Reference Arguments passed to a function in one of the two ways: (a)sending the values of the arguments (call by value) In this method valueof each of the actual arguments in the calling functions is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. Example:

Compiled by H.Srimathi

Page 29 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

# include <stdio.h> void swap( int x, int y) { int t; printf( swap function: before swap x = %d and y = %d, x,y); t=x; x=y; y=t; printf( swap function: after swap x = %d and y = %d, x,y); }

void main() { int a= 10, b=20; printf(Main function: Before swap a= %d and b=%d, a,b); swap(a,b); printf(Main function: after swap a= %d and b=%d, a,b); }

(b) sending the address of the arguments (call by reference) In this method the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them.

Example: # include <stdio.h> void swap( int *x, int *y) { int t; printf( swap function: before swap x = %d and y = %d, *x,*y); t=*x; *x=*y; *y=t; printf( swap function:after swap x = %d and y = %d, *x,*y); } void main() { int a= 10, b=20; printf(Main function: Before swap a= %d and b=%d, a,b); swap(&a,&b); printf(Main function: after swap a= %d and b=%d, a,b); } Compiled by H.Srimathi Page 30 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

32.

Recursive Function

Recursion is a process by which a function calls itself repeatedly, until a specified condition has been satisfied. The process is used for repetitive computations in which action is stated in terms of previous result. For example, the factorial of a number is expression by a recursive formula: n! = n * (n-1) !

Example # include<stdio.h> long int fact(int x) { if x(==1) return 1; else return (x *fact(x-1); } void main() { long int factorial; factorial = fact(10); printf(factorial of 10 is %ld\n, factorial); }

Compiled by H.Srimathi

Page 31 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 8: Structures and pointers 33. Structures

A structure is a collection of simple variables, which can be of diverse data types. Some can be int, some can be float, some can be char and so on. Array is a collection of variables of same data type. But structure is used to represent a collection of data items of different data types using a single name. The data items in the structure are called the data members of the structure. The general form of the structure declaration is: struct structure_name { data_type member1; data_type member2; data_type member3; }; struct is a reserved word and tells the C compiler that a new structure is declared. The word struct is followed by its name, which is programmer coined. The members of the structure are enclosed within curly brackets. Each member is describe by its own declaration. Finally we have a semicolon to close off the definition of the structure like any other variable. Structure declaration has not declared any variables. It simply describes a format called template to represent information. Example: # include <stdio.h> struct student{ int rollno; char *name; int m1,m2,m3,total; }; void main() { struct student s; printf(\n enter input values\n); scanf(%d%s%d%d%d, &s.rollno, s.name, &s.m1, &s.m2,&s.m3); s.total = s.m1 + s.m2 + s.m3; printf( Rollno = %d, Name = %s, Total Marks = %d, s.rollno, s.name, s.total); }

Compiled by H.Srimathi

Page 32 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

34. Pointers Variables declared in program refer to specific memory locations in the computer memory. Every byte of computer memory has an address. Addresses are simply numbers just to identify the memory uniquely. If the memory size is 64 k then the highest memory address is 655359 and for 1 MB memory it is 1048575. Address operator: Consider the declaration: int j =5; This declaration tells the C compiler to: (a) reserve space in memory to hold the integer value. (b) Associate the name j with this memory location (c) Store the value 3 at this location. j location name 5 6485 value at the location location number / address

Representation of j in memory The address of a variable in the memory can be found using the address operator &. For example the address of a variable j is given by &j. Pointer variable: A variable that holds an address value is called a pointer variable or simply a pointer. A pointer variable is declared by putting an asterik mark infront of the name. For example, a pointer variable that holds the address of an integer is declared as int *a; The asterik means the pointer to. More examples on pointer variable char *x; /* pointer to char */ float *y; /* pointer to float */ When a variable is declared as pointer, initially it has no value. This means that it does not point to anything. To assign an address to a pointer, the programmer must assign it a value.

Compiled by H.Srimathi

Page 33 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

For example int *p, a=5; p = &a;

a 5 6485 This means, assign the address of a to p.

p 6485 3276

When the address of a data item is passed to the function, then any alteration made to the data item within the function, is carried over into the calling function. Example: # include <stdio.h> void func(int *x) { printf(*x=%d, *x * 10); /* } void main() { int k; k =50; func(&k); printf(k =%d,k); }

*x stores the value , x stores the address */

Compiled by H.Srimathi

Page 34 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 9: Additional Information

35.

Symbolic Constants

A symbolic constant also called a substitution constant is a same that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a string constant. The general form is # define name text For example # define PI 3.141

Later in the program one can write a statement as area = PI *r *r; The computation will be done by taking the value of PI as defined. In general, the constant name is written in all caps to distinguishing it from variables. Such constant values cannot be changed in the program. Constant definitions must be made before main(). 36. Strings

In C, Strings are considered as one dimensional array of characters terminated by a null. A string constant can be represented by enclosing its characters (without null) inside double quotes. For example one can write as Programming. This is actually a string of 12 characters, though there are only 11 characters. C will automatically insert the null characters at the end. A string variable to assign the value Programming is declared as char name[12]; You must provide one extra character for the null. If initialization is done in the declaration itself, the dimension need not be given explicitly. char name = Programming; In this case the size of the array will be determined automatically based on the number of initialization elements. Individual characters can be accessed by using the subscripts. For example the first character can be accessed by name[0], the second by name[1] and so on. Important Note: For assigning a string variable s2 to another string variable s1, one cannot write simply s1=s2. But one has to use the library function.

Compiled by H.Srimathi

Page 35 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Character arrays can be intialised in either of the following form: char x[8] =chennai; char y[] = chennai; char z[8] = {c,h,e,n,n,a,i}; Reading strings from terminal: The scanf function can be used with %s format specification to read in a string of characters. Example: char *city; /* array with unlimited size */ scanf(%s,city); The problem with the scanf function is that it terminates its input on the first white space it finds. (A white space includes blanks, tables, carriage returns, form feeds, and new lines). For example if the input value is Tamil Nadu, then only the string Tamil will be read into the array city, since the blank space after the word Tamil will terminate the string. To read the string with white space, we use the function gets(city) Writing strings to screen: The printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example printf(%s,city); puts(city); Combining two strings together: strcat() function is used to combine two strings. The general form is strcat(string1, string2); where string1 and string2 are character arrays. When the function strcat is executed, string2 is appended to string1. It does so by removing the null character at the ed of string1 and placing string2 from there. The string at string2 remains unchanged. For example: char *s1=hai; char *s2=welcome strcat(s1,s2); Before execution of strcat: s1 = h a s2 = w e

i l

\0 c o m e \0

Compiled by H.Srimathi

Page 36 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

after execution of strcat statement: h a i w e l c o m \0

Copying one string to another: The strcpy function works almost like a string-assignment operator. It takes the form strcpy(string1, string2); and assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. char *s1=hai; char *s2=welcome strcpy(s1,s2); Comparing strings for equality: The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are not, it has the numeric difference between the first characters in the strings. It takes the form strcmp(string1, string2) String1 and string2 may be string variables or string constants. Example: int i; i=strcmp(their,there); if the strcmp function returns 0 then the two strings are equal. If it returns negative the string1 is alphabetically above string2. Length of the string: The length of the string is found using strlen function. The general form is n=strlen(string) where n is the integer variable which receives the value of the length of the string. The argument may be a string variable or constant. The counting ends at the first null characters. Strings and Two dimensional arrays: A list of string values can be stored in two dimensional character array . For example: char capital[][2] = {chennai,delhi, culcutta, bombay}; To access the name of the ith capital in the list, we write capital[i-1];

Compiled by H.Srimathi

Page 37 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

sprintf and sscanf functions: The sprintf function works similar to the printf function with one different. Instead of sending the output to the screen as printf() does, this function writes the output to an array of characters. int i=10,b=20; float x = 34.5; char s = x; char *str; sprintf(str, %d%d %f %c,i,b,x,s); sscanf() function allows to read characters from string and to covert and store them in variables according to specified format. Read line of text from terminal /* to read a line of text from terminal */ # include <stdio.h> # include <conio.h> void main() { char line[81], c; int count=0; printf(enter text and press carriage return at the end\n); do { c=getch(); line[count++]=c; }while(character != \n); count = count-1; line[count]=\0; printf(\n %s\n, line); }

Compiled by H.Srimathi

Page 38 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

37. User defined data type C supports a feature known as type definition that allows users to define an identifer that would represent an existing data type. The user defined data type identifier can later be used to declare variables. a)typedef: It takes the general form: typedef type identifer; where type refers to an existing data type and identifier refers to the new name given to the data type. Example: typedef unsigned int units; They can be later used to declare variables as follows: units u1,u2; where u1 and u2 are declared as unsigned integers indirectly. b)enum: Its general form is: enum identifer {value1, value2,valuen}; The identifier is a user defined enumerated data type which can be used to declare variables that can have one of the values enclosed within the curly bracket (known as enumeration constants). After this definition, variables can be declared to be of this new type as follows: enum identifier v1,v2; The enumerated variables v1 and v2 can only have one of the values value1, value2valuen. Example: enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} enum day week_day; week_day=Monday; week_day=1;

Compiled by H.Srimathi

Page 39 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

38.More on operators
Assignment Operators Simple Assignment operators are used to assign the result of an expression to a variable. Example: a= 5; a = b + c;

Compound assignment or shorthand assignment operators: It can be applied only when the left hand side variable and the first variables in the right hand side expression or same. Statement with Statement with simple assignment operator shorthand operators a = a+5 a += 5 a=ab a -= b a = a* x/y a *= x / y a = a/b a /= b a=a%b a %=b Note: There is no blank space between the arithmetic and = operator Multiple assignment operators are carried our from right to left. Example a = b= 5; Stepwise of the above statement is b=5; a=b;

Other Special operators


(a) Conditional or ternary operator A ternary operator pair ?: is available in C to construct conditional expressions of the form exp1 ? exp2: exp3;

Compiled by H.Srimathi

Page 40 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

The operator ?: works as follows: exp1 is evaluated first. If it is non-zero, then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is zero, exp3 is evaluated and its value becomes the value of the expression. Note that only one of the expression either exp2 or exp3 is evaluated. Example C = (3 < 4) ? 3 : 4; /* value of C is 3 */

(b) Bitwise operator

C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. These operators can operate upon int and char, but not on float and double. Bitwise Operator & | << >> ~ ^ Meaning Bitwise AND Bitwise OR Shift Left Shift Right Ones complement Bitwsie XOR Example Result in Binary

Decimal Number 5&3 5|3 5 << 2 5 >> 2 ~5 5^3

Binary Number 0000 0101 & 0000 0011 0000 0101 | 0000 0011 0000 0101 << 2 0000 0101 >> 2 ~ 0000 0101 0000 0101 ^ 0000 0011

Result in Decimal

Compiled by H.Srimathi

Page 41 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(c) Comma operator The comma operator can be used to link the related expressions together. A commalinked list of expressions are evaluated left to right and the value of right most expression is the value of the combined expression. For example, the statement value = (x=10, y=5, x+y) first assigns the value 10 to x, then assigns 5 to y and finally assigns 15 to value. In for loops: for(i=1,j=1,i <=k, i++,j++) In while loops: while(a=getch(), a!=x) Exchanging values t=x, x=y, y=t; (d) sizeof operator

The sizeof is a compile time operator and, when used with an operand, it returns the number of bytes the operand occupies. Example: m = sizeof(sum); n = sizeof(long double); o = sizeof(456ul);

Compiled by H.Srimathi

Page 42 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Complete set of operator precedence Operator () [] + ++ -! ~ * & sizeof (type) * / % + << >> < <= > >= == != & ^ | && || ?: = *= /= %= += -= &= ^= |= <<= >>= , Description Function call / parenthesis Array element reference Unary plus Unary minus Increment Decrement Logical negation Ones complement Pointer reference (indirection) Address Size of an object Type cast (conversion) Multiplication Division Modulus Addition Subtraction Left shift Right shift Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional operator Assignment operators Associativity Order of Precedence Left to right 1 Right to left 2

Left to right

Left to right Left to right Left to right

4 5 6

Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left

7 8 9 10 11 12 13 14

Comma operator

Left to right

15

Compiled by H.Srimathi

Page 43 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

39. Formatted Input / Output a) Formatted Input: Formatted input refers to an input data that has been arranged in a particular format. Data type integer float string character Format %wd %w.pf %ws %wc Example scanf(%2d%2d,&i,&j); scanf(%5.3f,%,&g); scanf(%5s,name) scanf(%5c,name) Data line 50 314 56.45 vanitha vanvani Assigns

b) Formatted output: It refers to an output data that has been printed in a desired format. Data type integer float string character float exponential form float Format %wd %w.pf %ws %wc %w.pe Example printf(%4d,i) printf(%5.2f,j) printf(%3s,s) printf(%4c,k) printf(%4.2e,v) Value 24 56.45 vanitha vanvani 45.6789 Prints

printf(%*.*f,7,2,x) %*.*f, width, precision, number

67.3

40. Goto statement The goto statement is used to transfer control to some other statement or statement block within a function. It is called as unconditional control statement / jumping statement and usage of goto in a program is not entertained. It is not a good programming practice to use goto statement in the program. The label name is programmer coined. The general form is goto label; . label: statement;

Compiled by H.Srimathi

Page 44 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example: for(i=0; i<=10;i++) { scanf(%d, &a); if(a==5) goto correct; } printf(not correct); goto last; correct: printf(correct); last: printf(end of the program);

41. Break statement The break statement causes an immediate termination from the do, for, swtich, or while statement in which it appears. It is used to jumping out of a loop. The program continues executing the next statement following the do, for, switch or while statement. When the loops are nested, the break would only exit from the loop containing it. That is, the break will exit only a single loop. Example: do { scanf(%d, &x); if (x <0) { printf( negative value for x); break; } }while(x <=100);

42. Continue statement The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, the remaining loop statements skipped and the computation proceeds directly to the next pass through the loop. The continue statement can be included within a while, a do.. while or a for statement. Example:

Compiled by H.Srimathi

Page 45 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

for(i=1;i<=5;i++) { scanf(%d, &x); if (x==0) continue; printf(%d,x); } 43. Compare Do..while, While and For statement Dowhile 1. Loop will be executed atleast once While 1. Loop will be executed only if the expression evaluates nonzero value do while (expression) { { statement; statement; }while(expression); } For 1. Loop will be executed only if the expression evaluates non-zero value

for(initial counter; test counter; increment counter)

{ statement; }

Initialisation of the index variable is Initailisation, increment and testing the done before the looping statement expression is done in a single line Increment the index value is done inside the looping Testing the Testing the expression is done expression is done at the end of the at the beginning of loop the loop

44. Storage classes or Scope and Life time of the variables The complete definition of variable consists of two parts such as data type and its storage class. When a variable declaration not include any storage class specifier, then the compiler will assume a default storage class depending on the context in which the variable is used. A variable name identifies some physical location within the computer where the string of bits representing the variables value is stored. There are basically two kinds of locations in a computer where such a value may be kept: Memory and CPU registers. It is the variables storage class which determines in which of these two locations the value is stored. Storage class gives the information about

Compiled by H.Srimathi

Page 46 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(a) (b) (c) (d)

where the variable would be stored what will be the initial value of the variable, if the initial value is not specifically assigned. (ie. Default initial value) What is the scope of the variable,i.e. in which functions the value of the variable would be available (where it can be accessed - visibility) What is the life of the variable; i.e how long would the variable exist ( the time period between the creation and destruction of that variable)

There are four storage classes in C Automatic Memory Storage garbage value) Default initial value Local to the Scope block in which the variable is declared Till the control Life remains within the block in which the variable is defined

Register CPU register Garbage value Local to the block in which the variable is defined Till the control remains within the block which the variable is defined

Static Memory Zero Local to the block in which the variable is defined Value of the variable persists between different function calls

External Memory Zero Global

As long as the programs execution does not come to an end

(a) Automatic storage class: The moment the control comes out of the block in which the variable is defined, the variable and its value is irretrievably lost. Example # include <stdio.h> void main() { auto int i=1; { auto int i= 2; printf(%d, i); } printf(%d, i); } output: 2 1 (b) Register storage class: A value stored in a CPU can always be accessed faster than the one which is stored in memory. A good example of frequently used variable is counter in looping statement. Though a variable is declared as register variable, one may not sure about its register storage class, since there is limited number of registers available. Example register int a; Compiled by H.Srimathi Page 47 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(c ) static storage class: Like auto variables, static variables are also local to the block in which they are declared. The difference between them is that static variables does not disappear when the function is no longer active. Their value persist. If the control comes back to the same function again the static variables have the same values they had last time around. # include <stdio.h> void increment() { auto int i = 1; printf(%d,i) i++; } void main() { increment(); increment(); } output: 1 1 # include <stdio.h> void increment() { static int i = 1; printf(%d,i) i++; } void main() { increment(); increment(); } output: 1 2

(e)external storage class: The scope of external variable is global. External variables are declared outside all function. Example: # include <stdio.h> int j; void func() { printf(j = %d, k= %d,j, k) j++; } void main() { extern int k; k =50; func(); printf(j = %d, k =%d,j,k); } Output: 0 50 1 50

Compiled by H.Srimathi

Page 48 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

45. The C preprocessor Preprocessor processes source program before it is passed to the compiler. Preprocessor directives begin with a # symbol. a)Macro expansion: During preprocessing, the preprocessor replaces every occurrence of Macro definition with the value assigned for it. Example # include <stdio.h> # define PI 3.1415 void main() { float r = 4.5; float area; area = PI * r * r; printf(area of circle =%f, area); } (b) Macros with arguments: Macros can have arguments just as functions can. # include <stdio.h> # define AREA(x) (3.14*x*x) void main() { float x; printf(area of circle %f, AREA(4.5)); } (i)Do not include blank between the macro template and its argument. AREA ( 4.5 ) is wrong. (ii)The entire macro expansion should be enclosed within the parenthesis. # define AREA(X) 3.14*x*x is wrong. (iii) Calling Macro do not allow expression as arguments c= AREA(a*b) is wrong . (c ) Macros Versus Function: (i)Function allows flexibility in parameter passing. Function allows expression in parameters. (ii)Macro expansion goes into source code at all the places, thus increase the program size, however function is stored only once in memory and referred whenever required.

Compiled by H.Srimathi

Page 49 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

46. Pointers and one dimensional array Consider the defined array int x[5] = {125,136,121,167,345}; x[0] x[1] 125 136 4000 4002 x[2] x[3] x[4] 121 167 345 4004 4006 4008 address

The name x gives the address of the first element x[0] of the array. *x refers the 0th element of the array. By giving *(x+1) one can refer the 1st element of the array. All the following notations are same: (a) x[j] (b) *(x+j) (c) *(j+x) (d) j[x] /* Program illustrates the use of pointers in single dimensional arrays */ # include <stdio.h> void main() { int x[5] = {125,136, 121, 167,345}; int *p, j; p=x; /* pointer p assigns the address of first element x[0] */ printf(\n array values accessed using subscripts \n ); for(j=0;j<5;j++) printf(%d , x[j]); printf(\n address of array elements are \n ); for(j=0;j<5;j++) printf(%d , x+j); printf(\n array values accessed through the addresses are \n ); for(j=0;j<5;j++) printf(%d , *(x+j)); printf(\n array values accessed through pointers are \n ); for(j=0;j<5;j++) printf(%d , *(p+j)); }

Compiled by H.Srimathi

Page 50 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

One dimensional arrays passed as arguments to function /* program to illustrate the passing of arrays to function using pointers */ # include <stdio.h> void modify(int *p) { int j; for(j=0;j<3;j++) *p++ =5; } void main() { int a[3], count; for(count=0;count<3;count++) a[count]=4; printf(\n Before calling modify function\n); for(count=0;count<3;count++) printf(%d\n,a[count]);

modify(a); printf(\n after calling modify function\n); for(count=0;count<3;count++) printf(%d\n,a[count]); }

47. Pointers and two dimensional arrays The C language treats parts of arrays as array. (ie) each row of a two dimensional array can be though of as a one dimensional array. Example

int x[4][2] = {{4,5},{6,7},{3,2},{1,81}}; The above int x[4][2] can be thought of as setting up a one dimensional array of 4 elements, each of which is a one dimensional array of 2 element. x[0] gives the address of the 0th element of the 0th row (first one dimensional array). x[1] gives the address of the 0th element of 1st row (second one dimensional array ) and so on. x+0 is interpreted as x[0] (0th row, 0th column) and x+1 is interpreted as x[1] (1st row, 0th column). To reach element in individual row *(*(x+row)+col) is used.

Compiled by H.Srimathi

Page 51 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

x pointer to first row x+i pointer to ith row *(x+i) pointer to first element in the ith row *(x+i)+j pointer to jth element in the ith row *(*(x+i)+j) value stored in the cell (i,j) /* Program to illustrate the pointers and two dimensional array */ # include <stdio.h> void main() { int x[4][2] = {{4,5},{6,7},{3,2},{1,81}}; int row, col; printf(\n address of each one dimensional array for(row=0;row <4;row++) printf(\n %d th one dimensional array =%d, row, x[row]);

printf(\n Print two dimensional array value using pointers \n); for(row=0;row<4;row++) { for(col=0;col<2;col++) printf( %d , *(*(x+row)+col)); printf(\n); } }

48. Arrays of pointers Array of pointer is declared to store collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other address. /* addresses of isolated variables to array of pointers */ int *p[3]; int a = 2,b = 43,c = -57; p[0]= &a; p[1]=&b; p[2]=&c;

Compiled by H.Srimathi

Page 52 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

/* array of pointers can even contain the addresses of other arrays */ int a[3] = {12,45,67}; int *p[3] = {a, a+1, a+2}; p *p *(*p) gives the address of p[0] gives the address of a[0] gives the value of a[0]

49.Two dimensional arrays passed as arguments to the function # include <stdio.h> void modify(p) int p[2][2]; { int i,j; for(i=0;i<2;i++) for(j=0;j<2;j++) *(*(p+i)+j) = 4; } void main() { int a[2][2]={1,2,3,5}; printf("\nbefore modification %d", a[0][2]); modify(a); printf("\n after modification%d", a[0][2]); }

50. Pointers to functions A function like a variable, has an address location in the memory. It is therefore possible to declare a pointer to a function, which can then be used as an argument in another function.

Compiled by H.Srimathi

Page 53 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

/* Program illustrates that uses a function pointer as function argument */ # include <stdio.h> int sq(int a) { return (a*a); } int func(fp) int (*fp)(); { int value; value = (*fp)(4); return value; } void main() { int s; s= func(sq); printf("%d",s); }

51. More on Structures a) Arrays within the structure # include <stdio.h> struct student{ int rollno; char *name; int m[3],total; }; void main() { struct student s; int count; printf(\n enter input values\n); scanf(%d%s, &s.rollno, s.name,); s.total =0; for(count=0;count<3;count++) { scanf(%d,&s.m[count]); s.total +=s.m[count]); } printf( Rollno = %d, Name = %s, Total Marks = %d, s.rollno, s.name, s.total); } Compiled by H.Srimathi Page 54 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(b) Arrays of structures # include <stdio.h> struct student{ int rollno; char *name; int m[3],total; }; void main() { struct student s[4]; int count,i; for(i=0;i<4;i++) { printf(\n enter input values\n); scanf(%d%s, &s[i].rollno, s[i].name,); s[i].total =0; for(count=0;count<3;count++) { scanf(%d,&s[i].m[count]); s[i].total +=s[i].m[count]); } printf(rollno = %d, name = %s,total marks = %d\n, s[i].rollno, s[i].name, s[i].total); } } (c) structures within structures # include <stdio.h> struct student{ int rollno; char *name; struct {int m[3]; }mark; total; }; void main() { struct student s[4]; int count,i; for(i=0;i<4;i++) { printf(\n enter input values\n); scanf(%d%s, &s[i].rollno, s[i].name,); s[i].total =0; for(count=0;count<3;count++) { scanf(%d,&s[i].mark.m[count]); s[i].total +=s[i].mark.m[count]); } printf(rollno = %d, name = %s,total marks = %d\n, s[i].rollno, s[i].name, s[i].total); } } Compiled by H.Srimathi Page 55 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(d) Passing structures to a function Like an ordinary variable, a structure variable can also be passed to a function. We may pass entire structure as argument to the function. # include <stdio.h> struct student{ int rollno; char *name; int m1,m2,m3,total; }; void display(struct student x) { printf( Rollno = %d, Name = %s, Total Marks = %d, x.rollno, x.name, x.total); }

void main() { struct student s; printf(\n enter input values\n); scanf(%d%s%d%d%d, &s.rollno, s.name, &s.m1, &s.m2,&s.m3); s.total = s.m1 + s.m2 + s.m3; display(s); } (e) Structures and Pointers We can have a pointer pointing to a struct. Such pointers are known as structure pointers. The symbol -> is called the arrow pointer to refer to the structure of elements # include <stdio.h> struct student{ int rollno; char *name; int m1,m2,m3,total; }; void main() {struct student s; struct student *sp; sp = s; printf(\n enter input values\n); scanf(%d%s%d%d%d, &s.rollno, s.name, &s.m1, &s.m2,&s.m3); s.total = s.m1 + s.m2 + s.m3; printf(Rollno=%d, Name=%s,Total Marks = %d, sp->rollno, sp->.name, sp->.total); }

Compiled by H.Srimathi

Page 56 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(f)Array of structures and pointers # include <stdio.h> struct student{ int rollno; char *name; int m1,m2,m3,total;

};

void main() { struct student s[3]; struct student *sp; sp = s; printf(\n enter input values\n); while(sp < s+3) { scanf(%d%s%d%d%d,&sp->rollno, sp->name, &sp->m1, &sp->m2,&sp->m3); sp->total = sp->m1 + sp->m2 + sp->m3; printf(Rollno=%d, Name=%s,Total Marks = %d, sp->rollno, sp->.name, sp->.total); sp++; } } (G)Passing address of a structure variable # include <stdio.h> struct student{ int rollno; char *name; int m1,m2,m3,total;

};

void display(struct student *x) { printf(Rollno=%d,Name = %s,Total Marks = %d, x->rollno,x->name, x->total); } void main() { struct student s; printf(\n enter input values\n); scanf(%d%s%d%d%d, &s.rollno, s.name, &s.m1, &s.m2,&s.m3); s.total = s.m1 + s.m2 + s.m3; display(&s); }

Compiled by H.Srimathi

Page 57 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(h) Self-Referential structures It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type. In general terms, this can be expressed as struct tag { member 1; member 2; struct tag *name; }; where name refers to the name of a pointer variable. Thus, the structure of type tag will contain a member that points to another structure of type tag. Such structures are known as self-referential structures. Example: struct single_list { int value; struct single_list *next; }; Self-referential structures are very useful in applications that involve linked data structures, such as lists and tress.

52.Union
Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Example union item { int itemcode; float price; int quantity; float amount; }; union item purchase; /* to declare a variable purchase of union item */ Sharing of storage locations by union members:

|---------itemcode--------| |---------------------price----------------------------| |---------quantity--------| |---------------------amount-------------------------|

Compiled by H.Srimathi

Page 58 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union. In the declaration above, the member price and amount requires 4 bytes.

53. File Management


Files are required to store data permanently on the disk and read whenever necessary. A file is a place on the disk where a group of related data is stored. File manipulation functions available in C Function Name fopen() fclose() getc() putc() fprintf() fscanf() getw() putw() fwrite() fread() fseek() ftell() rewind() Description Creates a new file,Opens an existing file for use Closes a file which has been opened for use Reads a character from file Writes a character to a file Writes a set of data values to a file Reads a set of data vales from a file Reads an integer from a file Writes an integer to a file writes a set of data values to file reads a set of data values from file Sets the position to a desired point in the file Gives the current position in the file Sets the position to the beginning of the file

(a) Defining and Opening a File: Example: FILE *fp; fp = fopen(filename, mode); Mode r w Meaning Open an existing file for read only Open a new file for writing only. If a specified file currently exists, it will be destroyed and a new file created in its place Open an existing file for adding data at end. A new file will be created if the file with the specified name does not exist Open a new file for both reading and writing Open an existing file for both reading and writing Open an existing file for both reading and appending

w+ r+ a+

Compiled by H.Srimathi

Page 59 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(b) Closing a file: A file must be closed as soon as all the operations on it have been completed. This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental misuse of the file. Example fclose(fp); (c) reading and writing a data in a file using getc() & putc() function: # include <stdio.h> # include <conio.h> void main() {FILE *fp; char c; printf(enter data into a file); fp = fopen(datafile, w); /* create or open file name data using write mode */ while((c = getchar()) != EOF) putc(c,fp); /* write a character to file */ fclose(fp); printf(display the information fromfile); fp= fopen(datafile,r); while((c=getc(fp)) != EOF)* read character from file */ printf(%c,c); fclose(fp); } (d) reading and writing a data in a file using getw() & putw() function: (integer data) # include <stdio.h> # include <conio.h> void main() { file *fp; int value, count; printf(enter data into a file); fp = fopen(datafile, w); /* create or open file name data using write mode */ for(count=1; count<=3;count++) {scanf(%d, &value); putw(value,fp); /* write a character to file */ } fclose(fp); printf(display the information fromfile); fp= fopen(datafile,r);

Compiled by H.Srimathi

Page 60 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

while((value=getw(fp)) != EOF) /* read character from file */ printf(%d,value); fclose(fp); } (e) reading and writing a data in a file using fgets() and fputs() function: # include <stdio.h> void main() { FILE *fp; char s[80]; fp = fopen(test.txt,w); if(fp== null) { puts(cannot open file); exit(1); } printf(enter a few lines of text\n); while(strlen(gets(s)) >0) { fputs(s,fp); fputs(\n); } fclose (fp); fp = fopen(test.txt,r); if(fp== null) { puts(cannot open file); exit(1); } printf(information from the file\n); while(fgets(s,79,fp)) !=NULL) { puts(s); } fclose (fp); }

Compiled by H.Srimathi

Page 61 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(f) reading and writing a data in a file using fscanf() and fprintf() to handle a group of mixed data simultaneously # include <stdio.h> void main() { FILE *fp; int itemcode,quantity; float unitprice, amount; int count; fp = fopen(itemfile,w); for(count=1;count<=2; count++) { printf(enter itemcode, quantity, unitprice \n); scanf(%d%d%f%f, &itemcode, &quantity, &unitprice, &amount); fprintf(fp,%d %d%f%f, itemcode, quantity, unitprice, amount); } fclose(fp); fp = fopen(itemfile,r); while(!feof(fp)) { fscanf(fp,%d%d%f%f, &itemcode, &quantity, &unitprice, &amount); printf(%d%d%f%f,itemcode, quantity, unitprice,amount) ; } flcose(fp); }

(g) reading and writing a data in a file using fread() and fwrite() Some application involve the use of data files to store blocks of data, where each block consists of fixed number of contiguous bytes. Each block will generally represent a complex data structure, such as structure or an array. The function fread() and fwrite() are intended to beused in situations of this types. Each of these functions require four arguments such as a pointer to data block, size of the data block, the number of data block being transferred, and the stream pointer.

Compiled by H.Srimathi

Page 62 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

# include <stdio.h> struct inventory { int itemcode,quantity; float unitprice, amount; }; void main() { FILE *fp; struct inventory item; int count; fp = fopen(itemfile,w); for(count=1;count<=2; count++) { printf(enter itemcode, quantity, unitprice \n); scanf(%d%d%f%f, &item.itemcode, &item.quantity, &item.unitprice, &item.amount); fwrite(&item,sizeof(item), 1, fp); } fclose(fp); fp = fopen(itemfile,r); while(!feof(fp)) { fread(&item,sizeof(item),1,fp); printf(%d%d%f%f,itemcode, quantity, unitprice,amount) ; } flcose(fp); }

(i) fseek function The disk file has distinct advantage over the other types of files, such as the monitor, keyboard, printer etc., Disk file is said to be direct access, as any characters can be written to or read from an exact location of the file. The general form of fseek is fseek(file pointer, argument1, argument2); The first parameter is the FILE pointer, which enables operation upon the open file.

Compiled by H.Srimathi

Page 63 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

The second and third parameters are used to specify the repositioning according to the following rules. The second parameter, argument1 is long integer; it may be a constant or variable. If the third parameter, argument2 can assign any one of the three integers 0: beginning position 1: relative position 2: end position Example: fseek(fp, 6L,0) It indicates that file pointer is positioned to the 7th character of the file from the beginning. fseek(fp, -4L,1) It indicates that file pointer is positioned back 4 characters from the current position fseek(fp, 2L,2) It indicates that file pointer is positioned back 2 characters from the end of file. Statement fseek(fp,0L,0) fseek(fp,0L,1) fseek(fp,0L,2) fseek(fp,m,0) fseek(fp,m,1) fseek(fp,-m,1) fseek(fp,-m,2) (j) ftell function ftell returns the present position of the file marker. The function must be furnished with the file pointer as argument. It returns a long itn as the file position. Consider the following statements which return the size or total number of bytes of a file. The size is in long int. fseek(fp, 0L, 2); number_of_bytes = ftell(fp); Here fseek positions the marker on the last character of the file, while number_of_bytes contains the size of the file, in number of bytes. Meaning Go to the beginning Stay at the current position Go to the end of file, past the last character of the file Move to (m+1)th byte in the file Go forward by m bytes Go backward by m bytes from the current positon Go backward by m bytes from the end

Compiled by H.Srimathi

Page 64 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

(k) rewind(): rewind takes a file pointer and resets the position to the start of the file. For example, the statement rewind(fp); n =ftell(fp); would assign 0 to n because the file position has been set to the start of the file by rewind. Remember the first byte in the file is numbered as 0, second as 1 and so on.

(j) Error handling during I/O operations It is possible that an error may occur during I/O operations on a file. If we fail tocheck such read and write errors, a program may behave abnormally when an error occurs. An unchecked error may result in a premature termination of the program or incorrect output. Typical error situations include: Trying to read beyond the end of file mark Device overflow Trying to use a file that has not been opened Trying to perform an operation on a file, when the file is opened for another type of operation Opening a file with an invalid filename attempting to write to a write-protected file

feof(): The feof() function can be used to test for an end of file conditon. It takes a FILE pointer as its only argument and returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. Example: if(feof(fp)) printf(end of data \n); ferror(): The ferror function reports the status of the file indicated. It also takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected upto that point during processing. It returns zero otherwise. The statement if(ferror(fp)!= 0) printf(an error has occured \n);

Compiled by H.Srimathi

Page 65 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

54. Command line arguments


A command line argument is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. For example to copy the X_file to Y_file , the command line is like C:> program X_file Y_file program is the filename where the executable code of the program is stored. The command line arguments are passed with the help of main function arguments. main() function can take two arguments called argc and argve and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system. The variable argc is an argument counter that counts the number of arguments on the command line. The argv is an argument vector and represent an array of character pointers that point to the command line arguments. The size of this array will be equal to the value of argc. For the above command line argc is three and argv is an array of three pointers to strings as argv[0] program argv[1] X_file argv[2] Y_file

Example program: # include <stdio.h> void main(int argc, char *argv[]) { int count; for(count=0;count<argc;count++) printf(%s, argv[count]); }

55.Dynamic Memory allocation


Real time programmings are dynamic in nature. That is the number of data items keep changing during execution of the program. Such situations can be handled more easily and effectively by using dynamic data structures in conjunction with dynamic memory management techniques. The process of allocating memory at run time is known as dynamic memory allocation. Although C does not inherently have this facility, there are four library functions known as memory management functions that can be used for allocating and freeing memory during program execution. They are

Compiled by H.Srimathi

Page 66 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Function malloc calloc free realloc

Task allocates requested size of bytes and returns a pointer to the first byte of the allocated memory allocates space for an array of elements, intialises them to zero and return a pointer to the memory frees previously allocated space modifies the size of previously allocated space

Memory allocation process: The conceptual view of storage of a C program in memory is Local variables Free memory Global variables C program instructions The program instructions, global and static variables are stored in a permanent storage area. Local variables are stored in stack. The memory space that is located between these two regions is available for dynamic memory allocation. The free memory region is called the heap. The size of the heap keeps changing when program is executed due to creation and destruction of variables that are local to functions and blocks. Therefore, it is possible to encounter memory overflow during dynamic memory allocation process. In such situations, the memory allocation functions mentioned above return a NULL pointer(when they fail to locate enough memory requested). Allocating a block of memory: It can be done by using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. The malloc allocates a block of contiguous bytes. The allocation can fail if the space in the heap is not sufficient to satisfy the request. If if fails, it returns a NULL. The general form is ptr = (cast-type *) malloc(byte-size); Example: int *p; p = (int *) malloc(100 *sizeof(int)); on successful execution of this statement, a memory space equivalent to 100 times the size of an int bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer p of type of int. Example for complex data type: struct item *sp; sp = (struct item *) malloca(sizeof(struct(item));

Compiled by H.Srimathi

Page 67 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Allocating Multiple blocks of Memory: calloc is normally used for requesting memory space at run time for storing derived data types such as arrays and structures. While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all bytes to zero. The general form of calloc is ptr = (cast-type *) calloc(n,elemnt-size); Example: struct item { int itemcode, quantity; float unitprice, amount; }; struct item *p; p = (struct item *) malloc(30, sizeof(struct item)); if(p== NULL) { printf(available memory not sufficient); exit(1); } Releasing the used space: The release of storage space becomes important when the storage is limited. Block of allocated memory is released with the help of free function free(p); Altering the size of a block: realloc is used to allocate more space, when the previously allocated memory is not sufficient. For Example, the original allocation is int *p; p = (int *) malloc(100 *sizeof(int)); the reallocation is p = realloc(p, 400); This function allocates a new memory space of size to the pointer variable. The new size may be larger or smaller than the size. Remember, the new memory block may or may not begin at the same place as the old one. The function guarantees that the old data will remain intact.

Compiled by H.Srimathi

Page 68 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

C++ Fundamentals

Compiled by H.Srimathi

Page 69 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 10: Classes and Objects 35. Object Oriented Characteristics (i) Data is more emphasized. (ii) Data and functions that operate on data are bind together as object. (iii) Real world things are directly mapped into objects in the model, which minimizes the semantic gap. (iv) Data structures are designed to characterize the objects. (v) Data is hidden and cannot be accessed by external functions. (vi) Follows bottom-up goal driven approach (Requirements are analyzed in terms of users who use and affect the system). (vii) Seamless transition of software development is achieved by using same Meta language for various phases. (viii) Communication of objects is achieved only through proper interfaces. 36. OO Concepts: Term Object Definition A person, place, thing, concept, event, screen, or report. Object is a software unit packaging together data and methods to manipulate the data. Defines the general structure of similar kinds of objects. Objects that share the same operations / method and common characteristics are grouped into a class. So it is template for creating objects. Data item defined as part of a class or object. Procedure or function defined as part of a class; refers the implementation. An instruction to invoke some action on object. It is a request sent to an object to execute one of its methods. Packaging data and operations into an object. Allows essential operations and data to be public without including their background details. Making the encapsulated data of an object inaccessible and invisible to other objects. Mechanism for defining a new class in terms of an existing class. Capability of a method to be applied to objects of different types; Ability to hide different implementations behind a common interface. kind of polymorphism (compile time), which allows two, or more methods use the same name with different parameter list.

Class

Attribute Method Message Encapsulation Data Abstraction Data hiding Inheritance Polymorphism Overloading

Compiled by H.Srimathi

Page 70 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

37.Simple Program # include <iostream> int main () { cout << "Hello World!"; return 0; } Explanation: // my first program in C++ This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. #include <iostream> Lines beginning with a pound sign (#) are directives for the preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program. cout << "Hello World"; This line is a C++ statement. cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the screen). cout is declared in the iostream standard file. 38. Program using Input and Output function

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. #include <iostream> int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; return 0; }

Compiled by H.Srimathi

Page 71 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

39. Class Declaration Classes are generally declared using the keyword class, with the following format class class_name { access_specifier_1: member1; access_specifier_2: member2; ... }; Where class_name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, or optionally access specifiers. These specifiers modify the access rights that the members following them acquire:

private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. public members are accessible from anywhere where the object is visible.

By default, all members of a class declared with the class keyword have private access for all its members. Example: // class example #include <iostream> class Csquare { int x; public: void set_value (int); int area () {return (x*x);} }; void Csqaure::set_value (int a) { x = a; int main () { CSquare sq; sq.set_values (3); cout << "area: " << sq.area(); return 0;} }

Compiled by H.Srimathi

Page 72 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

We must use the operator of scope (::) to specify that we are defining a function that is a member of the class Csquare and not a regular global function Example 2: // program to read two integers and add their sum // using object & class # include <iostream.h> class demo { public : int a,b,c; void getdata(); void sum(); void putdata(); }; void demo :: getdata() { cout<<"enter a,b values"<<endl; cin>>a>>b; } void demo :: sum() { c = a+b; } void demo :: putdata() { cout<<"value of a"<<a<<endl; cout<<"value of b"<<b<<endl; cout<<"value of c"<<c<<endl; } void main() { demo obj1; obj1.getdata(); obj1.sum(); obj1.putdata(); }

Compiled by H.Srimathi

Page 73 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Example 3: // program to do basic arithmetic operations # include <iostream.h> class arith { int a,b; public: void getdata(); void putdata(); int addn(); int subn(); int muln(); int divn(); }; void arith :: getdata() { cout<<" enter a, b values"<<endl; cin>>a>>b; } void arith :: putdata() { cout<<" The values of a, b are "<<a<<", "<< b<<endl; cout<<"Addition value is "<<addn()<<endl; cout<<"Subtraction value is "<<subn()<<endl; cout<<"Multiplication value is "<<muln()<<endl; cout<<"Division value is "<<divn()<<endl; } int arith :: addn() { return(a+b); } int arith :: subn() { return(a-b); } int arith :: muln() { return(a*b); } int arith :: divn() { return(a/b); } void main() { arith obj1; obj1.getdata(); obj1.putdata(); }

Compiled by H.Srimathi

Page 74 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 10: Constructors and Destructors 40. Constructor Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. A class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void. // class example #include <iostream> class Csquare { int x; public: Csquare (int); int area () {return (x*x);} }; Csqaure:: Csqaure(int a) { x = a;} int main () { CSquare sq(3); cout << "area: " << sq.area(); return 0;}

Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created. Also they do not have any return value; not even void. 41. Destructors The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value. The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.

Compiled by H.Srimathi

Page 75 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

// class example #include <iostream.h> class Csquare { int x; public: Csquare (int); ~Csquare(); int area () {return (x*x);} }; Csqaure:: Csqaure(int a) { x = a;} // constructor Csquare::~Csquare () { delete x; } // destructor

int main () {

Csquare sq(3); cout << "area of sq: " << sq.area(); return 0;} 42. Overloaded Constructors More than one constructor with different arguments is called overloaded constructors. // class example #include <iostream.h> class Csquare { int x; public: Csquare(); // constructor 1 Csquare (int); // constructor 2 ~Csquare(); int area () {return (x*x);} }; Csqaure:: Csqaure(){ x = 0;} // constructor 1 Csqaure:: Csqaure(int a) { x = a;} // constructor 2 Csquare::~Csquare () { delete x; } Compiled by H.Srimathi Page 76 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

void Csqaure::set_value (int a) { x = a;}

int main () { // object declaration using constructor 1 Csquare sq1(); sq1.set_value(3); Cout << area of sq1 <<sq1.area(); // object declaration using constructor 2 Csquare sq2(3); cout << "area of sq2: " << sq2.area(); return 0;}

Compiled by H.Srimathi

Page 77 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 11: Single Inheritance 43. Inheritance

A key feature of C++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its "parent's" members, plus its own. Classes that are derived from others inherit all the accessible members of the base class. The accessibility rule is given in: Access Members of the own class Members of the derived class Not Members 44. Types of Inheritance Inheritance Type Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance Hybrid Inheritance Definition It represents a sub class with only one super class It represents a sub class with more than one super class It represents a super class with more than one sub class. It represents a sub class (sub sub class) derived from another sub class It represents the combination of multiple and multilevel inheritance Public Yes Yes Yes Private Yes No No Protected Yes Yes No

Compiled by H.Srimathi

Page 78 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

45.Single Inheritance

// program to explain single inheritance # include <iostream.h> class student { private : int regno; char name[20]; public: void getdata(); void putdata(); }; void student :: getdata() { cout<<"enter register no"<<endl; cin>>regno; cout<<"enter name "<<endl; cin>>name; } void student :: putdata() { cout<<"Register no :"<<regno<<endl; cout<<"Name of the student :"<<name<<endl; } class htwt : public student { int ht,wt; public: void getvalue(); void putvalue(); }; // student class inherited in htwt class

void htwt :: getvalue() { getdata(); // invoke student class function cout<<"enter height and weight "<<endl; cin>>ht>>wt; }

Compiled by H.Srimathi

Page 79 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

void htwt :: putvalue() { putdata(); // invoke student class function cout<<"Height of the student is "<<ht<<endl; cout<<"weight of the student is "<<wt<<endl; } void main() { htwt obj1; obj1.getvalue(); obj1.putvalue(); }

Compiled by H.Srimathi

Page 80 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 12: Function Overloading 46.Function overloading In C++ two different functions can have the same name if their parameter are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. For example

// overloaded function #include <iostream> int mul (int a, int b) { return (a*b); } float mul (float a, float b) { return (a*b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << mul (x,y); cout << "\n"; cout << mul (n,m); cout << "\n"; return 0; } In this case we have defined two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two ints as its arguments it calls to the function that has two int parameters in its prototype and if it is called with two floats it will call to the one which has two float parameters in its prototype. Notice that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type

Compiled by H.Srimathi

Page 81 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

Exercise 13: Operator Overloading

47.Overloading operators C++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example: int a, b, c; a = b + c; This is obviously valid code in C++, since the different variables of the addition are all fundamental types. Nevertheless, it is not so obvious that we could perform an operation similar to the following one: struct { string product; float price; } a, b, c; a = b + c; In fact, this will cause a compilation error, since we have not defined the behavior our class should have with addition operations. However, thanks to the C++ feature to overload operators, we can design classes able to perform operations using standard operators. Here is a list of all the operators that can be overloaded Here you have an example that overloads the addition operator (+). // illustrate operator overloading for + operator # include <iostream.h> class complex { float x,y; public: void getdata(); void result(); friend complex operator +(complex, complex); };

void complex :: getdata()

Compiled by H.Srimathi

Page 82 of 83

SRM

Univesity

C & C++ Fundamentals for non-computer science students

cout<<"enter real value"<<endl; cin>>x; cout<<"enter imaginary value"<<endl; cin>>y;

} void complex :: result() { cout<<"Resultant complex number"<<endl; cout<<" Real value is " <<x<<endl; cout<<" Imaginary value is"<<y<<endl; } complex operator +(complex a, complex b) { complex temp; temp.x = a.x + b.x; temp.y = a.y + b.y; return(temp); } void main() { complex obj1,obj2, obj3; obj1.getdata(); obj2.getdata(); obj3 = obj1 + obj2; // operator overloading obj3.result(); }

Compiled by H.Srimathi

Page 83 of 83

Anda mungkin juga menyukai