Professional Documents
Culture Documents
What Is A C++
What Is A C++
What Is A C++
C/C++ Programming
Computer Languages:- It is defined as the way of communication between a person and a computer, and between two
computers. A person can communicate with a digital computer in computer languages, e.g., C/C++, FORTRAN,
PASCAL, BASIC, etc, just as human communicate in natural languages, e.g., ENGLISH, PASHTO, URDU, etc. There
are hundreds of computer languages used for communication with a computer and these languages are also called
Artificial Languages. Computer languages are of the following types.
1. Low-Level Languages:- The lowest and most elementary language of a computer is the Machine language also
called Binary Language or Language of 0 and 1. This is also called the language of computer, because computer
directly understands it. But it is very much difficult for users and are machine depended i.e it varies from machine
to machine. All the program codes are in pure binary form, which are very much difficult for the humans to
memorize or understand. A little bit highest level of this language becomes the Assembly language also called
symbolic programming language, which carry English like instructions and is human-readable but still it needs
the knowledge of computer internal hardware/working structure.
2. High level Languages:- The languages, which are one step higher than Low-level languages in human
understanding, are called High-Level Languages. These languages have their own set of characters, words and
symbols in which a programmer can write his own programs according to certain rules similar to the Natural
Languages. The high-Level Languages are also called Compiler or Procedural Languages. Programs written in
these languages are easier and understandable to humans than the Low-level Languages. These languages are
machine independed because these languages are more User-oriented than the machine internal structure, i.e.
Programs written in these languages using one computer can easily be run on another computer, e.g., BASIC,
FORTRAN, COBOL, etc.
Computer Languages and Packages:- In computer languages we define the problems and give our own instructions to
the computer, e.g. BASIC, FORTRAN, PASCAL,C/C++ etc. But in computer packages we can solve our problems
without giving our instructions to the computer. They need only a few keystrokes and ready-made commands to help in
solving our specific problems. Computer languages are versatile to solve the problems where as the computer packages
are not versatile and are specific to problem solutions.
What is C ? C is a general purposes high-level programming language developed by Dennis Ritchie at Bell Labs in the
mid 1970s. Although originally designed as a systems programming language, C has proved to be a powerful and flexible
language that can be used for a variety of applications, from business programs to engineering. C is a particularly popular
language for personal computer programmers because it is relatively small -- it requires less memory than other
languages.
The first major program written in C was the UNIX operating system, and for many years C was considered to be
inextricably linked with UNIX. Now, however, C is an important language independent of UNIX.
Although it is a high-level language, C is much closer to assembly language than are most other high-level languages.
This closeness to the underlying machine language allows C programmers to write very efficient code. The low-level
nature of C, however, can make the language difficult to use for some types of applications.
What is C++?
C++ is an object oriented programming language created by Bjarne Stroustrup in 1985. It implements “data abstraction”
using a concept called “Classes”, along with other features to allow Object Oriented Programming. Parts of the C++
program are easily reusable and extensible, existing code is easily modifiable without actually having to change to code.
C++ adds a concept called “operator overloading” not seen in the earlier OOP languages and it makes the creation of
libraries much cleaner.
C++ maintains the aspect of the C programming language, yet has features which simplify memory management.
Additionally, some of the features of C++ allow low level access to memory but also contain high level features.
C++ is a superset of C. C programs will run in C++ compilers. C uses structural programming concepts and techniques
while C++ uses object oriented programming and classes which focus on data.
2
History of C: By 1960 a hoarde of computer languages had come into existence, almost each for a specific purpose. For
example, COBOL was being used for Commercial Applications, FORTRAN for Engineering and Scientific Applications
and so on. At this stage people started thinking that instead of learning and using so many languages, each for a different
purpose, why not use only one language, which can program all possible applications. Therefore, an international
committee was set up to develop such a language. This committee came out with a language called ALGOL 60. However,
ALGOL 60 never really became popular because it seemed too abstract, too general. To reduce this abstractness and
generality, a new language called Combined Programming Language (CPL) was developed at Cambridge University.
CPL turned out to be so big, having so many features, that it was hard to learn and difficult to implement.
Basic Combined Programming Language (BCPL), developed by Martin Richards at Cambridge University aimed to solve
this problem by bringing CPL down to its basic good features. But unfortunately it turned out to be too less powerful and
too specific. Around same time a language called B was written by Ken Thompson at AT&T Bell Labs, as a further
simplification of CPL. But like BCPL, B too turned out to be very specific. Ritchie inherited the features of B and BCPL,
added some of his own and developed C. Ritchie’s main achievement is the restoration of the lost generality in BCPL and
B, and still keeping it powerful.
Advantages of C
• Programs written in C are very efficient and fast. This is due to its variety of data types and powerful operators. It is
many time faster than BASIC. This helps developers in saving their valuable time.
• C is a powerful and flexible language, which helps system developers to deliver various complex tasks with ease. C is
used for diverse projects as operating systems, word processors, graphics, spreadsheets, and even compilers for other
languages.
• C is popular among professional programmers for programming, as a result, a wide variety of C compilers and helpful
accessories are available.
• C is highly portable language. This means that a C program written for one computer system can be run on another
system with little or no modification.
• C’s another striking feature is its ability to extend itself. A C program is basically a collection of various function
supported by C library (also known as header files). We can also add our own functions to the C library. These functions
can be reused in other applications or programs by passing pieces of information to the functions, you can create useful,
reusable code.
• Writing C program with user-defined functions makes program more simple and easy to understand. Breaking a problem
in terms of functions makes program debugging, maintenance and testing easier.
Disadvantages of C
C does not have OOPS feature that's why C++ is developed.
There is no runtime checking in C language.
There is no strict type checking (for ex: we can pass an integer value for the
floating data type).
C doesn't have the concept of namespace.
C doesn't have the concept of constructors and destructors.
C++ is an extension of C language. This means that you can not only use the new features introduced with C++ but can
also use the power and efficiency of C language. C++ is a direct descendant of C that retains almost all of the C features
as a subset. Here is a list of differences between C and C++.
1. The main difference between C and C++ is that C++ is object oriented while C is a function or procedure oriented
language.
2. C++ provides stronger types of checking that C and directly support a wider range of programming styles than C.
3. C does not have any classes or object. It is procedure and function driven.
4. C structures have a different behaviour compared to C++ structure.
5. The standard input & output functions differ in the two languages
C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output functions
6. C input/output is based on library and the processes are carried out by including it functions. C++ input/output is
made through console commands cin and cout.
7. C functions do not support overloading.
8. C does not support new or delete commands. The memory operations to free or allocate memory in C are carried
out by malloc() and free().
9. Undeclared functions in C++ are not allowed. The function has to have a prototype define before the main()
before use in C++ although in C the functions can be declared at the point of use.
10. After declaring structures and enumerators in C we cannot declare the variable for the structure right after the end
of the structure as in C++.
11. C has top down approach whereas C++ has a bottom up approach.
12. In C a character constant is automatically elevated to an integer whereas in C++ this is not the case.
13. In C declaring the global variable several times is allowed but this is not allowed in C++.
Structure of C/C++ program
A C/C++ program consists of three main parts. These are
1. Pre-processor Directives
2. The main( ) Function
3. C/C++ statements (Body of the program)
Preprocessor Directives
The instructions that are given to the computer before the beginning of the actual program are called Preprocessor
Directives. These are also known as Compiler Directives. The preprocessor directives consist of instructions for the
compiler. The compiler adds special instructions of code from these directives into the program at the time of compilation.
These pre-processor directives normally start with a number sing,( # ) and the keyword “include”. Pre-processor directives
are used to include header files in the program.
Example.
# include <iostream.h>
main( )
{
Statements;
Statements;
}
The main( ) Function
The only component that is required in every C/C++ program is the main( ) function. In its simplest form, the main( )
function consists of the name main followed by a pair of empty parentheses (( )) and a pair of braces ({ }). Within the
braces are statements that make up the main body of the program. Under normal circumstances, program execution starts
at the first statement in main( ) and terminates at the last statement in main( ).
4
Body of the program (C/C++ statements) : The statements of the program are written under the main( ) function
between the curly braces { }. These statements are the body of the program. Each statement in C/C++ ends with a
semicolon. ( ; )
The #include Directive
The #include directive instructs the C/C++ compiler to add the contents of an include file into your program during
compilation. An include file is a separate disk file that contains information needed by your program or the compiler.
Several of these files (sometimes called header files) are supplied with your compiler. You never need to modify the
information in these files; that's why they're kept separate from your source code. Include files should all have an .H
extension (for example, conio.h).
C/C++ character set.
A character denotes any alphabet, digit or symbols to represent information. The following are the valid alphabets
(letters), numbers (digits) and special symbols permitted in C / C++
1. Alphabets (Letters) :
C/C++ language comprises the following set of letters to form a standard program. They are :
A to Z in Capital letters.
a to z in Small letters.
2. Numbers/Digits :
C/C++ language comprises the following sequence of numbers to associate the letters. 0 to 9 digits.
3. Arithmetic Operations:
+, -, *, /, %(Mod)
4. Special Characters:
C language contains the following special character in association with the letters and digits.
Symbol Meaning Symbol Meaning
~ Tilde ! Exclamation mark
# Number sign $ Dollar sign
% Percent sign ^ Caret
& Ampersand * Asterisk
( Left parenthesis ) Right parenthesis
_ Underscore + Plus sign
| Vertical bar \ Backslash
` Apostrophe - Minus sign
= Equal to sign { Left brace
} Right brace [ Left bracket
] Right bracket : Colon
" Quotation mark ; Semicolon
< Opening angle bracket > Closing angle bracket
? Question mark , Comma
. Period / Slash
Keywords / Reserve words
Keywords (Reserved words) are the words that are reserved for specific purpose and can not be used for other purpose.
They have special meaning for the compiler and the computer knows their meaning. In C/C++ all the keywords are in
lowercase. Since the C/C++ language is case sensitive. Therefore the keywords must be entered in lowercase. Keywords
cannot be used as variable name in program. Some example of the keywords are:
break, default, for, case, do , return, if, int, float, long, double, else etc
5
Variables:
A quantity whose value may change during execution of the program is called variable. It is represented by a symbol or a
name.
A variable represents a storage or memory location in the computer memory. Data is stored into the memory location. The
name of the memory location i.e. the variable name, remain fixed during execution of the program but the data stored in
that location may change from time to time.
void main( )
{
clrscr( );
int a,b,c;
}
In the program the variables a,b and c are local variables because they are available only in main function. They can not
be used in other function.
Global Variables
The variables that are declared outside of any function are known as the global variables. Such variables can be seen,
accessed and changed from any function down in the program. These variables are declared at the top of the program,
before a function or between two functions in the program. Unlike the local variable the value of the global variable can
be changed in any functions. Consider the following programming example in which a , b and c are the global variables
and d is local variable.
#include <iostream.h>
#include <conio.h>
6
int a,b,c;
void main( )
{
int d;
Declaration of variables: Assigning the name and data type that a variable can hold is called declaration of the variable.
All variables that are used in a program are declared using variable declaration statement. The syntax to declare a variable
in C/C++ is
Type list of variables;
Where
type : Specifies data type of variables. For example, it may be int, float , char etc.
list of variables : Specifies a list of variables separated by commas, in a single statement more than one variable, separated
by commas, of same data type can be declared.
For example, to declare variables “abc” , “xyz” , and “s” of integer type, the statement is written as.
int abc, xyz , s;
To declare variable with different data types the statement can be written as.
int abc;
float xyz;
char name[15];
Initialization of variables:
When a variable is declared, a memory location is assigned to it. A know value can be assigned to the variable at the time
of its declaration. If we assign a value to a variable at the time of its declaration, it is called initialization of variable. For
example to declare variables a,b and c of integer type and assigning values a = 110 and b = 60, the statement is written as:
int a = 110, b = 60, c;
Constants :
A quantity that cannot change its value during execution of the program is called constant. It is represented by a symbol or
a name. Constants have fixed value. There are four types of constants in C/C++. These are.
1. Integer constants 2. Floating point constants
3. Character constants 4. String constants
Integer Constants:
A numerical value without a decimal part is called integer constant. The plus (+) and minus ( - ) signs can also be used
with an integer constant. Integer constants are used in expression for calculations. To print an integer constant, it is given
in the output statement without quotation marks. For example, to print integer constants 510 and 662 the output statement
is written as:
cout<< 520;
cout<< 662;
Floating point constants: Numeric values that have an integer as well as a decimal part are called floating point values.
These values can also be written in exponential notation. In exponential notation, a floating point constant is written as
123.5E2. The symbol E represents the exponent. A floating point constant may be a positive or a negative value. The
exponent may also be a +ve or a –ve value.
Character constants: A single character enclosed in single quotation marks is called character constant. For example ‘a’ ,
‘/’ , ‘b’ etc represents character constants.
7
String constants : A sequence of characters consisting of alphabets, digits and/or special characters enclosed in double
quotation marks is called string constant. For example, “Pakistan” and “Lahore” are examples of string constants.
Data types in C/C++
The variable type specifies the type of data that can be stored in it. Each variable is declared by its type.
C/C++ has the five basic data types.
1. Bool Boolean
2. int Integer
3. float Floating Point
4. double Double Precision
5. char Character
The Bool data type:
The word bool stands for Boolean. It is used to declare logic type variables. In logic type variables only two values can be
stored. The true is equivalent to 1 and false is equivalent to 0.
The short int: The storage capacity of a short int type variable is two bytes. It can store integer values form –32768 to
32767.
The long int: The storage capacity of a long int type variable is four bytes. It can store integer from –2147483648 to
2147483647
The unsigned int: The unsigned int can store only positive whole-numbers. Its storage capacity is tow bytes. It can store
integer values form 0 to 65535.
The float data type: The float represent real or floating type data. The real type data is represented in decimal or
exponential notation. Float data may be signed or unsigned. For example, 23.23 , 16.21 , 0.56 , -9.87 are examples of
floating type data. The storage capacity of float type variable is four bytes and it can store real values form 3.4x10 -38 to
3.4x10+38.
The long float data type: The storage capacity of a long float type variable is twice the storage capacity of float type
variable. Its storage capacity is 8 bytes.
The double data type: The double is the real or floating type data. Its storage capacity is twice the capacity of float data
type. It is used to store large real values. The storage capacity for a double variable type is 8 bytes and it can store real
values from 1.7x10-308 to 1.7x10+308
The long double data type: The long double type variables are used to store very large real data values. The storage
capacity for long double variables is ten bytes. A long double variable can store real values from 3.4x10 -4932 to 3.4x10+4932
The char data type: The char stands for character. It is used to declare character type variable. In character type variables,
alphabetic characters, numeric digits and special characters can be stored. The storage capacity for a single character is 8
bits or one byte. A char type variable can hold from 1 byte to 65535 bytes.
8
Operators
An operator is a symbol that instructs C/C++ to perform some operation, or action, on one or more operands. An operand
is something that an operator acts on. In C/C++, all operands are expressions. C/C++ operators fall into several categories:
Operators are special symbols used for specific purposes. C/C++ provides six types of operators. Arithmetical operators,
Relational operators, Logical operators, Unary operators, Assignment operators, Conditional operators, Comma operator .
Relational operators
The relational operators are used to test the relation between two values. All relational operators are binary operators and
therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is
true. The following table shows the relational operators.
Relational Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to
Examples
Operator Symbol Question Asked Example
Equal == Is operand 1 equal to operand 2? x == y
Greater than > Is operand 1 greater than operand 2? x>y
Less than < Is operand 1 less than operand 2? x<y
Greater than or equal to >= Is operand 1 greater than or equal to operand 2? x >= y
Less than or equal to <= Is operand 1 less than or equal to operand 2? x <= y
Not equal != Is operand 1 not equal to operand 2? x != y
Logical Operators
Sometimes you might need to ask more than one relational question at once. For example, "If it's 7:00 a.m. and a weekday
and not my vacation, ring the alarm." C/C++ logical operators let you combine two or more relational expressions into a
single expression that evaluates to either true or false.
9
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in x
y= j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10
The conditional operator can't be used in all situations in place of an if...else construction, but the conditional operator is
more concise. The conditional operator can also be used in places you can't use an if statement.
Order Operators
First ()
Second *, /, %
Third +, -
Statements
Statements are the instructions given to the computer to perform any kind of action. Action may be in the form of data
movement, decision making etc. Statements form the smallest executable unit within a C++ program. Statements are
always terminated by semicolon.
Compound Statement
A compound statement is a grouping of statements in which each individual statement ends with a semi-colon. The group
of statements is called block. Compound statements are enclosed between the pair of braces ({}.). The opening brace ({)
signifies the beginning and closing brace (}) signifies the end of the block.
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is quite useful when the
syntax of the language needs to specify a statement but the logic of the program does not need any statement. This
statement is generally used in for and while looping statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++ provides the following
statements for implementing the selection control structure.
if statement
if else statement
nested if statement
switch statement
The if Statement
The fundamental decision making statement in C/C++ is the “if statement”. This statement is also called as conditional
jump statement or conditional transfer of control statement, because it is mostly used to transfer the control to another
statement if and only if a condition is true. If the condition is not fulfilled i.e if the condition is false, transfer of control
does not occur and the program execution moves on the next statement following the if structure. If condition has the
following form:
if(condition)
statement;
or
if(condition)
{
statement;
statement;
statement;
}
The reserved word “if” is followed by a condition which is followed by a statement to be carried out if the condition is
true. A statement may be a single statement or a block of statements or nothing. When more than one statements are going
to be executed after the if statement, then the statements must be grouped by enclosing them within a pair of braces. Every
statement in the if block must end with a semicolon. Consider the following example.
if(marks<33)
cout<<”Fail”;
12
In the above example the condition (marks<33) is tested. In case the marks is less than 33 , then the condition is true, the
statement in the if block will be executed and the message “ Fail “ will be printed. The flowchart of the if statement is as
below.
False True
is
condition?
If-else statement
The second form of the if statement is if-else statement. With the if-else statement, we test a condition and we perform
one of two alternatives. When one conditions is true then action first is performed and a different action is performed
when the condition is false. The general syntax of the if-else statement is as below.
if(condition)
statement;
else
statement;
OR
if(condition)
{
statement;
statement;
statement;
}
else
{
statement;
statement;
statement;
}
If the condition is true then the statements following the condition are executed. If the condition is false, the else clause is
executed. The flowchart of the if-else statement could be as.
False True
is
condition
?
Action 2
Action 1
In the above example “Pass” will be printed if marks is greater than or equal to 33 else “Fail” will be printed.
Nested if statement
The if structure can be nested within one other i.e when an if statement is contained with in another, they are known to be
nested. The nested if statement is used for multiple way decision making. In case of nested statement one need to know
which else goes with which if. The rule is each else is paired with the previous if that does not have else. The general form
could be as:
If(condition)
{
if(condition)
{
statement;
}
else
{
statement;
}
}
esle
{
statement;
}
In the above example if marks obtained is greater than 60, then “First division” will be printed, if marks obtain is less than
60 but greater than 45 then “Second Division” will be printed, if marks obtained is less 45 but greater than 33 then “Third
Division” will be printed and if marks obtained is less than 33 then “Fail” will be printed.
The switch-case statement is a special form of multiple alternative decision making i.e when multiple chice possibilities
are based on a single value; the switch statement is best choice. Actually switch statement is more efficient way of
representing nested-if statement. This statement is used to transfer the control to a selected case of any one of the several
stated cases; depending on the value of the switch expression. It has the following general form.
Switch(expression)
{
case valueone: statement(s);
break;
case valuetwo: statement(s);
break;
---------------------------------
case valuen: statement(s);
break;
default: statement(s);
}
1. Any legal C/C++ expression may be used in switch expression but it must be enclosed in the parenthesis.
2. After evaluation of the expression, control is transferred directly to the statement whose case value matches
the result.
3. If no match is found then control is transferred to the default statement. The default statement is optional.
4. The break statement is used to break switch statement i.e it is used to transfer the control out of the entire
switch statement to the first statement following the switch statement.
5. Any integer or a character constant follows the reserved word case.
6. If more than one statement are required to be executed in case body, no need to enclose them with in the
braces.
void main( )
{
clrscr( );
int op = 2;
switch(op)
{
case 1: cout<<” I am in case 1”;
case 2: cout<<” I am in case 2”;
case 3: cout<<” I am in case 3”;
case 4: cout<<” I am in case 4”;
default: cout<<” I am in default”;
}
getch( );
{
The output for the following program would be as:
I am in the case 2.
Looping : ( Define loop)
A loop is an essential part of programming technique that permits the repetitive execution of a statement or a group of
statements, whereas the counter is a technique for controlling a looping process. C/C++ has three looping statements, the
“for statement” the “while statement” and the “do-while statement”.
15
void main( )
{
clrscr( );
for(int num = 1; num<=10; num++)
{
cout<<num;
}
getch( );
}
In the above program the initial value of the num variable is 1. So the first iteration 1 is printed. Then at the end of the
loop the value of num is incremented by 1 which is 2. The value is compared with 10 which is less than ten. So again the
body of the loop is executed and 2 is printed. Then again at the end of the loop the value of num is incremented by 1. The
condition is checked and the next number is printed. This process goes on until the value of number becomes greater than
10.
void main( )
{
clrscr( );
for(outer=1; outer<=5; outer++)
{
16
while(condition)
{
statement-1;
statement-2;
statement-3;
-------------
-------------
}
As long as the conditional expression in the while statement is true, the statement or group of statements in the body of the
loop will be repeated and this process continues until the condition becomes false and the control skips down to the
statement after the while loop.
Example.
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
int num = 1;
while <num<=10)
{
cout<<num;
cout<<endl;
num++;
}
getch( );
}
output of the above program will be as under.
1
2
17
3
4
5
6
7
8
9
10
condition is any C/C++ expression, and statement is a single or compound C/C++ statement. When program execution
reaches a do...while statement, the following events occur:
1. The statements in statement are executed.
2. The condition is evaluated. It it is true, execution returns to step 1. If it is false, the loop terminates.
Example
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr();
int num = 1;
do
{
cout<<num;
cout<<endl;
num++;
}while(num<=10);
getch();
}
Output of the above program will be as:
1
2
3
4
5
18
6
7
8
9
10
The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant
string Output sentence, the numerical constant 120 and variable x into the standard output stream cout. Notice that the
sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters.
19
Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can
be clearly distinguished from variable names. For example, these two sentences have very different results:
1 cout << "Hello"; // prints Hello
2 cout << Hello; // prints the content of Hello variable
The “putchar” stands for put a character. This function is used to put or print a single character on the standard output
device, i.e. the computer screen.
Where
string: represents the string whose characters are to be converted to upper case. It may be a constant string or a string
type variable.
The “strrev( )” function
The “strrev” stands for string reverse. This function is used to reverse alphabetic characters ( A to Z) or (a to z) in the
input string str.
Its syntax is: strrev(string);
Where
string: represents the string whose characters are to be reversed. It may be a constant string or a string type variable.
The “pow10( )” function
This function is used to calculate 10 to the power of a given integer number x.
Its syntax is: pow10(x);
Where
x: is an integer number that represents the exponent of the number 10.
Example: If the value of 103 is to be calculated. The function is written as
Pow10(3).