C++ Fundemental
C++ Fundemental
Dharani Abeysinghe
Programming with C++
Basic syntax
▸ When we consider a C++ program, it can be defined as a collection of
objects that communicate via invoking each other's methods.
▸ Object − Objects have states and behaviors. Example: A dog has states
- color, name, breed as well as behaviors - wagging, barking, eating. An
object is an instance of a class.
4
▸ C++ Program Structure
#include <iostream>
using namespace std;
5
▸ The C++ language defines several headers, which contain information
that is either necessary or useful to your program. For this program, the
header <iostream> is needed.
▸ The line using namespace std; tells the compiler to use the std
namespace. Namespaces are a relatively recent addition to C++.
▸ The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop
at the end of the line.
6
▸ The line int main() is the main function where program execution begins.
▸ The next line cout << "Hello World"; causes the message "Hello World" to
be displayed on the screen.
▸ The next line return 0; terminates main( )function and causes it to return
the value 0 to the calling process.
7
▸ In C++, the semicolon (;) is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the
end of one logical entity.
x = y;
y = y + 1;
add(x, y);
▸ A block is a set of logically connected statements that are surrounded
by opening and closing braces. {}
{
cout << "Hello World"; // prints Hello World
return 0;
}
8
x = y;
y = y + 1;
add(x, y);
x = y; y = y + 1; add(x, y);
9
Identifiers
▸ Identifier is a name used to identify a variable, function, class, module,
or any other user-defined item.
11
Keywords
▸ The following list shows the reserved words in C++.
Ex:
12
Whitespace in C++
▸ A line containing only whitespace, possibly with a comment, is known as
a blank line, and C++ compiler totally ignores it.
No whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish for readability purpose.
13
Comments
▸ Program comments are explanatory statements that you can include in
the C++ code.
▸ These comments help anyone reading the source code.
▸ All programming languages allow for some form of comments.
▸ C++ supports single-line and multi-line comments.
▸ All characters available inside any comment are ignored by C++ compiler.
▸ /* This is a comment */
▸ /* C++ comments can also
span multiple lines
*/
▸ // this line prints value
14
Variable types
▸ Variables are nothing but reserved memory locations to store values.
▸ This means that when you create a variable you reserve some space in
memory.
15
▸ bool - Stores either value true or false.
▸ char - Typically a single octet (one byte). This is an integer type.
▸ int- The most natural size of integer for the machine.
▸ float- A single-precision floating point value.
▸ double- A double-precision floating point value.
16
Data types
▸ Information of various data types like character, wide character, integer,
floating point, double floating point, boolean etc are required to be stored.
▸ Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Type Keyword
Boolean bool
Character char
Integer int
int i, j, k;
char c, ch;
Declaration of a variable
float f, salary;
double d;
18
▸ Variables can be initialized (assigned an initial value) in their declaration.
type variable_name = value;
Ex:
int d = 3, f = 5; // definition and initializing d and f.
char x = 'x'; // the variable x has the value 'x'.
19
▸ Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or
block of code. Local variables are not known to functions outside their
own.
▸ Global Variables
Global variables are defined outside of all the functions, usually on top of
the program. The global variables will hold their value throughout the life-
time of your program. A global variable can be accessed by any function.
20
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
21
Constants
▸ Constants refer to fixed values that the program may not alter.
▸ Constants can be of any of the basic data types and can be divided into
Integer Numerals, Floating-Point Numerals, Characters, Strings and
Boolean Values.
22
#define identifier value
Ex:
#define LENGTH 10
#define WIDTH 5
23
Operators
▸ An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
24
Arithmetic Operators
A holds 10 and variable B holds 20
25
Relational Operators
Operator Description Example
26
< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if yes
then condition becomes true.
<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes then
condition becomes true.
27
Logical Operators
▸ A holds 1 and variable B holds 0
28
Bitwise Operators
Operator Description
29
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
30
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
31
Assignment Operators
Operator Description Example
32
/= Divide AND assignment operator, It divides left
operand with the right operand and assign the
result to left operand. C /= A is equivalent to C = C / A
33
Expressions
▸ C++ expression consists of operators, constants, and variables which are
arranged according to the rules of the language.
▸ It can also contain function calls which return values.
▸ An expression can consist of one or more operands, zero or more
operators to compute a value.
▸ Every expression produces some value which is assigned to the variable
with the help of an assignment operator.
▸ Ex:
(a+b) - c (x/y) -z
4a2 - 5b +c (a+b) * (x+y)
34
▸ An expression can be of following types:
Constant expressions
Integral expressions
Float expressions
Pointer expressions
Relational expressions
Logical expressions
Bitwise expressions
Ex: <iostream>
Ex: cout << "Value of ary is: " << ary << endl;
36
Simple input/output programs
▸ A simple program to print “ Hello World !”.
#include <iostream>
Output
using namespace std;
int main() {
Hello World!
cout << "Hello World!";
return 0;
}
37
▸ Print a number entered by a user.
#include <iostream>
using namespace std;
int main() {
int number; Output
cout << "Enter an integer: “<< endl;
Enter an integer: 23
cin >> number;
You entered 23
cout << "You entered " << number;
return 0;
}
38
▸ Simple program to add two given numbers.
#include <iostream>
using namespace std;
int main() {
int a=5, b=7;
int sum=a+b;
cout << "Sum of a and b is :" << sum << endl;
return 0;
}
39
40
▸ Simple program to add two numbers given by user.
#include <iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter first number : a= ";
cin>> a;
cout<<"Enter second number : b= ";
cin>> b;
int sum=a+b;
cout << "Sum of a and b is :" << sum << endl;
return 0;
}
41
42
▸ Try these programs….
43
Control statement
▸ Control statement redirects the flow of a program in order to execute
additional code.
▸ It controls the flow of the program.
▸ Based on the given condition, it evaluates the result and executes the
corresponding statements.
C++ if-else C++ switch
C++ For Loop C++ While Loop
C++ Do-While Loop C++ Break Statement
C++ Continue Statement C++ Goto Statement
44
if-else
▸ To test the condition in C++ programming if the statement is been
used. They are different types of if statement
one condition.
45
if statement
▸ #include <iostream>
using namespace std;
int main () {
int number = 10;
▸ if(condition) if (number % 2 == 0)
{
{
cout << "The Number you have Enter it is Even";
//code should be executed; }
} return 0;
}
46
if-else statement
▸ #include<iostream>
▸ if(condition) using namespace std;
{ int main () {
int number = 15;
//code should be executed;
if (number % 2 == 0)
} {
else cout << "The Number you have Enter it is
{ Even";
//code should be executed; }
else
}
{
cout << "The Number you have Enter it is Odd";
}
return 0;
}
47
if-else -if
▸ If(condition1)
{
// code should be executed if condition1 is true
}
else if(condition2)
{
// code should be executed if condition2 is true
}
else if(condition3)
{
// code should be executed if condition3 is true
}
...
else{
// code should be executed if all condition is false
}
48
▸ #include <iostream> else if (number >= 60 && number < 70)
using namespace std; {
int main () { cout <<" C Grade";
int number; }
cout << "To Check Grade Enter a Number:"; else if (number >= 70 && number < 80)
{
cin >> number;
cout << "B Grade";
if (number < 0 || number > 100) }
{ else if (number >= 80 && number < 90)
cout << "wrong No"; {
} cout << "A Grade";
else if(number >= 0 && number < 40){ }
cout << "Fail"; else
} {
else if (number >= 40 && number < 60) cout << "A+ Grade";
{ }
}
cout << "D Grade";
}
49
for loop
▸ A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.
statement(s);
50
OUTPUT :
#include <iostream> value of a: 10
using namespace std; value of a: 11
int main () { value of a: 12
// for loop execution value of a: 13
for( int a = 10; a < 20; a = a + 1 ) value of a: 14
{ value of a: 15
cout << "value of a: " << a << endl; value of a: 16
} value of a: 17
return 0; value of a: 18
} value of a: 19
51
While loop
▸ A while loop statement repeatedly executes a target statement as
long as a given condition is true.
while(condition)
statement(s);
}
52
#include <iostream> OUTPUT:
using namespace std; value of a: 10
int main () { value of a: 11
// Local variable declaration value of a: 12
int a = 10; value of a: 13
// while loop execution value of a: 14
while( a < 20 ) { value of a: 15
cout << "value of a: " << a << endl; value of a: 16
a++; value of a: 17
} value of a: 18
return 0; value of a: 19
} 53
Do-while loop
▸ Unlike for and while loops, which test the loop condition at the top of
the loop, the do...while loop checks its condition at the bottom of the
loop.
do {
statement(s);
} while( condition );
54
#include <iostream> OUTPUT:
using namespace std; value of a: 10
int main () { value of a: 11
// Local variable declaration value of a: 12
int a = 10; value of a: 13
// do loop execution value of a: 14
do {
If while condition is false :i.e. a < 5,
cout << "value of a: " << a << endl;
Then,
a = a + 1;
OUTPUT:
} while( a < 15 );
value of a: 10
return 0;
} 55
Nested loops
▸ A loop can be nested inside of another loop. C++ allows at least 256
levels of nesting.
56
Switch statement
▸ Switch statement executes a single statement. It’s like a ladder
statement if-else-if in C++.
Switch(expression)
{
case value1:
//code should be executed;
break;
case value2:
//code should be executed;
break;
…
Default:
//Code to execute if not all cases matched
break;
}
57
#include<iostream>
using namespace std;
int main () {
int number;
cout << "To check the grade enter a number:";
cin >> number;
switch (number)
{
case 2:
cout << "It is 2"; break;
case 3:
cout << "It is 3"; break;
case 4:
cout << "It is 4"; break;
default:
cout << "Not 2, 3 or 4"; break;
}
}
58
break statement
▸ When the break statement is encountered inside a loop, the
loop is immediately terminated and program control resumes
at the next statement following the loop.
break;
59
#include <iostream>
using namespace std;
OUTPUT:
int main () {
// Local variable declaration value of a: 10
int a = 10; value of a: 11
// do loop execution value of a: 12
value of a: 13
do {
value of a: 14
cout << "value of a: " << a << endl; value of a: 15
a = a + 1;
if( a > 15) {
// terminate the loop
break; }
} while( a < 20 );
return 0; }
60
continue statement
▸ The continue statement works somewhat like the break statement.
continue ;
61
#include <iostream>
using namespace std;
int main () {
OUTPUT:
// Local variable declaration
int a = 10; value of a: 10
// do loop execution value of a: 11
value of a: 12
do {
value of a: 13
if( a == 15) { value of a: 14
// skip the iteration. value of a: 16
a = a + 1;
value of a: 17
value of a: 18
continue; } value of a: 19
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0; } 62
Functions
▸ A function is a group of statements that together perform a task.
▸ Every C++ program has at least one function, which is main(), and all
the most trivial programs can define additional functions.
63
▸ Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the return_type
is the keyword void.
▸ Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
▸ Parameters − A parameter is like a placeholder. When a function is called,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is,
a function may contain no parameters.
▸ Function Body − The function body contains a collection of statements
that define what the function does.
64
// function returning the max between two numbers
if (num1 > num2) cout << "Max value is : " << ret << endl;
result = num1; return 0;
else }
result = num2;
return result; }
66
Array
▸ An array, a data structure which stores a fixed-size sequential
collection of elements of the same type.
67
68
▸ type arrayName [ arraySize ];
Ex:
double balance[10];
69
Writing a program
▸ Program to print half pyramid using *
*
**
***
****
*****
70
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = 1; i <= rows; ++i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << "\n"; }
return 0; } 71
▸ Program to print half pyramid a using numbers
1
12
123
1234
▸ Programs to print inverted half pyramid using *
*****
****
***
**
*
72
▸ C++ Program to Check Whether a character is Vowel or Consonant.
▸ Find Largest Number Among Three Numbers
▸ Program to Reverse a Number
▸ Program to Check Whether a Number is Palindrome or Not
▸ Program to Check Prime Number By Creating a Function
▸ Program to Calculate Average of Numbers Using Arrays
▸ Program to Find Largest Element of an Array
73
Thank you!
You can contact me through my email.
74
Refer…
▸ Nested loops
▸ Goto statement
▸ Files in C++
75