C++ Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Tutorials For

Beginners
● computer program Introduction to
Programming

● Programmer
programming
● Source Code (Code) languages
● Hardware
● Program Execution
● Machine Language
● Assembly Language
● High Level Language
2
High Level Language Assembly Language Machine Language

3
Compiler VS Interpreter

4
Compiler

Interpreter

5
Compiler VS Interpreter
Compiler Interpreter
● Scans whole program at ● Translate one statement
one go at a time(line by line)
● Errors are shown at the ● Errors are shown line by
end line
● Compilation is slow ● Translation is done fast
● Execution is fast ● Execution is slow
● Generates an intermediate ● Execute the program
code without intermediate code
● C,C++ ● Python,Javascript

6
C/C++ Compiler and VS code setup
To Run C/C++ program we need :

● Text Editor (VS code)


● C++ compiler (GCC compiler)

Extra Setup:
● C/C++ - VS code extension
● Code Runner - VS code extension

7
How to run
C/C++
program in
mobile ?

8
Basic Structure Of
C++ Program
INPUT/OUTPUT
In C++
● CIN and COUT
● Extraction >> and insertion << operator
● endl vs \n
● Code Runner(Extension) issue with CIN

10
Comments in C++

● SIngle Line Comment -//


● Multiline Comment - /* */

11
Variables & Data Types
in C++

12
Rules for naming a variable
● Variable names in C++ can range from 1 to 255
characters.
● All variable names must begin with a letter of the
alphabet or an underscore(_).
● After the first initial letter, variable names can also
contain letters and numbers.
● Variable names are case sensitive.
● No spaces or special characters are allowed.
● You cannot use a C++ keyword (a reserved word)
as a variable name.
13
14
Modifiers in C++

15
Data Type Size Value Range
int 4 Bytes -2147483648 to 2147483647

char 1 Bytes -127 to 127 or 0 to 255


float 4 Bytes - 3.4E38 to 3.4E38
double 8 Byte - 1.7E308 to 1.7E + 308
bool 1 Byte
16
Modifiers in c++

● Signed
● unsigned
● short
● long

17
Data Type Size Value Range

int 4 Bytes -2147483648 to 2147483647

Unsigned int 4 Bytes 0 to 4294967295

signed int 4 Bytes -2147483648 to 2147483647

Sort int 2 Bytes -32768 to 32767

long int 8 Bytes -2,147,483,648 to 2,147,483,647

char 1 Bytes -127 to 127 or 0 to 255

Unsigned char 1 Bytes 0 to 255

Signed char 1 Byte -127 to 127

float 4 Bytes - 3.4E38 to 3.4E38

double 8 Byte - 1.7E308 to 1.7E + 308

long double 12 Bytes - 3.4E4932 to 1.1E + 4932

bool 1 Byte 18
Scope of Variables
in C++
● Local Variables
● Global Variables
Constant Variables
● A const variable must be assigned a value at the
time of its declaration.
● If we declare a variable as const, we cannot
change its value.
● Once initialized, if we try to change its value, then
we will get compilation error.

20
Manipulators in c++
Manipulator Purpose Header File

endl causes line feed to be inserted i.e. ‘\n’ iostream.h

dec,oct,hex set the desired number system iostream.h

setbase (b) output integers in base b iomanip.h

setw(w) read or write values to w characters iomanip.h

setfill (c) fills the whitespace with character c iomanip.h

setprecision(n) set floating point precision to n iomanip.h

21
Operators in C++
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Other Operators

22
Operators in C++

23
Arithmetic Operators
Assume A=20 and B=10
Operator Description Example

+ Adds two operands A+B=30

- Subtracts second operand from the first A-B=10

* Multiplies both operands A*B=200

/ Divides numerator by de-numerator A/B=2

% Modulus operator – the result is the remainder of the A%B=0

division

++ Increment operator, increases integer value by one A++ will give 21

-- Decrement operator, decreases integer value by one B-- will give 9


24
Relational Operators
Assume A=20 and B=10
Operator Description Example

== Checks if the values of two operands are equal or not. (A == B) = false

!= Checks if the values of two operands are equal or not. (A != B) = true

> Checks if the value of left operand is greater than the value of (A>B) = true
right operand

< Checks if the value of left operand is less than the value of right (A<B) = false
operand,

>= Checks if the value of left operand is greater than or equal to (A>=B) = true
the value of right operand

<= Checks if the value of left operand is less than or equal to the (A<=B) = false
value of right operand
25
Logical Operators
Assume A=20 and B=10
Operator Description Example

&& Logical AND. True only if all the operands are true. (A>10 && B>20) = false

|| Logical OR. True if at least one of the operands is true. (A>10 || B>20) = true

! Called Logical NOT Operator. Use to reverses the !(A>10) = false


logical state of its operand. If a condition is true, then
Logical NOT operator will make false.

26
Logical Operators

A B A && B A|| B !A
false false false false true
false true false true true
true false false true false
true true true true false

27
Assignment Operators
Operator Description Example

= Assigns values from right side operands to left side A =5


operand.

+= It adds right operand to the left operand and assign the A +=5 same as A=A+5
result to left operand

-= It subtracts right operand from the left operand and A-=5 same as A=A-5
assign the result to left operand.

*= It multiplies right operand with the left operand and A*=5 same as A=A*5
assign the result to left operand.

/= It divides left operand with the right operand and assign A/=5 same as A=A/5
the result to left operand.

%= It takes modulus using two operands and assign the A%=5 same as A=A%5
result to left operand. 28
Bitwise Operators

A B A&B A|B A^B ~A


0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

29
Bitwise Operators
A=3 (0000 0011 ) and B=1 (0000 0001)

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (A & B) = 1 (00000001)
both operands.

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 3 (00000011)

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 2 (00000010)
but not both.

~ Binary Ones Complement Operator is unary and has the !A=!3= -4 (11111100)
effect of 'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left A<<1 = 6 (00000110)
<<
by the number of bits specified by the right operand.

Binary Right Shift Operator. The left operands value is moved right by A>>1 = 1 (00000001)
>>
the number of bits specified by the right operand.
30
Other Operators
Operator Description Example

sizeof Returns the size of variable sizeof(int) =4

Condition ? x:y If condition is true then it returns value of X Int y=20;


otherwise returns value of Y int x= (y < 10) ? 30 : 40;

cast Convert one data type to other int(2.2000) = 2

causes a sequence of operations to be Int j=1;


, performed. The value of the entire comma int i= (j++, j+10, j+20);

expression is the value of the last expression


of the comma-separated list.

& Returns the address of a variable

* Is pointer to a variable

31
Operators Precedence and Associativity
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Left to right

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

32
Operators Precedence and Associativity
Category Operator Associativity

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

33
Increment (++) and decrement (--)
1. The increment operator ++ increases the value of a variable
by 1
2. Similarly, the decrement operator -- decreases the value of a
variable by 1
3. Increment and decrement operators can be used only with
variables. They can't be used with constants or
expressions.
Eg. x=5,y=6;
x++; // valid
5++; // invalid
(x+y)++; // invalid 34
Types of Increment ++ operator
1. In pre-increment first increment the value of variable and then
used inside the expression (initialize into another variable).
2. In post-increment first value of variable is use in the expression
(initialize into another variable) and then increment the value of
variable.

Increment ++

Pre-increment Post-increment
Eg. ++a Eg. a++
35
Types of decrement -- operator
1. In pre-decrement first decrement the value of variable and then
used inside the expression (initialize into another variable).
2. In post-decrement first value of variable is use in the expression
(initialize into another variable) and then decrement the value of
variable.

decrement --

Pre-decrement Post-decrement
Eg. --a Eg. a--
36
Control Statement
● If-else
● Switch
● For Loop
● While loop
● Do-While Loop
● Break /Continue
● Goto

37
If-else
● If statement
● If...else statement
● If…else if…else statement
● Nested if statement

38
If-else practice questions :
● Write a C++ program to accept two integers and check whether they are
equal or not.
● Write a C++ program to accept a integer and check whether number is
even or odd.
● Write a C++ program to accept a integer and check whether number is
positive,negative or zero.
● Write a program in C++ to read any day number in integer and display day
name in the word.
● Write a C++ program to accept two integers and find maximum between
two numbers.

39
switch-case

40
Switch-case practice questions :
● Write a C++ program to print day of week name using switch case.
● Write a C++ program print total number of days in a month using switch
case.
● Write a C++ program to accept a integer and check whether number is
positive,negative or zero using switch case.
● Write a program in C++ to read any day number in integer and display day
name in the word using switch case.

41
Loops in C++ :
● For loop
● While loop
● Do-while loop

42
For loop :
Syntax :
for(initialization;condition;increment){
// your code
}

Example:
for(int i=0;i<5;i++){
cout<<i<<”\n”;
}
43
While loop :
Syntax :
while(condition){
// your code
}

Example:
int i=0;
while(i<10){
cout<<i<<”\n”;
i++;
} 44
do-while loop :
Syntax :
do{
// your code
}while(condition)

Example:
int i=0;
do{
cout<<i<<”\n”;
i++;
}while(i<10)
45
Loop practice questions :
● Write a program in C++ to find the first 10 natural numbers
○ 1 2 3 4 5 6 7 8 9 10
● Write a program in C++ to print a square pattern with # character.

● Write a program in C++ to find the factorial of a number.


● Write a program in C++ to display the pattern like right angle triangle using
an asterisk.

46
Loop practice questions :
● Write a program in C++ to display the pattern like right angle triangle using
an asterisk.

● Write a program in C++ to make such a pattern like a pyramid with an


asterisk.

47
Break
● In C++, the break statement terminates the loop when it is encountered.

48
Continue
● In C++, the continue is used to skip the current iteration of the loop and the
control of the program goes to the next iteration

49
C++ Functions

50
C++ Functions
● A function is a block of code that performs a specific task.
● Functions help us in reducing code redundancy.
● If functionality is performed at multiple places in software,
then rather than writing the same code, again and again, we
create a function and call it everywhere.
● This also helps in maintenance as we have to change at one
place if we make future changes to the functionality.

51
C++ Functions
● There are two types of function:
○ Library Functions (Built in functions)
○ User defined functions
● Function declaration
returnType functionName (parameter1, parameter2,...) {
// function body
}

52
Function Prototype
● The code of function declaration should be before the
function call.
● However, if we want to define a function after the function
call, we need to use the function prototype.
● Function prototype is a declaration statement.
type function-name (arguments-list);
Eg. int sum(int num1,int num2);
OR
int sum(int,int); // Variable name is optional

53
Default Parameters
● In C++, we can provide default values for function parameters.
● In this case, when we invoke the function, we don’t specify
parameters.
● Instead, the function takes the default parameters that are
provided in the prototype.
● Note that while providing default parameters, we always start from
the right-most parameter. Also, we cannot skip a parameter in
between and provide a default value for the next parameter.
● Eg.
Void add(int x, int y, int z = 0)

Default parameter
54
Const Parameters
● We can pass constant parameters to functions using the
‘const’ keyword.
● When a parameter or reference is const, it cannot be
changed inside the function.

Void add(const x, const y)

Const parameter

55
Inline Functions
● When we make a function call, internally it involves a compiler
storing the state of the program on a stack before passing
control to the function.
● When the function returns, the compiler has to retrieve the
program state back and continue from where it left.
● This poses an overhead. Hence, in C++ whenever we have a
function consisting of few statements, there is a facility that
allows it to expand inline.
● This is done by making a function inline. So inline functions are
the functions that are expanded at runtime, saving the efforts to
call the function and do the stack modifications.

56
Inline Functions
● But even if we make a function as inline, the compiler
does not guarantee that it will be expanded at runtime.
● In other words, it’s completely dependent on the compiler
to make the function inline or not.
● Eg.
inline int addition(const int a,const int b)

57

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy