[Read more…] about Write A C++ Program To Operator Which Accepts Three Values.
Write A C++ Program To Use Ternary Operator in Cout.
Write A C++ Program For Shorthand Assignment Operator.
Write A C++ Program To Signify Importance Of Assignment (=) And Shorthand Assignment (+=) Operator.
Write A C++ Program To Comparing Integers Using If Statements, Relational Operators And Equality Operators.
Write A C++ Program To Use All Arithmetic Operators.
Basic Structure of A Complete C++ Program With Classes
A C++ program can be developed from a basic structure. The general structure of C++ program with classes is as shown below (which is also called overview of a C++ program):
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
(i) Link Section
(ii) Definition Section
3. Global Declaration Section
4. Class declaration or definition
5. Main C++ program function called main ( )
6. Beginning of the program: Left brace {
(i) Object declaration part;
(ii) Accessing member functions (using dot operator);
7. End of the main program: Right brace}
Documentation Section
In Documentation section we give the Heading and Comments. Comment statement is the non-executable statement. Comment can be given in two ways:
(i) Single Line Comment: Comment can be given in single line by using “II”.
The general syntax is: II Single Text line
For Example: II Add Two Numbers (Heading of the program)
C= a + b; II Store the value of a + b in C.(Comment to explain given statement)
(ii) Multiple Line Comment: Comment can be given in multiple lines starting by using “/*” and end with “*/”.
The general syntax is: /* Text Line 1
Text Line 2
Text Line 3 */
For Example: /* Write a C++ program to find the sum and average of five numbers. */
Preprocessor Directives
These are compiler preprocessor statements. These are also optional statements, but becomes compulsory if your compiler has INCLUDE and LIB subdirectories in the specified drive TCPLUS or having any name.
Pre-compiler statements are divided into two parts.
(i) Link Section: In the Link Section, we can link the compiler function like cout<<, cin>>, sqrt ( ), fmod ( ), sleep ( ), clrscr ( ), exitO, strcatO etc. with the INCLUDE subdirectory having header files like iostream.h, conio.h, math.h, dos.h, string.h, ctype.h, process.h etc. It becomes very useful during the compilation and the linkage phase.
The general syntax is: #include <header file> .or #include “header file”
For example:
#include <iostream.h>
#include <conio.h>
#include “dos.h”
ii) Definition Section: The second section is the Definition section by using which we can define a variable with its value. For this purpose define statement is used.
The general syntax is: #define variable name value
For example:
#define PI 3.142
#define A 100
#define NAME “Dinesh”
Global Declaration Section
In this section, we declare some variables before starting of the main program or outside the main program. These variables are globally declared and used by the main function or sub function. These variables are called global variables. In some programs we use function sub-programs. So we declare some variables in the main program and function sub program having common name. This creates the duplicity or redundancy in defining the variables. So we can take the common variable declaration above the main program, which is also called global variable declaration. The global variables are automatically initialized with zero, hence there is no chance of garbage value. The global variable declaration can be done by the statement given below.
The general syntax is:
data type vl,v2,v3………. vn;
Here data types are int, float, char, double etc. vl,v2,v3, …. vn is the list of global variables(v). For example: Following are the some valid global declaration statement as:
int a, b, c;
float x,y,z;
char ch, name[10], address[20];
Class Declaration or Definition
A class is an organization of data and functions which operate on them. Data types are called data members and the functions are called member functions. The combination of data members and member functions constitute a data object or simply an object.
The general syntax or general form of the class declaration is as follows:
class <name of class>
{
privat:
data members;
member functions O;
public:
data members;
member functions O;
protected:
data members;
member functions O;
};
mainO
{
<name of class> obj1;
obj1.member function O;
obj1.member functionO;
getchO;
}
(i) Class name or name of class
It is mainly the name given to a particular class. It serves as a name specifier for the class, using which we can create objects. The class is specified by keyword “class”.
For example: class Circle
Here Circle is the class name.
(ii) Data Members
These are the data-type properties that describe the characteristics of a class. We can declare any number of data members of any type in a class. We can say that the variables in C and data members in C++.
For example: float area;
(iii) Member Functions
These are the various operations that can be performed to data members of that class. We can declare any number of member functions of any type in a class. Member functions are access using object and dot operator.
For example: void read(); void display();
How member function access: cl.read();
Here c1 is object of class circle and operator dot (.) is used to access member functions.
(iv) Access Specifiers
Access Specifiers are used to identify access rights for the data members and member functions of the class. Depending upon the access level of a class member, access to it is allowed or denied.
There are three main types of access Specifiers in C++ programming language:
1. Private: A private member within a class denotes that only members of the same class have accessibility. The private member is not accessible from outside the class.
2. Public: Public members are accessible from outside the class.
3. Protected: A protected access specifier is a stage between private and public access. If member functions defined in a class are protected, they cannot be accessed from outside the class but can be accessed from the derived class (inheritance).
main()
main function is where a program starts execution. Main () program is the C++ program’s main structure in which we process some statements. The main function usually organizes at a high level the functionality of the rest of the program.
The general syntax is: main ( )
Beginning of the Main Program: Left Brace {
(The beginning of the main program can be done by using left curly brace “{“).
(i) Object declaration part
We can declare objects of class inside the main program or outside the main program. A class declaration only uses to builds the structure of an object. The data members and member functions are combined in the class. The declaration of objects is same as declaration of variables of basic data types. Defining objects of class data type is known as class instantiation (instances of class).When we create objects during that moment,· memory is allocated to them.
For example: c1 is the object of the class Circle. We can create any number of objects of a given class.
(ii) Accessing member functions (using dot operator)
The member function define in the class are access by using dot (.) operator. Suppose we have two member functions void read () and void display (). We have to access these member function in the main program.
The general syntax is:
Obj1. member function();
For example: c1.read();
Here c1 is object and read() is the member function of class Circle ..
Ending of The Main Program: Right Brace}
(The right curly brace “}” is used to end the main program).
Program 2: Write a C++ program to find the area of circle using basic structure of C++ program with c1asses.
1. Documentation Section: Use single line comment
II Program to find the area of circle using basic structure of C++ program
2. Preprocessor Directives: Link and Definition Section
#include <iostream.h> II Link Section
#include <conio.h> II Link Section
#define PI 3.142 II Definition Section
3. Global Declaration Section
float r;
4. Class declaration or definition
class Circle // Class definition (Circle class is created)
{
private:
float area; // Data member
public:
void readO // Member function
{
couk<“Enter the radius of the circle:”;
cin>>r;
}
void displayO
{
.area = PI * r*r;
Cout<< “Area of circle is ” <<area;
}
};
5. Main program starts
main ( )
6. Beginning of the main program: Left brace
{
Circle c1;
c1.readO;
c1.displayO;
getch( );
7. Ending of the main program: Right brace
}
Variables – What is Variable in C++?
A variable is an identifier that refers to the data item stored at a particular memory location. This data item can be accessed in the program simply by using the variable name. The value of a variable can be changed by assigning different values to it at various places in a program.
A variable name should be carefully chosen by the programmer so that its use is reflected in a useful way in the entire program. Variable names are case sensitive.
Examples of variable names are: Sun, number, Salary, Emp_name, average etc.
Any variable declared in a program should confirm to the following points:
1. They must always begin with a letter, although some systems permit underscore as the first character.
2. The length of a variable must not be more than 8 characters.
3. White space is not allowed and
4. A variable should not be a Keyword
5. It should not contain any special characters.
Examples of Invalid Variable names are: 123, (area), 6th, %abc etc.
Declaration of Variables
Definition: “Variables are those quantities whose value can vary during the execution of the program”
Variables must be declared in a program before they are used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function Variables uses the primary storage area.
Variables are basically memory locations which are given names and these locations are refereed in the program by variable names to read and write data in it. Variables are used for identification for entering the information or data. In variable you can enter integer value or real or character value (string value) according to the requirement. So we can say that variable are either of integers or float type or string type according to the data type used in C++ programming. Variables are used in C++ programs for reading data from the keyboard or from the file, process some formula and printing the information. In C++ language variables have no length for declaration, but some compilers allow either 31 character or 8 character long variables. It contains the name of a valid identifier. The syntax for declaring a variable is
data_type variable_name;
For example, a variable a of type int can be declared using this statement.
int a;
At the time of the variable declaration, more than one variable of the same data type can be declared in a single statement. For example, consider this statement.
int x, y, z;
Note that in C++, it is not necessary to declare the variables in the beginning of a program as required in C. It can be declared at the place where it is used first.
Initialization of Variables
Declaration of variables allocates sufficient memory for variables. However, it does not store any data in the variables. To store data in variables, they need to be initialized at the time of declaration. For example, consider this statement.
int i=10;
In this statement, a variable i of the integer type is declared and initialized with a value of 10. We can assign a value to a variable by using assignment operator (=).
Variables can either be initialized at the compile-time or at the run-time initialization at the compile-time using a constant is known as static initialization. However, variables can also be initialized at the run-time using expressions initialization of variables at the run-time is known as dynamic initialization.
To understand the concept of static initialization and dynamic initialization, consider this example.
Example 1:A program to demonstrate static and dynamic initialization
#include<iostream>
using namespace std;
int main ()
{
int num1 = 5, num2 = 6; //static initialization using
I I constant
int num3 = num1 + num2; // Dynamic initialization
II using expression
cout<<num3;
return 0;
}
The const qualifier: When the qualifier const precedes a data type in the declaration of a variable, it implies that the value of the variable cannot be changed throughout the program. For example, consider this statement.
const float pie_val = 3.14;
The qualifier const with variable pie_val ensures that the program cannot alter its value inadvertently. If any attempt to alter the value of pie_val is made within a program, a compile-time error is generated. Moreover, if any data type is not specified with the const qualifier, by default it is int. For example, consider these statements.
const int max = 20; II Both these statements
const max = 20; II are equivalent.
Note that C also allows to create canst values. However, there are some differences in the implementation of const values in C and C++, which are discussed here.
• In C++, the variable declared as a constant must be initialized at the time of its declaration. While in C, const value is automatically initialized to 0 if it is not initialized by the user.
• In C++, const can be used in expressions. For example, consider these statements.
const int max =20;
char name [max] ;
However, it is invalid in C.
• In C++, by default, a const value is local to the file in which it is declared. However, it can be made global by explicitly defining it as an extern variable, as given here.
extern canst max=10;
In C, by default, canst value is recognized globally, that is, it is also visible outside the file in which it is declared. However, it can be made local by declaring it as static.
Reference Variables
A Reference variable, a new kind of variable that is introduced in C++ provides an
alias for an already defined variable. Like other variables, reference variables must
be declared in a program before they are used. The syntax for declaring a reference variable is
data_type & refname = varname;
where,
data_type = any valid C++ data type
& = reference operator
refname = the name of the reference variable being declared
varname = the name of the variable whose reference is being declared
To understand the concept of reference variable, consider this example.
Example 2: A Program to demonstrate the use of reference variable
#include<iostream>
using namespace std;
int main ( )
{
float cost = 200;
float &price = cost;
II Declaration of Reference variable
Cout<<“price: ” <<price<<“\n”;
price = price+20;
cout<<“cost: ” <<cost<<“\n”;
cout<<“price: ” <<price;
return 0;
}
The output of the program is
price: 200
cost: 220
price: 220
In this example, price is declared as a reference variable for the variable cost. Since both the variables refer to the same memory location, the statement price=price + 20 changes the value of both price and cost.
Storage Class Specifiers
In addition to data type, a storage class is also associated with a variable which determines the scope and life-time of a variable. The scope refers to the part of the program that can access that variable and life-time refers to the duration for which a variable stays in existence. The syntax for declaring a variable with the storage class is
storage_class data_type variable;
There are four storage class Specifiers supported by c++ namely, auto, extern, static and register, which are discussed here.
Automatic Variable: A variable defined within a block or a function is known as local variable and can be accessed within that block or function only. In C++, this local variable is referred to as automatic variables. A variable is made automatic by prefixing its declaration with the keyword auto.
An automatic variable is created only when the function or block in which it is declared is called and is automatically destroyed when the function returns. In addition, it needs to be initialized explicitly with a valid value; otherwise, it will be initialized with a garbage value.
External Variable: A variable that is accessible to all the functions in the file in which it is declared is known as global variable. However, if a global variable has to be accessed by some other file, it has to be declared as an external variable in that file by prefixing its declaration using the keyword extern. The keyword extern informs the compiler that the variable is defined in the same file or another file. An external variable remains in existence throughout the life of the program and its value is retained between the function calls. In addition, an external variable is automatically initialized to zero.
Static Variable: A variable that is recognized only inside the function in which it is declared, but remains in existence throughout the life of program is known as static variable. A variable is declared static by prefixing its declaration by the keyword static. Both local and global variables can be declared as static.
When a local variable is declared as static, it is known as static local variable. A static local variable retains its value between the function calls. Moreover, it can be initialized with the constants only at the time of declaration and its value can be changed later at any point within the function. However, it is initialized only once, that is, at the time of creation.
When a global variable is declared as static, it is known as static global variable. A static global variable can be accessed by all the functions of the program in the same file in which it is declared. However, functions in other files cannot access it. The lifetime and initialization of static global variable is the same as that of static local variable.
Register Variable A variable that is stored in the register (a special storage area within the central processing unit) instead of the main memory where other variables are stored is known as a register variable. A register variable speeds up the execution of a program as it does not require a memory access like normal variables. The register variable is declared with the help of the keyword register.
The scope and life-time of the register variable is the same as that of the automatic variable. Note that, the register storage Specifiers is applied only to pointers and to variables of type int and char. In addition, only local variables and the arguments which are passed to the functions can be declared as register variables. Moreover, declaring a variable as register does not guarantee that it will be a treated as register variable. In that case, it will be treated as an automatic variable.
Constants – Type of Constants in C++
Constants refer to fixed values that the program may not alter. Constants can be of any of the basic data types. The way each constant is represented depends upon its type. Constants are also called literals.
Definition: “A constant value is the one which does not change during the execution of a program.”
Constant uses the secondary storage area. Constants are those quantities whose value does not vary during the execution of the program i.e. constant has fixed value. Constants in every language are the same. For example, in the C++ language some valid constant are: 53.7 , -44.4, +83.65, “Dinesh”, ‘M’, “2013” , “\n” etc.
In C++ language constants are of two types:
1. Numeric Constant
2. Non-Numeric Constant (Character Constant)
These are further sub-divided into more categories.
Numeric Constant
These have numeric value having combination of sequence of digits i.e. from 0-9 as alone digit or combination of 0-9 with or without decimal point (precision value) having positive or negative sign. These are further sub-divided into two categories as:
(i) Integer Numeric Constant
(ii) Float or Real Numeric Constant
(i) Integer Numeric Constant
An Integer Numeric Constant is a sequence of digits (combination of 0-9 digits without any decimal point or without precision), optionally preceded by a plus or minus sign.
There are 3 types of integer numeric constant namely decimal integer, octal integers and hexadecimal integer.
(a) Decimal Integer Numeric Constant: These have no decimal point in it and are either be alone or be the combination of 0-9 digits. These have either +ve or -ve sign. For example: 1214, -1321, 10,254, -78, +99 etc.
(b) Octal Integer Numeric Constant: These consist of combination of digits from 0-7 with positive or negative sign. It has leading with 0 or 0 (upper or lower case) means Octal or octal. For example: 0317,003, -045 etc.
(c) Hexadecimal Integer Numeric Constant: These have hexadecimal data. It has leading ox, OX, Ox or x, X. These have combination of 0-9 and A-F (a-f) or alone. The letters a-f or A-F represents the numbers 10-15. For example: 0x232, 0x92, 0xACD, 0xAEF etc.
(ii) Float or Real Numeric Constant
Float Numeric Constants consists of a fractional part in their representation; Integer constants are inadequate to represent quantities that vary continuously. These quantities are represented by numbers containing fractional parts like 26.082.
Examples of real constants are: 0.0026, -0.97, 435.29, +487.0, 3.4E-2, 4.5E5
A floating-point constant consists of a sequence of decimal digits, a decimal point, and another sequence of decimal digits. A minus sign can precede the value to denote a negative value. Either the sequence of digits before the decimal point or after the decimal point can be omitted, but not both.
Float Numeric constants are further divided into two parts. One is Mantissa Part and the other is Exponent Part.
(a) Mantissa part: The part without E and having a decimal point is called Mantissa Real part e.g. 45.5, -22.43, 0.5 etc. it is also called without exponent part.
(b) Exponent part: The exponent part has an E within it. It is also called a scientific notation. Here E has base value 10. it computes the power. For example: 4.2xl02 can be written as 4.2E2, 4.2xlO-5 can be written as 4.2E- 5.-Similarly some more valid real numeric constant are as: 54.73 E -4,51.9 E +11 etc.
Character Constant
Character constants have either a single character or group of characters or a character with backslash used for special purpose. These are further subdivided into three types:
(i) Single Character Constant
(ii) String Character Constant
(iii) Backslash Character Constant
(i) Single Character Constant
Single Character constants are enclosed between single quotes(‘). For example, ‘a’ and ‘%’ are both character constants. So these are also called single quote character constant.
For example: ‘a’, ‘M’, ‘5’, ‘+’, ‘1’ etc. are some valid single character constant.
(ii) String Character Constant
C++ supports another type of constant: the string. A string is a set of characters enclosed in double quotes (“). For example: “Punar Deep” is a string.
You must not confuse strings with characters. A single character constant is enclosed in single quotes, as in ‘a’. However, “a” is a string containing only one letter.
For example: “Dinesh”, “Hello”, “2013”, “2013-2020”, “5+3”, “?+!” etc. are some valid string character constant. These are used for printing purpose or display purpose in the C++ program’s output statements. These can also be used for assigning the string data to the character (string) type variables.
(iii) Backslash Character Constants
Enclosing character constants in single quotes works for most printing characters. A few, however, such as the carriage return, can’t be. For this reason, C++ includes the special backslash character constants, shown below, so that you may easily enter these special characters as constants.
These are also referred to as escape sequences. You should use the backslash codes instead of their ASCII equivalents to help ensure portability.
These are used for special purpose in the C++ language. These are used in output statements like cout etc.
Escape Sequences
A list of backslash character constant or escape sequence is as in the below table:
Keywords And Identifiers
Every word in C++ language is a keyword or an identifier. Keywords in C++ language cannot be used as a variable name. They are specifically used by the compiler for its own purpose and they serve as building blocks of a C++ program. C++ language has some reserve words which are called keywords of C++ language. These are the part of the C++ Tokens.
There are 63 keywords currently defined for Standard C++. These are shown in Table. Together with the formal C++ syntax, they form the C++ programming language. Also, early versions of C++ defined the overload keyword, but it is obsolete. Keep in mind that C++ is a case-sensitive language and it requires that all keywords be in lowercase.
Identifier
The name of a variable, function, class, or other entity in C++ is called an identifier. C++ gives you a lot of flexibility to name identifiers as you wish. However, thereare a few rules that must be followed when naming identifiers:
• An identifier that cannot be used as a variable name is a reserved word.
• The identifier can only be composed of letters, numbers, and the underscore character. That means the name can not contains no symbols (except the underscore) or whitespace.
• The identifier must begin with a letter or an underscore. It can not start with a number.
• C++ distinguishes between lower and upper case letters nvalue is different than nValue is different than NVALUE.
Character Set – What is Character Set in C++?
Character set is the combination of English language (Alphabets and White spaces) and math’s symbols (Digits and Special symbols). Character Set means that the characters and symbols that a C++ Program can understand and accept. These are grouped to form the commands, expressions, words, c-statements and other tokens for C++ Language.
Character Set is the combination of alphabets or characters, digits, special symbols and white spaces same as learning English is to first learns the alphabets, then learn to combine these alphabets to form words, which in turn are combined to form sentences and sentences are combined to form paragraphs. More about a C++ program we can say that it is a sequence of characters. These character from the character set plays the different role in different way in the C++ compiler. The special characters are listed in Table
In addition to these characters, C++ also uses a combination of characters to represent special conditions. For example. character combinations such as ‘\nt, ‘\b’ and ‘\t’ are used to represent newline, backspace and horizontal tab respectively.
When we have to learn English language we start from beginning as given below:
When we have to learn C language we start from beginning as given below:
There are mainly four categories of the character set as shown in the Figure.
1. Alphabets
Alphabets are represented by A-Z or a-z. C- Language is case sensitive so it takes different meaning for small and upper case letters. By using this character set C statements and character constants can be written very easily. There are total 26 letters used in C-programming.
2. Digits
Digits are represented by 0-9 or by combination of these digits. By using the digits numeric constant can be written easily. Also numeric data can be assigned to the C-tokens. There are total 10 digits used in the C-programming.
3. Special Symbols
All the keyboard keys except alphabet, digits and white spaces are the special symbols. These are some punctuation marks and some special symbols used for special purpose.
There are total 30 special symbols used in the C-programming. Special symbols are used for C-statements like to create an arithmetic statement +, -, * etc. , to create relational statement <, >, <=, >=, == etc. , to create assignment statement =, to create logical statement &&, II etc. are required.
4. White Spaces
White spaces has blank space, new line return, Horizontal tab space, carriage ctrl, Form feed etc. are all used for special purpose. Also note that Turbo-C Compiler always ignore these white space characters in both high level and low level programming.
Inline Function in C++
Functions used in the program help reduce the program’s size as multiple calls to a function causes the execution of the same set of instructions which appears only once in the memory without any duplication. However, each time a function called, it involves substantial execution time overheads for tasks such as storing memory address of the instruction following the function call, saving values of registers, pushing actual arguments onto the stack and passing control to the function where the arguments of the called function are popped (removed) from the stack. Then the body of function executes. If there is any return statement, the value returned to the calling program. Finally, the control transferred back to the calling program. All these overheads increase the execution time and consequently reduces the efficiency of the program. [Read more…] about Inline Function in C++
Union in C++
Union is also like a Structure means Unions is also used for Storing data of different data types But the Difference b/w Structure and Union is that Structure Consume the Memory of addition of all elements of Different Data Types but a Union Consume the Memory that is Highest among all variables. [Read more…] about Union in C++
Structure in C++ Language
We Know that C++ Language Provides us the various types of data types like Int,Float Char etc These are also called the Predefined Data types those are used for Storing the values in the Variables
The C++ Language also provides us to create a data type which includes all the other data types of int , float and character The Main user defined data type is Structure Which Provides us the facility to make a data types which hold either the int value, float value of character values
Structure is the user defined data type that is used for creating a single Variable which makes us possible to declare a value either a int, float or character A user First Make a Structure of different data types with their respective variables A structures is like container which hold all the different variables with their different values and their different length.
Always Remember that the member of the Structure is always Accessed with the help of the. Operator or if we wants to access a variable of the structure then we must use the .(dot) Operator. The Member of the Structure are always Accessed through the Structure variables or For Accessing the Elements of the Structure First you have to create the instance of the Structure then with the help of the Structures you can use the any variable that is defined in the Structure.
for declaring the structure we can use this
struct stu
{
char name[10],lastname[10];
int age;
float height;
}
in this structure will consume the 26 bytes of the Memory
10 for name
10 for Lastname
2 for Age
4 For Height
As you can see the Memory size of the Structure is equals to the Number of Bits of particular data types consume And the Total Memory Sized is Judge by the Total Number of Variables with their Respective memory Size Like For
An Integer consume 2 Bytes in the Memory
An Character Consume 1 Byte In Memory
An Float Consume 4bytes in Memory.
What is to Pointers
These are the Special Variables those are used storing the address of variable .We know that Every variable must be Stored in Memory of Computer or in other words a Small part of Memory if used by a Variable For Storing his value So that For Storing a Value into a variable
There must be need some Memory When We declare a variable and after when we Compiles our program then Compiler will gives the Some Memory For Storing his value So that if you wants to Check where in Memory , Value of variable is Actually Stored , Then we have to use Pointers Which Returns us Address of Memory Where the Variable is Actually Stored.
As I Mentioned Pointer is also a Variable So that the Pointer variable also must be declared With the Sign of asterisk or star (*) in front of variable
A Variable is declared with a asterisk Sign is known as pointer variable. For Retrieving a Address of Variable you have to put the Address of variable with the help of & Address Operator in Front of variable like this
Int a ,*p
a=10
p = &a
Here p is a Pointer variable and this will stores the Address of a Variable a if you wants to see the Address of a variable then we uses the cout Function with the name if variable.
Pointer to Pointer:- Pointer to Pointer is used when we wants to Retrieve the value that is stored in Memory of Actual value that is stored in a pointer variable When at the Time Print when we again put the asterisk sign in front of pointer variable then this will be the Pointer to pointer variable.
Benefits of Pointers: –
1) For Displaying the Memory Location and When we knows about the Address of a Variable then we can change the value of variable
2) When we doesn’t know about the actual size of data then we declare the variable as pointer We can declare a pointer as Pointer , An Array and Also a Strings
3) The Number of Length needs not to be count .The Actual Length of Pointer variable will be depends of Number of Elements or values those are put into the variables
4) We can Pass a Pointer to Function in the Form of Array and Also as Strings
What is Array in C++ ? Type of Array
Arrays: When there is a need to use many variables, then there is a big problem because we will Conflict with the name of variables. So that in this situation where we want to Operate on many numbers, we can use array. The Number of Variables also increases the complexity of the Program so that we use Arrays.
Arrays Set of Elements having the same data type, or we can Say that Arrays are Collections of Elements having the same name and same data type. But Always Remember Arrays Always started From their index value, and the index of the array starts From 0 to n-1. [Read more…] about What is Array in C++ ? Type of Array
File Handling in C++
We know that Files are used for Storing Permanent information. And C++ provides a Facility to a developer the Retrieve the Information from File and he may also modify the Contents of a File So that we can say that File Handling is the Concept to Store, Retrieve and Modify the Information which is stored in the Form of Files in your Computer.
There are Many Built in Classes of C++ , Which Provides Various Functionality for Performing the Operations on Files . A user has a Ability to Modify the data of a File With the help of these Functions. Generally a user can use a File Read, Write or For Appending More data into the File so that C++ Provides Various Classes For Performing these Operations. There are two most important Classes which are known as ifstream and ofstream. Ifstream stands for input Stream which is used for Reading the Contents from a File and output Stream or Simply ofstream is used for writing data into the Files.
There is one More Class Which is used for Both Performing read and write known as fstream class and Always Remember for using Any Class First we have to use or include a header file which is called as Fstream.h header file.
Various Functions for Reading and writing data of Files
1) get: – This Functions Stands for Reading data from a File in the Form of Character .
2) Put :- This Function is used for Writing the data into a File in the Form of Characters
3) << and >> These Operators are also used for Writing the data into the File , The Data may int,float or any other data type . << Operator is used for Writing data into a File and >> Operator is used for Reading data from a File.
4) Read and Write: – With the help of C++ one can also Read or Write the Data from a File . But C++ also Provides a Write Method or Function For Writing the data of A Class into a File Like Data of a Member Functions, Values of data Members of a Class and One Can also Read the Information once this written into a File with the help of Read Method or Function.
But Always Remember for reading or Writing data from a Class , first a user have to Explicitly Cast or Convert the data of a class in the form of characters because data is written into a File in the Form of Characters and a user have to create some Memory for Specifying how mush data is to be Written into a file and vive-versa for Reading data of a class from a File Whenever a user open a File, The File will Opened and the Pointer of File is stood on first Character or First Line of a File and if a user wants to Read all the data from a File then a user have to use eof () or Simply End of File Functions , a user can read the data until a File doesn’t comes to end A user have also a ability to read data from any Location from a File So that a User have to use Seekg function for Reading data from a Random Position With the help of Seekg function a user can read data from a file , from any position
Increment Operator and Decrement Operator
All the Above Operators are Called as Binary Operators because they takes two Operands for Performing an Operation. But the Increment and decrement operators are called as Unary because they takes only one operand For Performing an Operation This Operator Contains ++ for Increment and — for Decrement. [Read more…] about Increment Operator and Decrement Operator
Different types of Operators.
An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C++ language program to operate on data and variables. C++ has a rich set of operators which can be classified as [Read more…] about Different types of Operators.
Scope Resolution Operator
A global variable is one whose value can be used anywhere in the program. Its value can be used in the Main() function and all other functions in the program. However, a local variable is one whose value is local to the function i.e. its value can be used in that particular function only where it is declared. A global variable is defined before the Main() function. Same name can be given to local and global variables. For example in the following program segment [Read more…] about Scope Resolution Operator
What is Control Statements?Explain
The Control Statements are used for controlling the Execution of the program there are the three control statements those are break, goto, continue. [Read more…] about What is Control Statements?Explain
What is to Loop? Type of Loop
A Computer is used for performing many Repetitive types of tasks The Process of Repeatedly performing tasks is known as looping .The Statements in the block may be Executed any number of times from Zero to Up to the Condition is True. The Loop is that in which a task is repeated until the condition is true or we can say in the loop will Executes all the statements are until the given condition is not to be false. [Read more…] about What is to Loop? Type of Loop
What is Control Statements? Explain
We know that Instruction those are written in c++ Language are Executed in Sequence wise or Step Wise as they are Written in Program. Or these are executed in Sequence Order.Decision Making statements are used when we wants to execute the statements as according to the user needs. A User can Change the Sequence of the Statements for Execution.
Many Times we Wants to Execute the Set of Instructions to be executed in one Situation and other Statements in other Situations for Executing the Statements in Specific Situation there are Some Decision Making Statements or Decision Control Statements those are provided by the C++ Language. In The Decision First a Condition is checked it is true then it Executes the next Instruction otherwise it Executes other Statements.
There are three decision making statements :-
1) if
2) if-else
3) The Conditional Operators.
Understanding If statement
The Keyword if tells the compiler what follows The Condition Following the Keyword if is always enclosed within a pair or Parentheses if The Condition id True Then the Statements is Executed if the Condition is not true then the Statement is not Executed For Checking a condition. Relational Operators are Used Like > ,< ,==, >=,<= etc. The if statement is widely used for checking a particular condition
Suppose you want to check the condition and then execute the condition
if your condition is met
for ex:
if(a>b)
then print a is greater then here we first check the condition
that either a is greater than b if yes then execute the condition
1) if-else= the if Statement is used for Executing a Single Statement or a Group of Statements When the Condition Following is true. It does nothing when the Condition is False , For Executing the group of Statements either a Condition is False we uses else The if-else is similar to if but the difference is that is also provides us the alternative to execute the other statement if a condition is not true for ex:
if(a>b)
cout <<a
else
cout <<b
Here if first checks the condition either the a is greater than b if yes then it will print a suppose if a is not greater than b then it will be print b because we specify the b in the else statement.
2) if-elseif
The if-elseif is similar to the if-else but here the first if is used for checking a condition and the other elseif is used for checking a one more condition suppose if we wants to check the two or more conditions then we can use the if-elseif In This first if Statement Checks the Condition whether it is true or not if the first Condition is false then it jumps to the Second if Statement for Checking the next Condition so and so. if all the Conditions are false the Control will jump to the else block
3) Conditional Operator: – This Operates is also same like a if –else Statement., In this we first Checks the Condition and then this will gives us the Result after Checking the Condition. This Operators uses ? and : Signs . In this ? is used for Checking a Condition after Checking this will gives us the Results but if a Condition has Failed then this will Execute the Statements those are Written in the : ( Colon ) For Example
int a,b,c
a=10
b=20
c= (a>b) ? a : b
Now here we are seeing that the value f a is Less than so this will Store the value of b variable into the C variable. Means c Contains 20.
Switch Statement:-This Statement is Similar to if –else but it uses matching operations rather than checking a condition if we Wants to Check Many Conditions then the Program will very Complex So in that Situation We Will use Switch Statement Switch Statement Uses Many Cases rather and it matches the value with Case where it Matches it will Execute the Statement But There is Very Necessary to Stop the Execution of Each Case So that it Doesn’t Execute Next Case So that for this Purpose we have to put the break Statement after Ending of an Each Case We Know if uses Else Statement if Condition is False or All Conditions are False The Code of Else Statement is Executed if Code of all if statements is false So that in Switch Default is used when all Cases are not Matched.
Enumeration Data Type
An enumerated data type is also an user defined data type. The enum keyword is given before the enumerated data type. A list can tell the compiler which values a given variable can take. Consider the following example:
enum temp{Veryhot, Hot, Medium, Cold};
temp is of enum type and has four members Veryhot, Hot, Medium and Cold. The value 0 is assigned to Veryhot, value 1 is assigned to Hot, 2 is assigned to Medium and so on. The enum specifier allows the user to specify the possible value of the type. If an initial value of -1 is assigned to the first element of the enum type, the subsequent elements are assigned the values 0, 1, 2, etc.
A variable of enum type can be declared as follows:
temp t1;
This indicates that t1 is a variable of type temp which is of enum type.
Example
Write C++ program illustrates the use of enumerated data type.
#include <iostream.h>
#include<conio.h>
enum qlty{excellent, good, average};
struct product
{
char prodno[10];
char prodname[20];
qlty q1;
} prod;
void main()
{
clrscr();
cout<<"Enter Product Number :";
cin>>prod.prodno;
cout<<"Enter Product Name :";
cin>>prod.prodname;
cout<<"Enter quality code for the product.";
cout<<"\n0 for excellent, 1 for good, 2 for average \n";
cin>>int(prod.q1);
cout<<"\n\nProduct Number :"<<prod.prodno;
cout<<"\nProduct Name :"<<prod.prodname;
if(prod.q1==0)
cout<<"\nQuality Excellent";
else if(prod.q1==1)
cout<<"\nQuality Good ";
else
cout<<"\nQuality Average ";
getch();
}
What is Function Overloading and Operator Overloading
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler.
selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn’t add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).
What is Inline Member Function?
As we know that when we call the Member Function from the Class then the Compiler will jump to that Function and after Executing all the Statements the Compiler will execute the Remaining Statements.
And Many Times there is a Situation when we Wants to Call a Function again and Again. So that Compiler will also jump to that Function Again and Again So that this will Decrease the Speed of Execution so that for Removing this Jumping. We uses the Inline Member Functions. The Member Functions those are declared by using the Inline are copied into the Memory of the Compiler.
So that when we first Time Call the Member Function of the Class all the Statements are gets copied into the Memory of the Compiler. So that When Compiler will execute that Method then this will never jump to that Method Again and again instead this will execute that Member Function from his Memory.
What is Friend Functions in C++
In C++, a class encapsulates data and functions that operate on that data. Data members are usually made private so that they cannot be accessed from the class’s non-member functions. However, in certain situations, there is a need to access the private data members of a class by a function that is not the class member. It can be achieved by making the non-member function as a: friend function. [Read more…] about What is Friend Functions in C++
What is Static Data Members and Static Member Functions
As we know that For Accessing anything means Data Members and Member Functions from a Class, we must have to Create an Object First, So that When we Create an Object of Class, then all the Data of Class will be Copied into an Object so that this will Consume Some Memory. So that double Memory will be used for Storing the Data of single Class. First, Memory used by the Class for storing his data and Second by Object. So that for Removing the Problem for storing the data and Member Functions twice. We use the Static and Static Member Functions. [Read more…] about What is Static Data Members and Static Member Functions
What is Functions? Explain Features of Functions,Types of Functions and Calling a Function
Functions are used for Placing or Storing the Code which is to be Repeated Several Times. For Example, if we need Same Code, then we must have to Write that Code Again and Again So that for Removing this Task, we uses functions.
The Functions are Some Storage Area which Contains set of Statements and the Function Executes all the Contained Statements when a Special Call is made to them. Once a Code is stored in the Function, then we can Store that Function any time and Any Time we can call that Functions.
Functions are used for performing the repetitive task or we can say the functions are those which provides us the better efficiency of a program it provides us the facility to make a functions which contains a set of instructions of the repetitive types or we need them in a program at various places Thus a functions provides us the ability to make a function which contains a code and then use them when a functions can call then it executes the statements those are contained in it.
Functions Provides us Following Features
• Reusability of Code : Means Once a Code has Developed then we can use that Code any Time.
• Remove Redundancy: Means a user doesn’t need to Write Code Again and Again.
• Decrease Complexity: Means a Large program will be Stored in the Two or More Functions. So that this will makes easy for a user to understand that Code.
There are Two Types of Functions
• Built in Functions
• User Defined functions
The Functions those are provided by C Language are refers to the Built in Functions For example. cin and cout, getch , Clrscr are the Examples of Built in Functions. So that all the functions those are provided by the C++ Language are Pre defined and Stored in the Form of header Files so that a user doesn’t need to Know how this Function has developed and a user just use that Function.
But in the other hand the Functions those are developed by the user for their Programs are known as User Defined Programs. When a user wants to make his Own Function, then he must have to follow the Following Operations.
• Function Declaration or Prototyping
• Function Defining
• Calling a Function
1) Function Declaration or Prototyping:For using a Function a user must have to declare a Function. The Function declaration contains the Name of Function, Return type of the Function and also the Number of Arguments that a User will takes for performing the Operation.
The Function Prototyping Contains
1) Return Type of a function: The Return Function determines whether a Function will return any value to the Function. If a Function is declared with the void Keyword or if a Function Contains a void then that’s means a Function Never Returns a value. Means a Function will Executes his statements one by one. And if a Function Contain any other data type means if a Function Contains int or Float then the Function must return a value to the user.
2) Name of Function : The Name of Function must be valid and the name of function must be Start from any Alphabet and the Name of Function doesn’t Contains any Spaces and the Doesn’t Contains any Special Character For Example Space , * sign etc.
3) Argument List: A Function may have zero or More Arguments. So that if we want to call a Function. Then we must have to Supply Some Arguments or we must have to pass some values those are also called as the Argument List. So that The Argument List is the total Number of Arguments or the Parameters those a Function Will takes. So that We must have Supply Some Arguments to the Functions,. The Arguments those are used by the Function Calling are known as the Actual Arguments and the Arguments those are used in the Function declaration are Known as the Formal Arguments, When we call any Function then the Actual Arguments will Match the Formal Arguments and if a proper Match is Found, then this will Executes the Statements of the Function otherwise this will gives you an error Message.
There are Two Ways for Calling a Function
1) Call by Value:-when we call a Function and if a function can accept the Arguments from the Called Function, Then we must have to Supply some Arguments to the Function. So that the Arguments those are passed to that function just contains the values from the variables but not an Actual Address of the variable.
So that generally when we call a Function then we will just pass the variables or the Arguments and we doesn’t Pass the Address of Variables , So that the function will never effects on the Values or on the variables. So Call by value is just the Concept in which you must have to Remember that the values those are Passed to the Functions will never effect the Actual Values those are Stored into the variables.
2) Call By Reference :-When a function is called by the reference then the values those are passed in the calling functions are affected when they are passed by Reference Means they change their value when they passed by the References. In the Call by Reference we pass the Address of the variables whose Arguments are also Send. So that when we use the Reference then, we pass the Address the Variables.
When we pass the Address of variables to the Arguments then a Function may effect on the Variables. Means When a Function will Change the Values then the values of Variables gets Automatically Changed. And When a Function performs Some Operation on the Passed values, then this will also effect on the Actual Values.
What is Method or Function Overriding
As the name suggest Override means to hide or Remove the Detail which is already Exists .Method or Function Overriding always Occur in the Inheritance, when a base Class and Derived Class both have a same name of Method. Then we will call that Method then this will Call the Method of Derived Class and Override the Body of Base Class Method.
Suppose there is a Class Whose Name is First and there is also a second Class which uses the First Class and First Class Contains a Member Function whose name is show and Second Class also Contains a Member Function whose is show, then we will Creates the Object or Second Class and call the show Method then this will Override the Body or Statements of the First Class Member Function and this will Execute the Method of Derived Class. This is the Concept of Method Overriding.