c and c++ notes

August 18, 2017 | Author: Sean Norman | Category: Data Type, Subroutine, C (Programming Language), Control Flow, Variable (Computer Science)
Share Embed Donate


Short Description

Download c and c++ notes...

Description

C Programming Chapter

Topic

Page No.

1

BASICS OF C PROGRAM

2

2

VARIBLES IN C

4

3

KEYWORDS IN C

7

4

OPERATORS

8

5

CONDITIONAL CONSTRUCTS

17

6

FUNCTION IN C

35

7

ARRAY

41

8

STRUCTURE

46

9

POINTER

52

10

File HANDLING

59

11

PROGRAMS FOR PRACTICE

66

Institute for Design of Electrical Measuring Instruments

-1-

C++ Programming

Chapter

Topic

Page No.

1

C++ FUNDAMENTALS

77

2

BASIC DATA TYPES IN C++

82

3

VARIABLES IN C++

85

4

OPERATORS

86

5

CLASS AND OBJECTS

89

6

CONSTRUCTORS AND DESTRUCTORS

103

7

FUNCTION AND OPERATOR OVERLOADING

112

8

INHERITANCE

121

9

FILE HANDLING WITH STREAM

127

PROGRAMS FOR PRACTICE

129

10

Institute for Design of Electrical Measuring Instruments

-2-

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

Institute for Design of Electrical Measuring Instruments

-3-

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

Institute for Design of Electrical Measuring Instruments

-4-

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

Institute for Design of Electrical Measuring Instruments

-5-

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

Institute for Design of Electrical Measuring Instruments

-6-

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

Institute for Design of Electrical Measuring Instruments

-7-

Chapter 3 KEYWORDS IN C Reserved words or keywords have a predefined meaning in the C programming language. Keywords cannot be used as identifiers. C has a set of 32 keywords specified always in lowercase. If used in uppercase, they are not recognized as keywords. Table lists the various keywords in the C programming language: Keywords in C auto break case char else enum void const

extern float goto long if struct volatile default

register switch continue int do union short for

static signed return double while typedef sizeof unsigned

Institute for Design of Electrical Measuring Instruments

-8-

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

Institute for Design of Electrical Measuring Instruments

-9-

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

Institute for Design of Electrical Measuring Instruments

- 10 -

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

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

Institute for Design of Electrical Measuring Instruments

- 11 -

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

is not allowed.

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

Institute for Design of Electrical Measuring Instruments

- 12 -

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

Institute for Design of Electrical Measuring Instruments

- 13 -

e.g. printf("how are you."); printf has two argument, separated by a comma. e.g. printf("Entered value is %d", i); "Entered value is %d" represents a format control string, the function of which is to control the conversion and formatting of the following argument. Above string contains : • •

Plain characters such as familiar text means ("Entered value is") Conversion specification such as %d. These are not displayed as a text but act as a format for the following arguments of a %d is a format for decimal int.

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

Institute for Design of Electrical Measuring Instruments

- 14 -

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

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

Institute for Design of Electrical Measuring Instruments

- 15 -

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

Institute for Design of Electrical Measuring Instruments

- 16 -

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

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

Institute for Design of Electrical Measuring Instruments

- 17 -

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

Assignment statement Declaration statement Functional statement etc.

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

Institute for Design of Electrical Measuring Instruments

- 18 -

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

PROGRAM:

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

Institute for Design of Electrical Measuring Instruments

- 19 -

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

Institute for Design of Electrical Measuring Instruments

- 20 -

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

Institute for Design of Electrical Measuring Instruments

- 21 -

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

Institute for Design of Electrical Measuring Instruments

- 22 -

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

Institute for Design of Electrical Measuring Instruments

- 23 -

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

Institute for Design of Electrical Measuring Instruments

- 24 -

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

Institute for Design of Electrical Measuring Instruments

- 25 -

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

Institute for Design of Electrical Measuring Instruments

- 26 -

e Occurrence of ‘e' character within 'incremented ' string is 3 times Program to concatinate any two strings #include void main() { int i,j,k; char str1[50],str2[50]; /* declaration of two string*/ i=j=0; clrscr(); printf("Enter the first string \n"); scanf("%s",&str1); printf("Enter the second string \n"); scanf("%s",&str2); while(str1[i++]); /* finding the length of str1*/ while(str2[j++]); /* finding the length of str2*/ i--; /* last position is a NULL character*/ for(k=0;k1) { value=value*p; p=p-1; /* or p--*/ } /* end of while */ return(value); }/* end of a function */ Output Enter a number 5 Factorial of 5 is 120 Above program is the example of function passed by a value. Consider the above program, before starting the program with main function. there is a declaration of a function. Until now, we seen the declaration of data type. Declaration of a function means, declaration of a function's return value type. long factor (int p) means factor is a function. Its Return type is of long. int p is a parameter passed to a function having integer type. p is called as a argument to factor function. Argument means value passed to a function. From a main program, it will accept a value from terminal. To calculate its factorial value. here scanf() function is used as scanf(" \n%d", & num); It clears previous buffer & from the new line it reads a value for num variable. Next statement is result = factor (num); Here factor is a function called with num as a argument. Control transfers to where details about factor function is written. long factor (int p).It is a function header with p is a parameter. It will take a value of num variable, which is already passed from main (function) program. Just

Institute for Design of Electrical Measuring Instruments

- 38 -

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

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

Institute for Design of Electrical Measuring Instruments

- 39 -

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

Institute for Design of Electrical Measuring Instruments

- 40 -

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

Institute for Design of Electrical Measuring Instruments

- 41 -

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

Institute for Design of Electrical Measuring Instruments

- 42 -

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

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

Institute for Design of Electrical Measuring Instruments

- 43 -

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

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF