Professional Documents
Culture Documents
Basic Programming Elements and Concepts
Basic Programming Elements and Concepts
a programming language, Program development and execution, Program structure, Data types
and variable declarations, Standard I/O streams, and statements, Control structures, Standard
library functions, User defined functions and parameter passing, Arrays, pointers, and strings,
Structures, unions, and bit manipulation operators
Contents
1 Computer programming language...........................................................................................1
1.1 Language Types................................................................................................................1
1.1.1 Low level...................................................................................................................1
1.1.2 High level...................................................................................................................1
2 Elements of Programming.......................................................................................................2
2.1 5 Basic elements of Programming....................................................................................2
2.1.1 Variables:...................................................................................................................2
2.1.2 Loops:........................................................................................................................2
2.1.3 Conditionals:..............................................................................................................2
2.1.4 Input/output:..............................................................................................................3
2.1.5 Subroutines and functions:........................................................................................3
3 Programming language components........................................................................................3
3.1 Syntax:..............................................................................................................................3
3.2 Semantics:.........................................................................................................................3
3.3 statements:.........................................................................................................................3
3.4 variables:...........................................................................................................................4
4 Problem solving and program design.....................................................................................4
4.1 Problem solving................................................................................................................4
4.2 Design an Algorithm If problem was broken into subproblems.......................................4
4.3 Write the Code Once the algorithm is designed and correctness verified........................4
5 Program structure of C language.............................................................................................5
5.1 Following is the basic structure of a program...................................................................5
5.2 Hello World Program in C++............................................................................................5
5.2.1 Comments..................................................................................................................5
5.2.2 #include<iostream>...................................................................................................6
5.2.3 Using namespace std;................................................................................................6
5.2.4 int main()...................................................................................................................6
5.2.5 cout << “Hello World!”;............................................................................................6
6 Data types and Variable declaration in C++............................................................................7
6.1 Built in data types.............................................................................................................7
6.1.1 char:...........................................................................................................................7
6.1.2 int:..............................................................................................................................7
6.1.3 float:...........................................................................................................................7
6.1.4 double:.......................................................................................................................8
6.1.5 bool:...........................................................................................................................8
6.1.6 wchar_t:.....................................................................................................................8
6.2 User-defined data types.....................................................................................................8
6.2.1 Derived data types in C++.........................................................................................8
7 Variables in C++......................................................................................................................8
7.1 Syntax of declaring a variable in C++..............................................................................8
7.2 Types of variables.............................................................................................................9
7.2.1 int: These type of variables holds integer value........................................................9
7.2.2 char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc...........................................9
7.2.3 bool: holds boolean value true or false......................................................................9
7.2.4 double: double-precision floating point value...........................................................9
7.2.5 float: Single-precision floating point value...............................................................9
7.3 Types of variables based on their scope............................................................................9
7.3.1 Global Variable..........................................................................................................9
7.3.2 Global variable example..........................................................................................10
7.3.3 Local variable..........................................................................................................10
7.3.4 Local variable example............................................................................................10
7.3.5 Can global and local variable have same name in C++?.........................................11
8 Standard I/O streams in c++..................................................................................................11
8.1 Streams............................................................................................................................12
8.2 Standard streams in C++.................................................................................................13
9 Control Statements.................................................................................................................14
9.1 If else Statement in C++..................................................................................................14
9.2 Switch Case statement in C++ with example..................................................................23
9.2.1 Example of Switch Case..........................................................................................24
9.2.2 Switch Case Flow Diagram.....................................................................................25
9.2.3 Break statement in Switch Case..............................................................................25
9.2.4 Why didn’t I use break statement after default?......................................................27
9.2.5 Important Notes.......................................................................................................28
9.3 LOOP:.............................................................................................................................29
9.3.1 For loop in C++ with example.................................................................................29
9.3.2 Syntax of for loop....................................................................................................29
9.3.3 Flow of Execution of the for Loop..........................................................................29
9.3.4 Example of a Simple For loop in C++.....................................................................30
9.3.5 Infinite for loop in C++...........................................................................................30
9.3.6 Example: display elements of array using for loop.................................................31
9.4 while-loop:......................................................................................................................31
9.4.1 While loop in C++ with example.............................................................................32
9.4.2 Syntax of while loop................................................................................................32
9.4.3 How while Loop works?..........................................................................................32
9.4.4 Flow Diagram of While loop...................................................................................33
9.4.5 While Loop example in C++...................................................................................33
9.4.6 Infinite While loop...................................................................................................34
9.4.7 Example: Displaying the elements of array using while loop.................................34
9.5 Do-while Loop................................................................................................................34
9.5.1 do-while loop in C++ with example........................................................................34
9.5.2 Syntax of do-while loop...........................................................................................35
9.5.3 How do-while loop works?......................................................................................35
9.5.4 do-while loop example in C++................................................................................35
9.5.5 Example: Displaying array elements using do-while loop......................................36
9.6 Continue Statement.........................................................................................................37
9.6.1 Continue Statement in C++ with example...............................................................37
9.6.2 Syntax of continue statement...................................................................................37
9.6.3 Example: continue statement inside for loop...........................................................37
9.6.4 Flow Diagram of Continue Statement.....................................................................38
9.6.5 Example: Use of continue in While loop.................................................................38
9.6.6 Example of continue in do-While loop....................................................................39
9.7 Break statement:..............................................................................................................39
9.7.1 Break statement in C++ with example.....................................................................39
9.7.2 Syntax of break statement........................................................................................39
9.7.3 break statement flow diagram..................................................................................40
9.7.4 Example – Use of break statement in a while loop.................................................40
9.7.5 Example: break statement in for loop......................................................................41
9.7.6 Example: break statement in Switch Case...............................................................41
9.8 Go to statement...............................................................................................................42
9.8.1 goto statement in C++ with example.......................................................................42
9.8.2 Program structure:...................................................................................................42
9.8.3 Example of goto statement in C++..........................................................................42
10 Functions in C++...................................................................................................................43
10.1 Syntax of Function......................................................................................................43
10.2 A simple function example..........................................................................................43
10.3 Function Declaration:..................................................................................................44
10.3.1 syntax of function declaration:................................................................................44
10.4 Function definition:.....................................................................................................45
10.4.1 syntax of function definition:...................................................................................45
10.5 Types of function.........................................................................................................45
10.5.1 1) Build-it functions.................................................................................................45
10.5.2 Example: C++ built-in function example................................................................46
10.6 2) User-defined functions............................................................................................46
10.7 User-defined functions................................................................................................46
10.8 Parameters Pass:..........................................................................................................47
10.8.1 Parameter Passing Techniques in C/C++................................................................47
10.8.2 Terminology............................................................................................................47
10.8.3 Important methods of Parameter Passing................................................................48
10.8.4 Pass by reference(aliasing) :....................................................................................49
10.8.5 Other methods of Parameter Passing.......................................................................49
10.9 C++ Recursion with example......................................................................................50
10.9.1 C++ recursion example: Factorial...........................................................................51
10.9.2 Base condition.........................................................................................................51
10.9.3 Direct recursion vs indirect recursion......................................................................51
10.9.4 Indirect Recursion Example in C++........................................................................52
11 Arrays....................................................................................................................................52
11.1 Arrays in C++..............................................................................................................52
11.2 Declaring an array in C++...........................................................................................53
11.3 Accessing Array Elements..........................................................................................53
11.4 Multidimensional Arrays in C++................................................................................55
11.5 A two dimensional array:............................................................................................55
11.6 A three dimensional array:..........................................................................................55
11.6.1 Two dimensional array............................................................................................55
11.6.2 How to declare a two dimensional array?................................................................55
11.6.3 Three dimensional array..........................................................................................56
11.6.4 Declaring a three dimensional array:.......................................................................56
11.7 Passing Array to Function in C++...............................................................................57
11.7.1 Example: Passing arrays to a function.....................................................................57
11.7.2 Example 2: Passing multidimensional array to function.........................................58
12 Strings:...................................................................................................................................59
12.1 Strings in C++.............................................................................................................59
12.2 1) Array of Characters – Also known as C Strings.....................................................59
12.3 Example 2: Getting user input as string......................................................................60
12.4 Example 3: Correct way of capturing user input string using cin.get.........................60
12.5 Drawback of this method............................................................................................61
12.5.1 String object in C++................................................................................................61
13 Pointers..................................................................................................................................62
13.1 Pointers in C++............................................................................................................62
13.2 Syntax of pointer.........................................................................................................62
13.3 How to Use Pointers?..................................................................................................63
13.4 NULL Pointers............................................................................................................63
13.5 Pointers in Detail.......................................................................................................64
13.6 How to declare a pointer?............................................................................................65
13.7 Assignment..................................................................................................................65
13.8 How to use it?..............................................................................................................65
13.9 Example of Pointer......................................................................................................66
13.10 Pointer and arrays........................................................................................................66
13.11 Example: Traversing the array using Pointers............................................................67
13.12 How to increment pointer address and pointer’s value?.............................................67
13.13 C++ ‘this’ Pointer........................................................................................................68
13.14 C++ Example: this pointer..........................................................................................68
13.15 Example 2: function chaining calls using this pointer................................................69
14 Structures, Union in C++.......................................................................................................69
14.1 Syntax for declaring union..........................................................................................70
14.2 Accessing the union members.....................................................................................70
14.3 Syntax for creating object of union.............................................................................70
14.4 Example for creating object & accessing union members..........................................71
14.5 Example of comparing size of union and structure.....................................................74
15 Structure in C++....................................................................................................................75
15.1 Syntax for declaring structure.....................................................................................76
15.2 Example for declaring structure..................................................................................76
15.3 Accessing the structure members................................................................................76
15.4 Syntax for creating object............................................................................................77
15.5 Example for creating object & accessing structure members.....................................77
15.6 Initialization of structure.............................................................................................78
15.7 Example for declaring & initializing structure at same time.......................................79
15.8 Array of Structure........................................................................................................80
15.9 Syntax for declaring structure array............................................................................80
15.10 Example for declaring structure array.........................................................................80
15.11 Array within Structure.................................................................................................83
15.12 Syntax for array within structure.................................................................................83
15.13 Example for array within structure..............................................................................83
15.14 Nested Structure in C++..............................................................................................85
15.15 Syntax for structure within structure or nested structure............................................85
15.16 Example for structure within structure or nested structure.........................................86
15.17 Structure and Function in C++....................................................................................88
15.18 Passing structure as function argument.......................................................................88
15.19 Passing Structure by Value..........................................................................................89
15.20 Example for passing structure object by value............................................................89
15.21 Passing Structure by Reference...................................................................................90
15.22 Example for passing structure object by reference.....................................................90
15.23 Function Returning Structure......................................................................................91
15.24 Example for passing structure object by reference.....................................................92
16 Bit manipulation....................................................................................................................94
16.1 Bits manipulation........................................................................................................94
16.2 Bitwise Operators:.......................................................................................................94
16.3 Bit Fields.....................................................................................................................97
16.4 (Important tactics).......................................................................................................97
https://www.tutorialspoint.com/computer_programming/
computer_programming_overview.html
2 Elements of Programming
Process to develop various sets of instruction is known as programming.
To develop any instruction there are some elements are needed or we can essentially
present in all language.
So any programming language is made up of 5 basic elements of the instructions
Variables in programming tell how the data is represented which can be range from very
simple value to complex one.
The value they contain can be change depending on condition.
As we know program consist of instructions that tell the computer to do things and data
the program use when it is running.
Data is constant with the fixed values or variable.
They can hold a very simplex value like an age of the person to something very complex
like a student track record of his performance of whole year.
3.1.2 Loops:
We can define loop as a sequence of instructions that are repeated continuously till a
certain condition is not satisfied.
How a loop start understand this first a certain process is done, to get any data and
changing it after that applied condition on the loop is checked whether counter reached
to prescribed number or not.
o Basically a loop carry out execution of a group of instruction of commands a
certain number of times.
o There is also a concept of infinite loop which is also termed as endless loop is a
piece of code that lack from functional exit and goes to repeat indefinitely.
3.1.3 Conditionals:
Conditionals specify the execution of the statements depending on the whether condition
is satisfied or not.
Basically it refers to an action that only fulfill when the applied condition on instructions
satisfied. They are one of the most important components of the programming language
because they give freedom to program to act differently every time when it execute that
depends on input to the instructions.
3.1.4 Input/output:
The element of computer programming that allows interaction of the program with the
external entities.
o Example of input/output element are printing something out to the terminal
screen, capturing some text that user input on the keyboard and can be include
reading and writing files.
o Let’s take a language example to understand the concept of input and output. C+
+ use streams to perform input and output operation in sequential media in terms
of screen, the keyboard or a file. We can define stream as an entity that can insert
or extract characters and there is no need to know details about the media
associated to the stream or any of its internal specification. We need to know
about streams is that they are source or destination of characters and the
characters are accepted sequentially.
The element of the programming allows a programmer to use snippet of code into one
location which can be used over and over again.
The primary purpose of the functions is to take arguments in numbers of values and do
some calculation on them after that return a single result.
Functions are required where you need to do complicated calculations and the result of
that may or may not be used subsequently used in an expression.
If we talk about subroutines that return several results. Where calls to subroutines cannot
be placed in an expression whether it is in the main program where subroutine is
activated by using CALL statement which include the list of inputs and outputs that
enclosed in the open and closed parenthesis and they are called the arguments of the
subroutines.
There are some of the rules follow by both to define name like less than six letters and
start with the letters. The name should be different that used for variables and functions.
Statements (Instructions that say what to do – compute values, make decisions, repeat sequences
of operations)
variables: (places to hold data in memory while program is running – numbers, text, ...)
most languages are higher-level and more expressive than the assembly language for the
toy machine –
statements are much richer, more varied, more expressive
variables are much richer, more varied –
grammar rules are more complicated –
semantics are more complicated
but it's basically the same idea Why study / use Javascript?
return 0;
}
Output:
Hello World!
Let’s discuss each and every part of the above program.
5.2.1 Comments
You can see two types of comments in the above program
For example:
5.2.2 #include<iostream>
This statement tells the compiler to include iostream file.
This file contains pre-defined input/output functions that we can use in our program.
6.1.1 char:
For characters. Size 1 byte.
char ch = 'A';
6.1.2 int:
For integers. Size 2 bytes.
bool b = true;
6.1.6 wchar_t:
Wide Character. This should be avoided because its size is implementation defined and not
reliable.
7 Variables in C++
A variable is a name which is associated with a value that can be changed.
For example when I write int num=20; here variable name is num which is associated
with value 20, int is a data type that represents that this variable can hold integer values.
7.2.2 char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
int main {
//Some code
}
Any variable declared inside these curly braces have scope limited within these curly
braces, if you declare a variable in main() function and try to use that variable outside
main() function then you will get compilation error.
Now that we have understood what is scope. Lets move on to the types of variables based on the
scope.
1. Global variable
2. Local variable
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Value of myVar: A
Value of myVar: Z
7.3.3 Local variable
Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope limited
inside those braces.
char myFuncn() {
// This is a local variable
char myVar = 'A';
}
Int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Compile time error, because we are trying to access the variable myVar outside of its scope. The
scope of myVar is limited to the body of function myFuncn(), inside those braces.
7.3.5 Can global and local variable have same name in C++?
Lets see an example having same name global and local variable.
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0;
}
Output:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
As you can see that when I changed the value of myVar in the main function, it only changed the
value of global variable myVar because local variable myVar scope is limited to the
function myFuncn().
When you include the iostream header, you gain access to a whole hierarchy of classes
responsible for providing I/O functionality (including one class that is actually named iostream).
The class hierarchy for the non-file-I/O classes looks like this:
The first thing you may notice about this hierarchy is that it uses multiple inheritance (that thing
we told you to avoid if at all possible). However, the iostream library has been designed and
extensively tested in order to avoid any of the typical multiple inheritance problems, so you can
use it freely without worrying.
8.1 Streams
The second thing you may notice is that the word “stream” is used an awful lot.
At its most basic, I/O in C++ is implemented with streams. Abstractly, a stream is
just a sequence of bytes that can be accessed sequentially. Over time, a stream
may produce or consume potentially unlimited amounts of data.
Typically we deal with two different types of streams. Input streams are used to
hold input from a data producer, such as a keyboard, a file, or a network. For
example, the user may press a key on the keyboard while the program is currently
not expecting any input. Rather than ignore the users key press, the data is put
into an input stream, where it will wait until the program is ready for it.
Conversely, output streams are used to hold output for a particular data consumer,
such as a monitor, a file, or a printer. When writing data to an output device, the
device may not be ready to accept that data yet -- for example, the printer may
still be warming up when the program writes data to its output stream. The data
will sit in the output stream until the printer begins consuming it.
Some devices, such as files and networks, are capable of being both input and output sources.
The nice thing about streams is the programmer only has to learn how to interact
with the streams in order to read and write data to many different kinds of
devices. The details about how the stream interfaces with the actual devices they
are hooked up to is left up to the environment or operating system.
Although the IOS class is generally derived from ios_base, IOS is typically the most base class
you will be working directly with. The ios class defines a bunch of stuff that is common to both
input and output streams. We’ll deal with this stuff in a future lesson.
The istream class is the primary class used when dealing with input streams. With input streams,
the extraction operator (>>) is used to remove values from the stream. This makes sense: when
the user presses a key on the keyboard, the key code is placed in an input stream. Your program
then extracts the value from the stream so it can be used.
The ostream class is the primary class used when dealing with output streams. With output
streams, the insertion operator (<<) is used to put values in the stream. This also makes sense:
you insert your values into the stream, and the data consumer (eg. monitor) uses them.
The iostream class can handle both input and output, allowing bidirectional I/O.
Finally, there are a bunch of classes that end in “_withassign”. These stream classes are derived
from istream, ostream, and iostream (respectively) with an assignment operator defined, allowing
you to assign one stream to another. In most cases, you won’t be dealing with these classes
directly.
cin -- an istream_withassign class tied to the standard input (typically the keyboard)
cout -- an ostream_withassign class tied to the standard output (typically the monitor)
cerr -- an ostream_withassign class tied to the standard error (typically the monitor), providing
unbuffered output
clog -- an ostream_withassign class tied to the standard error (typically the monitor), providing
buffered output
Unbuffered output is typically handled immediately, whereas buffered output is typically stored
and written out as a block. Because clog isn’t used very often, it is often omitted from the list of
standard streams.
9 Control Statements
If, if..else-if statement
Switch Case in C++
For loop
while loop
do while loop
Continue statement
Break statement
goto statement
if statement
nested if statement
if-else statement
if-else-if statement
If statement in C++
if(condition){
Statement(s);
The statements inside if parenthesis (usually referred as if body) gets executed only when the
given condition is true. If the condition is false then the statements inside if body are completely
ignored.
#include <iostream>
int main(){
int num=70;
*/
*/
return 0;
Output:
When there is an if statement inside another if statement then it is called the nested if statement.
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the
conditions( condition_1 and condition_2) are true.
Sometimes you have a condition and you want to execute a block of code if condition is true and
execute another piece of code if the same condition is false. This can be achieved in C++ using
if-else statement.
if(condition) {
Statement(s);
else {
Statement(s);
The statements inside “if” would execute if the condition is true, and the statements inside “else”
would execute if the condition is false.
#include <iostream>
int main(){
int num=66;
else {
//This would run if above condition is false
return 0;
Output:
if-else-if statement is used when we need to check multiple conditions. In this control structure
we have only one “if” and one “else”, however we can have multiple “else if” blocks.
if(condition_1) {
statement(s);
else if(condition_2) {
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
*/
statement(s);
else {
*/
statement(s);
Note: The most important point to note here is that in if-else-if, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is
met then the statements inside “else” gets executed.
Example of if-else-if
#include <iostream>
int main(){
int num;
cin>>num;
else {
return 0;
}
Output:
Switch case statement is used when we have multiple conditions and we need to perform
different action based on the condition.
When we have multiple conditions and we need to execute a block of statements when a
particular condition is satisfied. In such case either we can use lengthy if. Else-if
statement or switch case.
The problem with lengthy if..else-if is that it becomes complex when we have several
conditions. The switch case is a clean and efficient method of handling such scenarios.
case constant:
//C++ code
case constant:
//C++ code
default:
//C++ code
;
}
Switch Case statement is mostly used with break statement even though the break statement is
optional. We will first see an example without break statement and then we will discuss switch
case with break
#include <iostream>
int main(){
int num=5;
switch(num+2) {
case 1:
case 2:
case 3:
default:
return 0;
}
Output:
Explanation: In switch I gave an expression, you can give variable as well. I gave the expression
num+2, where num value is 5 and after addition the expression resulted 7. Since there is no case
defined with value 4 the default case got executed.
It evaluates the value of expression or variable (based on whatever is given inside switch braces),
then based on the outcome it executes the corresponding case.
Before we discuss about break statement, Let’s see what happens when we don’t use break
statement in switch case. See the example below:
#include <iostream>
int main(){
int i=2;
switch(i) {
return 0;
Output:
Case2
Case3
Case4
Default
In the above program, we have the variable i inside switch braces, which means whatever the
value of variable i is, the corresponding case block gets executed. We have passed integer value
2 to the switch, so the control switched to the case 2, however we don’t have break statement
after the case 2 that caused the flow to continue to the subsequent cases till the end. However this
is not what we wanted, we wanted to execute the right case block and ignore rest blocks. The
solution to this issue is to use the break statement in after every case block.
Break statements are used when you want your program-flow to come out of the switch body.
Whenever a break statement is encountered in the switch body, the execution flow would
directly come out of the switch, ignoring rest of the cases. This is why you must end each case
block with the break statement.
Let’s take the same example but this time with break statement.
#include <iostream>
int main(){
int i=2;
switch(i) {
case 1:
cout<<"Case1 "<<endl;
break;
case 2:
cout<<"Case2 "<<endl;
break;
case 3:
cout<<"Case3 "<<endl;
break;
case 4:
cout<<"Case4 "<<endl;
break;
default:
cout<<"Default "<<endl;
}
return 0;
Output:
Case2
Now you can see that only case 2 got executed, rest of the subsequent cases were ignored.
The control would itself come out of the switch after default so I didn’t use break statement after
it, however if you want you can use it, there is no harm in doing that.
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after
case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them
in any order based on the requirement.
#include <iostream>
int main(){
char ch='b';
switch(ch) {
break;
break;
break;
return 0;
3) Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.
9.3 LOOP:
Repeat again and again until getting the desire result.
Do loop
Do while loop
For loop
First step: In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each loop iteration, if the condition is
true then the statements inside for for loop body gets executed. Once the condition
returns false, the statements in for loop does not execute and the control gets transferred
to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-
evaluated.
The steps from second to fourth repeats until the loop condition returns false.
#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Output:
For example:
#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
This is an infinite loop as we are incrementing the value of i so it would always satisfy the
condition i>=1, the condition would never return false.
// infinite loop
for ( ; ; ) {
// statement(s)
}
9.3.6 Example: display elements of array using for loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,9,56,99, 202};
/* We have set the value of variable i
* to 0 as the array index starts with 0
* which means the first element of array
* starts with zero index.
*/
for(int i=0; i<5; i++){
cout<<arr[i]<<endl;
}
return 0;
}
Output:
21
9
56
99
202
9.4 while-loop:
#include <iostream>
using namespace std;
int main(){
int i=1; while(i<=6) {
cout<<"Value of variable i is: "<<i<<endl; i--;
}
}
9.4.7 Example: Displaying the elements of array using while loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,87,15,99, -12};
/* The array index starts with 0, the
* first element of array has 0 index
* and represented as arr[0]
*/
int i=0;
while(i<5){
cout<<arr[i]<<endl;
i++;
}
}
Output:
21
87
15
99
-12
9.5 Do-while Loop
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6
9.5.5 Example: Displaying array elements using do-while loop
Here we have an integer array which has four elements. We are displaying the elements of it
using do-while loop.
#include <iostream>
using namespace std;
int main(){
int arr[]={21,99,15,109};
/* Array index starts with 0, which
* means the first element of array
* is at index 0, arr[0]
*/
int i=0;
do{
cout<<arr[i]<<endl;
i++;
}while(i<4);
return 0;
}
Output:
21
99
15
109
9.6 Continue Statement
#include <iostream>
using namespace std;
int main(){
for (int num=0; num<=6; num++) {
/* This means that when the value of
* num is equal to 3 this continue statement
* would be encountered, which would make the
* control to jump to the beginning of loop for
* next iteration, skipping the current iteration
*/
if (num==3) {
continue;
}
cout<<num<<" ";
}
return 0;
}
Output:
012456
9.6.4 Flow Diagram of Continue Statement
Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0
9.6.6 Example of continue in do-While loop
#include <iostream>
using namespace std;
int main(){
int j=4;
do {
if (j==7) {
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j<10);
return 0;
}
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used
along with if statement, whenever used inside loop(see the example below) so that it
occurs only for a particular condition.
It is used in switch case control structure after the case blocks. Generally all cases in
switch case are followed by a break statement to avoid the subsequent cases (see the
example below) execution. Whenever it is encountered in switch-case block, the control
comes out of the switch-case body.
#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
Value of num is: 10
Value of num is: 11
Value of num is: 12
Hey, I'm out of the loop
9.7.5 Example: break statement in for loop
#include <iostream>
using namespace std;
int main(){
int var;
for (var =200; var>=10; var --) {
cout<<"var: "<<var<<endl;
if (var==197) {
break;
}
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop
9.7.6 Example: break statement in Switch Case
#include <iostream>
using namespace std;
int main(){
int num=2;
switch (num) {
case 1: cout<<"Case 1 "<<endl;
break;
case 2: cout<<"Case 2 "<<endl;
break;
case 3: cout<<"Case 3 "<<endl;
break;
default: cout<<"Default "<<endl;
}
cout<<"Hey, I'm out of the switch case";
return 0;
}
Output:
Case 2
Hey, I'm out of the switch case
In this example, we have break statement after each Case block, this is because if we don’t have
it then the subsequent case block would also execute. The output of the same program without
break would be:
Case 2
Case 3
Default
Hey, I'm out of the switch case
9.8 Go to statement
goto label_name;
9.8.2 Program structure:
label1:
...
...
goto label2;
...
..
label2:
...
In a program we have any number of goto and label statements, the goto statement is followed by
a label name, whenever goto statement is encountered, the control of the program jumps to the
label specified in the goto statement.
goto statements are almost never used in any development as they are complex and makes your
program much less readable and more error prone. In place of goto, you can
use continue and break statement.
print:
cout<<"Even Number";
return 0;
}
Output:
Enter a number: 42
Even Number
10 Functions in C++
A function is block of code which is used to perform a particular task, for example let’s say you
are writing a large C++ program and in that program you want to do a particular task several
number of times, like displaying value from 1 to 10, in order to do that you have to write few
lines of code and you need to repeat these lines every time you display values. Another way of
doing this is that you write these lines inside a function and call that function every time you
want to display values. This would make you code simple, readable and reusable.
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Output:
100
The same program can be written like this: Well, I am writing this program to let you
understand an important term regarding functions, which is function declaration. Lets see the
program first and then at the end of it we will discuss function declaration, definition and calling
of function.
#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);
//Main function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
10.4.1
syntax of function definition:
return_type function_name(parameter_list) {
//Statements inside function
}
Calling function: We can call the function like this:
function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++
1) Built-in functions
2) User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
32
We have already seen user-defined functions, the example we have given at the beginning of this
tutorial is an example of user-defined function. The functions that we declare and write in our
programs are user-defined functions. Lets see another example of user-defined functions.
int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;
Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not
get transmitted back to the caller. Any modifications to the formal parameter variable inside the
called function or method affect only the separate storage location and will not be reflected in the
actual parameter in the calling environment. This method is also called as call by value.
// C program to illustrate
// call by value
#include <stdio.h>
filter_none
edit
play_arrow
brightness_4
// C program to illustrate
// call by reference
#include <stdio.h>
int main(void)
{
int a = 10, b = 20;
3. Pass by name : This technique is used in programming language such as Algol. In this
technique, symbolic “name” of a variable is passed, which allows it both to be accessed and
update.
Example:
To double the value of C[j], you can pass its name (not its value) into the following
procedure.
4. procedure double(x);
5. real x;
6. begin
7. x:=x*2
8. end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call
for the corresponding parameter in the body of the procedure.
Implications of Pass-by-Name mechanism:
The argument expression is re-evaluated each time the formal parameter is passed.
The procedure can change the values of variables used in the argument expression and
hence change the expression’s value.
In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
10.9.1 C++ recursion example: Factorial
#include <iostream>
using namespace std;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
if (n <= 1)
return 1;
else
return n*f(n-1);
}
int main(){
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"Factorial of entered number: "<<f(num);
return 0;
}
Output:
Enter a number: 5
Factorial of entered number: 120
10.9.2 Base condition
In the above program, you can see that I have provided a base condition in the recursive
function. The condition is:
if (n <= 1)
return 1;
The purpose of recursion is to divide the problem into smaller problems till the base condition is
reached. For example in the above factorial program I am solving the factorial function f(n) by
calling a smaller factorial function f(n-1), this happens repeatedly until the n value reaches base
condition(f(1)=1). If you do not define the base condition in the recursive function then you will
get stack overflow error.
120
11 Arrays
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Method 2:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:
11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is not
recommended. When you want to access a particular array element then this is fine but if you
want to display all the elements then you should use a loop like this:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=0;
while(n<=4){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
11.4 Multidimensional Arrays in C++
Multidimensional arrays are also known as array of arrays. The data in multidimensional array
is stored in a tabular form as shown in the diagram below:
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
#include <iostream>
Using namespace std;
Int main (){
Int arr [2][3] = {{11, 22, 33}, {44, 55, 66}};
for (int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
11.6.3 Three dimensional array
Lets see how to declare, initialize and access Three Dimensional Array elements.
int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
Three dimensional array example
#include <iostream>
using namespace std;
int main(){
// initializing the array
int arr[2][3][2] = {
{ {1,-1}, {2,-2}, {3,-3} },
{ {4,-4}, {5,-5}, {6,-6} }
};
// displaying array values
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 2; z++) {
cout<<arr[x][y][z]<<" ";
}
}
}
return 0;
}
Output:
1 -1 2 -2 3 -3 4 -4 5 -5 6 -6
function_name(array_name);
11.7.1 Example: Passing arrays to a function
In this example, we are passing two arrays a & b to the function sum(). This function adds the
corresponding elements of both the arrays and display them.
#include <iostream>
using namespace std;
/* This function adds the corresponding
* elements of both the arrays and
* displays it.
*/
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}
Output:
11
22
33
44
55
11.7.2 Example 2: Passing multidimensional array to function
In this example we are passing a multidimensional array to the function square which displays
the square of each element.
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}
Output:
1
4
9
16
25
36
12 Strings:
Lets discuss these two ways of creating string first and then we will see which method is better
and why.
#include <iostream>
using namespace std;
int main(){
char book[50] = "A Song of Ice and Fire";
cout<<book;
return 0;
}
Output:
A Song of Ice and Fire
This can be considered as inefficient method of reading user input, why? Because when we read
the user input string using cin then only the first word of the string is stored in char array and rest
get ignored. The cin function considers the space in the string as delimiter and ignore the part
after it.
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
//reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;
}
Output:
12.4 Example 3: Correct way of capturing user input string using cin.get
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
For example, lets say you have created an array of character with the size 10 and user
enters the string of size 15 then the last five characters would be truncated from the
string.
On the other hand if you create a larger array to accommodate user input then the
memory is wasted if the user input is small and array is much larger then what is needed.
2) In this method, you can only use the in-built functions created for array which don’t help
much in string manipulation.
#include<iostream>
using namespace std;
int main(){
// This is how we create string object
string str;
cout<<"Enter a String:";
/* This is used to get the user input
* and store it into str
*/
getline(cin,str);
cout<<"You entered: ";
cout<<str<<endl;
Enter a String:XYZ
You entered: XYZ
The string after push_back: XYZA
The string after pop_back: XYZ
The advantage of using this method is that you need not to declare the size of the string, the size
is determined at run time, so this is better memory management method. The memory is
allocated dynamically at runtime so no memory is wasted.
13 Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation, cannot
be performed without using pointers. So it becomes necessary to learn pointers to
become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes
an address in memory. Consider the following example, which prints the address of the
variables defined −
#include <stdio.h>
int main () {
int var1;
char var2[10];
return 0;
}
int main () {
return 0;
}
#include <stdio.h>
int main () {
int *ptr = NULL;
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system.
However, the memory address 0 has special significance; it signals that the pointer is
not intended to point to an accessible memory location. But by convention, if a pointer
contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers
3 Pointer to pointer
C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.
13.7 Assignment
As I mentioned above, an integer type pointer can hold the address of another int variable. Here
we have an integer variable var and pointer p holds the address of var. To assign the address of
variable to pointer we use ampersand symbol (&).
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;
//Assignment
p = &var;
First and very important point to note regarding arrays is that the array name alone
represents the base address of array so while assigning the address of array to pointer
don’t use ampersand sign(&). Do it like this:
p = arr;
Incorrect:
p = &arr;
13.11 Example: Traversing the array using Pointers
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p;
//Array declaration
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment
p = arr;
for(int i=0; i<6;i++){
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
}
Output:
1
2
3
4
5
6
/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);
13.13 C++ ‘this’ Pointer
The this pointer holds the address of current object, in simple words you can say that
this pointer points to the current object of the class. Let’s take an example to understand this
concept.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}
Output:
100
A
13.15 Example 2: function chaining calls using this pointer
Another example of using this pointer is to return the reference of current object so that you can
chain function calls, this way you can call all the functions for the current object in one go.
Another important point to note in this program is that I have incremented the value of object’s
num in the second function and you can see in the output that it actually incremented the value
that we have set in the first function call. This shows that the chaining is sequential and the
changes made to the object’s data members retains for further chaining calls.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
Demo &setNum(int num){
this->num =num;
return *this;
}
Demo &setCh(char ch){
this->num++;
this->ch =ch;
return *this;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
//Chaining calls
obj.setNum(100).setCh('A');
obj.displayMyValues();
return 0;
}
Output:
101
A
Declaration of union must start with the keyword union followed by the union name and
union's member variables are declared within braces.
Union union-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
#include<iostream.h>
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
Employee E;
Output :
Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000
Employee Id : -20536
Employee Name : ?$?$ ?
Employee Age : -20536
Employee Salary : 45000
In the above example, we can see that values of Id, Name and Age members of union got
corrupted because final value assigned to the variable has occupied the memory location and
this is the reason that the value of salary member is getting printed very well. Now let's look
into the same example once again where we will use one variable at a time which is the main
purpose of having union:
#include<iostream.h>
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
Employee E;
Output :
Enter Employee Id : 1
Employee Id : 1
Here, all the members are getting printed very well because one member is being used at a
time.
#include<iostream.h>
struct Employee1
int Id;
char Name[25];
long Salary;
};
union Employee2
int Id;
char Name[25];
long Salary;
};
void main()
Output :
Size of Employee1 is : 31
Size of Employee2 is : 25
15 Structure in C++
Structure is commonly referred to as user-defined data type. Structure is similar to an array but
the only difference is that array is collection of similar data type on the other hand structure is
collection of different data type. A structure can contain any data type including array and
another structure as well. Each variable declared inside structure is called member of structure.
Declare Structuration
Declaration of structure must start with the keyword struct followed by the structure name and
structure's member variables are declared within braces.
struct structure-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
structure-name obj;
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
Employee E; //Statement 1
Output :
Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
Employee E = {2,"Suresh",35,35000};
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
15.8 Array of Structure
Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can
be of structure type.
struct structure-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
cout << "\nEnter details of " << i+1 << " Employee";
Output :
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using array of
object. Statement 1 is creating an array of Employee Emp to store the records of 3 employees.
struct structure-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
----------
datatype varN;
};
structure-name obj;
#include<iostream.h>
struct Student
{
int Roll;
char Name[25];
int Marks[3]; //Statement 1 : array of marks
int Total;
float Avg;
};
void main()
{
int i;
Student S;
S.Total = 0;
for(i=0;i<3;i++)
{
cout << "\n\nEnter Marks " << i+1 << " : ";
cin >> S.Marks[i];
S.Avg = S.Total / 3;
Output :
Roll : 10
Name : Kumar
Total : 223
Average : 74.00000
In the above example, we have created an array Marks[ ] inside structure representing 3 marks
of a single student. Marks[ ] is now a member of structure student and to access Marks[ ] we
have used dot operator(.) along with object S.
struct structure2
{
----------
----------
structure1 obj;
};
#include<iostream.h>
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int Id;
char Name[25];
float Salary;
Address Add;
};
void main()
{
int i;
Employee E;
Output :
Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Display(Emp);
}
void Display(struct Employee E)
{
cout << "\n\nEmployee Id : " << E.Id);
cout << "\nEmployee Name : " << E.Name);
cout << "\nEmployee Age : " << E.Age);
cout << "\nEmployee Salary : " << E.Salary);
}
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Display(&Emp);
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
15.23 Function Returning Structure
Structure is user-defined data type, like built-in data types structure can be return from
function.
#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Emp = Input();
}
Employee Input()
{
Employee E;
return E; //Statement 2
}
Output :
Enter Employee Id : 10
Enter Employee Name : Ajay
Enter Employee Age : 25
Enter Employee Salary : 15000
Employee Id : 10
Employee Name : Ajay
Employee Age : 25
Employee Salary : 15000
In the above example, statement 1 is declaring Input() with return type Employee. As we know
structure is user-defined data type and structure name acts as our new user-defined data type,
therefore we use structure name as function return type.
Input() have local variable E of Employee type. After getting values from user statement 2
returns E to the calling function and display the values.
16 Bit manipulation
then:
then
To illustrate many points of bitwise operators let us write a function, Bit count, that counts bits
set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.
int count;
if ( x & 01)
count++;
return count;
Packing several objects into a machine word. E.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit
integers.
C allows us do this in a structure definition by putting: bit length after the variable. For example:
struct packed_struct {
} pack;
Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit
my_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum
length of the field is less than or equal to the integer word length of the computer. If this is not
the case then some compilers may allow memory overlap for the fields whilst other would store
the next field in the next word.
int main()
{
auto number = 0b011;
cout << number;
return 0;
}
Output: 3
7. The Quickest way to swap two numbers:
a ^= b;
b ^= a;
a ^= b;
Refer swap two numbers for details.
8. Simple approach to flip the bits of a number: It can be done by a simple way, just simply
subtract the number from the value obtained when all the bits are equal to 1 .
For example:
Number : Given Number
Value : A number with all bits set in given number.
Flipped number = Value – Number.
Example :
Number = 23,
Binary form: 10111;
After flipping digits number will be: 01000;
Value: 11111 = 31;
9. We can find the most significant set bit in O(1) time for a fixed size integer. For example
below cocde is for 32 bit integer.
int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
n |= n>>4;
n |= n>>8;
n |= n>>16;