0% found this document useful (0 votes)
66 views

Programming in 'C++'

The document provides an overview of key concepts in C++ programming including input/output functions, data types, operators, control flow statements, arrays, functions and classes. It discusses the main components of a C++ program and covers topics like header files, streams, tokens and console input/output functions like getchar(), putchar() and gets().

Uploaded by

paroothi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Programming in 'C++'

The document provides an overview of key concepts in C++ programming including input/output functions, data types, operators, control flow statements, arrays, functions and classes. It discusses the main components of a C++ program and covers topics like header files, streams, tokens and console input/output functions like getchar(), putchar() and gets().

Uploaded by

paroothi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

~ ~ ~ INDEX ~ ~ ~
TOPIC PAGE 02 INTRODUCTION of C++ ....................................................................... ..................... 02 ~ 04 HEADER FILE & INPUT/OUTPUT OPERATORS ................................. ..................... 04 ~ 05 CONSOLE I/O FUCTIONS ...................................................................... ..................... 05 ~ 06 KEYWORDS, PUNCTUATORS & IDENTIFIERS ................................... ..................... 06 ~ 11 OPERATORS ............................................................................................ ..................... 11 DATA TYPES ............................................................................................ ..................... 12 CONSTANT, VARIABLES & ESCAPE SEQUENCE ............................ ..................... 12 ~ 14 IF STATEMENT ....................................................................................... ..................... 14 ~ 15 SWITCH STATEMENT ............................................................................. ..................... 15 ~ 16 FOR LOOP ............................................................................................... ..................... 16 ~ 17 WHILE LOOP ........................................................................................... ..................... 17 DO-WHILE LOOP ................................................................................... ..................... JUMP STATEMENTS ............................................................................... ..................... 18 ~ 20 20 ~ 21 ARRAY & its TYPES ................................................................................. ..................... FUNCTIONS ............................................................................................ ..................... 21 ~ 22 22 ~ 23 RETURN STATEMENT ............................................................................ ..................... 23 ~ 24 STRUCTURE ............................................................................................ ..................... CLASS, INHERTANCE ............................................................................. ..................... 24

Note: If you find any typing or printing error/s, inform immediately to your branch office.
PROGRAMMING WITH C++

ADCPM

Page - 1

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

Introduction of C++ The C++ programming language was developed at AT&T Bell Laboratories in the early 1980 by Bjarne Stroustrup. It was found C lacking for simulations and decided to extend the language by adding features from the language, Simula 67. Simula 67 was one of the earliest object oriented languages. The name C++ was coined by Rick Mascitti where ++ is the C increment operator. Thus C++ flashes out to deal with problems encountered by users and through discussions at AT &T . Features of Program The first statement of the program instructs the compiler to include the header file iostream.h which defines basic input/output facilities. The second statement main() defines a function called main. Curly braces, { }, are used to express grouping in C++, here they indicates the start and end of the body of the function main(). # include Directive The # include directive instructs the compiler to read and include another file in the current file. The compiler compiles the entire code. A header file may be included in one of two ways. #include<iostream.h> or #includeiostream.h The header file in angle brackets <and> means that file reside in standard include directory. The header files in double quotes means that file reside in current directory. Program: #include"stdio.h" #include"iostream.h" #include"conio.h" void main( ) { char A[100]; cout<<"Input a string"; gets(A); puts(A); getch(); } Header File in C++: C++ contains only statements, not any built in functions. The C++ language does not, within the actual definition of the language, provide any method of performing I/O operations. Therefore, functions that help to perform I/O operations and some other operations, that can not directly perform using C++ basic statements, are stored together in the form of a library. These stored functions can be called and used for the required operations. The C++ library of functions of same category under separate files known as header files. stdio.h This header file defines types and macros needed for the standard I/O package. When you include iostream.h file in your program, this file automatically gets included in your program. The standard functions contained in stdio.h are: feof clearer fclose fcloseall fdopen fgetpos fflush fgetc fgetchar ferror fprintf fileno flushall fopen fgets
Page - 2

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

fputc fscanf fwrite perror putw scanf strerror vfprintf

fputchar fseek getc printf remove setbuf tempnam vfscanf

fputs fsetpos getchar putc rename setvbuf tmpfile vprintf

fread fsopen gets putchar rewind sprintf tmpram vscanf

freopen ftell getw puts rmtmp streror ungetc vsprintf

string.h This header file declares several string manipulations and memory manipulates routines. The functions contained in string.h are: memcpy memccpy memchr memcmp movedata memmove memset memicmp strchr stpcp strcat movemem strcspn strcoll strcpy strcmp strcmpi strerror stricmp strdup strncmp strlwr strncat strlen strnset strncpy strnicmp strncmpi strset strrchr strew strpbrk strupr strstr strtok strspm ctype.h If you want to use some character function, you have to include ctype.h file. isdigit isalnum isalpha touppet isupper islower tolower iostream.h This header file declares the basic C++ streams I/O routines. Some of the functions are: read open close get getline clear put seekg seekp write flush ignore peek putback tellp fail bad cout cin good The header file iostream.h is included in every C++ program to implement input/output facilities. I/O library: Input and Output operations are supported by the istream(input stream) and ostream(output stream) classes. Stream Objects for Input and Output: cin: cin as istream class object tied to standard input. cin stands for console input. cout: cout is an ostream class object tied to standard output. cout stands for console output. Input/Output Operators: Input coming from the user terminal, referred to as standard input is tied to the predefined iostream cin and output directed to the user terminal referred to as standard output, is tied to the predefined iostream cout.
ADCPM

PROGRAMMING WITH C++

Page - 3

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

Output operator <<: The output operator << (cout) is used to direct a value to standard output. Input operator >>: The input operator >> (cin) is used to read a value from standard input. Console I/O functions The header file for above functions is stdio.h. getchar( ): The getchar( ) function returns a single character from a standard input device (keyboard). It takes no parameter and the returned value is the input character. The general form of the getchar( ) function is: A = getchar( ) ; The variable A is of the character type. It inputs a character from the keyboard and assigns it to variable A. putchar( ): The putchar( ) function takes one argument, which is the character to be sent to output device. It also returns this character as a result. The general form of the putchar( ) function is: putchar(ch) ; Program: # include<iostream.h> # include<stdio.h> #include<conio.h> void main( ) { char ch; ch=getchar( ) ; putchar(ch); getch(); } gets( ): The gets( ) function gets a string terminated by a newline character from the standard input stream stdin. The gets( ) replaces the newline by a null character (\0). It also allows input string to contain white space characters (spaces, tabs); gets return when it encounters a newline; everything upto the newline is copied into A. Program: # include<stdio.h> # include<iostream.h> #include<conio.h> void main( ) { char A[100]; cout<<Input a string; gets(A); puts(A); getch(); } The getch( ) and getche( ): The general form of the getch( ) and getche( ) is: ch=getche( ) ; ch1= getch( ) ;
Page - 4

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

ch and ch1 are the variables of character type. They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character. The value of the character returned from getche( ) is assigned to ch. The getche( ) function echoes the character to the screen. Another function, getch( ), is similar to getche( ) but does not echo the character to the screen. Program: # include<iostream.h> # include<conio.h> void main( ) { char ch; int chcnt=0,wdcnt=1; while((ch= getche( ))!=\r) { if(ch== ) wdcnt++ ; else chcnt++ ; } cout<<No. of characters <<chcnt<<\n; cout<<No. of words <<wdcnt; } TOKENS The smallest individual unit in a program is known as a token. C++ has following tokens: Keywords: Keywords are the words that convey a special meaning to the language compiler. These are reserved for special purpose and must not be used as normal identifier. asm auto break case catch char class const continue default delete do double else enum extern float for friend goto if inline integer lang new Operator Private Protected Public Register Return Short signed sizeof static struct switch template this throw try typedef union unsigned virtual void volatile while

Punctuators: Punctuators are also known as separators in C++. The following characters are used as punctuators: # [] () {} , ; : = [ ] (Brackets): Opening and closing brackets indicates single and multidimensional array subscripts. ( ) (Parentheses): Opening and closing parentheses indicate function calls and function parameters. { } (Braces): Opening and closing braces indicates the start and end of a compound statement. , (Comma): It is used as a separator in a function argument list. ; (Semicolon): It is used as a statement terminator. Every executable statement is terminated by a semicolon. : (Colon): It indicates a labeled statement.
ADCPM

PROGRAMMING WITH C++

Page - 5

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

(Asterisk): It is used for pointer declaration. Asterisk is also used as an operator to either pointer or as the multiplication operator. = (Equal to sign): It is used for variable initialization and as an assignment operator in expressions. # (Pound sign): The pound sign is used for preprocessor directive. Identifiers Identifiers are fundamental building blocks of a program and are used as the general terminology for the names given to different parts of the program. Example: MARKS = 50 The symbol = is an assignment operator. The significance of the above statement is that MARKS is a symbolic name for a memory location where the value 50 is being stored. A symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rules for the formation of an identifier are: An identifier can consist of alphabets, digits or underscores. It must not start with a digit. C++ is case sensitive, i.e., upper case and lower case letters are considered different form each other. It may be noted that TOTAL and total are two different identifier names. It should not be a reserved word. Operators: C++ offers different classes of operators: arithmetic, relational, logical, increment, decrement, conditional etc. C++ has some special operators for particular task. Each operator performs a specific task it is designed for. The operations are represented by operators and the objects of the operations are referred to as operands. Arithmetic Operator: It provides operators for five arithmetic calculations: addition, subtraction, multiplication, division and remainder which are +, -, , / and %. Each of these operators is Binary operators. Operators that act upon two operands are referred as Binary Operator. + (Addition) operator: The arithmetic binary operator + adds values of its operands and the result is the sum of the values of its operands. Its operands may be of integer or float types. Example: c=4+20; (c=24); Program: #include<iostream.h> #include<conio.h> void main() { int a,b,result; a=5; b=7; result=a+b; cout<<The result of the two values is <<result; getch(); } Result is 12
Page - 6

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

- (Subtraction) operator: This operator subtracts the second operand from the first. Its operands may be of integer or float types. Example: c=20-4; (c=16); Program: #include<iostream.h> #include<conio.h> void main() { int a,b,result; a=7; b=5; result=a-b; cout<<The result of the two values is <<result; getch(); } Result is 2 (Multiplication) operator: This operator multiplies the values of its operands. Its operands may be of integer or float types. Example: c=20 4; (c=80); Program: #include<iostream.h> #include<conio.h> void main() { int a,b,result; a=7; b=5; result=ab; cout<<The result of the two values is<<result; getch(); } Result is 35 / (Division) operator: This operator divides its first operand by the second. Its operands may be of integer or float types. Example: c=20/4; (c=5); Program: #include<iostream.h> #include<conio.h> void main() { int a,b,result; a=25; b=5; result=a/b;
ADCPM

PROGRAMMING WITH C++

Page - 7

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

cout<<The result of the two values is<<result; getch(); } Result is 5 % (Modulus) operator: This operator finds the modules of its first operand relative to the second. It produces the remainder of dividing the first by the second operand. Both operands must be integer types. Example: c=21/4; (c=1); Program: #include<iostream.h> #include<conio.h> void main() { int a,b,result; a=22; b=3; result=a/b; cout<< The result of the two values is<<result; getch(); } Result is 1 Logical Operators: C++ provides three logical operators to combine existing expressions. These are || (OR), && (AND) and ! (NOT) logical operators. || (OR) operator: This operator combines two expressions which make its operands. The logical OR operator evaluates to true, if either of its operands evaluates to true. This operator is used while testing evaluating expressions. Example: (5==8) || (5==5) Result into 1(true) because second expression is true. && (AND) operator: It is used to combines two expressions into one. The resulting expression has the value 1 (true) only if both of the expressions are true. Program: #include<iostream.h> #include<conio.h> void main() { int a,b,c; a=6; b=4; c=7; if((a>b)&&(a>c)) cout<<"\n A is greater "<<a; else if((b>c)&&(b>a)) cout<<"\n B is greater "<<b;
Page - 8

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

else cout<<"\n C is greater "<<c; getch(); } ! (NOT) operator: This operator works on single expression or operand. It is a unary operator. It negates or reverses the truth value of the expression, it means if the expression is truth, the answer is false and when expression is false, then answer is true. ? Conditional Operator: This operator stores a value depending upon a condition. This operator is ternary operator. It requires three operands. Syntax: Expression1? Expression2 : Expression3 Program: #include<iostream.h> #include<conio.h> void main() { int a,b,c,large; cout<<"Enter three no."; cin>>a>>b>>c; large=a>b?(a>c?a:c):(b>c?b:c); cout<<"The largest no. is "<<large<<"\n"; getch(); } Relational Operators: Relational refers the relationship that values can have with one another. This operator determines the relation among different operands. < (Less than) Syntax: value1<value2 Program: #include<iostream.h> #include<conio.h> void main() { int a,b; clrscr(); a=6; b=4; if(a<b) cout<<"\n A is smaller "<<a; else cout<<"\n B is smaller "<<b; getch(); } <= (Less than or equal to) Program: #include<iostream.h> #include<conio.h> void main() { int i;
ADCPM

PROGRAMMING WITH C++

Page - 9

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

clrscr(); for(i=1;i<=10;i++) cout<<\n<<i; getch(); } > (Greater than) Syntax: value1>value2 Program: #include<iostream.h> #include<conio.h> void main() { int a,b; clrscr(); a=6; b=4; if(a>b) cout<<"\n A is smaller "<<a; else cout<<"\n B is smaller "<<b; getch(); } >= (Greater than or equal to) Program: #include<iostream.h> #include<conio.h> void main() { int i; clrscr(); for(i=10;i>=1;i--) cout<<\n<<i; getch(); } Assignment Operator The assignment operator = stores the value of the expression on the right hand side of the equal sign to the operand on the left hand side. In addition to standard assignment operator shown above, C++ also supports compound assignment operators. C++ provides two special operators ++ and - - for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. With the prefix version of these operators, C++ performs the increment or decrement operation before using the value of the operand. Example: int sum, ctr; sum = 12;
Page - 10

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

ctr = 4; sum = sum + (++ctr); It will produce the value of sum as 17 because ctr will be first incremented and then added to sum producing value 17. With the postfix version of these operators, C++ first uses the value of the operand in evaluating the expression before incrementing or decrementing the operands value. Example: sum = 12; ctr = 4; sum = sum + (ctr + +); It will produce the value of sum as 16 because ctr will be first used in the expression producing the value of sum as 16 and then increment the value of ctr by 1. Example: A=A+2 += A+=2 A=A-2 A = 2 -= A=A%2 A%=2 %= A=A/2 A/=2 /= The Comma Operator The comma operator gives left to right evaluation of expressions. It enables to put more than one expression separated by comma on a single line. Example: int i = 20, j = 25; In the above statements, comma is used as a separator between two statements. DATA TYPES Data can be stored in any data type. A program needs a means to identify stored data. Data can be many types such as string, integer, character and float etc. Data types are means to identify the type of data and associated operations of handling it. Any thing enclosed in quotes represents character data. Numbers without fraction represents integer data. Numbers with fraction represents float data and anything enclosed in double quotes represents a string. There are five fundamental data types in C++, char, int, float, double and void. All other data types in C++ are based upon one of these types. int data type(for integer): integers are whole numbers such as 6,89,-100 etc. They have no fractional parts. Integers are represented in C++ by int data type. An identifier declared as int can not have fractional part. char data type (for characters): char type is often said to be an integer type. It is said so because letters, symbols are represented in memory by associated numbers codes. float data type (for floating point numbers): A number having fractional part is a floating point number. The decimal point signals that it is a floating point number not an integer. double data type (for double precision floating point numbers): double data type is also used for handling floating point numbers. But it is treated as a distinct data type because, it occupies twice as much memory as type float and stores floating point numbers with much larger range and precision. Double data type is larger and slower than float. void data type (for empty set of values and non returning functions): void specifies an empty set of values. It is used as the return type for function that does not return a value. CONSTANTS A number which does not change its value during execution of a program is known as a constant. Any attempt to change the value of a constant will result in an error message. A constADCPM

PROGRAMMING WITH C++

Page - 11

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

ant in C++ can be of any of the basic data types. const float Pi = 3.1215; VARIABLES Variable represents named storage locations, whose values can be manipulated during program run. Declaration of a Variable: A variable name is an identifier. To declare the variable, place the type of data before the variable name. Syntax: data_type variable_name; Example: int(type) age(variablename); When more than one identifier of a type is being defined, a comma separated list of identifiers may follow the type specifier. Example: int age,marks; float salary,wages; Initialization of Variable: A first value may be specifies in the definition of a variable. A variable with a declared first value is said to be an initialized variable. Example: int age=20; Escape Sequence C++ allows non-graphic characters which cannot be typed directly from keyboard. These characters can be represented by using an escape sequence. Escape Sequence Non- Graphic Character \n Newline or line feed \b Backspace \r Carriage return \t Horizontal tab \v Vertical tab \\ Backslash \ Single quote \ Double quote SELECTION STATEMENTS The selection statements allow choosing the set of instructions for execution depending upon an expression value. C++ provides two types of selection statements: if and switch. The selection statements are also called conditional statements or decision statements. The if statement: An if statement tests a particular condition, if the condition evaluates to true, a course of action is followed. It means a statement or set of statements is executed. Syntax: if(expression) statement; There is another form of if that allows for this kind of either-or condition by providing an else clause. Syntax: if(expression) statement1; else statement2;
Page - 12

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

Program: #include<iostream.h> #include<conio.h> void main() { int num; clrscr(); cout<<"enter the value of num"; cin>>num; if(num%2==0) {cout<<"\n It is an even number!!"; } else {cout<<"\n It is an odd number!!"; } getch(); } A nested if: A nested if is an if that has another if in its body or in it elses body. Syntax: if(expression1) statement1; else if(expression2) statement2; else statement3; Program: #include<iostream.h> #include<conio.h> void main() { float a,b,res; char ch; clrscr(); cout<<"enter the value of a &b"; cin>>a>>b; cout<<"enter the operator(+,-,)"; cin>>ch; cout<<"\n; if(ch=='+') res=a+b; else if(ch=='-') res=a-b; else if(ch=='*') res=ab; else cout<<"\n""<<Wrong Operator"<<"\n"; cout<<"The result is "<<res; getch();
ADCPM

PROGRAMMING WITH C++

Page - 13

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

} The switch statement: C++ provides a multi branch selection statement known as switch. This selection statement tests the value of an expression against a list of integer or character constants. When a match is found, the statement associated with that constant are executed. Syntax: switch(expression) { case constant1: statement1; break; case constant2: statement2; break; } Program: #include<iostream.h> #include<conio.h> void main() { int days; clrscr(); cout<<"enter the values"; cin>>days; switch(days) { case 1: cout<<"Today is Sunday"; break; case 2: cout<<Today is Monday"; break; case 3: cout<<Today is Tuesday"; break; case 4: cout<<Today is Wednesday"; break; case 5: cout<<Today is Thursday"; break; case 6: cout<<Today is Friday"; break; case 7: cout<<Today is Saturday"; break; default: {cout<<"Invalid day no"; break;} }
Page - 14

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

getch(); } LOOPING/ITERATION statement: The iteration statement allows a set of instructions to be performed repeatedly until certain condition is fulfilled. The iteration statements are also called loops or looping statements. C++ provides three kinds of loops: for loop, while loop and do-while loop. The for loop: The for loop is the easiest to understand of loops. All its loop control elements are gathered in one place, while in the other loop construction of C++, they are scattered the program. Syntax: for(initialization expression;test expression;update expression ) { body of the loop; } (Parts of Loop): Every loop has its element that controls its execution. A loop has four elements that have different purpose. Initialization expression: Before entering in a loop, its control variable must be initialized. The initialization of the control variable takes place under initialization expression. The initialization expression gives the loop variable their first value. The initialization expression is executed only once, in the beginning of the loop. Test expression: The test expression is an expression whose truth value decides whether the loop body will be executed or not. If the test expression evaluates to true, the loop body gets executed, otherwise the loop is terminated. Update expression: The update expression change the value of loop variable. The update expression is executed at the end of the loop after the loop body is executed. The Body of the loop: The statements that are executed repeatedly form the body of the loop. First the test expression is evaluated and if it is non zero, the body of the loop is executed. Program: #include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> void main() { char pass[8]; clrscr(); for(int i=0;i<3;i++) { cout<<"Enter the password"<<"\n"; cin.getline(pass,20); if(strcmp(pass,"PACE")) { cout<<"\n"<<"SORRY!! PASSWORD IS INCORRECT!"<<"\n"; } else { cout<<"\n"<<"O.K!! "; } } getch(); }
ADCPM

PROGRAMMING WITH C++

Page - 15

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

Program (nested for): #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { int i,k,j; char name[20]; clrscr(); printf("Enter the name "); gets(name); for(i=4,k=0;i>=0;i--,k++) { cout<<"\n"; for(j=0;j<=i;j++) {cout<<name[k]; } } for(i=4,k=4;i>=0;i--,k--) {cout<<"\n\t"; for(j=0;j<=i;j++) {cout<<name[k]; } } for(i=4,k=0;i>=0;i--,k++) { cout<<"\n"; for(j=0;j<=i;j++) {cout<<name[k]; } } for(i=4,k=4;i>=0;i--,k--) {cout<<"\n\t"; for(j=0;j<=i;j++) {cout<<name[k]; } } getch(); } The while loop: The while loop is entry controlled loop. In a while loop, a loop control variable should be initialized before the loop begin as an uninitialized variable can be used in an expression. The loop variable should be updated inside the body of the while. Syntax: initialization expression; while(test expression) { body of the loop; updation expression; } Program: #include<iostream.h>
Page - 16

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

#include<conio.h> void main() { int i,num; int fact=1; clrscr(); cout<<"enter the value of num"; cin>>num; i=num; while(num) { fact=factnum; num--; } cout<<"the factorial of the num is "<<fact; getch(); } do-while loop: The do-while loop is an exit controlled loop. It evaluates its test expression at the bottom of the loop after executing its loop body statements. This means that a do-while loop always executes at least once. Syntax: initialization expression; do { body of the loop; updation expression; } while(test expression); Program: #include<iostream.h> #include<conio.h> void main( ) { int n,number,sum; cout<<"enter the value of n"; cin>>n; sum=0; number=1; do { sum=sum+number; number++ ; } while(number<=n) ; cout<<sum; getch(); } JUMP STATEMENT The jump statements unconditionally transfer program control within a function. C++ has four statements that perform an unconditional branch: return, goto, break and continue. You may use return and goto anywhere in the program whereas break and continue are used inside
ADCPM

PROGRAMMING WITH C++

Page - 17

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

smallest enclosing like loop. The goto statement: A goto statement can transfer the program control anywhere in the program. The target destination of a goto statement is marked by a label. The target label and goto must appear in the same function. Program: #include<iostream.h> #include<conio.h> void main() { char ch; int num,i; clrscr(); do { cout<<"enter a number"; cin>>num; if(num%2==0) cout<<"Even\n"; else cout<<"Odd\n"; if(num==1) cout<<"prime\n"; else {for(i=2;i<=num/2;++i) if(num%i==0) {cout<<"Not prime\n"; goto lb; } cout<<"Prime"; } lb: cout<<"\nWant to continue(y/n)?"; cin>>ch; } while(ch=='y'||ch=='Y'); getch(); } The break statement: A break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes at the statement immediately following the body of the terminated statement. Program: #include<iostream.h> #include<conio.h> void main() { int a,b,c,i; clrscr(); for(i=0;i<20;++i) {cout<<"Enter 2 numbers";
Page - 18

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

cin>>a>>b; if(b==0) break; else c=a/b; cout<<"\nQuotient="<<c<<"\n"; } cout<<"\n Program Over!!!"; getch(); } The exit() function: You can break out of a program using library function of C++, the exit() function. This function causes the program to terminate as soon as it is encountered, no matter where it appears in the program listing. Program: #include<iostream.h> #include<conio.h> #include<process.h> void main() { int num,i; clrscr(); cout<<"enter the value"; cin>>num; for(i=2;i<=num/2;++i) if(num%i==0) {cout<<"\nNot prime"; exit(0); } cout<<"\n Prime"; getch(); } The continue statement: The continue is another jump statement like the break as both the statements skip over a part of the code. But the continue statement is different from break. Instead of forcing termination, it forces of the loop to take place, skipping any code in between. For the for loop, continue causes the next iteration by updating the variable and then causing the test expression evaluation. For the while and do-while loop, the program control passes to the conditional tests. Program: #include<iostream.h> #include<conio.h> void main() { int a,b,c,i; clrscr(); for(i=0;i<20;++i) { cout<<"Enter two numbers"; cin>>a>>b; if(b==0) { cout<<"\n The denominator can not be zero"<<"Enter again!";
ADCPM

PROGRAMMING WITH C++

Page - 19

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

continue; else c=a/b; cout<<"\nQuotient="<<c<<"\n";

} getch(); } ARRAY In C++ array consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Arrays are a way to group a number of items into a larger unit. An array is a collection of variables of the same type that are referenced by a common name. Types of Arrays: Arrays are of different types: one (single)dimensional array: The simplest form of an array is a single dimensional array. The array is given a name and its elements are referred to by their subscripts or indices. C++ array index numbering starts with 0. Declaration of Array: type array_name[size]; Program: #include<iostream.h> #include<conio.h> void main() { const int size=3; clrscr(); float sale[size],avg=0,total=0; for(int i=0;i<size;i++) {cout<<"enter sales made on a day"; cin>>sale[i]; total+=sale[i]; } avg=total/size; cout<<"\n Total sale="<<total; cout<<"\n Average sale="<<avg; getch(); } two dimensional array: In two dimensional array, each element is itself an array. The number of elements in a 2-D array can be determined by multiplying number of rows with number of columns. Program: #include<iostream.h> #include<conio.h> void main() { int sale[2][4]; int i,j; unsigned long total; for(i=0;i<2;i++)
Page - 20

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

{ total=0; cout<<"enter sales of salesman"<<i+1<<"\n"; for(j=0;j<12;j++) {cout<<"Month "<<j+1; cin>>sale[i][j]; total+=sale[i][j]; } cout<<"\n Total sales of salemen="<<i+1<<total<<"\n"; } getch(); } Multi dimensional array: C++ allows you to have arrays with dimensions more than two. The maximum limit of dimensions is compiler dependent. FUNCTIONS A function is a named unit of a group of program statements. This unit can be invoked from other parts of the program. Main reason to use functions is to reduce program size. Function Definition: In C++, a function must be defined before it is used anywhere in the program. A function definition must have a return statement. data_type function-name (parameter list) { body of the function } Function Prototype: Function prototype is one very useful feature of C++ function. A function prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. float area(float, float) Accessing a Function Call by Value: A function can be invoked in two manners: call by value and call by reference. The call by value method copies the values of actual parameter into the formal parameter that is the function creates its own copy of argument values and then uses them. Program: #include<iostream.h> #include<conio.h> void swap(int, int); void main( ) { int a, b; cout<<"Enter the value of a & b"; cin>>a>>b; swap(a, b); cout<<a<<b<<\n; } void swap(int c, int d) { int t; t=c; c=d;
ADCPM

PROGRAMMING WITH C++

Page - 21

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

d=t; cout<<c<<"\n"<<d<<\n; getch(); } Call by Reference: When a function is called by reference, then the formal parameters become reference to the actual parameter. This means that in the call by reference method, the called function does not create its own copy of original values, rather it refers to the original values only by different names, the reference. The call by reference method is useful in situation where the values of the original variable are to be changes using a function. Program: #include<iostream.h> #include<conio.h> void swap(int &,int &); void main( ) { int a , b; cout<<"enter the value of a and b"; cin>>a>>b; swap(a, b); cout<<a<<b<<\n; } void swap(int &c, int &d) { int t; t=c; c=d; d=t; cout<<c<<d<<\n; getch(); } Returning from a Function The return statement: The return statement is useful in two ways. First, an immediate exit from the function is caused as soon as a return statement is encountered and the control passes back to the operating system which is main caller. Second use of return statement is that it is used to return a value to the calling code. A function may contain several return statements. However, only one of them gets executed because the execution of the function terminates as soon as return is encountered. Program: #include<iostream.h> #include<conio.h> #include<process.h> int main() { void cal(int,int,char); int a,b; char ch; cout<<"enter two digits\n"; cin>>a>>b; cout<<"\n enter any operator(+,-,*):\n";
Page - 22

PROGRAMMING WITH C++

ADCPM

BLY / JAN - 2011

COMPUTER PROGRAMMING

Module 5

cin>>ch; cal(a,b,ch); return 0; } void cal(int x, int y, char c) { switch(c) { case '+': cout<<"\n sum of" <<x<<"and"<<y<<(x+y); break; case '-': cout<<"\n difference of"<<x<<"and"<<y<<(x-y); break; case '': cout<<"\n product of"<<x<<"and"<<y<<(xy); break; default: cout<<"\nwrong operator!!"; break; } getch(); } STRUCTURE A structure is a collection of simple variables which can be of same or different types. The data items in a structure are called the members of the structure. It is a user defines data type and declared with the struct keyword and in which you can declare different type of data members. Program: #include<iostream.h> #include<conio.h> struct student { char name[20]; int marks; }; void main ( ) { student S1, S3; cout<<"enter the student name and marks "; cin>>S1.name>>S1.marks; cout<<"\n"<<S1.name<<"\t"<<S1.marks; student S2={Ankita,32}; cout<<"\n"<<S2.name<<"\t"<<S2.marks; S3=S2; cout<<"\n"<<S3.name<<"\t"<<S3.marks; getch(); } Program (structure with loop): #include<iostream.h>
ADCPM

PROGRAMMING WITH C++

Page - 23

Module 5

COMPUTER PROGRAMMING

JAN - 2011 / BLY

#include<conio.h> #include<stdio.h> struct student { int rno; char name[45]; int marks; }s[5]; void main() { int i; clrscr(); for(i=1;i<5;i++) { cout<<"enter the no" ; cin>>s[i].rno; cout<<"enter the name" ; cin>>s[i].name; cout<<"enter the marks" ; cin>>s[i].marks; } textcolor(52); cprintf("Records are") ; for(i=1;i<5;i++) { cout<<"\n "<<s[i].rno; cout<<"\n "<<s[i].name; cout<<"\n "<<s[i].marks; } getch(); } CLASS A class is a group of objects that share common properties and relationships. It represents a group of similar objects. A base class is a class whose properties are inherited by derived class. A derived class is a class that inherits properties from some other classes. INHERITANCE Inherit means to grab something from giving element. Inheritance is the capability of one class of things to inherit capabilities or properties from another class. The object oriented languages express this inheritance by allowing one class to inherit from another. Thus a model developed by language is much closer to the real world. The principal behind this sort of division is that each subclass shares common characteristics with the class from which it is derived. An object can inherit a general set of properties to which it can add those features that are specific only to itself. Inheritance is important because it allows an object to support the concept of hierarchical classification. Most information is made manageable by hierarchical classification. The child class inherits all those qualities associated with the parent and adds to them its own defining characteristics. The main advantage of inheritance is reusability. F1 F2 F3 Help Save Open ALT + F9 Compile CTRL + F9 Run ESC Cancel SHIFT + Delete Cut CTRL + Insert Copy SHIFT + Insert Paste ALT + Backspace Undo ALT + X Exit ALT+ F3 Close

Note: If you find any typing or printing error/s, inform immediately to your branch office.
Page - 24

PROGRAMMING WITH C++

ADCPM

You might also like