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

Unit-3 (C++ Programming) 26-March-2025

The document outlines the syllabus for a C++ programming course, covering topics such as the basics of C++, programming constructs, data types, user input, and output. It explains key concepts like comments, identifiers, variables, and constants, along with practical examples for better understanding. Additionally, it provides guidance on setting up a C++ environment and writing simple programs, including a basic calculator and string manipulation.

Uploaded by

Tanishqa Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Unit-3 (C++ Programming) 26-March-2025

The document outlines the syllabus for a C++ programming course, covering topics such as the basics of C++, programming constructs, data types, user input, and output. It explains key concepts like comments, identifiers, variables, and constants, along with practical examples for better understanding. Additionally, it provides guidance on setting up a C++ environment and writing simple programs, including a basic calculator and string manipulation.

Uploaded by

Tanishqa Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit-III Syllabus

C Versus C++- Programming with C++:General forms of a C++programme, I/O


with cout and cin, different operators, scope resolution operator, Data types, For
while, do while, if-else, switch and conditional statements, Unary Operators -
Increment Operator(++), Prefix Notation, Postfix, Notation, Decrement
Operator(--). Conditional Constructs-Switch…Case, Construct, Break
Statement, Default Keyword, Conditional Operator, Examples on Programming
Construct

1
What is C++?
(C++ history read by student)

C++ is a cross-platform language that can be used to create high-performance


applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and
memory.

The language was updated 3 major times in 2011, 2014, and 2017 to C++11,
C++14, and C++17, C++20, C++23 (realised in 2024).

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.

C++ is an object-oriented programming language which gives a clear structure


to programs and allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C# and Java, it makes it easy for programmers to switch to


C++ or vice versa.

C++ Get Started

It is not necessary to have any prior programming experience.

To start using C++, you need two things:

• A text editor, like Notepad, to write C++ code


• A compiler, like GCC, to translate the C++ code into a language that the
computer will understand

There are many text editors and compilers to choose from. We can use
TurboC++ or DevC++.

2
Note : we are using DevC++ platform for C++ programming and for this
mention #include<iostream> .
C++ Quickstart

Let's create our first C++ file.

Open Codeblocks and go to File > New > Empty File.

Write the following C++ code and save the file as myfirstprogram.cpp (File >
Save File as):

Here writing a simple C++ program that prints “Hello World!” message. Lets
see the program first and then we will discuss each and every part of it in detail.

Hello World Program in C++

/*
* Multiple line
* comment
*/
#include<iostream>

//Single line comment


using namespace std;

//This is where the execution of program begins


int main()
{
// displays Hello World! on screen
cout<<"Hello World!";

return 0;
}
Output:
Hello World!
Let’s discuss each and every part of the above program.

1. Comments – You can see two types of comments in the above program

// This is a single line comment


/* This is a multiple line comment
* suitable for long comments
*/

3
Comments as the names suggests are just a text written by programmer during
code development. Comment doesn’t affect your program logic in any way, you
can write whatever you want in comments but it should be related to the code
and have some meaning so that when someone else look into your code, the
person should understand what you did in the code by just reading your
comment.

For example:

/* This function adds two integer numbers


* and returns the result as an integer value
*/
int sum(int num1, int num2) {
return num1+num2;
}

Now if someone reads my comment, he or she can understand what I did there
just by reading my comment. This improves readability of your code and when
you are working on a project with your team mates, this becomes essential
aspect.

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.

3. using namespace std; – A namespace is like a region, where we have


functions, variables etc and their scope is limited to that particular region. Here
std is a namespace name, this tells the compiler to look into that particular
region for all the variables, functions, etc.

4. int main() – As the name suggests this is the main function of our program
and the execution of program begins with this function, the int here is the return
type which indicates to the compiler that this function will return a integer
value. That is the main reason we have a return 0 statement at the end of main
function.

5. cout << “Hello World!”; – The cout object belongs to the iostream file and
the purpose of this object is to display the content between double quotes as it is
on the screen. This object can also display the value of variables on screen.

4
6. return 0; – This statement returns value 0 from the main() function which
indicates that the execution of main function is successful. The value 1
represents failed execution.

Omitting Namespace

You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:

Example
#include <iostream>

int main() {
std::cout << "Hello World!";
return 0;
}

It is up to you if you want to include the standard namespace library or not.

C++ Output (Print Text)

The cout object, together with the << operator, is used to output values/print
text:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
5
cout << "I am learning C++";
return 0;
}
New Lines

To insert a new line, you can use the \n character:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}

Tip: Two \n characters after each other will create a blank line:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}

Another way to insert a new line, is with the endl manipulator:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

6
Both \n and endl are used to break lines. However, \n is used more often and is
the preferred way.

C++ Comments

Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code. Comments
can be singled-lined or multi-lined.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not
be executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment

C++ Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for short comments,
and /* */ for longer.

7
C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:

Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

• Names can contain letters, digits and underscores


• Names must begin with a letter or an underscore (_)
• Names are case sensitive (myVar and myvar are different variables)
• Names cannot contain whitespaces or special characters like !, #, %, etc.
• Reserved words (like C++ keywords, such as int) cannot be used as name

C++ User Input

Here already learned that cout is used to output (print) values. Now we will
use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).

In the following example, the user can input a number, which is stored in the
variable x. Then we print the value of x:

Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

8
Good To Know

cout is pronounced "see-out". Used for output, and uses the insertion operator
(<<)

cin is pronounced "see-in". Used for input, and uses the extraction operator
(>>)

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by
calculating (adding) the two numbers:

Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

C++ Constants

When you do not want others (or yourself) to override existing variable values,
use the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):

Example
const int Num = 15; // Num will always be 15
Num = 10; // error: assignment of read-only variable 'Num'
cout>>Num;
cin>>num;
cout>>num;

You should always declare the variable as constant when you have values that
are unlikely to change:

9
Example
const int minutesPerHour = 60;
const float PI = 3.14;

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.

Syntax of declaring a variable in C++


data_type variable1_name = value1, variable2_name = value2;

For example:
int num1=20, num2=100;

We can also write it like this:


int num1,num2;
num1=20;
num2=100;

Types of variables
Variables can be categorised based on their data type. For example, in the above
example we have seen integer types variables. Following are the types of
variables available in C++.

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords),
for example:

• int - stores integers (whole numbers), without decimals, such as 123 or -


123
• double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• string - stores text, such as "Hello World". String values are surrounded
by double quotes
• bool - stores values with two states: true or false

10
Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax
type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

You can also declare a variable without assigning the value, and assign the
value later:

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the
previous value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

11
Other Types

A demonstration of other data types:

Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

Display Variables

The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example
int myAge = 35;
cout << "I am " << myAge << " years old.";
Add Variables Together

To add a variable to another variable, you can use the + operator:

Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
cout<<x+y;
Declare Many Variables

To declare more than one variable of the same type, use a comma-separated
list:

Example
int x = 5, y = 6, z = 50, sum;
cout << x + y + z;

12
Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate
the power of 10:

Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

C++ String Data Types

The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes:

Example
string greeting = "Hello";
cout << greeting;

To use strings, you must include an additional header file in the source code,
the <string> library:

Example
// Include the string library
#include <string.h>
// Create a string variable
string greeting = "Hello";

greeting[0]=H,
greeting [1]=e,
greeting [2]=l
greeting [3]=l,
greeting [4]=o,
greeting [5]=\0

// Output string value


cout << greeting;

13
C++ Access Strings
Access Strings

You can access the characters in a string by referring to its index number inside
square brackets [].

This example prints the first character in myString:

Example
string myString = "Hello";
cout << myString[0];
cout << myString[1];
cout << myString[2];
cout << myString[3];
cout << myString[4];
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.

This example prints the second character in myString:

Example
string myString = "Hello";
cout << myString[1];
// Outputs e

Change String Characters

aTo change the value of a specific character in a string, refer to the index
number, and use single quotes:

Example
string myString = "Hello";
myString[0] = 'J';
myString[3]= ‘L’;
cout << myString;
// Outputs JelLo instead of Hello

14
C++ User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered
by a user:

Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John


// Your name is: John

However, cin considers a space (whitespace, tabs, etc) as a terminating


character, which means that it can only display a single word (even if you type
many words):

Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John

From the example above, you would expect the program to print "John Doe",
but it only prints "John".

That's why, when working with strings, we often use the getline() function to
read a line of text. It takes cin as the first parameter, and the string variable as
second:

Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John Doe
15
C++ String Concatenation

The + operator can be used between strings to add them together to make a new
string. This is called concatenation:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
In the example above, we added a space after firstName to create a space
between John and Doe on output. However, you could also add a space with

Append

A string in C++ is actually an object, which contain functions that can perform
certain operations on strings. For example, you can also concatenate strings
with the append() function:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;

It is up to you whether you want to use + or append(). The major difference


between the two, is that the append() function is much faster. However, for
testing and such, it might be easier to just use +.

quotes (" " or ' '):

Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

16
C++ String Length

To get the length of a string, use the length() function:

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();

Tip: You might see some C++ programs that use the size() function to get the
length of a string. This is just an alias of length(). It is completely up to you if
you want to use length() or size():

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
Boolean Types

A boolean data type is declared with the bool keyword and can only take the
values true or false. When the value is returned, true = 1 and false = 0.

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing.
Types of variables based on their scope
Before going further lets discuss what is scope first. When we discussed
the Hello World Program, we have seen the curly braces in the program like
this:

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.

17
Types of variables based on the scope as below:

1. Global variable
2. Local variable

Global Variable
A variable declared outside of any function (including main as well) is called
global variable. Global variables have their scope throughout the program, they
can be accessed anywhere in the program, in the main, in the user defined
function, anywhere.

Lets take an example to understand it:

Global variable example

Here we have a global variable myVar, that is declared outside of main. We


have accessed the variable twice in the main() function without any issues.

#include <iostream>
using namespace std;
// This is a global variable
char Var = 'A';
int main()
{
cout <<"Value of Variable is: "<< Var<<endl;
Var='Z';
cout <<"Value of Variables: "<< Var;
return 0;
}
Output:

Value of Variable : A
Value of Variable: Z

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.

18
Local variable example

#include <iostream>
using namespace std;

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.

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;
}
19
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().

Data Types in C++


Data types define the type of data a variable can hold, for example an integer
variable can hold integer data, a character type variable can hold character data
etc.

Data types in C++ are categorised in three groups: Built-in, user-


defined and Derived.

Built in data types

char: For characters. Size 1 byte.

char ch = 'A';
int: For integers. Size 2 bytes.

int num = 100;


float: For single precision floating point. Size 4 bytes.

20
float num = 123.78987;
double: For double precision floating point. Size 8 bytes.

double num = 10098.98899;


bool: For booleans, true or false.

bool b = true;
wchar_t: Wide Character. This should be avoided because its size is
implementation defined and not reliable.

User-defined data types

We have three types of user-defined data types in C++


1. struct
2. union
3. enum

Derived data types in C++


We have three types of derived-defined data types in C++
1. Array
2. Function
3. Pointer

Operators in C++

Operator represents an action. For example + is an operator that represents


addition. An operator works on two or more operands and produce an output.
For example 3+4+5 here + operator works on three operands and produce 12 as
output.

Types of Operators in C++

21
Note : Students are required to make program in C++ for using all below types
of Operators

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two x+y


values

- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y

22
remainder

++ Increment Increases the value of ++x


a variable by 1

-- Decrement Decreases the value --x


of a variable by 1

.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0

Example of Arithmetic Operators

#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:

num1 + num2: 280


num1 - num2: 200
num1 * num2: 9600
num1 / num2: 6
num1 % num2: 0

2) Assignment Operators

Assignment operators are used to assign values to variables.

Assignments operators in C++ are: =, +=, -=, *=, /=, %=

A list of all assignment operators:


23
Operator Example Same As Try it

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x–3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

num2 = num1 would assign value of variable num1 to the variable.

num2+=num1 is equal to num2 = num2+num1

num2-=num1 is equal to num2 = num2-num1

num2*=num1 is equal to num2 = num2*num1

num2/=num1 is equal to num2 = num2/num1

num2%=num1 is equal to num2 = num2%num1

24
Example of Assignment Operators

#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;
}

Output:

= Output: 240
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0

3) Auto-increment and Auto-decrement Operators

++ and —
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

#include <iostream>
using namespace std;
int main(){
25
int num1 = 240;
int num2 = 40;
num1++; num2--;
cout<<"num1++ is: "<<num1<<endl;
cout<<"num2-- is: "<<num2;
return 0;
}
Output:

num1++ is: 241


num2-- is: 39

4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.

Logical operators in C++ are: &&, ||, !

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical Returns true if both x < 5 && x < 10


and statements are true

|| Logical or Returns true if one of the x < 5 || x < 4


statements is true

! Logical not Reverse the result, returns !(x < 5 && x <
false if the result is true 10)

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false
and it would return false if b1 is true.

26
Example of Logical Operators

#include <iostream>
using namespace std;
int main(){
bool b1 = true;
bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
cout<<"b1 || b2: "<<(b1||b2)<<endl;
cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;
}
Output:

b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1

5) Relational operators

We have six relational operators in C++: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
Comparison Operators

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if 5
is greater than 3:

Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

27
A list of all comparison operators:

Operator Name Example Try it

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Example of Relational operators

#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 =40;
if (num1==num2) {
cout<<"num1 and num2 are equal"<<endl;
}
else{
cout<<"num1 and num2 are not equal"<<endl;
}
if( num1 != num2 ){
cout<<"num1 and num2 are not equal"<<endl;
}
else{
cout<<"num1 and num2 are equal"<<endl;
}
if( num1 > num2 ){
cout<<"num1 is greater than num2"<<endl;
}
else{
cout<<"num1 is not greater than num2"<<endl;
}
if( num1 >= num2 ){
cout<<"num1 is greater than or equal to num2"<<endl;
}
else{
cout<<"num1 is less than num2"<<endl;
28
}
if( num1 < num2 ){
cout<<"num1 is less than num2"<<endl;
}
else{
cout<<"num1 is not less than num2"<<endl;
}
if( num1 <= num2){
cout<<"num1 is less than or equal to num2"<<endl;
}
else{
cout<<"num1 is greater than num2"<<endl;
}
return 0;
}
Output:

num1 and num2 are not equal


num1 and num2 are not equal
num1 is greater than num2
num1 is greater than or equal to num2
num1 is not less than num2
num1 is greater than num2

6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates
1 if both bits are equal, else it returns 0. In our case it would return: 2 which is
00000010 because in the binary form of num1 and num2 only second last bits
are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1
if either bit is 1, else it returns 0. In our case it would return 31 which is
00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1
if they are not equal, else it returns 0. In our example it would return 29 which
is equivalent to 00011101

29
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to
0. In our example it would return -12 which is signed 8 bit equivalent to
11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far
left bit, and assigns the rightmost bit a value of 0. In our case output is 44 which
is equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift
operator that is the reason bits are moving two places to the left side. We can
change this number and bits would be moved by the number of bits specified on
the right side of the operator. Same applies to the right side operator.

num1 >> 2 is right shift operator that moves the bits to the right, discards the
far right bit, and assigns the leftmost bit a value of 0. In our case output is 2
which is equivalent to 00000010

Example of Bitwise Operators

#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
cout<<"num1 | num2: "<<result<<endl;
result = num1 ^ num2;
cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
cout<<"~num1: "<<result<<endl;
result = num1 << 2;
cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
cout<<"num1 >> 2: "<<result;
return 0;
}
Output:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
30
~num1: -12
num1 << 2: 44 num1 >> 2: 2

7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the
result.
Syntax:

variable num1 = (expression) ? value if true : value if false


If the expression results true then the first value before the colon (:) is assigned
to the variable num1 else the second value is assigned to the num1.

Example of Ternary Operator

#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:

num2: 200
num2: 100

31
C++ Math

C++ has many functions that allows you to perform mathematical tasks on
numbers.

Max and min

The max(x,y) function can be used to find the highest value of x and y:

Example
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number)


and log (natural logarithm), can be found in the <cmath> header file:

Example
// Include the cmath library
#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

Other Math Functions

A list of other popular Math functions (from the <cmath> library) can be found
in the table below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

32
atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x

cosh(x) Returns the hyperbolic cosine of x

exp(x) Returns the value of Ex

expm1(x) Returns ex -1

fabs(x) Returns the absolute value of a floating x

fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer

hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z) Returns x*y+z without losing precision

fmax(x, y) Returns the highest value of a floating x and y

fmin(x, y) Returns the lowest value of a floating x and y

fmod(x, y) Returns the floating point remainder of x/y

pow(x, y) Returns the value of x to the power of y

sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of a double value

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

33
C++ Boolean Expression
A Boolean expression is a C++ expression that returns a boolean value: 1 (true)
or 0 (false).

You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:

Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Or even easier:

Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

In the examples below, we use the equal to (==) operator to evaluate an


expression:

Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15

Booleans are the basis for all C++ comparisons and conditions.

C++ Conditions and If Statements

C++ supports the usual logical conditions from mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

34
You can use these conditions to perform different actions for different
decisions.

C++ has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is


true
• Use else to specify a block of code to be executed, if the same condition
is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition


is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:

Example
if (20 > 18) {
cout << "20 is greater than 18";
}

We can also test variables:

Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

35
C++ Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

• The switch expression is evaluated once


• 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
• The break and default keywords are optional, and will be described later
in this chapter

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:

36
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
The break Keyword

When C++ reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

C++ Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

C++ While Loop

The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:

37
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

Do not forget to increase the variable used in the condition, otherwise the
loop will never end!

38
C++ For Loop

When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).


Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Another Example

This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

39
C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.


This example jumps out of the loop when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}

C++ Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}

Break and Continue in While Loop


You can also use break and continue in while loops:
Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

40
Continue Example
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}

41

You might also like