Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
7 views
C++ Programming
Very nice pdf for coding purpose
Uploaded by
Aryan Waligonda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save C++ Programming For Later
Download
Save
Save C++ Programming For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
7 views
C++ Programming
Very nice pdf for coding purpose
Uploaded by
Aryan Waligonda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save C++ Programming For Later
Carousel Previous
Carousel Next
Save
Save C++ Programming For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 174
Search
Fullscreen
++ Programming C++ history History of C+ language is interesting to know. Here we are going to discuss brief history of C++ language. C+ programming language was developed in 1980 by Bjarne ‘Stroustrup at bell laboratories of AT&T (American Telephone & Telegraph), located in U.S.A. Bjarne Stroustrup is known as the founder of C+ language. It was develop for adding a feature of OOP (Object Oriented Programming) in C without significantly changing the C ‘component. C++ programming is “relative” (called a superset) of C, it means any valid C program is also a valid C++ program. Let's see the programming languages that were developed before C+ language. Language Year Algol 1960 BCPL 1967 8 1970 ‘Traditional C 1972 K&RC 1978 C++ 1980 C++ Features Developed By International Group Martin Richard Ken Thompson Dennis Ritchie Kernighan & Dennis Ritchie Bjame Stroustrup Edit with WPS Office © sexed with OK ScannerC++ is object oriented programming language. It provides a lot of features that are given below. simple Machine Independent or Portable Mid-level programming language ‘Structured programming language Rich Library Memory Management Fast Speed Pointers Recursion Extensible Object Oriented Compiler based \Y//) Edit with WPS Office OF seamed ith OK Scanner1) Simple C++ is a simple language in the sense that it provides structured approach (to break the problem into parts), rich set of library functions, data types etc. 2) Machine Independent or Portable Unlike assembly language, c programs can be executed in many machines with little bit or no change. But it is not platform-independent. 3) Mid-level programming language C++ is also used to do low level programming. It is used to develop system applications such as kernel, driver etc. It also supports the feature of high level language. That is why itis known as mid-level language. 4) Structured programming language C++ is a structured programming language in the sense that we can break the program into parts using functions. So, itis easy to understand and modify. 5) Rich Library C++ provides a lot of inbuilt functions that makes the development fast. 6) Memory Management It supports the feature of dynamic memory allocation. In C++ language, we can free the allocated memory at any time by calling the freeQ function. 7) Speed The compilation and execution time of C+ language is fast, 8) Pointer C++ provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array etc. 9) Recursion In C++, we can call the function within the function. It provides code reusability for every function 10) Extensible C++ language is extensible because it can easily adopt new features. 11) Object Oriented C++ is object oriented programming language. OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows. 12) Compiler based Edit with WPS Office © sexed with OK ScannerC++ is a compiler based programming language, it means without compilation no C+ program can be executed. First we need to compile our program using compiler and then we can execute ur program, C++ Variable A variable is a name of memory location. It is used to store data. Its value can be changed and it can be reused many times. Itis a way to represent memory location through symbol so that it can be easily identified. Let's see the syntax to declare a variable type variable lst; The example of declaring variable is given below: int x float y; char 2; Here, x,y,z are variables and int, float, char are data types. We can also provide values while declaring the variables as given below: int x=5,b=10; //declaring 2 variable of integer type float f-30.8; char Rules for defining variables A variable can have alphabets, digits and underscore. A variable name can start with alphabet and underscore only. It can't start with digit No white space is allowed within variable name. A variable name must not be any reserved word or keyword e.g. char, float ete. C++ Data Types A data type specifies the type of data that a variable can store such as integer, floating, character ete. \V/4, Edit with WPS Office © sexed with OK ScannerData Types in C++ ‘There are 4 types of data types in C+ language. ‘Types: Basic Data Type Derived Data Type Enumeration Data Type User Defined Data Type Basic Data Types Data Types char, float, double, ete array, pointer, etc enum structure ‘The basic data types are integer-based and floating-point based. C++ language supports both signed and unsigned literals. \V/4, Edit with WPS Office © sexed with OK Scanner‘The memory size of basic data types may change according to 32 or 64 bit operating system, Let's see the basic data types. It size is given according to 32 bit OS. Data Types Memory Size Range char 1 byte “12810 127 unsigned char 1 byte 0t0 127 int 2byte “32,768 to 32,767 unsigned int 2byte oto 32,767 float Abyte double Bbyte C++ Keywords A keyword is @ reserved word. You cannot use it as a variable name, constant name etc. A list of 32 Keywords in C++ Language which are also available in C language are given below. auto break case char const continue default. = do. double else enum extern float for goto if int long register return. short signed sizeof static struct switch typedef union unsigned void volatile while A\list of 30 Keywords in C-++ Language which are not available in C language are given below. asm dynamic cast namespace reinterpret_cast bool Edit with WPS Office © sexed with OK Scannerexplicit new static_cast false catch ‘operator template friend private class this inline public throw const_cast delete mutable protected true ty typeid ‘typename using virtual wehar_t C++ Operators Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. Operators in C++ can be classified into 6 types: Arithmetic Operators ‘Assignment Operators Relational Operators Logical Operators Bitwise Operators Other Operators 1. C++ Arithmetic Operators Arithmetic operators are used to perform arithmetic operations on variables and data. For example, a+b; Here, the + operator is used to add two variables a and b. Similarly there are various other arithmetic operators in C++. Operator Operation \V/4, Edit with WPS Office © sexed with OK Scanner+ Addition - Subtraction * Multiplication I Division % Modulo Operation (Remainder after division) Increment and Decrement Operators C++ also provides increment and decrement operators: ++ and ~ respectively. ++ increases the value of the operand by 1 ~ decreases it by 1 2. C++ Assignment Operators In C++, assignment operators are used to assign values to variables. For example, JL assign 5to a Here, we have assigned a value of 5 to the variable a. Operator Example Equivalent to . arb; a=b; + a+b; azatb; asa-b; aza*b; I al=b; aza/b; \V/4, Edit with WPS Office © sexed with OK Scannera% 3. C++ Relational Operators A relational operator is used to check the relationship between two operands. For example, 11 checks if a is greater than b a>b; Here, > is a relational operator. It checks if a is greater than b or not. If the relation is true, it returns 1 whereas if the relation is false, it returns 0. Operator Meaning Is Equal To Is Not Equal To > Greater Than < Less Than Greater Than or Equal To Less Than or Equal To 4, CH Logical Operators Example gives us false 31= S gives us true 3> Sgives.us false 3
= Sgiveus false 3<=Sgivesus true Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. \V/4, Edit with WPS Office © sexed with OK ScannerOperator Example Meaning Logical AND. a& expression! && expression2 True only if all the ‘operands are true. Logical OR. True if at least one of the operands is true. il expression1 || expression? Logical NOT. ! ‘expression True only if the operand Is false. 5. C+ Bitwise Operators In C++, bitwise operators are used to perform operations on individual bits. They can only be used alongside char and int data types. Operator Description & Binary AND wary OR A Binary XOR ~ Binary One's Complement « Binary Shift Left > Binary Shift Right 6 Other C++ Operators \V/4, Edit with WPS Office © sexed with OK ScannerHere's a list of some other common operators available in C++. We will learn about them in later tutorials, Operator sizeof C++ Identifiers Description returns the size of data type returns value based on the condition represents memory address of the operand accesses members of struct variables or class objects used with pointers to access the class or struct variables prints the output value gets the input value Example sizeof(int); // 4 string result = (5 > 0) ? "even" : odd’; // "even" # // address of num s1.marks = 92; ptromarks = 92; cout << 5; cin >> num; C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other user-defined data types created by the programmer. They are the basic requirement of any language. Every language has its own rules for naming the identifiers. In short, we can say that the C++ identifiers represent the essential elements in a program which are given below: Constants Variables Functions \V/4, Edit with WPS Office © sexed with OK ScannerLabels Defined data types Some naming rules are common in both C and C++. They are as follows: Only alphabetic characters, digits, and underscores are allowed. ‘The identifier name cannot start with a digit, ie., the first letter should be alphabetical. After the first letter, we can use letters, digits, or underscores. In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++ identifiers are case-sensitive. A declared keyword cannot be used as a variable name. C++ Program Before starting the abed of C++ language, you need to learn how to write, compile and run the first C+ program. To write the first C++ program, open the C+ console and write the following code: include
#include
void main() 4 clrser(); cout << "Welcome to C+ Programming.’ getch0); ) #include
includes the standard input output library functions. It provides cin and cout methods for reading from input and writing to output respectively. ‘include
includes the console input output library functions. The getch() function is defined in conio.h file. void main() The main() function is the entry point of every program in C++ language. The void keyword specifies that it retums no value. cout << "Welcome to C++ Programming."is used to print the data "Welcome to C++ Programming." on the console. getch() The getch() function asks for a single character. Until you press any key, it blocks the screen, \V/4, Edit with WPS Office © sexed with OK ScannerFillelp Alt-FO Next Msg Alt-F? Prev Msg Alt-F9 Compile F9 Make 10 Menu How to compile and run the C++ program There are 2 ways to compile and run the C++ program, by menu and by shortcut, Bymenu Now click on the compile menu then compile sub menu to compile the c++ program. Then click on the run menu then run sub menu to run the c+ program, By shortcut Or, press ctrl#f9 keys compile and run the program directly You will see the following output on user screen, Edit with WPS OfficeYou can view the user screen any time by pressing the alt+{5 keys. Now press Esc to return to the turbo c++ console, Program to print Hello World! #include
using namespace std; int maing) { cout << "Hello, World!" return 0; } Output Hello, World! Program to Add Two Number or Integers #include
using namespace std; int maing) { int firstNumber, secondNumber, sumOfTwoNumbers; cout << “Enter two integers: Edit with WPS Office OF seamed ith one Secin >> firstNumber >> secondNumber, // sum of two numbers in stored in variable sumOfTwoNumbers sumOfTwoNumbers = firstNumber + secondNumber, 1/ Prints sum cout << firstNumber <<" +" << secondNumber <<" = "<< sumOfTwoNumbers; return 0; } Output Enter two integers: 4 5 4+5=9 Program to Find Size of a Variable include
using namespace std; int main { cout << "Size of char: "<< sizeof(char) <<" byte" << endl; cout << "Size of int: "<< sizeof{int) <<" bytes" << endl, cout << "Size of float: * << sizeof{{loat) <<" bytes" << endl; cout << "Size of double: " << sizeof(double) << " bytes" << endl, return 0; ) Output Size of char: 1 byte Size of int: 4 bytes \V/4, Edit with WPS Office © sexed with OK ScannerSize of float: 4 bytes Size of double: 8 bytes Program to Compute quotient and remainder include
using namespace std; int main) { int divisor, dividend, quotient, remainder, cout << "Enter dividend: "; cin >> dividends; cout << “Enter divis 5 0in >> divisor, quotient = dividend / divisor, remainder = dividend % or; cout << “Quotient = " << quotient << endl; cout << "Remainder = "<< remainder; return 0; } Output Enter dividend: 13 Enter divisor: 4 Quotient = 3 Remainder = 1 Program to Swap Numbers (Using Temporary Variable) #include
using namespace std; int maing) { inta b= 10, temp; cout << "Before swapping.” << endl; \V/4, Edit with WPS Office © sexed with OK Scannercout <<"a="<
using namespace std; int main, { char ¢; cout << "Enter a character: cin >> ¢; cout << "ASCII Value of "<< <<" is "<< int(c); return 0; , Output Enter a character: p ASCII Value of p is 112 \V/4, Edit with WPS Office © sexed with OK ScannerControl Statement Sometimes we need to execute a block of statements only when a particular condition is met or ‘not met. This is called decision making, as we are executing a certain code after making a decision in the program logic. For decision making in C+, we have four types of control statements (or control structures), which are as follows: a) if statement b) nested if statement 0) if-else statement d) ifelse‘if statement ° If statement in C++ If statement consists a condition, followed by statement or a set of statements as shown below: if(condition){ uw Statement(s); ) ea The statements inside if parenthesis (usually referred as if body) gets executed only when the given condition is true. If ° the condition is false then the statements inside if body are completely ignored Example 1: C++ if Statement // Program to print positive number entered by the user // Ifthe user enters a negative number, it is skipped #include
using namespace std; int main { int number, \V/4, Edit with WPS Office © sexed with OK Scannercout << "Enter an integer: " cin >> number; 1/ checks if the number is positive if (number > 0) { cout << 'You entered a positive integer: " << number << endl, } cout << "This statement is always executed." return 0; i Output Enter an integer: 5 You entered a positive number: 5 This statement is always executed. Ifelse statement in CH Sometimes you have a condition and you want to execute a block of code if condition is true and execute another piece of code if the same condition is false. This can be achieved in C++ using if-else statement. This is how an if-else statement looks: if(condition) { Statement(s); ) Tue else { Statement(s) ~ fatement(s); Cae ae Fae oy ) The statements inside “if” would execute if the Code inside condition is true, and the statements inside "else" balan would execute if the condition is false. eh Example 2: C++ if..else Statement \V/4, Edit with WPS Office © sexed with OK Scanner1 Program to check whether an integer is positive or negative 1 This program considers 0 as a positive number #include
using namespace std; int main { int number; cout << "Enter an integer." cin >> number, if (number >= 0) { cout << "You entered a positive integ } else { << number << endl cout << "You entered a negative integer: * << number << endl; } cout << "This line is always printed.’ return 0; } Output Enter an integer: 4 You entered a positive integer: 4 This line is always printed. Example of if-else statement #include
using namespace std; int main int num=66; if(num < 50) //his would run if above condition is true \V/4, Edit with WPS Office © sexed with OK Scannercoute<"num is less than 50°; t else { //This would run if above condition is false cout<<"num is greater than or equal 50°; t return 0; C++ If-else Example: with input from user ude
using namespace std; int main 0 { int num; coute<"Enter a Number: ° cin>snum; if (num % 2 == 0) { cout<<"it is even number"<
using namespace std; int main () { int num; coute<'Enter a number to check grade: cin>>num; if (rum <0 jl num >100) { cout<<'wrong number’; } else if(num >= 0 && num < 50){ cout<<"Fail’; ) else if (num >= 50 && num < 60) { coute'D Grade’; } else if (num >= 60 && num < 70) { cout<<"C Grade"; } else if (num >= 70 && num < 80) { cout<<"B Grade", \V/4, Edit with WPS Office © sexed with OK Scannerelse if (num >= 80 && num < 90) { coutss"A Grade"; ) else if (num >= 90 && num <= 100) { cout<<"At Grade"; } } Output: Enter a number to check grade:66 C Grade Program to Find Largest Number Using if Statement #include
using namespace std; int maing) { float n1, n2,n3; cout << "Enter three numbers: "; cin >> n1>>.n2>>n3; f(a >= n2.8& m1 { cout << ‘Largest number: " << n1; } if(n2 >= n1 && n2>=n3) { cout << "Largest number: "<< n2; 3) \V/4, Edit with WPS Office © sexed with OK Scannerif(n3 >= nt && n3 >= m2) { cout << "Largest number: " << n3; } return 0; , Output Enter three numbers: 2.3 83 42 Largest number: 8.3 Program to Check Vowel or a Consonant Manually #include
using namespace std; int main, { char ¢; int isLowercaseVowel, isUppercase Vowel, cout << "Enter an alphabet: "; cin>>c; // evaluates to 1 (true) ifc is a lowercase vowel isLowercaseVowel = (c =='a' Ile // evaluates to 1 (true) if ¢ is an uppercase vowel Elle isUppercaseVowel = (c =="A' llc // evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true ‘Olle if (isLowercaseVowel || is UppercaseVowel) cout << ¢ << "is a vowel.”; else cout << ¢ << "is a consonant.’; \V/4, Edit with WPS Office © sexed with OK Scannerreturn 0; } Output Enter an alphabet: u uis a vowel. C++ switch ‘The C++ switch statement executes one statement from multiple conditions. Its like ifelse-if ladder statement in C++. switch(expression){ case value1: J/code to be executed; break; case value: i/code to be executed; break; default: //e0de to be executed if all cases are not matched; break; } ° Fie Svc uemct C++ Switch Example #include
oe ms using namespace std; eas iment a int num; . cout
num; switch (num) { case 10: coute<'It is 10°; break; case 20: cout<<'It is 20°; break; case 30: coute<'tt is 30°; break; default: coute<'Not 10, 20 or 30; break; 2 Output: Enter a number: 10 Itis 10 Example: Create a Calculator using the switch Statement // Program to build a simple calculator using switch Statement #include
using namespace std; int main { char oper; float num, num2; cout <<"Enter an operator (+,-,4,/):": cin >> oper, cout << "Enter two numbers: "<< end}; cin >> num’ >> num2; ‘switch (oper) { case '#: cout << numt <<" +" << num2 <<"="-<< num +num2; break; case“! \V/4, Edit with WPS Office © sexed with OK Scannercout << numt <<"= "<< num2 <<" ="<< num = num2; break; case: cout << numt <<" * "<< num2 <<" =" << numt * num2; break; case cout << numt <<" /" << num2.<<"="<« numt /num2; break; default: // operator is doesn't match any case constant (+, -,*, /) cout << "Error! The operator is not correct"; break; return 0; } Output 1 Enter an operator (+, Enter two numbers: 23 45 234+45=68 Example #include
using namespace std; int main () // local variable declaration: char grade = 'D; \V/4, Edit with WPS Office © sexed with OK Scannerswitch(grade) { case'A' cout << "Excellent!" << endl; break; case 'B': case'C’ cout << "Well done" << endl; break; case 'D’ cout << "You passed’ << endl; break; case 'F: cout << "Better try again’ << endl; break; default cout << "invalid grade" << endl; + ‘cout << "Your grade is * << grade << endl; return 0; ) This would produce the following result - You passed Your grade is D C++ For Loop \V/4, Edit with WPS Office © sexed with OK ScannerThe C++ for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop than while or do-while loops. The C++ for loop is same as C/C#. We can initialize variable, check condition and increment/decrement value. for(initialization; condition; incr/decr) { Icode to be executed } Flowchart: False Tre C++ For Loop Example \clude
using namespace std; int main { ! O44) coute
using namespace std; int maid { int num, sum; sum cout << “Enter a positive integer: * cin >> num; for (int count = 1; count <= num; +4count) { sum += count; } cout << "Sum << sum << endl; return 0; } Output Enter a positive integer: 10 sum = 55 Example: Find Factorial of a given number #include
using namespace std; int main) { intn; unsigned long long factorial cout << "Enter a positive integer: "; cin >> n; if(n<0) cout << "Error! Factorial of a negative number doesn't exist." \V/4, Edit with WPS Office © sexed with OK Scannerelse { for(int i= 1; i <=n; +i) { factorial ) cout << "Factorial of "<< n <<" =" << factorial; } return 0; } Output Enter a positive integer: 12 Factorial of 12 = 479001600 Example 1: Fibonacci Series up to n number of terms #include
using namespace std; int main { int n, 1 = 0,12 = 1, nextTerm = 0; cout << “Enter the number of terms: " cin >>; cout << "Fibonacci Series: "; for (int i= 1;1<= 1; +4) { 1 Prints the first two terms. if(@==1)4 cout << tl << continue; \V/4, Edit with WPS Office © sexed with OK Scannercout <
using namespace std; int maind « int rows cout << "Enter number of rows: *; cin >> rows; fori rows; +i) \V/4, Edit with WPS Office © sexed with OK Scannerfor(int j= 1; )<= i, +4)) { cout << "*"; } cout << "\n'; } return 0; ) Example 2: Program to print half pyramid a using numbers 1 12 123 1234 12345 Source Code include
using namespace std; int main) { int rows; cout << "Enter number of rows: *; cin >> rows; for(int i= 1;i<= rows; +i) { for(int { cout <
using namespace std; int main, { int rows; cout << "Enter number of rows: *; cin >> rows; for(int i= rows; i>= { for(int j= 1; 1) +4) cout << endl; } return 0; \V/4, Edit with WPS Office © sexed with OK ScannerExample 5: Inverted half pyramid using numbers 12345 1234 123 az 1 Source Code include
using namespace std; int maing, { int rows; cout << "Enter number of rows: *; cin >> rows; for(int = rows; i>=1;~i) { for(int j= 15) <= +4) { cout <
using namespace std; int maing) { int rows, number = 1; cout << "Enter number of rows: *; cin >> rows; for(i { for(int} = 1; <= i +4)) { cout << number <<"; rows; i++) ‘++number; } cout << endl; return 0; Example: C++ program to print full star pyramid pattern #include. ream> using namespace std; \V/4, Edit with WPS Office © sexed with OK Scannerint main) { int rows, i,j, space; cout << “Enter number of rows: ”; cin >> rows; for(i = 1; <= rows; i++) { 1/for loop for displaying space for(space = i space < rows; space++) /ifor loop to display star equal to row number for = 15) 4 (2* 1-1); j++) cout << "* Loop Terminates } v C++ while Loop ‘The syntax of the while loop is: while (condition) { 1/ body of the loop } Here, \V/4, Edit with WPS Office © sexed with OK Scanner‘Awhile loop evaluates the condition If the condition evaluates to true, the code inside the while loop is executed, The condition is evaluated again. This process continues until the condition is false. When the condition evaluates to false, the loop terminates. Example 1: Display Numbers from 1 to 5 // C++ Program to print numbers from 1 to 5 #include
using namespace std; int maid { inti= 1; // ihile loop from 1 to 5 while ((<= 5) { cout <
using namespace std; int main { int number; \V/4, Edit with WPS Office © sexed with OK Scannerint sum = 0; // take input from the user cout << "Enter a number: cin >> number, while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << ‘Enter a number: *; cin >> number, } // display the sum cout << "\nThe sum is "<< sum << endl; return 0; } Output Enter a number: 6 Enter a number: 12 Enter a number: 7 Enter a number: 0 Enter a number: -2 The sum is 25 ‘While Loop example in C++ #include
using namespace std; int main0{ int \V/4, Edit with WPS Office © sexed with OK Scanner/* The loop would continue to print * the value of i until the given con + ic=6 retums false, 4 while(ic=6){ cout<<"Value of variable iis: “«
using namespace std; int main { inti= 1; 1/ d0...while loop from 1 to do{ cout << <<"; +i } while ((<= 5); return 0; , Output 12345 Example : Sum of Positive Numbers Only 1/ program to find the sum of positive numbers // Ifthe user enters a negative number, the loop ends // the negative number entered is not added to the sum #include
using namespace std; int main( { int number = 0; int sum = 0; do{ sum += number; \V/4, Edit with WPS Office © sexed with OK Scanner//take input from the user cout << Enter a number: cin >> number; ) while (number >= 0); i fom | 1/ display the sum cout <<"\nThe sum is "<< sum << endl; retum 0; tie k Output Figure: owchart of break statemost Enter a number: 6 Enter @ number: 12 Enter a number: 7 Enter a number: 0 Enter a number: -2 The sum is 25 C++ Break Statement ‘The C++ break is used to break loop or switch statement. It breaks the current flow of the program at the given condition. In case of inner loop, it breaks only inner loop, jump-statement; break; Flowchart: \V/4, Edit with WPS Office © sexed with OK ScannerC++ Break Statement Example Let's see a simple example of C++ break statement which is used inside the loop. #include
using namespace std; int maind { for (int i= si <= 10; 44) cout<
using namespace std; int maint int num =10; while(num<=200) { cout<<"Value of num is: "<
using namespace std; int maint int var, for (var =200; var>=10; var ~) { cout<<"var: “<
using namespace std; int maint int num=2; switch (num) { case 1: cout<<'Case 1 "<
using namespace std; int main) continue; } coutecic<"\n', i } Output: 1 2 3 4 6 7 8 \V/4, Edit with WPS Office © sexed with OK Scanner9 10 Example: Use of continue in While loop #include
using namespace std; int main0{ int while (/>=0) { continue; } coute<"Value of j:“<
using namespace std; int mainO{ \V/4, Edit with WPS Office © sexed with OK Scannercontinue; + coute<"j is: "<
using namespace std; int main, { int origNum, num, rem, sum = cout << "Enter a positive integer: "; cin >> origNum; \V/4, Edit with WPS Office © sexed with OK Scannernum = origNum; while(num != 0) { digit = num % 10; num /= 10; } if(sum rigNum) cout << origNum <<" is an Armstrong number."; else cout << origNum <<" is not an Armstrong number.’ return 0; , Output 371 is an Armstrong number. goto statement in C++ ‘The goto statement is used for transferring the control of a program to a given label. The syntax of goto statement looks like this: goto label_name; Program structure: label: goto label2; label2: \V/4, Edit with WPS Office © sexed with OK ScannerExample of goto statement in C++ include
using namespace std; int main0{ int num; cout<«"Enter a number: "; cin>>num; if (num % 2==0) goto print; y else { cout<<"Odd Number’, print: cout<<"Even Number"; return 0; Output: Enter @ number: 42 Even Number Example: goto Statement 11 This program calculates the average of numbers entered by the user. // Ifthe user enters a negative number, it ignores the number and // calculates the average number entered before it. # Include
using namespace std; int main) \V/4, Edit with WPS Office © sexed with OK Scannerfloat num, average, sum = 0.0; inti,n; cout << "Maximum number of inputs: " cin>>n; for(i = T;i<= 9; +4i) { cout << "Enter n" << i <<":"; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / 1 cout << "\nAverage =" << average; return 0; } Output Maximum number of inputs: 10 Enter nt: 2.3 Enter n2: 5.6 Entern3: 5.6 Average = 3.95 C++ Goto Statement Example \V/4, Edit with WPS Office © sexed with OK ScannerLet’s see the simple example of goto statement in C++, #include
using namespace std; int maing) { ineligible: cout<<"You are not eligible to vote!\n’; couts<"Enter your age:\ int age; cins>age; if (age < 18) goto ineligible; else cout<<"You are eligible to vote!”, } Output: ‘You are not eligible to vote! Enter your age: 16 You are not eligible to vote! Enter your age: 7 ‘You are not eligible to vote! Enter your age: 22 You are eligible to vote! \V/4, Edit with WPS Office © sexed with OK ScannerC++ Arrays Like other programming languages, array in C++ is a group of similar types of elements that have contiguous memory location. In C++ stdarray is a container that encapsulates fixed size arrays. In C+4, array index starts from 0. We can store only fixed set of elements in C++ array. Data Index. > 0 1 2 3 Advantages of C++ Array Code Optimization (less code) Random Access Easy to traverse data Easy to manipulate data Easy to sort data ete. Disadvantages of C++ Array Fixed size C++ Array Types: ‘There are 2 types of arrays in C++ programming Single Dimensional Array Multidimensional Array G++ Array Declaration \V/4, Edit with WPS Office © sexed with OK Scannerdatatype arrayNamelarraySizel For example, int x{6]; Here, int -type of element to be stored x- name of the array 6- size of the array ‘Access Elements in C++ Array In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices. 1/ syntax to access array elements arraylindex}; Consider the array x we have seen above. ArrayMembers—> x(0] xi], xia] xls] xl4] x8) — o 1 2 3 4 5 Elements of an array in C++ Array Indices Few Things to Remember: The array indices start with 0. Meaning x0] is the first element stored at index 0. If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is the last element. Elements of an array have consecutive addresses. For example, suppose the starting address: of x{0] is 21204. Then, the address of the next element x{1] will be 2124d, the address of x[2] will be 2128d and so on. Here, the size of each element is increased by 4. This is because the size of int is 4 bytes. (C+ Array Initialization \V/4, Edit with WPS Office © sexed with OK ScannerIn C++, it's possible to initialize an array during declaration. For example, 1/ declare an int x[6] = {19, 10, 8, 17, 9, 15}; lize and array ArrayMembers —> x(0] >it} xi2]— xf] xl] x8] — o 1 2 3 4 5 C++ Array elements and their data Array Indices Another method to initialize array during declaration: 1/ declare and initialize an array int x{] = {19, 10, 8, 17, 9, 15}; Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size. Example: Calculate Average of Numbers Using Arrays include
using namespace std; int main { inti: float num[100], sum=0.0, average; cout << "Enter the numbers of data: *; cin >> n; while (n > 100 | n <= 0) { cout << "Error! number should in range of (1 to 100).” << endl; cout << "Enter the number again: "; \V/4, Edit with WPS Office © sexed with OK Scannercin >> n; } for(i = 0; i
> numiil; sum += numlil; y average = sum / n; cout << "Average = "<< average; return 0; } Output Enter the numbers of data: 6 1. Enter number: 45.3 2. Enter number: 67.5 3. Enter number: -45.6 4, Enter number: 20.34 5, Enter number: 33 6. Enter number: 45.6 Average = 27.69 Example: Display Largest Element of an array #include
using namespace std; int maing) { inti n; float arr{1 00]; \V/4, Edit with WPS Office © sexed with OK Scannercout << “Enter total number of elements(1 to 100): " >> cout << endl: // Store number entered by the user for(i = 0;1< n; +4i) { cout << 'Enter Number" <
> arrlil; } // Loop to store largest number to arr{0] for(i = 1yi< n;+4i) { // Change < to > if you want to find the smallest element if(arrf0] < arrfil) arr{0] = arrli]; } cout << "Largest element = " << arr{Q]; return 0; } Output Enter total number of elements: 8 Enter Number 1: 23.4 Enter Number 2:-34.5 Enter Number 3: 50 Enter Number 4: 33.5, Enter Number 5: 55.5 Enter Number 6: 43.7 Enter Number 7: 5.7 Enter Number 8: -66.5, \V/4, Edit with WPS Office © sexed with OK ScannerLargest element = 55.5 simple example of C+ array include
using namespace std; int main) { int arr{5]=(10, 0, 20, 0, 30}; //creating and initializing array Iikraversing array for (int i= 0;i < 5; i++) { coute
using namespace std; int main { int test{3][2] = 42, -5}, {4,0}, 9. J/.use of nested for loop // access rows of the array for (int i= 0; 1< 3; +41) { // access columns of the array for (int j= 0;)< 2; ++) { \V/4, Edit with WPS Office © sexed with OK Scannercout <<"test{ << i << 'I["<
using namespace std; int main { int numbers{2][3}; cout << "Enter 6 numbers: *<< endl; // Storing user input in the array for (int i= 0;i< 2; +4i) { for (intj = 0;j <3; ++i) { cin >> numbers[ilj; Edit with WPS Office © sexed with OK Scannercout << "The numbers are: "<< endl; 1/ Printing array elements for (int i= 0; 1< 2; +41) { for (int j= 0;) < 3; +4)){ cout << "numberst" << i << "If << <<": " << numbersiil] << endl; return 0; , Output Enter 6 numbers: 1 oan won The numbers are: numbersfolfol: 1 numbers[0][1]}: 2 numbers|0][2}: 3 numbers[1]{0}: 4 numbersf]I1I: 5 numbers{1](2I: 6 \V/, Edit with WPS Office © sexed with OK ScannerExample: Add Two Matrices using Multi-dimensional Arrays ude
using namespace std; int main { int r,c, a{100][100), b[1 00][100], sum[100]{109}, i,j; cout << “Enter number of rows (between 1 and 100): *; cin >> r; cout << "Enter number of columns (between 1 and 100):"; >c cout << endl << "Enter elements of 1st matrix: * << endl; 1/ Storing elements of first matrix entered by user. forli=O:i< 7 +4i) for(| = 0;
> ali // Storing elements of second matrix entered by user. cout << endl << "Enter elements of 2nd matrix: "<« endl; for(i = O;1< 1; +4) for(| = 0;)
> blll 1/ Adding Two matrices for(i = 0;1< 1; +4i) for() = 0; <6; +4)) il) + blll: sumiilfi] = // Displaying the resultant sum matrix. cout << endl << "Sum of two matrix is: * << endl; )
using namespace std; int mainO { int a[10]{10], transpose[10][1 0], row, column, i,j cout << "Enter rows and columns of matrix: "; cin >> row >> column; cout << "\nénter elements of matrix: " << endl; // Storing matrix elements for (inti = 0,1 < row; +¥i){ for (int j = 0;j < column; +) { cout << "Enter element a° << i+ 1 <
> alll; \V/4, Edit with WPS Office © sexed with OK Scanner// Printing the @ matrix cout << "\nEntered Matrix: "<< endl; for (int i= 0; i < row; ++i) { for (int j= 0;) < column; ++i) { cout <<"* << alll; if cout << endl << endl; column=1) // Computing transpose of the matrix for (int < row; +i) for (int = 0;j < column; +4) { transposeljlti] = alil{i; + // Printing the transpose cout << “\nTranspose of Matrix: "<< endl; for (inti= 0;i< column; ++i) for (int j = 0;] < row; +4) { cout <<"* <« transposelill iG cout << endl << endl, row-1) return 0; ) Output Enter rows and columns of matrix: 2 3 \V/4, Edit with WPS Office © sexed with OK ScannerEnter elements of matrix: Enter element a11: Enter element a12: 2 Enter element a13: 9 Enter element a21: 0 Enter element a22: 4 Enter element 23: 7 Entered Matrix: 129 047 Transpose of Matrix: 10 24 o7 C++ Strings In this tutorial, you'll learn to handle strings in C++. Youll learn to declare them, initialize them and use them for various input/output operations. String is a collection of characters. There are two types of strings commonly used in C++ programming language: Strings that are objects of string class (The Standard C++ Library string class) C-strings (C-style Strings) \V/4, Edit with WPS Office © sexed with OK ScannerC-strings In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming, Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \O (ASCII value of null character is 0). How to define a C-string? char strf] = "C++" In the above code, str is a string and it holds 4 characters. Although, "C++" has 3 character, the null character \0 is added to the end of the string automatically. Alternative ways of defining a string char str[4] = "C++"; char strl] = (C,+,'+,N0}; char str{4] = (C’ 0%; Like arrays, it is not necessary to use all the space allocated for the string. For example: char str[100] = "C++"; Example 1: C++ String to read a word C++ program to display a string entered by user. ‘include
using namespace std; int main, { char str{100); cout << "Enter a string: "; cin >> str; \V/4, Edit with WPS Office © sexed with OK Scannercout << "You entered: " << str<< endl; cout << "\nEnter another string: " cin >> str; cout << "You entered: "<
> works as scanf() in C and considers a space *" has a terminating character. Example 2: C++ String to read a line of text C+ program to read and display an entire line entered by user. #include
using namespace std; int main) { char str[100]; cout << Enter a string: cin.get(str, 100); cout << "You entered: " << str<< endl; \V/4, Edit with WPS Office © sexed with OK Scannerreturn 0; } Output Enter a string: Programming is fun. ‘You entered: Programming is fun. Example 1; Find Frequency of Characters of a String Object #include
using namespace std; int main) { string str = "C++ Programming is awesome"; char checkCharacter int count for (int i = 0; i< str.sizeQ); i++) { if (sti) { ++ count; ‘checkCharacter) cout << "Number of * << checkCharacter <<" = " << count; return 0; Output \V/4, Edit with WPS Office © sexed with OK ScannerNumber of a= 2 Example 1: Remove all characters except alphabets This program takes a string (object) input from the user and removes all characters except alphabets, \clude
using namespace std; int main { string line; string temp ="; cout << "Enter a string: *; getline(cin, line); for (int i= 0; 1< line.size(; ++) { if (inefi] >= ‘a’ && linefi] <='2') || (line{i] >= 'A’ && line[i] <='Z') { temp = temp + line[i; } } line = temp; cout << “Output String: " << line; return 0; } Output Enter a string: p2ro@grams4iz./ Output String: programiz Example: Length of String Object #include
\V/4, Edit with WPS Office © sexed with OK Scannerusing namespace std; int main { string st ‘C+ Programming’; // you can also use str.ength() cout << "String Length = * << str.size(); return 0; } Output String Length = 15 Example 1: Concatenate String Objects include
using namespace std; int main { string s1, s2, result; cout << "Enter string $1 getline (cin, s1); cout << "Enter string s2:"; getline (cin, $2); \V/4, Edit with WPS Office © sexed with OK Scannerresult = 81452; cout << "Resultant String = "<< result; return 0; } Output Enter string s1: C++ Programming Enter string s2: is awesome. Resultant String = C++ Programming is awesome. Example 1: From a C-style string This program takes a C-style string from the user and calculates the number of vowels, consonants, digits and white-spaces. #include
using namespace std; int main) { char line[150]; int vowels, consonants, digits, spaces; vowels = consonants = digits = spaces = cout << "Enter a line of string: cin.getline(line, 150); for(int \V/4, Edit with WPS Office © sexed with OK Scanner+tvowels; x else if((\ineli: { +#consonants; } else if(linel>="0' 88 line { +#digits; } else if (lineli} { +#spaces; && lineli) ‘VII Cinefi cout << "Vowels: * << vowels << endl; cout << "Consonants: "<< consonants << endl; cout << "Digits: "<< digits << endl; cout << "White spaces: " << spaces << endl; return 0; ) Output Enter a line of string: This is 1 hell of a book. Vowels: 7 \V/4, Edit with WPS Office © sexed with OK ScannerConsonants: 10, Digits: 1 White spaces: 6 C++ Functions A function is a block of code that performs a specific task. Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem: a function to draw the circle a function to color the circle Dividing @ complex problem into smaller chunks makes our program easy to understand and reusable, There are two types of function: Standard Library Functions: Predefined in C++ User-defined Function: Created by users In this tutorial, we will focus mostly on user-defined functions. C++ User-defined Function C++ allows the programmer to define their own function. ‘user-defined function groups code to perform a specific task and that group of code is given a name (identifier) When the function is invoked from any part of the program, it all executes the codes defined in the body of the function. C++ Function Declaration The syntax to declare a function is: retumType functionName (parameter1, parameter?,...) { // function body } Here's an example of a function declaration. \V/4, Edit with WPS Office © sexed with OK Scanner// function declaration void greet() { cout << "Hello World’; ) Here, the name of the function is greet() the return type of the function is void the empty parentheses mean it doesn't have any parameters ‘the function body is written inside {} Note: We will learn about returnType and parameters later in this tutorial. Calling a Function In the above program, we have declared a function named greet(). To use the greet() function, we need to call it Here's how we can call the above greet() function. int main { // calling a function greet(); \V/4, Edit with WPS Office © sexed with OK Scanner#include
void greet() { <—__ // code —? function int main() { call greet(); How Function works in C++ Example 1: Display a Text include
using namespace std; 1/ declaring a function void greet() { cout << "Hello there!’; int main { //-calling the function greet(); return 0; } Output Hello there! \V/4, Edit with WPS Office © sexed with OK ScannerFunction Parameters ‘As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function. For example, let us consider the function below: void printNum(int num) { cout <
using namespace std; // display a number void displayNum(int n1, float n2) { cout << "The int number is "<< n1; cout << "The double number is " << n2; \V/4, Edit with WPS Office © sexed with OK Scannerint main { int num = 5; double num2 = 5.5; // calling the function displayNum(numt1, num2); return 0; } Output The int number is 5 ‘The double number is 5.5 In the above program, we have used a function that has one int parameter and one double parameter. We then pass num and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively. #includeciostream> void displayNum(int n1, double n2) {<—— 1 code function call int main() { displayNum(numt, num2); L_, + C++ function with parameters Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration. \V/4, Edit with WPS Office © sexed with OK ScannerReturn Statement In the above programs, we have used void in the function declaration. For example, void displayNumber() { I. code , This means the function is not returning any value. It's also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration. Then, the return statement can be used to return a value from a function. For example, int add (int a, int b) { return (a +b); } Here, we have the data type int instead of void. This means that the function returns an int value. The code retum (a +b); returns the sum of the two parameters as the function value. The return statement denotes that the function has ended. Any code after return inside the function is not executed, Example 3: Add Two Numbers // program to add two numbers using a function include
using namespace std; 1/ declaring a function int ada(int a, int b) { return (a +b); int main0 { \V/4, Edit with WPS Office © sexed with OK Scannerint sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " <« sum << endl; return 0; } Output 100 + 78 = 178 In the above program, the add() function is used to find the sum of two numbers. We pass two int literals 100 and 78 while calling the function We store the returned value of the function in the variable sum, and then we print it. #include
int add(int a, int b) ¢ return (a + b); -—? int main() { funetion int sum; call sum = add(100, 78); > Working of C++ Funetion with retum statement Notice that sum is a variable of int type. This is because the return value of add() is of int type. Function Prototype \V/4, Edit with WPS Office © sexed with OK ScannerIn C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example, function prototype void addtint, int); int main { 1/ calling the function before declaration add(5, 3); return 0; 11 function definition void add(int a, int b) { cout << (a+ b); , In the above code, the function prototype is: void ada(int, int); This provides the compiler with information about the function name and its parameters. That's why we can use the code to call a function before the function has been defined. The syntax of a function prototype is: retumType functionName(dataTypet, dataType2, ..); Example 4: C++ Function Prototype using function definition after main() function // function prototype is declared before main) #include
using namespace std; // function prototype \V/4, Edit with WPS Office © sexed with OK Scannerint add{ int, int); int main { int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout <<"100 +7 << sum << endl return 0; 1/ function definition int add(int a, int b) { return (a +b); , Output 100+ 78 = 178 ‘The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call That's why we have used a function prototype in this example. Benefits of Using User-Defined Functions Functions make the code reusable. We can declare them once and use them multiple times. Functions make the program easier as each small task is divided into a function. Functions increase readability. C++ Library Functions Library functions are the built-in functions in C++ programming. \V/4, Edit with WPS Office © sexed with OK ScannerProgrammers can use library functions by invoking the functions directly; they don't need to write the functions themselves. Some common library functions in C++ are sqrt), abs(), isdigit), etc. In order to use library functions, we usually need to include the header file in which these library functions are defined. For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath. Example 5: C++ Program to Find the Square Root of a Number #include
#include
Using namespace std; int main { double number, squareRoot; number = 25.0; // sqrt() is a library function to calculate the square root squareRoot = sqrt(number); cout << "Square root of "<< number <<" =" << squareRoot, return 0; } Output Square root of 25 = 5 In this program, the sqrt() library function is used to calculate the square root of a number. ‘The function declaration of sqrt() is defined in the cmath header the code #include
to use the sqrt) function. ‘Types of User-defined Functions in C++ That's why we need to use For better understanding of arguments and retum in functions, user-defined functions can be \V/4, Edit with WPS Office © sexed with OK Scannercategorised as: Function with no argument and no return value Function with no argument but return value Function with argument but no return value Function with argument and return value Consider a situation in which you have to check prime number. This problem is solved below by making user-defined function in 4 different ways as mentioned above. Example 1: No arguments passed and no return value # include
using namespace std; void prime(); int mainO) { // No argument is passed to prime() prime(); return 0; // Return type of function is void because value is not returned void prime() { int num, j, flag = 0; cout << "Enter a positive integer enter to check: " cin >> num; \V/4, Edit with WPS Office © sexed with OK Scanner2;i <= num/2;+4i) if(num % i { flag =1; break; if (flag == 1) { cout << num <<" is not a prime number." ) else { cout << num <<" is a prime number.’ } In the above program, prime() is called from the main() with no arguments. prime() takes the positive number from the user and checks whether the number is a prime number or not. Since, return type of prime() is void, no value is returned from the function. Example 2: No arguments passed but a return value #include
using namespace std; int prime(j \V/4, Edit with WPS Office © sexed with OK Scannerint main { int num, i flag = 0; // No argument is passed to prime() num = prime(); if (flag == 1) { cout<
> n; return n; } In the above program, prime() function is called from the main() with no arguments. prime( takes a positive integer from the user. Since, return type of the function is an int, it returns the inputted number from the user back to the calling main() function. Then, whether the number is prime or not is checked in the main() itself and printed onto the screen, Example 3: Arguments passed but no return value include
using namespace std; void prime(int int main, { int num; cout << Enter a positive integer to chee! cin >> num; // Argument num is passed to the function prime() prime(num); return 0; 11 There is no return value to calling function, Hence, return type of function is void. */ void prime(int n) \V/4, Edit with WPS Office © sexed with OK Scannerinti, flag = 0; for (i= 2:1<= 1/2; +41) { if (n%i { flag = 7; break; if (flag == 1) { cout << n<<"is nota prime number." } else { cout << <<"is a prime number." } In the above program, positive number is first asked from the user which is stored in the variable num, Then, num is passed to the prime() function where, whether the number is prime or not is checked and printed. Since, the return type of prime() is a void, no value is returned from the function Example 4: Arguments passed and a return value. #include
using namespace std; int prime(int n); \V/4, Edit with WPS Office © sexed with OK Scannerint main) { int num, flag = 0; cout << "Enter positive integer to check: "; cin >> num; // Argument num is passed to check() function flag = prime(num); if(flag == 1) cout << num << "is not a prime number." else cout<« num <<"is a prime number." return 0; /* This function returns integer value. */ int prime(int n) { inti for(i { if(n %i== 0) return 1; 2 ics n/2; +i) return 0; \V/4, Edit with WPS Office © sexed with OK ScannerC++ OOPs Concepts ‘The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc. The programming paradigm where everything is represented as an object is known as truly object- oriented programming language. Smalltalk is considered as the first truly object-oriented programming language OOPs (Object Oriented Programming System) Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is 2 methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Objects © Object © Class ©. Inheritance ‘©. Polymorphism © Abstraction ‘© Encapsulation \V/4, Edit with WPS Office © sexed with OK ScannerObject ‘Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical. Class Collection of objects is called class. itis a logical entity Inheritance ‘When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Polymorphism When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc. In G++, we use Function overloading and Function overriding to achieve polymorphism. Abstraction Hiding internal details and showing functionality is known as abstraction. For example: phone call, ‘we don't know the internal processing. In C++, we use abstract class and interface to achieve abstraction. Encapsulation Binding (or wrapping) code and data together into a single uni example: capsule, itis wrapped with different medicines. known as encapsulation. For C++ Object In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality. Object is a runtime entity, itis created at runtime. Object is an instance of a class. All the members of the class can be accessed through object. Edit with WPS Office © sexed with OK ScannerNoh eNo Let's see an example to create object of student class using s1 as the reference variable. Student s1; //creating an object of Student In this example, Student is the type and s1 is the reference variable that refers to the instance of Student class. C++ Class In Cts, object is a group of similar objects. It is a template from which objects are created. it can have fields, methods, constructors etc. Let's see an example of C++ class that has three fields only class Student 4 public: Intid; //field or data member float salary; //field or data member String name;//field or data member ' Write a program to create a class Student having following data members: 1) Name 2)Roll No 3)Percentage for one Student #includeciostream> using namespace std; class Student { private: char name[30]; int rollno; \V/4, Edit with WPS Office © sexed with OK Scannerfloat per; Public: void getdata() { coute<"Enter Name:"; cin>>name; coute<"Enter RolINo:”"; cinz>rolino; coute<"Enter Per"; cin>>per, void putdata() { cout<<"Display Student Data:\r coute<"\nName*"
using namespace std; class Employee { private: char Emp_Name[30]; int Emp_td; float Salary, public: void getdata() { couts<"Enter Employee Data’; cout<<"Enter Employee Name:" cin>>Emp_Name; cout<<"Enter Employee Id"; cin>>Emp_Id; coutss'Enter Employee Salary: cin>>Salary; void putdata() { cout<<"Display Employee Data\n’; coute<"\nEmp_Name:"<
using namespace std; class Book { private: char Book_Name(30]; char Author[30];, float Price; public: void getdata() { cout<"Enter Book Data\n'; cout<<"Enter Book Name: cin>> Book_Name; coute<'Enter Author Name cin>>Author, cout<<"Enter Book Price: cin>>Price; \V/4, Edit with WPS Office © sexed with OK Scannervoid putdata() { cout<<"\nDisplay Book Data:\n"; cout<<"\nBook Name:"<
using namespace std; class Student { private: char name[30}; int rolino; float per; public: void getdata() \V/4, Edit with WPS Office © sexed with OK Scannercout<<"\nEnter Name:"; cin>>name; couts<"Enter RolINo; cin>>rolino; couts<"Enter Per:"; cin>>per; ) void display) { coute<"Display Student Data:\n"; cout<<"\nName:"<
using namespace std; class Book { private: char Book Name{30}; char Author{30}; float Price; int Page_No; int year, publi void getdata() { coutss"Enter Book Data\n’; coute<"Enter Book Name: cin>> Book Name; coute<"Enter Author Name :* cin>>Author; coutss"Enter Book Price: cin>>Price; cout<"Enter Page No:"; cin>>Page_No; cout<"Enter Book Publish Vear:" cin>>year; void putdata() { cout<<"\nDisplay Book Data:\n’; ‘cout<<"\nBook Name:"<
using namespace std; class Employee { private: char Emp_Name(30); int Emp_ld; float Salary; public: void getdata() { \V/4, Edit with WPS Office © sexed with OK Scannercoute<"Enter Employee Data’, cout<<"Enter Employee Name-"; cin>>Emp_Name; coute<"Enter Employee Id; cins>Emp_Id; coute<"Enter Employee Salary:"; cin>>Salary; void display() { cout<<'Display Employee Data:\n’; cout<<"\nEmp_Name:"<«
using namespace std; class Book { private: char Book Name[30]; char Author[30}; float Price; publi void getdata() { couts<"Enter Book Data\n"; couts<"Enter Book Name: cin>> Book_Name; coute<"Enter Author Name :"; cin>>Author, cout<<"Enter Book Price:"; cin>>Price; void display() { cout<<"\nDisplay Book Data:\n'; cout<"\nBook Name:"<
Constructor have the same name as class > Constructor do not return any value >» They cannot be inherited > Cannot refers to address > They can have default argument ‘Syntax Edit with WPS Office © sexed with OK Scannerclass user_name { Private: protected: public: user_name(); //Constructor Declare user_name::user_name() //Constructor defined { Example:- class Rectangle { Edit with WPS Office © sexed with OK Scannerint width height; public: Rectangle(); //constructor declared int area(void); ‘ Rectangle:Rectangle() { Types of Constructor 1) Default Constructor 2) Parameterized Constructor 3) Copy Constructor 4) Dynamic Constructor 1) Default Constructor: - A constructor which has no argument is known as. default constructor. It is invoked at the time of creating object ‘Syntax: className( ); Program for default constructor #include
Edit with WPS Office © sexed with OK Scannerusing namespace std; 1/ declare a class class Wall ( private: double length; public: // create a constructor Wall { //initialize private variables length = 5.5; cout << "Creating a wall.” << endl; cout << ‘Length = "<< length << endl, % int mainO { // create an object Wall wallt; return 0; Program for default constructor #include
using namespace std; class construct { public: int a, b; \V/4, Edit with WPS Office © sexed with OK Scanner// Default Constructor construct() { a=10; b= 20; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a:" << c.a << endl "cob; return 0; 2) Parameterized Constructor:- It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. Eg:- XVZ{int a, int b) 4 ) XYZ obj(10, 20); \V/4, Edit with WPS Office © sexed with OK ScannerProgram for Parameterized constructor #include
using namespace std; class Add public: //Parameterized constructor Ada(int num1, int num2) { cout<<(num14num2)<
using namespace std; 1/ declare a class class Wall { private: double length; double height; public: // create parameterized constructor Wall(double len, double hgt) { /Lipitialize private variables length = len; height = hgt; } double calculateArea() { \V/4, Edit with WPS Office © sexed with OK Scannerreturn length * height; b int main( { 1/ create object and initialize data members Wall wallt(10.5, 8.6); Wall wall2(8.5, 6.3); cout << "Area of Wall 1: "<< wall1.calculateArea() << endl; cout << “Area of Wall 2:" << wall2.calculateArea() << endl; return 0; 3) Copy Constructor:- Copy Constructors is a type of constructor which is used to create a copy of an already existing object of a class type. Itis usually of the form X (X8), Where X is the class name. The compiler provides a default Copy Constructor to all the classes. ‘Syntax: Classname(const classname Sobjectname) { Program for Copy constructor #includesiostream> using namespace std; \V/4, Edit with WPS Office © sexed with OK Scannerclass copyconstructor { private: int x,y; //data members public: copyconstructor(int x1, int y1) { x=xt; yey; } /* Copy constructor */ copyconstructor (const copyconstruetor &sam) { x= samx; y=samy; void display() { coutcexc<" "“ccyccendl; k int main) { copyconstructor obj1(10, 15); // Normal constructor copyconstructor obj2 = obj1; // Copy constructor cout<<’Normal constructor obj1 display(; cout<<"Copy constructor :* obj2.display(); \V/4, Edit with WPS Office © sexed with OK Scannerreturn 0; Program for Copy constructor #include
Using namespace std; class Date { public: int day, month, year, Date() { cout<<"\n Default Constructor." day=15; month=12; year=2013; Date(int d, int m, int y) { coute<"\n Copy Constructor:\n", year=y; } void show() \V/4, Edit with WPS Office © sexed with OK Scannercouts<"\nDay:"<
#includesstring.h> using namespace std; class Sample { char *name; int length; \V/4, Edit with WPS Office © sexed with OK Scannerpublic: ‘Sample() { length = 0; name = new char{ length + 1]; Sample (char *s) { length = strlen(s); name = new char[ length + 1]; strepy(name , s ); } void display() ( cout
#includescstring> using namespace std; class String { char *name; int length; public : String Q) { length=0; name=new char[length+1]; } ‘String (char *s) // constructor 2 { length=strlen(s); name=new charflength+1]; //one additional strepy(name.s); // character for \O \V/4, Edit with WPS Office © sexed with OK Scanner} Void display() { std:cout<
using namespace std; class Rect{ private: int area; public: Rect(){ area = 0; } Reet(int a, int b){ area=a*b; } void display(){ cout << “The area is: * << area << endl; \V/4, Edit with WPS Office © sexed with OK Scanner} k main()( Rect r1; Rect r2(2, 1 isplay(); 12.display(); Dynamic initialization of object #include
using namespace std; class simple_interest float principle, time, rate interest; public: simple_interest (float a, float b, float c) { principle = a; } void display () { interest =(principle* rate* time)/100; cout<<"interest ="<
using namespace std; //structure definition with private and public members class Student ( private int No; float perc; public: [constructor Student(int r, float p) //function to read details void read(void) { cout << "Enter roll number: cin >> rNo; cout << ‘Enter percentage: " cin >> perc; } //funetion to print details void print(void) { \V/4, Edit with WPS Office © sexed with OK Scannercout << endl; cout << "Roll number: * << rNo << endl; cout << ‘Percentage: " << pere << "%" << endl; i 1/Main code int main { //reading roll number and percentage t //the members while creating object cout << "Enter roll number to initialize the object: *; int roll_number, cin >> roll_number, cout << "Enter percentage to initialize the object: float percentage; cin >> percentage; //declaring and initialize the object struct Student sta(roll_number, percentage); //print the value cout << “After initializing the object, the values are..." << endl; std.print() //reading and printing student details //oy calling public member functions of the structure std.read(); std.print(); return 0; \V/4, Edit with WPS Office © sexed with OK ScannerDestructor A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically. A destructor is defined like constructor. It must have same name as class. But itis prefixed with atilde sign (~), Rules for Writing a Constructor > The destructor must have the same name as the class name with a tilde(~) prefix. > It never takes any arguments and no return value. >» It cannot be declared as static volatile and constant > It takes no argument and therefore cannot be overloaded » It should have public access in the class declaration. ‘Syntax:- ~className(); Program for Destructor #include
using namespace std; class Employee { public: Employee() { Edit with WPS Office © sexed with OK Scannercoute<'Constructor Invoked"<
using namespace std; class HelloWorld{ public: 1/Constructor HelloWorld(){ cout<<"Constructor is called’<
using namespace std; class A { int num, static int count; public: //Constructor A(int n=0); //Destructor ~A0; Static int getcount(); i int A::count: AzA(int n) numer count++; cout<<"Object Created with value"<
Using namespace std; class Account { public: feat salary = 60000; ‘class Programmer: public Account { public: float bonus = 5000; ys int main(void) { Programmer p1; cout<<'Salary: "<
using namespace std; class A { inta int public: int mul() \V/4, Edit with WPS Office © sexed with OK Scanner{ inte = atb; return ¢; % class B: private A { public: void display() { int result = mulQ; std::cout <<'Multiplication of a and bis : "<
using namespace std; 1/ base class class Vehicle NY public: Vehicle() { cout << "This is a Vehicle" << endl; } i // first sub_class derived from class vehicle class fourWheeler: public Vehicle { public: fourWheeler() { cout<<"Objects with 4 wheels are vehicles"<
Using namespace std; \V/4, Edit with WPS Office © sexed with OK Scanner
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2061)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel