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

Chapter 1

Chapter 1 provides an overview of C++, including its history, advantages, and differences from C. It covers the structure of a C++ program, data types, variables, constants, comments, and input/output operations. The chapter emphasizes the object-oriented nature of C++, its portability, and its compatibility with C.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 1

Chapter 1 provides an overview of C++, including its history, advantages, and differences from C. It covers the structure of a C++ program, data types, variables, constants, comments, and input/output operations. The chapter emphasizes the object-oriented nature of C++, its portability, and its compatibility with C.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter 1:

Basics of Programming:

History of C++:
The C++ is an object-oriented programming language design and developed by – Bjarne
Stroustrup at AT & T Bell Laboratories in Murray Hill, New Jersey located in USA in 1979.
As he wanted a flexible & a dynamic language which was similar to C with all its features,
It was developed for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.
Since the class was major addition to the original language, Stroustrup called the new
language “C with Classes”, however later in 1983, the name was changed to C++. The idea
of C++ comes from the increment operator ++, thereby suggesting that C++ is an
incremented version of C.
Let's see the programming languages that were developed before C++ language.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
C++ 1979 Bjarne Stroustrup

Advantages of C++:
1. OOPS (Object Oriented Programming System)
One of the main advantages of the programming language is the Concept of OOPS, as many
times the developer have to solve real-world interfacing problem. Hence, they uses
programming languages like C wastes a lot of time doing so, but, when the developer
shifted to the CPP language, he solved the problem easily because of the Object-oriented
programming system. That helps programmers to enhance and improve their code. The
OOPS includes many the features like classes, inheritance, polymorphism, data,
abstraction, and encapsulation. In the OOPS standard, the programmer treats data as an
object and easily solves a real-world problem. This feature in the C++ language helps
many programmers to get numerous jobs.
2. Portability
The CPP language is a language that is highly coded portable; CPP language is highly
portable as you can write code in one system and use the code in another system. The
portability of the language allows programmers to run the same program on different
operating systems. For example, the programmer writes code in the windows operating
system on his laptop, and for some bad reason, he has to shift to his friend's laptop for the
code in the LINUX Operating system. He can easily display and modify that file.
3. Low level manipulation Language

Compiled By: Mr. Vinod S. Mahajan


Since C++ is Brother associated with C, a procedural bases language closely related to the
machine-level language, C++ allows low-level manipulation of data programming at a
certain level of codes. Embedded systems, compilers, and Operating Systems are created
with the help of C++.
4. Great Memory Management
C++ gives the developer the eye of total control over memory management. This can be
considered both a profit and loss as this increases the responsibility of the user to manage
memory efficiently rather than being managed by the Garbage collector. This concept is
implemented with the help of DMA (Dynamic memory allocation) using pointers. For
example, malloc for a mass storage area and calloc for the contiguous memory locations.
5. Multi-Paradigm Language
CPP is a multi-paradigm programming language; the word paradigm refers to the style of
writing the application's code which includes logic, data, and keywords. The procedure
and structure of the program in the C++ language generally follow three paradigms that
are generic, imperative, and object-oriented.
6. Compatibility With C
C++ is compatible with C. Virtually every error-free C program is a valid C++ program.
Depending on the compiler used, every program of C++ can run on a file with a .cpp
extension.
7. Scalability
Scalability refers to the ability of a program to scale. It means that the C++ program can
run on a small scale and a large scale of data. We can also build applications that are
resource intensive.
8. Standardization
C++ is an ISO standard programming language, meaning it has a well-defined set of rules
and guidelines that developers worldwide follow. This makes it easy for developers to
understand and use C++, even working on projects or in different countries.

Differences between C and C++.


• C++ was built as an extension of C, which means it can run most C code. The reverse
isn’t true though—C can’t run C++ code.
• As an object-oriented language, C++ supports polymorphism, encapsulation, and
inheritance, while C does not.
• In C, data and functions are “free entities,” which means you can manipulate them
with outside code. Since C++ encapsulates data and functions together into a single
object, those data structures and operators are hidden to outside code.

Compiled By: Mr. Vinod S. Mahajan


• C++ uses the namespace, which organizes code into logical groups and to prevent
name collisions. Name collisions can occur when your code base includes multiple
libraries. C does not use a namespace.
• C uses functions for input and output, whereas C++ uses objects for input and output.
• C++ supports reference variables, which C does not. A reference variable is an alias
for an already existing variable, used to create a short-hand notation for faster coding.
• C does not provide error or exception handling, but C++ does.

Character Set of C++:


In C++ Character set is a set of valid characters that can be used in C++ program. Character
set is used to specify the characters of symbols recognize by the language.
C++ character set includes following characters.

Letters: A to Z, a to z.
Uppercase Characters:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
LowerCase Characters:
abcdefghijklmnopqrstuvwxyz
Digits: 0 to 9
0123456789
Special Symbols:
Space + - ∗ ⁄ ^ \ ( ) [ ] { } = != < > . ′ ″ $ , ; : % ! & _ # <= >= @
White Spaces:
Blank space, Horizontal tab (→), Carriage return (↵), Newline, Form feed
Other Characters:
C++ can process any of the 256 ASCII characters as data or as literals.

Structure of C++ program:


Every C++ program consist of following building block

Documentation Section
Header Files / Pre-processors Statements
Global Declaration
Class Declaration
main() function
{

Compiled By: Mr. Vinod S. Mahajan


//Main function codding
}
User defined function

Documentation Section:
Documentation section is generally meant include set of comments, that is used to
provide the information about the program written like name of program, utility of
program, date of creation, date of last modification, author name, licensing or copyrights
information and any other information that programmer with to put for the references.
Pre-processor Statements:
This is the section where we write all of the pre-processor directive statements, pre-
processor statements usually with begins with a (#) symbol. Pre-processor statements
such #include tells the compiler to include header files and #define directive is used to
define constants prior to compilation of the program.
Global Declarations:
This is the section where all the global declaration comes. All of the variables, structures,
classes and function defined or declared outside the main function are treated as global.
Class definition:
The classes are used to map real world entities into programming. The classes are the key
building block of any C++ program. A C++ program may include several class definitions.
This is the section where we define all of our classes.
Main function definition:
This is the most vital part of each and every C++ program, it is mandatory for C++
program to have a main() function definition. There can be only one main() function in
C++ program. The execution of a C++ program starts with the main() function. The C++
program can not be executed without the main() function
User defined functions: -
This is the section of where we put all the user defined functions created to
perform a specific task. A user defined function must be defined before use it. User
defined function can written before or immediately after the main ( ) function and
called inside the main ( ) function.

First C++ program:


#include<iostream>
#include<conio.h>
void main()
{
cout<<”\nhello world”;
getch();
}

Compiled By: Mr. Vinod S. Mahajan


#include <iostream.h> includes the standard input / output statement. The cout
statement is defined in iostream.h.
int main() The main() function is the entry point of every program in C++ language. The
int keyword specifies that it returns a integer value.
cout is a predefined object is used to display the given text on output window.
How to compile and run the C++ program
There are 2 ways to compile and run the c program, by menu and by shortcut.
By menu
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.

Identifiers:
In C++, an identifier is a name given to program elements such as variables, array, class
and functions etc. An identifier is a sequence of letters, digits, and underscores.
Following are the rules to define identifier.
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
• It should not be a keyword.
• It must not contain white space.

Keywords / reserve words:


Keywords (also known as reserved words) have special meanings to the C++ compiler
and are always written or typed in short(lower) cases. Keywords are words that the
language uses for a special purpose, such as void, int, public, etc. It can’t be used for a
variable name or function name or any other identifiers. The total count of reserved
keywords is 95. Below is the table for some commonly used C++ keywords.
(auto, double, int, struct, Break, else, long, switch, Case, enum, register, typedef, Char,
extern, return, union, const, float, short, unsigned, Continue, for, signed, void, Default,
goto, sizeof, volatile, Do, if, static, while, asm, dynamic_cast, namespace, reinterpret_cast,
Bool, explicit, new, static_cast, catch, false, operator, template, Class, friend, private, this,
Const_cast, inline, public, throw, Delete, mutable, protected, true, Try, typeid, typename,
using, virtual, wchar_t)

Compiled By: Mr. Vinod S. Mahajan


C++ Data Types
All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it can
store. Whenever a variable is defined in C++, the compiler allocates some memory for
that variable based on the data-type with which it is declared. Every data type requires a
different amount of memory.

Datatypes in C++

Built In Derived User Defined

int, float, Array, Structure,


double, char, Union,
Pointer
Boolean, void Class

Built In:
int
Integers are used to store whole numbers. C++ supports several integer types, varying
internal sizes for storing signed and unsigned integers. Integers can be declared using int
keyword.
Type Storage size Value range
int 2 Bytes -32,768 to 32,767
unsigned int 2 Bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

float
Float data types are used to store single-precision data values i.e. decimal values. It
holds 4 bytes of memory space.
double
Double data types are used to store double-precision floating-point data values. It holds 8
bytes of memory space.
Type Storage size Value range
float 4 bytes 3.4e-38 to 3.4e+38
double 8 bytes 1.7e-308 to 1.7e+308

Compiled By: Mr. Vinod S. Mahajan


boolean
The Boolean data type is used to represent the truth values, which can be either True or
False. Boolean are commonly used in decision making statements. Boolean can be
declared using bool keyword.
char
The character data type is used to hold the single character, literal. Character are declared
char keyword.
Type Storage size Value range
char 1 byte -127 to 128
unsigned char 1 byte 0 to 255
Void
The void type means no values. It cannot be used with variable declaration. It is usually
used with function to specify its return type or its arguments.

Variables
Variables is name used to refer memory location in computer memory that holds a value
for that variable, this value can be changed during the execution of the program. When
you create a variable in C++, this means you are allocating some space in the memory for
that variable. The size of memory block allocated and type of the value it holds is
completely dependent upon the type of variable.
Rules for naming a variable in C++
• The name of variable always starts with alphabet or underscore
• Blank space not allowed between variable name.
• Special symbols not allowed between variable name except underscore ( _ )
• Kewords / reserve words are not allowed as a variable name.
• Variable names are case sensitive.
Declaration of variables:
Syntax:
<datatypes> <variable name>;
Or <datatypes> <variable name>=<value>;

Compiled By: Mr. Vinod S. Mahajan


Variable assignment In C++
The assignment operator (=) is used to assign values to a variable, the operand in the
left side of the assignment operator (=) indicates the name of the variable and the
operand in the right side of the assignment operator (=) indicates the value to be
stored in that variable.
int ctr;
ctr = 5; // Assignment Statement
Initializing Variable In C++
In C++, it is possible to declare and assign some initial value to a variable in single
statement.
<datatype> <variable name> = <value>;
Eg. int rollno=10;

Constant:
Constant are same like as a variable in c++, but the value of constant cannot be changed
or modified during the execution of program. Constant must be initialized when declared
as value cannot be assigned it to later.
Declaration of constant:
Syntax:
const <datatype> <constantname>=valueofconstant;
Eg. const float PI=3.14;
Types of Constants:
• Integer Constant
• Float constant
• Char constant
• String constant
Integer Constant: An integer constant can only hold integer quantity which is a
sequence of whole numbers or digits.
Float constant: floating point constants contains a decimal point or an exponent.
Character constant: a character constant is a single character, enclosed in single
quotation marks. It can be a single alphabet, a digit or a symbol.
String Constant: A string constant is sequence of characters enclosed in double quotes.
It may contain letters, digits, special characters and blank space.

Compiled By: Mr. Vinod S. Mahajan


Comments:
C++ Comments are a set of statements that are not executed by the C++ compiler. The
use of comments makes it easy for humans to understand the source code. Usually
comments gives you inside or explanation about the variable, method, class or any
statement that exists in source code. The comment statements are ignored during the
execution of the program.
Single-line Comments: -
A '//' (double forward slash) is used to specify a single line comment, which extends
up to the newline character.
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!"; // It prints Hello, WorLd!
return 0;
}
Output-
Hello W o r l d !
Multi-line Comments:-
If you want to comment multiple lines then you can do it using /* and */, everything in
between from /* to */ is ignored by the compiler-
#include <iostream>
using namespace std;
int main(){
/*It prints
Hello, WorLd! */
cout<<"Hello World!";
return 0;
}
Output-
Hello World!

Input / Output in C++


In C++ input and output are performed in the form of a sequence of bytes or more
commonly known as streams.
• Input Stream: If the direction of flow of bytes is from the device (for example,
Keyboard) to the main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory
to device (display screen) then this process is called output.

Compiled By: Mr. Vinod S. Mahajan


Standard output stream (cout)
The cout is a predefined object of ostream class. It is connected with the standard output
device, which is usually a display screen. The cout is used in conjunction with stream
insertion operator (<<) to display the output on a console
Let's see the simple example of standard output stream (cout):
#include <iostream>
using namespace std;
int main( )
{
cout << "Welcome to GHRIBM";
return 0;
}
Standard input stream (cin)
The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream extraction
operator (>>) to read the input from a console.
Let's see the simple example of standard input stream (cin):
#include <iostream>
using namespace std;
int main( )
{
int age;
cout<<”\nEnter your age=”;
cin>>age;
cout << "Your age is " << age ;
return 0;
}

Operators:
An operator is a special symbol that is used to carry out some Arithmetical or Logical
operation on its operand.
In C++, we have rich set of built in operators to carry out different type of operations.
Type of operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Increment and Decrement Operators
• Conditional Operators
• Assignments operators

Compiled By: Mr. Vinod S. Mahajan


Arithmetic Operators
Arithmetic Operators are used to perform arithmetic operations like addition,
subtraction, multiplication, division, %modulus, exponent, etc.
Let variable a holds 20 and variable b holds 10, then –
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator A / B will give 2
Modulus Operator and remainder of
% B % A will give 0
after an integer division

Relational Operators
Relational Operators are used to evaluate a comparison between two operands. The
result of a comparison operation is a Boolean value that can only be true or false.
Let variable a holds 20 and variable b holds 10, then –
Operator Description Example
< Less than a<b returns FALSE
> Greater than a>b returns TRUE
<= Less than or equal to a<=b returns FALSE
>= Greater than or equal to a>=b returns TRUE
== Equal to a==b returns FALSE
!= Not equal to a!=b returns TRUE

Logical Operators
Logical operators are used to combine expressions with conditional statements using
logical (AND, OR, NOT) operators, which results in true or false.
Let variable a holds true or 1 and variable holds false or 0 then-
Operator Name Description Example

&& Logical AND Return true if all expressions are true (a && b) returns false
Return true if any one expression is
|| Logical OR ( a || b) returns true
true

! Logical NOT Return complement of expression !a returns false

Compiled By: Mr. Vinod S. Mahajan


Increment/decrement Operators
Increment operator (++)
Increment operators are used to increase the value of the variable by one.
Syntax:
a++;
++a;
Type of Increment Operator
• pre-increment
• post-increment
pre-increment (++ variable)
In pre-increment first increment the value of variable and then used inside the
expression.
++variable;
post-increment (variable ++)
In post-increment first value of variable is use in the expression and then increment the
value of variable.
variable++;
Decrement operator:
decrement operators are used to decrease the value of the variable by one.
Syntax:
a--;
--a;
Type of Decrement Operator
• pre-decrement
• post-decrement
Pre-decrement (-- variable)
In pre-decrement first decrement the value of variable and then used inside the
expression
--variable;
post-decrement (variable --)
In Post-decrement first value of variable is use in the expression and then decrement
the value of variable.
variable--;
Example of increment and decrement operator
#include<iostream>
#include<conio.h>

Compiled By: Mr. Vinod S. Mahajan


void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
cout<<"x: "<<x;
getch();
}
Output
x: 0

C++ Conditional operator ( ? : )


In C++, conditional operator is considered as short hand for if-else statement.
Conditional operator is also called as 'Ternary Operator.
Syntax:
condition ? resultl : result2
Example
result = (10 > 15) ? "Greater" : "Smaller";
cout<<result;
Output:
smaller

Assignment Operators:
Assignment operators are used to assign value to a variable, you can assign a variable
value or the result of an arithmetical expression.
Operator Description Example
= Assignment Operator A=b – assign a value of b to a
+= Add and assign A+=b is equivalent to a=a+b;
-= Subtract and assign A-=b is equivalent to a=a-b;
*= Multiply and assign A*=b is equivalent to a=a*b;
/= Divide and assign A/=b is equivalent to a=a/b;
%= Mod and assign A%=b is equivalent to a=a%b;

Compiled By: Mr. Vinod S. Mahajan


Operator Precedence and Associativity in C++
In C++, operator precedence and associativity are important concepts that determine the
order in which operators are evaluated in an expression. Operator precedence tells the
priority of operators, while associativity determines the order of evaluation when
multiple operators of the same precedence level are present.

Operator Precedence in C++


In C++, operator precedence specifies the order in which operations are performed
within an expression. When an expression contains multiple operators, those with higher
precedence are evaluated before those with lower precedence.
For expression:
int x = 5 - 17 * 6;
As, multiplication has higher precedence than subtraction, that’s why 17 * 6 is evaluated
first, resulting in x = -97. If we want to evaluate 5 – 17 first, we can use parentheses:
int x = (5 - 17) * 6;
Now 5 – 17 is evaluated first, resulting in x = -72.

Operator Associativity in C++


Operator associativity determines the order in which operands are grouped when
multiple operators have the same precedence. There are two types of associativity:
Left-to-right associativity: In expressions like a + b – c, the addition and subtraction
operators are evaluated from left to right. So, (a + b) – c is equivalent.
Right-to-left associativity: Some operators, like the assignment operator =, have right-to-
left associativity. For example, a = b = 4; assigns the value of b to a.
For expression:
int x = 10 - 5 - 2;
As, subtraction is left-associative, that’s why 10 – 5 evaluated first, resulting in x = 3. But
in case of multiplication:
int x = 2 * 3 * 4;
Now 3 * 4 is evaluated first, resulting in x = 24 because multiplication is right-associative.

Operator Precedence Table in C++


The operator precedence table in C++ is a table that lists the operators in order of their
precedence level. Operators with higher precedence are evaluated before operators with
lower precedence. This table also includes the associativity of the operators, which
determines the order in which operators of the same precedence are processed.
The operators are listed from top to bottom, in descending precedence

Compiled By: Mr. Vinod S. Mahajan


Operator Name Associativity
() [] -> . Function call, Subscript, Member access Left
++ — Increment/Decrement Right
!~–+ Logical/Bitwise NOT, Unary plus/minus Right
*/% Multiplication, Division, Modulus Left
+– Addition, Subtraction Left
<< >> Bitwise shift Left
< <= > >= Relational operators Left
== != Equality operators Left
& Bitwise AND Left
^ Bitwise XOR Left
| Bitwise OR Left
&& Logical AND Left
|| Logical OR Left
?: Ternary conditional Right
= += -= *= /= %= &= ^= |= Assignment and compound assignment Right
<<= >>=
, Comma Left

******
List of Exercise:
• Write a program to print “hello world”.
• Write a program to print your name and address on separate line.
• Write a program to demonstrate different types of variables (int, float, char).
• Write a program to read a two numbers and print addition of those numbers.
• Write a program to read a number and find out square of that number.
• Write a program to read a three numbers and print addition of those numbers.
• Write a program to read a number and find out cube of that number.
• Write a program to read two numbers and interchange (swap) their values.
• Write a program to read two numbers and interchange (swap) their values.
(without using 3rd variable)
• Write a program to find out maximum between two numbers using conditional
operator.

Compiled By: Mr. Vinod S. Mahajan

You might also like