0% found this document useful (0 votes)
11 views64 pages

Introduction of C++ (Ayush)

C++ is a high-level programming language developed by Bjarne Stroustrup, initially named C with Classes, and is an extension of the C language. It is widely used for developing software, including system software, commercial applications, and video games. The document also covers C++ programming structure, operators, data types, and control statements.

Uploaded by

arpanvawhal8
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)
11 views64 pages

Introduction of C++ (Ayush)

C++ is a high-level programming language developed by Bjarne Stroustrup, initially named C with Classes, and is an extension of the C language. It is widely used for developing software, including system software, commercial applications, and video games. The document also covers C++ programming structure, operators, data types, and control statements.

Uploaded by

arpanvawhal8
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/ 64

Introduction of C++

Introduction of C++ Language


● C++ is a general purpose high-level computer programming
language . Developed by Bjarne Stroustrup at Bell Laboratories over a
period starting in 1983.
● C++ is an extension of C programming and the programs written in C
language can run in C++ complier.
● The development of C++ actually began four years before its release
in 1979. It did not start with the name C++. Its first name was C with
Classes.
● In the late part of 1983 , C with classes was first used for AT & T’s
internal programming needs. Its name was changed to C++ later in
the same year.
● C++ is an Object Oriented Programming Language
Uses of C++ Language
● C++ is used by programmers to develop computer software.
● It is used to create general system software.
● It is used to design commercial application.
● Used to build drivers for various computer devices.
● Software for servers and software for specific applications.
● Used in the creation of video games.
Form of C++ Program
● Line 1: #include <iostream> is a header file library that work
with input and output objects, such as cout (used in line 5).
Header files add functionality to C++ programs.
● Line 2: using namespace std means that use names for objects
and variables from the standard library.
● Line 3: A blank line. C++ ignores white space. But it use to make
the code more readable.
● Line 4: Another thing that always appear in a C++ program, is int
main(). This is called a function. Any code inside its curly
brackets {} will be executed.
● Line 5: cout (pronounced "see-out") is an object used together
with the insertion operator (<<) to output /print text. In our
example it will output "Hello World".
● Note: Every C++ statement ends with a semicolon ;.
● Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
● Remember: The compiler ignores white spaces. However,
multiple lines makes the code more readable.
● Line 6: return 0 ends the main function.
● Line 7: Do not forget to add the closing curly bracket } to
actually end the main function.
Header files in c++
● Standard library header files: These are the pre-existing header
files already available in the C++ compiler.
● User-defined header files: Header files starting #include can be
designed by the user.
Syntax:
#include<filename.h>
#include “filename.h”
Cout and Cin
Iostream is a class in C++ in which cout and cin are two
objects which are used for display and read the value to / from
the console respectively.
● Istream (input stream): – It is a class for which cin object is
created. Cin is used to read the value from console(a computer
terminal where a user may input commands and view output
such as the results of inputted commands or status messages
from the computer) to the address of variable.
Syntax: –
Declaration of cin: –
Cin>>variable;
Ex: – cin>>x; //x is variable.
Cin>>variable x>>variable y;
Ex: – cin>>x>>y; //x and y are variables.
● Ostream (output stream): – It is also a class for which cout
object is created. Cout is used to print or display the value from
the address of variable to the console.
Syntax: –
Declaration of cout: –
cout <<variable;
Ex: – cout<<x; //The content or value of x will be printed on
console.
cout <<variable x<<variable y;
Ex: – cout<<x<<y; //The contents of both variables will be
printed on console.
Introduction to flowcharts and problem
solving.
Problem Solving:
● It is a process of understanding the problem, finding solution for the
problem and finally implementing the solution to it.
● Design the solution before coding in the form of algorithms and
flowcharts.
A successful problem-solving process depends on the following
factors:
● understanding the problem and defining it precisely.
● designing proper algorithms and flowcharts of the solution.
● implementing the algorithm successfully.
● Algorithm
It’s the sequence of steps that needs to be followed in order to
achieve certain task.
● Flowchart
1. It is basically a diagrammatic representation of an algorithm.
2. It uses various symbols and arrow to describe the beginning,
ending and flow of the program.
● Syntax
The set of rules that define what the various combinations of
symbols mean. OR Syntax means an approved set of pre-defined
protocols or rules that we need to follow while working in a
programming language.
Symbols:
Symbols cont.
Token
A token is the smallest unit of a program that the
compiler understands.
Type of Tokens?
- Keywords
● Identifiers
● Variables
● Constants
● Operators
● Special Symbols
C++ Character Set
The input and output of a program are made up of characters and
symbols. C++ Character Set is a collection of characters and
symbols that have a specified meaning. It consists of:
● Letters: uppercase (A-Z) and lowercase (a-z) alphabets.
● Digits: Numbers from 0-9.
● Special characters: There are various special characters like , ; \
_ ? {} [] () : “ ‘ <> ? & # ~ etc.
● White spaces: blank space, new line
Keywords
● Reserved word whose meaning is predefined to the complier.
● Keywords can be used only for their specific purpose.

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
Additional Keywords
● asm bool catch class
● const_cast delete dynamic cast explicit
● export false friend inline
● mutable namespace new operator
● private protected public reinterpret
cast
● static_cast template this throw
● true try typeid typename
● using virtual wchar_t
Identifier
Identifiers in C++ refer to the name of the variables, functions,
arrays, class etc. Created by the programmer using the combination of
following characters.
Rules of Identifier
● An identifier name should be made up of letters, digits and
underscores only.
● Identifiers should not start with digits.
● Special characters and white spaces are not allowed.
● No keyword can be used as an identifier.
● Identifier names are case sensitive.
● Length of an identifier name should not exceed 2,047 characters,
beyond which it becomes insignificant.
Variables
● A named memory location whose value can be changed during
program execution.
● Declaration:
Syntax : [data_type] [variable_name];

● Initialization : Providing initial value to the variable is


called Initialization
Syntax : Variable_Name= Value;
Constants
Constants refer to fixed value which can not be changed
during program execution.
Syntax:
const data_type variable_name = value;
Types of Constants in C++
The different types of constants are:
● Integer constants – These constants store values of the int data type.
const int a = 5;
● Floating constants – These constants store values of the float data
type.
const float e = 2.71;
● Character constants – These constants store values of the character
data type.
const char ch = ‘x’;
● String constants – These constants are also of the character data
type but differ in the declaration part.
const char title[] = ‘‘Data’’;
Constants cont’d:
● Decimal constants: A decimal constant begins with a nonzero
digit.
const int dec = 255;
● Octal constants – A number that begins with a leading zero is
interpreted as an octal constant. Octal (or base eight) notation
uses only the digits from 0 to 7.
const int oct = 034;
● Hexadecimal constants – The hexadecimal constant begins
with the prefix 0x . The hexadecimal digits A to F can be
uppercase or lowercase.
const int hex = 0x40;
Strings:
● Strings are used to store letters and digits.
● It is enclosed within double quotes, whereas characters are
stored within single quotes.
● The size of a string is the number of individual characters it has.
● Declaration:
char name[30] = ‘’Hello!”;
char name[] = “Hello!”;
char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};
string name = “Hello”
Operators:
An operator is a symbol used for performing operations on
variables and values .The operations can be mathematical or
logical.
● Types Of Operators in C++
1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
Arithmetic Operators: Arithmetic operators are used to
perform common mathematical operations.
Operator Name Description

+ Addition Adds together two values

nd st
– Subtraction Subtracts 2 value from 1 value.

* Multiplication Multiplies two values

/ Division Divides numerator by denominator.

% Modulus Returns remainder after division.

++ Increment Increases the value of a variable by 1.

-- Decrement Decreases the value of a variable by 1.


Relational Operators:
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 (true) or 0 (false). These values are known
as Boolean values.
Operator Name Description

== Equal Checks equality of two values.

!= Not equal Checks equality of two values.

Checks whether value of left variable is greater than value of right


> Greater than
variable.

Checks whether value of left variable is less than value of right


< Less than
variable.

Checks whether value of left variable is greater than or equal to


>= Greater than or equal to
value of right variable.

Checks whether value of left variable is less than or equal to value


<= Less than or equal to
of right variable.
Assignment Operators:
Assignment operators are used to assign values to variables
Operator Name Description

= Simple assignment It assigns value on the right to variable on the left.

It first adds value of left variable to value of right variable then


+= Add assignment
assigns result to variable on the left.

It first subtracts value of right variable from value of left variable then
-= Subtract assignment
assigns result to variable on the left.

It first multiplies value of right variable with value of left variable then
*= Multiply assignment
assigns result to variable on the left.

It first divides value of left variable by value of right variable then


/= Division assignment
assigns result to variable on the left.
Logical Operators: Logical operators are used to determine the
logic between variables or values

Operator Name Description

&& Logical AND operator. Returns true if both statements are true.

|| Logical OR operator. Returns true if one of the statements is true

Reverse the result, returns false if the result


! Logical NOT operator.
is true
Bitwise Operators:
Operator Name Description

It takes 2 numbers (operands) then performs AND on


& Bitwise AND each bit of two numbers. If both are 1,then returns 1,
otherwise 0.

Takes 2 numbers (operands) then performs OR on


| Bitwise OR every bit of two numbers. It returns 1 if one of the bits
is 1.

Takes 2 numbers (operands) then performs XOR on


^ Bitwise XOR every bit of 2 numbers. It returns 1 if both bits are
different.
Takes two numbers then left shifts the bits of the first
<< Left shift operand. The second operand determines total places
to shift.

Takes two numbers then right shifts the bits of the


>> Right shift first operand. The second operand determines
number of places to shift.

~ Bitwise NOT Takes number then inverts all its bits.


Special Operator:
● Unary operator
√ Pointer operator(*) Indirection operator
The indirection operator used to give the value of the variable whose
address stored in a pointer and hence indirection operator is also
referred as a value at address operator.
√ Address operator(&)
The address of any variable can get by using an ampersand(&),placing
in the prefix of the variable name.
√ Sizeof operator (sizeof)
It is a compile time unary operator which can be used to compute the
size of its operand.
√ Incrementer and decrementer operator (++,--)
The increment operator ++ increases the value of a variable by 1.
Similarly, the decrement operator -- decreases the value of a variable by
1.
++ and -- operator as prefix and postfix
● If you use the ++operator as a prefix like:++val, the value of val is
incremented by 1; then it returns the value.
● If you use the ++operator as a postfix like: val++,the original value of val
is returned first ;then val incremented by 1.
● The -- operator works in a similar way to the ++ operator except –
decreases the value by1.
● Cast operator
● Ternary operator(?:) expression1? expression2: expression3
● Comma operator(,)
● Scope operator(::)
Other operators
● Parentheses for grouping expression()
● Membership operator []
Data Type in C++
Primitive Data Type:
Variables can be categorised based on their data type. Following
are the types of variables available in C++.
● int: These type of variables holds integer value.
● float: Single-precision floating point value.
● double: Double-precision floating point value.
● char: Holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
● bool: Holds boolean value true or false.
● void: void datatype represents a valueless entity.
Data Type Modifiers in C++
● Long
● Short
● Unsigned
● Signed
C++ Control Statements:
● Selection Control Statement
if statement
if- else statement
switch-case statement
● Iteration /Looping Control Statement
for loop
while loop
do-while loop
● Jump Statement
break statement
continue statement
goto statement
If statement
Syntax: if (condition){
//block of code to be executed if the condition is true
}
If-else statement
Syntax: if( (condition) {
//block of code if condition is true
}
else {
// block of code if condition is false
}
If ….else….else if statement
Syntax: if(condition1) {
// code block 1
}
else if(condition2){
// code block 2
}
else {
//code block 3
}
Note: There can be more than else if statement but only one if
and else statements.
Nested if….else statement
Syntax: if(condition 1){
// statements
// inner if statement
if(condition 2) {
// statements
}
}
Switch-case statement
● The switch statement helps in testing the equality of a variable
against a set of values. Each value under comparison is known
as a case, and the variable being switched on is checked for
each case.
● The switch is similar to the if…else…if ladder. However, it
generates a cleaner and easy-to-understand code. The switch is
also faster compared to the if…else…if ladder. Use the switch
statement when you need to compare the value of a variable
against a set of other values.
Syntax:
switch(expression){
case constant1:
// code to be executed if expression is equal to constant1;
break;
case constant2:
// code to be executed if expression is equal to constant2;
break;
.
.
default:
// code to be executed if expression doesn’t match any constant
break;
}
● The switch expression is evaluated once.
● The expression provided in the switch should result in a constant value
otherwise it would not be valid.
● Switch statements are limited to integer values and characters only in the
check condition.
● The value of the expression is compared with the values of each case.
● If there is a match, the associated block of code is executed.
● If there is no match, the code after default is executed.
● The default statement is optional. Even if the switch case statement do
not have a default statement,
it would run without any problem.
Break: This keyword is used to stop the execution inside a switch block. It
helps to terminate the switch block and break out of it.
Default: This keyword is used to specify the set of statements to execute if
there is no case match.
Note: Sometimes when default is not placed at the end of switch case
program, we should use break statement with the default case.
There are mainly two types of loops:
● Entry Controlled loops: In this type of loop, the test condition is tested
before entering the loop body. For Loop and While Loop is entry-controlled
loops.
● Exit Controlled Loops: In this type of loop the test condition is tested or
evaluated at the end of the loop body. Therefore, the loop body will
execute at least once, irrespective of whether the test condition is true or
false. the do-while loop is exit controlled loop.
While loop:
● A while loop evaluates the condition
● If the condition evaluates to true, the
code inside the while loop is executed.
● The condition is evaluated again.
● This process continues until the condition
is false.
● When the condition evaluates to false, the
loop terminates.
While loop syntax:
Syntax:
Initialization expression;
while( test_expression)
{
// code block to be executed
update_expression;
}
Do-while loop
In do-while loops also the loop execution
is terminated on the basis of test conditions.
The main difference between a do-while loop
and the while loop is in the do-while loop the
condition is tested at the end of the loop body,
i.e do-while loop is exit controlled whereas the
other two loops are entry-controlled loops.
Note: In a do-while loop, the loop body will
execute at least once irrespective of the test
condition.
do-while loop
Syntax:
Initialization expression;
do
{
//statements
update_expression;
}while(test_expression);

Note: Notice the semi-colon(“;”) in the end of loop.


For loop:
Syntax:
for(initialization; condition ; increment or decrement)
{
// Body of loop
}
Flowchart (For loop)
Loop Type and Description:
While loop: First checks the condition ,then executes the body
For loop: firstly initializes, then ,condition check, execute
body ,update.
Do-while loop: firstly ,execute the body then condition check.
Jump statement
Break Statement:
Continue Statement
Continue statement with while loop:
Syntax:
Continue statement with do- while:
Syntax:
Continue statement with for loop:
Syntax:
Goto Statement:
Generation of Random numbers in C++
Random events happen all around us. Sometimes in
web-applications we require random results.
For ex: Dice
● C++ programming language comes with in built pseudo-
random number generate random numbers.
● A random number generator in C++ - rand() and srand()
● Header files: #include <cstdlib> and # include <ctime>
● Syntax: rand()
● A computer does not have a thinking process to select a
random number. So even though an output number produced
may seem random, the values are mathematically computed.
● The srand() function in C++ can perform pseudo-random
number calculation. This function requires a seed value which
forms the basis of computation of random numbers.
Syntax: srand(unsigned int seed_value)
With the help of the seed value ,srand() sets the stage for
generation of pseudo random numbers by the rand() function.
Syntax: int random=rand ();
Importance of a Seed value
● The seed value holds the key to the series of random numbers.
The set of numbers calculated will be similar if the same seed
value is provided to the function.
● The default seed value for the srand() function is 1.
● The problem here is that every time you run the program with
the seed value, the output will remain the same.
● Time- We used the concept of the current timestamp being the
current seed value.
Syntax:
Current_time=time(NULL);
The current time variable holds the no. of seconds passed .This
value is passed to the srand() function and then get a fresh
sequence of pseudo-random numbers.
Syntax:
srand((unsigned)time(NULL));
The seed value is provided once in a program no matter how
many random numbers are to be generated.
Generate random numbers within a range
● Syntax:
int random=offset+(rand()%range);
if we need to fetch random numbers from 1 to 9, we use:
int random=1+(rand()%9);
In the above equation:
● offset - The starting point for the range of random numbers
● range - The number of values between first and the last possible random number
including the limits.
● A pseudo-random number in the range from 0.0 to 32,767.
● The range of generated numbers using % (modulus) operator by specifying a
maximum value.
● the numbers generated by the rand() are not random because it generates the same
sequence each time the code executed.

You might also like