100% found this document useful (1 vote)
15 views75 pages

C++ Fundemental

The document provides an overview of C++ programming, covering fundamental concepts such as objects, classes, methods, and variable types. It explains the structure of a C++ program, including syntax, identifiers, keywords, and operators, along with examples of simple input/output programs. Additionally, it discusses constants, expressions, and the use of the I/O library in C++.

Uploaded by

Isuru Amarasena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
15 views75 pages

C++ Fundemental

The document provides an overview of C++ programming, covering fundamental concepts such as objects, classes, methods, and variable types. It explains the structure of a C++ program, including syntax, identifiers, keywords, and operators, along with examples of simple input/output programs. Additionally, it discusses constants, expressions, and the use of the I/O library in C++.

Uploaded by

Isuru Amarasena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

C++

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.

▸ Class − A class can be defined as a template/blueprint that describes


the behaviors/states that object of its type support.
▸ Methods − A method is basically a behavior. A class can contain
many methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.

▸ Instance Variables − Each object has its unique set of instance


variables. An object's state is created by the values assigned to
these instance variables.

4
▸ C++ Program Structure

#include <iostream>
using namespace std;

// main() is where program execution begins.


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

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);

Above is the same as,

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.

▸ An identifier starts with a letter A to Z or a to z or an underscore


followed by zero or more letters, underscores, and digits (0 to 9).

▸ C++ does not allow punctuation characters such as @, $, and % within


identifiers.

▸ C++ is a case-sensitive programming language.


Thus, Apple and apple are two different identifiers in C++.
10
▸ mohd ▸ #girl
▸ zara ▸ %right
▸ abc ▸ 21val
▸ move_name ▸ name@
▸ a_123 ▸ Her’s
▸ myname50 ▸ int
▸ _temp ▸ 2D4_t
▸ j ▸ Abc*
▸ a23b9 ▸ $ghl
▸ retVal

11
Keywords
▸ The following list shows the reserved words in C++.

▸ These reserved words may not be used as constant or variable or any


other identifier names.

Ex:

else new this int bool main if break while

do true false switch return

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.

▸ It separates one part of a statement from another and enables the


compiler to identify where one element in a statement, such as int, ends
and the next element begins.
int age;
fruit = apples + oranges; // Get the total fruit

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.

▸ The name of a variable can be composed of letters, digits, and the


underscore character. It must begin with either a letter or an
underscore.

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.

▸ void- Represents the absence of type.

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

Floating point float

Double floating point double


17
Defining a variable
▸ A variable definition tells the compiler where and how much storage to
create for the variable.

▸ A variable definition specifies a data type, and contains a list of one or


more variables of that type.

 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.

▸ There are two simple ways in C++ to define constants −

 Using #define preprocessor.

 Using const keyword.

22
#define identifier value
Ex:
#define LENGTH 10
#define WIDTH 5

const type variable = value;


Ex:
const int LENGTH = 10;
const int 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

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

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

-- Decrement operator, decreases integer value by A-- will give 9


one

25
Relational Operators
Operator Description Example

Checks if the values of two operands are equal


== (A == B) is not true.
or not, if yes then condition becomes true.

Checks if the values of two operands are equal


!= or not, if values are not equal then condition (A != B) is true.
becomes true.

Checks if the value of left operand is greater than


> the value of right operand, if yes then condition (A > B) is not true.
becomes true.

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

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition becomes
true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then condition becomes
true.

! Called Logical NOT Operator. Use to reverses !(A && B) is true.


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

28
Bitwise Operators
Operator Description

& Binary AND Operator copies a bit to the


result if it exists in both operands.

| Binary OR Operator copies a bit if it exists in


either operand.

^ Binary XOR Operator copies the bit if it is


set in one operand but not both.

~ Binary Ones Complement Operator is unary


and has the effect of 'flipping' bits.

29
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.

>> Binary Right Shift Operator. The left operands


value is moved right 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

= Simple assignment operator, Assigns values C = A + B will assign value of A + B into


from right side operands to left side operand. C
+= Add AND assignment operator, It adds right
operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left operand C -= A is equivalent to C = C - A
and assign the result to left operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.

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

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the
result to left operand. C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator.


C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator.


C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2


^= Bitwise exclusive OR and assignment operator.
C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator.


C |= 2 is same as C = C | 2

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

 Special assignment expressions


35
▸ I/O Library Header Files

Ex: <iostream>

▸ Standard output stream (cout)

Ex: cout << "Value of ary is: " << ary << endl;

▸ Standard input stream (cin)

Ex: cout << "Enter your age: ";

cin >> age;

▸ Standard end line (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….

1. To get perimeter of any rectangle by getting inputs from a user.


2. Program to Find Quotient and Remainder of a division specified by a
user.
3. Program to Swap Two Numbers. ( Initially a= 5 and b= 10. Output
should be a=10 and b=5.)
4. Program to Multiply two Numbers given by a user.

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

 If statement in C++ : If the condition is valid, it is executed.

 If-else statement in c++ : The declaration executes if the


condition is true otherwise the else block is carried out.

 If-else-if ladder in c++ : Executes from multiple statements in

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.

for ( initialization; condition; increment )

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.

▸ A do...while loop is similar to a while loop, except that a do...while loop


is guaranteed to execute at least one time.

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.

for ( init; condition; increment ) { while(condition) {


for ( init; condition; increment ) { while(condition) {
statement(s); statement(s);
} }
statement(s); // you can put more statement(s); // you can put more statements.
statements. }
}

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.

▸ It can be used to terminate a case in the switch statement.

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.

▸ Instead of forcing termination, however, continue forces the next


iteration of the loop to take place, skipping any code in between.

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.

return_type function_name( parameter list )


{
body of the function
}

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

int max(int num1, int num2) {


// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
65
#include <iostream>
int main () {
using namespace std;
// local variable declaration:
// function returning the max between 2 numbers
int a = 100; int b = 200; int ret;
int max(int num1, int num2) {
// local variable declaration // calling a function to get max value.

int result; ret = max(a, b);

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.

▸ Instead of declaring individual variables, such as number0, number1,


..., and number99, you declare one array variable such as numbers
and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.

67
68
▸ type arrayName [ arraySize ];
Ex:
double balance[10];

▸ Initialize array elements using a single statement.


double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
▸ Omit the size of the array.
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
▸ Insertion of an element to a certain index.
balance[4] = 50.0;

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

You might also like