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

C - Programming - COM 121

Programming language using C++

Uploaded by

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

C - Programming - COM 121

Programming language using C++

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Page |1

COM 121 – C-PROGRAMMING LANGUAGE


INTRODUCTION

Brief History of the C++ Programming Language


 1960s
During the 1960s many new programming languages appeared. A popular language that was a precursor
of C was ALGOL 60 which was developed as an alternative to FORTRAN, but included some concepts

on structured programming which were later added to CPL and eventually C. ALGOL 60 was updated
and released as ALGOL 68 which included data types that were later incorporated into C. Unfortunately
ALGOL was a very abstract language and it was impractical for solving most commercial tasks.

 1963
The language CPL (Combined Programming language) was released. It was an attempt to create a

language which could handle many of the programming tasks that were difficult with ALGOL or
FORTRAN. Unfortunately it was a very big language and that made it difficult to learn and implement.

 1967
Martin Richards developed BCPL (Basic Combined Programming Language). This was a much simpler

language than CPL but kept most of the important features but, it too was a very abstract and large
language.

 1970 
Ken Thompson, while working on developing the UNIX operating system at Bell Labs, created the B
language. It was a port of BCPL for a specific machine and system (DEC PDP-7 and UNIX). He adapted
it to suit his own specific programming needs, but it was limited. The most serious problem was that
there was no way to compile the source code into executable code. It was an interpreted language (it was
translated at run time) and thus was very slow. It just wasn’t adequate for developing an operating
system.

 1971
Dennis Ritchie, also from the Bell Labs team, began the development of a B compiler which could
produce executable code for Thompson's B language. This "New B" was finally called C. It added new
data types to the language (like char).

 1973
Dennis Ritchie, added more improvements to the C language including better arrays, and pointers. C was
more easily ported to other platforms because it was not really a high-level language. Languages like C
are sometimes referred to as "medium-level languages" because they are between assembly and high-
level languages in their capabilities. C was established as a prominent programming language with the
publication of "the White Book", The C Programming Language by Brian Kernighan and Dennis
Ritchie. This became the de facto standard until the publication of formal ANSI standard (ANSI X3J11
committee) in 1989.

 1980
BjarneStroustrup, from Bell labs, began the development of the C++ language.

1983
The name "C++" is formally adopted for the language. BTW: It was actually a play on words using the +
Page |2

+ increment operator from C.

1985
The first commercial release of the C++ language. The Publication of the first edition of the book "The
C++ Programming Language" by BjarneStroustrup.

During the 1980s the C++ language was being refined until it became a language with its own
personality but was still compatible with and included all of the original C language.

 1989
Publication of the formal ANSI standard C. A good part of the structured programming included in C
was actually taken from the work being done on C++.

 1990s
ANSI committee X3J16 began the development of a specific standard for C++. In this period C++ was
greatly expanded in its use.

 1998
Publication of the first standard for C++ by the ANSI committee. Today C++ is the preferred language
for the development of professional applications on all platforms.

 Coming Soon
C++ has been evolving, and a new version of the standard, c++0x, is being developed to be published
soon, with several new features.

C++ Definition:
1. It is a basic, high level and object oriented programming language.
2. It supports object oriented programming structure so it is called object oriented programming
language
3. It is developed by BjarneStroustrup.
4. It is similar to C programming that DennisRitchie created in 1970s.
5. It is known as an extension to the C programming language
6. C++ is so much compatible with C that it probably compiles over 99% of C programs without
changing a line of source code. Though, C++ is a much well-structured and safer language than C as
it is OOPs based.
7. It is right to call C++ as the superset of C; and/or “C with Classes”.
Features of C++ Language:
 Simple
 Powerful
 Portable
 Machine Independent
 Structure Oriented
 High Speed
 High Efficiency
 Flexible
Page |3

Basic Syntax of C++ Language

Iostream:
a) It represents input-outputs stream
b) It is a collection of predefined functions/methods
c) It is also called library of C++
Include: to include the header file into the program.
#:
a) It is called preprocessor.
b) It includes the library of C++ into the program before the execution of program.
Conio:
a) Stands for console input-output
b) It is used to show the output on console window
Void:
a) It is a keyword used to indicate that no one value is being returned by the function.
b) If in case other keywords like int, float, char etc. are used in place of void, then we will use return
keyword.
Main:
a) It is the function which is called the entry point of any program.
b) The execution of any program starts from the main function.
c) If in a program there is only one function then it should be the main function.
Clrscr()
a) Stands for clear screen and is a predefined function used for that purpose (clear output screen).
b) It acts like a duster on output screen.
c) It is defined in the conio.h header file.
Cout<<:
Page |4

a) It is the output statement used to print data or information on the output screen.
b) It is always used with insertion operator.
getch():
a) It is a predefined function which is used to hold the output screen.
b) It acts like a duster on output screen.
c) It is also defined in the conio.h header file.

VARIABLES IN C++ LANGUAGE


Definition:
a) Variable is a name of storage space which is used to store data.
b) Its value is changeable, not constant.
c) It always contains the last value stored to it.
d) It is always declared with data type.
Examples of Variable Declarations:
int rollNo;
float marks;
char grade;
Variable Initialization:
int rollNo = 20;
float marks = 80.0; // floating point numbers have decimal point
char grade = ‘A’; // this must be written with single quotes

Rules to Declare a Variable


1. The first character of a variable name should be alphabet or underscore ( _ ), and must not be a digit;
2. After the first character, it may be combination of alphabets and digits and even other symbols;
3. Blank spaces are not allowed with variable names
4. Variable names must not be a keyword or reserved words.
5. Combination of words should be distinguished with Capital letters at the beginning of the 2nd , 3rd, or
4th words as the case may be; or an underscore should be used.

CONSTANTS IN C++ LANGUAGE


Definition:
a) An element of program whose value cannot be altered at any time of the execution of program is
called a constant.
b) It may comprise of any data type e.g. int, float, char, etc.
Page |5

Rules for Constructing Integer Constants.


1. It must have at least one digit;
2. Must not have a decimal point;
3. It may be positive or negative ;
4. The range of integer constant is between -32768 to +32767;
5. No comma or blank spaces are allowed in integer constant.
Rules for Constructing Floating Points Constants
1. It must have at least one digit and a decimal point
2. It may be positive or negative;
3. No comma or blank spaces are allowed.
Rules for Constructing Char Constants
1. It is a single alphabet, digit or special symbol;
2. The length of a character constant is 1 character;
3. Character constants are enclosed within single quotes (e.g. c= ‘A’).
Use of Constants in Program
There are two ways of using constants in the C program.
1. Using const
2. Using #define

KEYWORDS IN C++ LANGUAGE


Definition
1. The word has a predefined meaning is called a keyword.
2. It’s functionality is also predefined.
3. It cannot be used as an identifier
Examples: default, float, register, struct, do, volatile, break, for, return, switch, while, case, double, goto,
short, typedef, char, else, if, signed, union, const, enum, int, sizeof, unsigned, continue, extern, long, static,
void, auto.
DATA TYPES IN C++ LANGUAGE
Definition:
1. It is a type of data which is used in the program.
2. There are many predefined data types in C library like int, char, float, etc.

Integer Type (int)


Basic Type Floating Point Type (float)
Character Type (char)
Pointer
Derived Type Array
Structure
Union
Page |6

Integer Data Type


Data Type Size in Range
bytes
Short 2 -32768 to +32767
Int 2 -32768 to +32767
Unsigned int 2 0 to 65536
long 4 -2147483648 to +2147483647
unsigned long int 4 0 to 4,294,967,295

Floating Point Type


Data Type Size in bytes Range
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

Character Type
Data Type Size in bytes Range
Char 1 -128 to +127
Signed char 1 -128 to +127
Unsigned char 1 0 to 255

STORAGE CLASSES IN C++


A storage classes in C++ defines the scope, lifetime, default initial value and storage space of a variable.
There are four storage classes in C++, thus:-
a) Automatic
b) Static
c) Register
d) External

Automatic Storage Class

 Automatic variables are declared inside a function in which they have to be used.
 When the function is called, automatic variables are created and destroyed when function is exited
 Automatic variables cannot be used outside that function in which it is declared. This means that it is
a private member.
 Automatic variables are also called local variables.
 The auto keyword is used to declare automatic type variable
Sample: This code segment represent an example of automatic storage class…
Page |7

#include<iostream>

using namespace std;


/*
int main(){
### Output ###
auto int x=5;
1
{
3
auto int x=3;
5
{ */
auto int x=1;

cout<<x<<endl;

cout<<x<<endl;

cout<<x<<endl;

Here, the value of the innermost x is 1, out of this block value is 3 and out of this block is 5.
Static Storage Class
 Static variables can be used anywhere in the program inside or outside of a function or block.
 The value of the static variable exists until the end of the program.
 The static variable which is declared inside a function is known as internal static variable and it
cannot be used outside that function.
 If declared outside the function then it is known as external variable which, can be used in all the
functions of that program.
Sample: Demonstration of a static variable (storage class)
#include<iostream>
using namespace std; /*
void Demo()
{ ### Output ###
static int x=0;
cout<<x<<endl; 0
x++;
} 1
int main() { 2
Demo(); //calling
Demo(); 3
Demo();
Demo(); */
}
Here; we can see that Demo function is called four times and each time value is incremented by 1.
Page |8

Register Storage Class


 Register variable is stored in one of the registers of the system, instead of the main memory.
 Values stored in the register can be accessed faster than one that is stored in memory.
 Registers are located inside the CPU
External Storage Class

 Variables That can be used anywhere in the program are called external variables
 External storage class does not create a variable, but it informs the compiler of its existence.
 Extern keyword is used to declare external variables.

OPERATORS IN C++ LANGUAGE


Operator: It is a special symbol which is used to perform logical or mathematical operations on data or
variables.
Types of Operators Include: Arithmetic operators; Relational operators; Logical operators; Assignment
operators, Bitwise, Increment/Decrement, Conditional and Special operators.
Operand: is a data or variable on which the operation is to be performs. For example; in an expression: x+y:
x and y (variables) are operands while the + sign is the addition operator.
Arithmetic Operators

Symbo Operation Example


l
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
Relational Operators

Symbo Operation Example


l
== Equal to 2==3 returns 0
!= Not equal to 2!=3 returns 1
> Greater than 2>3 returns 0
< Less than 2<3 returns 1
>= Greater than or equal to 2>=3 returns 0
<= Less than or equal to 2<=3 returns 1

Logical Operators
Page |9

Symbol Operation Example


&& Logical AND If(x>y&&x>z)
returns true if both conditions are true, otherwise its false
|| Logical OR If(x>y||x>z)
returns true if any one or both conditions are true,
otherwise the result is false
! Logical NOT If(!(x>y)) NOT operator reverses the state; i.e. if the
condition
is true it returns false, and vice versa.
Sample Code:
#include<iostream>
using namespace std;
int main(){
int a=10, b=50, c=30;
if(a>b&&a>c)
cout<<”a is the greatest”;
if(b>a&&b>c)
cout<<”b is the greatest”;
if (c>a&&c>b)
cout<<”c is the greatest”;
}

Assignment Operators

Symbol Example Same as


= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Bitwise Operators

Symbol Operation Example


& Bitwise x&y
AND
| Bitwise OR x|y
<< Shift Left x<<2
>> Shift Right x>>2
Increment/Decrement Operators

Symbol Name Function Example


++ Increment It increments ++x or
the value by 1 x++
-- Decremen It decrements --y or
t the value by 1 y--

Conditional Operators
P a g e | 10

1? 2: 3; if condition is false
Condition if condition is true
Sample Code:
#include<iostream>
using namespace std;
int main()
{
int a = 10, b=20;
a>b? cout<<”A is greater than B”: cout<<”B is greater than A”;
}
/*
### Output ###
B is greater than A
*/

Special Operators

Symbo Description Example


l
& Is used find the address int a=10;
of a variable cout<<&a;
* Used to declare pointer type variable int*p;
sizeof() Returns the memory size of variable int a=10;
cout<<sizeof(a);

CONTROL STURCTURES IN C++


The If_Statement; syntax:
if (condition)
{
//body (codes)
}
1. If the condition inside the parenthesis is evaluated to be true, then its body is executed otherwise it
doesn’t execute.
2. In the case of if in the place of condition always zero and non-zero value is checked in which zero means
condition is false and non-zero means condition is true.
#include<iostream.h>
#include<conio.h>
int main() {
//Assigning value to the variable
int x=50, y=20;
//checking the condition
if (x>y){
cout<<”x is greater than y”;
}
P a g e | 11

If_Else Statement in C++ Language


Syntax:
if (conditional stmt)
{
//if condition is true: execute code
}
else
{
//if condition is evaluated to false, execute here
}

Sample Code: #include<iostream.h>


int main(){
int x=50, y=20;
if(x==y){
cout<<”x is equal to y”;
}
else
{
cout<<”x is not equal to y”;
}
}

Nested If_Statement in C++ Language


Syntax:
if (condition)
{ if(another condition){
//statements…
}
}
a) Nested means one inside another; so one if inside another if is called nested if.
b) In the case of if in the place of condition always zero and non-zero value is checked in which
zero means condition is false and non-zero means condition is true
Sample Code:
#include<iostream.h>
int main() {
int x = 10;
if(x>5) //checking the condition_1
{
if(x<15)//checking the condition_2
{
cout<”x is greater than 5 and less than 15”;
P a g e | 12

}
}
}

In the above program, the outer if condition is true, so its body will execute and the condition of inner if is
also true so the output is: “x is greater than 5 and less than 15”
Assignment:
Change the above sample code but ensure it produces the same results. Hint: make use of the logical
operators: AND, OR, or NOT.
The Switch Statement in C++ Language
The switch statement allows us the opportunity to execute one statement from many statements and those
statements are called case. Actually, in switch statement, inside the body of switch a number of cases are
used and a parameter is passed and from which case this parameter is matched, executed.
Syntax:
switch(parameter){
case 1:
statement_1;
break;
case 2:
statement_2;
break;


case n:
statement_n;
break;
default;
default_statement;
}

1. In the switch statement, a value/number is passed in the place of parameter and that casewill
execute; which is equal to that value/number.
2. If no case matched with the parameter(s) then the default case will execute.
Sample Code:

#include<iostream.h>
int main() {
//assigning parameter’s value
intp=2;
switch (p){ OUTPUT:
case 1: it is case 2
cout<< “it is case1”;
break;
case 2:
cout<< “it is case 2”; Note: this is because P=2, so case
break; 2 will execute
case 3:
cout<< “it is case 3”;
break;
default:
cout<< “No case matched!”;
}
return 0;
}
P a g e | 13

Assignment:
Re-write the sample program above to compute students’ grade using the following parameters:
- 75 and above = ‘A’
- 65 – 74 = ‘B’
- 55 – 64 = ‘C’
- 45 – 54 = ‘D’
- 40 – 44 = ‘E’
- 0-39 = default = ‘F’
 Compile your source code and print the output.

For Loop in C++ Language


To run the body or segment of code continuously until a required condition is fulfilled, we use a loop control
structure. When the condition of the loop becomes false, the execution stops.
Syntax:
for (<initialization>; <condition>; <increment/decrement>)
{
//body of the loop
}
The initialization part executes only once. All the three parts of the loop are optional.
Sample:
#include<iostream.h>
int main()
{
for(int i=1; i<=10; i++)
{
cout<<i<<”\n”;
}
}//the output will generate numbers from 1-10

WhileLoop in C++ Language


Syntax:
while(condition)
{
//body of the loop
}
Its body will continue to execute until the given condition is false.
P a g e | 14

Sample:
#include<iostream.h>
void main() {
inti=1;
while(i<=10)
{//opens while-loop
cout<<i<<”\n”;
i++; //the value of i increased by 1
}//closed while-loop
}//closed main function.
//the program will print numbers 1-10

Do…while Loop in C++ Language


Syntax:
do {
// body of the loop
}
while(condition);
This type of loop will execute until when a certain condition (given) is true.
Exercises:
1. Re-write the sample program above using the do…while loop as shown in the syntax above.
2. Establish the distinction between the do...while and the while loops.
Nested Loop in C++ Language
Definition: A loop inside another loop is called nested loop; so one for loop inside another for loop is called
nested for-loop and so on.
Syntax:
for(..; …; …)
{
for(..; …; …)
{//statements
}
//statements
}
Sample:
#include<iostream>
int main() {
int n;
cout<<”Enter the range of numbers you want to print their primes\n”;
cin>>n; //cin>> is used as an input statement to assign value to ‘n’
for(int i=2; i<=n; i++)
{
int no=i, m=0;
P a g e | 15

for(int j=2; j<=no-1; j++)


{
if(no%j==0)
m=1;
}
if(m==0)
cout<<no<<” “;
}
return 0;
}//copy out this code in the console and run for results…

POINTERS IN C++ LANGUAGE


What is a Pointer?
1. It is a special type of variable which is used to store the address of another variable.
2. It can store the address of same data type; that means an integer pointer can store the address of an
integer variable, character can store for character, and so on…
3. If we add asterisk(*) symbol with any variable at the time of declaring the variable, then this
variable is marked out to be a pointer variable. E.g. int *p;
4. We use ampersand (&) symbol to get the address of variables
5. *symbol is used to get the value of address which is hold by pointer.

Sample:
#include<iostream.h>
void main() {
int a=10; //normal variable initialized
int *p; //pointer variable declared
p=&a; //address of variable a is assigned to p
cout<<”value of a=”<<a;
cout<<”address of a=”<<&a;
cout<<”value of p=”<<p;
cout<<”address of p=”<<&p;
cout<<”value of *p=”<<*p;
}
### Output ###
Value of a=10
Address of a=8284
Value of p=8284
Address of p=8288
Value of *p=10

ARRAYS IN C++
What is an Array?
1. It is a collection of data of same data type. This means that an integer array can store only integer
values, and so is character, and so on…
2. It is used to store group of data simultaneously.
3. We cannot fetch data from array directly therefore we use index point.
P a g e | 16

4. The indexing of array always start with 0; and must always be an integer number.
5. Array may be of any data type like int, char, float, etc.
Syntax (Array Declaration):
int arr[10];

data type array name array size


- Here; ‘arr’ is the name of the array
- Int is the data type of the array to be collected.
- Size of array is 10; which means it can collect maximum of 10 elements
Initialization of Arrays:
 Method 1:
int a [5] = { 10, 20, 25, 30, 55};
 Method 2:
int a[5];
a[0]=10;
a[1]=20;
a[2]=25;
a[3]=30;
a[4]=55;

Printing of Array Elements Using Loop; Sample Code:


#include<iostream>
using namespace std;
void main(){
int a[5]={20,10,80,70,60};
for(int i=0; i<=4; i++)
cout<<”Value at a[“<<i<<”]=”<<a[i]<<”\n”
}
Exercise:
1. Run the code and get the output.
2. Learn more on “User input in array using loop”.

Two-Dimension Arrays in C++


Syntax(Declaration):
int arr [3][3]
1) Here, arr is the name of the array;
2) Int is the data type of the array;
3) Size of array is 3x3, meaning we can store maximum of 9 values in this array.
4) The first 3 represent maximum number of rows while the other represents maximum number of
columns
Initialization of 2-dimension Arrays; Method 1:
P a g e | 17

int arr[3][3] = {{40,50,60},{10,20,30}, {70,80,90}};


The above can be represented in a matrix form as follows:
40 50 60 arr[0][0] arr[0][1] arr[0][2]
10 20 30 arr[1][0] arr[1][1] arr[1][2]
70 80 90 arr[2][0] arr[2][1] arr[2][2]
Method 2: Assignment: use the knowledge gained so far to construct the table of how arrays can be
represented.

Printing of Array Element Using Loop; Sample:


#include<iostream>
using namespace std;
int main() {
int a[3][3]={{10,20,30}, {70,80,90}, {40,50,60}};
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++) {
cout<<a[i][j]<<” “;
}
cout<<”\n”;
}
return 0;
}

C++ FUNCTIONS
What is a function?
1. It is a collection of statements grouped together under a name, which performs a special task when
called upon by the name.
2. A large program is divided into a number of small building block for simplicity and this block is
called function.
3. Functions can be called again and again and at each time perform a peculiar task.
4. The most important feature of functions is code reusability.
5. The C library provides many pre-defined functions.
Syntax of a Function:
return_typefunctionName(Parameter list)
{
//body
}
Description:
Return type (i) It is a keyword which indicates that which type of value is being
returned by the function
(ii) If we do not want to return any value then we use void keyword instead
Function name (i) It is the actual name of the function by which it can be called any time.
(ii) It is same as the variable name, but must start with an upper case letter
P a g e | 18

Parameter list (i) It is the place where we can pass a number of parameter/variable
(ii) The value of these parameters can be initialized or we can pass it from
calling the function
(iii) It is an optional part.
Body It is the place where the actual code is written to perform the task for which it
is being written.

Key Points about Function:


 Function Declaration: At this stage the function is declared e.g. void add();
 Function Definition: This is the place where actual code is written to perform the task e.g.
void add()
{
int x, y=20, z=30;
x=y+z;
cout<<”Add “<<x;
}
The definition of a function forms its body…
 Function Calling: At this stage the function is called or referenced. To call a function, just write its
name and put semi-colon, e.g. add();
Types of Functions
1. Predefined Functions
2. User-defined Functions.
Predefined Function:- is the function which is predefined in the library of the C++ compiler. Examples
include: printf(), scanf(), clrscr(), getch(), etc.
User-defined Function:- is made by the user (programmers) themselves. E.g. add(), sub(), multi(), div(),
etc.
Function Calling
There are two ways of calling a function:-
1) Call By Value
2) Call By Reference
Function Call by Value
In this type of function call, direct value is passed at the time of calling. The sample code below illustrate
function call by value:

#include<iostream>
using namespace std;
void add (int y, int z)//function definition
{
int x;
x=y+z;
cout<<”Add=”<<x;
}
P a g e | 19

int main () {
add(10,20);// function call by value
}
We have seen above how direct values (10, 20) are passed in the function “add()”.
Function Call by Reference
1. In this type of calling a function, the reference of the value is passed at the time of calling.
2. Reference is also called address.
3. When the address of data is passed at the time of calling so it is necessary to use pointer in the place
of parameter. For better understanding, see the example below:
#include<iostream>
using namespace std;
void sum (int *p, int *q)//function definition
{
int result =*p + *q;
cout<<”Sum=”<<result;
}
int main () {
int x=10, y=20;
/* reference of variable is got using ampersand(&) operator
* Sum(&x, &y); //function call with reference/address
*same output like the previous code. Study carefully…
*/
}
Function Recursion
The process of calling a function by itself is called Recursion and the function that calls itself is called a
Recursive Function.
Factorial of any Number Using Recursion
5!= 5*4*3*2*1
Sample Code:
#include<iostream>
using namespace std;
void factorial (int no, int f)//function definition
{
if(no>=1) {
f=f*no;
no--;
factorial(no,f);
}
else
cout<<”Factorial =”<<f;
}
int main () {
int n;
cout<<”Enter any number to find factorial\n”;
cin>>n;
factorial(n,1)//function calling with array
}

Exercise:
1) Write a program to compute the area of a circle using function
P a g e | 20

2) Differentiate function call by value from function call by reference


3) Explain the components of a function.

STRING FUNCTIONS IN C++ LANGUAGE


1. String is a collection of characters to be treated as a single entity
2. C does not support string data type therefore, char data type is used to make string
3. String in C is stored in single dimension character array.
4. There are many predefined string functions in C library.
5. All string functions are predefined in String.h header file.
Assignment: Make a list of C’s predefined string functions with their meanings.
Sample Codes:
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main () {
char name[200]=”Easy”;
cout<<strlen(name);
return 0;// return-type used
//the output is 4 because of only 4 characters in “Easy”
}
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main () {
char s1[200] = “Easy”;
char s2[200] = “Softwares”;
cout<<,strcat(s1,s2);//function concatenate s1 and s2
return 0;
}
//output becomes ‘Easy Softwares’

Math Function in C++ Language


1. It is used to perform the mathematical related operation.
2. There are many predefined math functions in C library.
3. All the math functions are predefined in Math.h header file.
4. Examples of such math functions include: sin(), sinh(), cos(), cosh(), tan(), tanh(), sqrt(), pow(),
exp(), log(), log10(), floor(), ceil(), round(), abs(), and fmod().

Look for their meaning.


Do more…
P a g e | 21

STRUCTURE IN C++ LANGUAGE


What is Structure?
1) It is a collection of data of different data types
2) It is a user defined data type
3) Data can be int, char, float, double, etc. data types
4) We can access the members of structure by making a variable of structure
5) Struct is the keyword used to create a structure.

Syntax:
Structstructure_name
{//body of structopens(begins)
Data_type var1;
Data_type var2;
……………….
Data_typevar n;
};//body of struct closes and must end with (;)

Example:

structstudent
{
char name[200];
introllNo;
float marks;
};
Sample: Code to store and display the student name, rollNo and marks
#include<iostream.h>
#include<string.h>
struct student
{
char name[200];
introllno;
float marks;
};
int main() {
P a g e | 22

struct student student1; //declaring structure variable


strcpy(student1.name, “lucky”);
student1.rollno=20;
student1.marks=85.5;
cout<<”student Name =”<<student1.name<<”\n”;
cout<<”Student Roll No:”<<student1.rollNo”\n”;
cout<<”Student Marks = “<<student1.marks”\n”;
return 0;
}//closes main method

UNION IN C++ LANGUAGE


What is Union?
a) It is a collection of data of different data type
b) It is user defined data type
c) We can access the member of union by making the variable of union.
d) Union is the keyword used to create a union.
e) Union doesn’t support multiple values simultaneously, but can store one value at a time.

Syntax:
unionstructure_name Example:
{ union student {
data_type var1;
char name [200];
data_type var2;
introllNo;
………………………..
float marks;
data_typevar n;
};
};

Assignment:
Write a program that will store and display the student name, roll no, and marks; using the union structure.
C++ FILE HANDLING MECHANISM
1. File handling is a mechanism to store the output of a program into a file and read from a file on a
disk permanently.
2. fstreamheader file is used to perform file operations in C++, this header file provides many classes
(ifstream, ofstream, fstream) to read from a file and write into a file.
3. ofstream: This data type represents the output file stream and is used to create files and to write
information to files.
4. fstream: This data type represents the file stream generally, and has the capabilities of both ofstream
and ifstream which means it can create files, write information to files and even read information
from files.
The Various Operations on a File
P a g e | 23

File Opening: modes


In C++, file can be opened in different mode to perform read and write operations on a file. open() function
is used to open a file, open function takes two arguments…
open (const char *filename,ios::openmode mode);
Different file opening modes are given below:

S/NO MODE DESCRIPTION


1 ios:: in Open a file for reading
2 ios::out Open a file for writing
3 ios::app Append data to the end of the file
4 ios::ate File pointer moves to the end of the file but allows to writes data
in any location in the file
5 ios::binary Binary file
6 ios::trunk Deletes the content of the file before opening

Sample Codes for Writing and Reading from a File:


//This program writes into a file
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstreamofile; //making object of class ofstream
ofile.open(“easy.txt”); //open file with filename: easy.txt
//now, write to a file opened
ofile<<”Easy Softwares”<<endl;
ofile<<”An ISO 9001:2021 Certified Center”<<endl;
ofile.close();
return 0;
}
//This program opens and read from a file
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char str[100]; //declaring variable to store data from file
ifstreamifile; //creating an object of class ifstream
ifile.open(“easy.txt”); //open “easy.txt” for reading
cout<<”Content of easy.txt file is given below:”<<endl;
//while the end of file [eof()]is not reached…
While(!ifile.eof()){
ifile.getline(str,100); //read a line from the file
cout<<str<<endl; //print the file contend read…
}
ifile.close(); //close the file
return 0;
}
P a g e | 24

Exercises:
1) Write a program in C++ that will count the number of alphabets in a file.
2) Write a C++ program that will count the number of digits in a file.
3) Write a C++ program that can count the spaces in a file

OBJECT ORIENTED PROGRAMMING IN C++


OOP in C++ is what make the language a subset with varying feature from the original C Language. The
object oriented design of the language is what makes the language more flexible and friendly. In this section,
we shall take a look at some of the features of the language that make it Object Oriented in nature.
Objects and Classes
What is Object?
Object is having states and behaviours in which state means what does it has and behavior means what does
it do. For example; a pen has:
States: ink, nib, needle, cap, etc.
Behavior: writing.
What is Class?
1. It is a collection of data members and member functions.
2. Data members are the variables used inside a class;
3. Member functions are the functions used inside a class;
4. It is also called User-defined data type.
Syntax of Class in C++

Important points to remember while making class programs:


 Declare variables with appropriate data type as per your requirement: For example to find the area of
rectangle, three variables are sufficient (height, width, and area)
P a g e | 25

 Declare function as per your requirements; for example, to find the area of rectangle, a single
function findArea() is sufficient.
 Create instance (object) of class to access the data members and member functions of the class.
Syntax: className objectName;
Example: Rectangle rec; where Rectangle is the name of the class while rec is the object
name.
 Accessing data members and member functions: Data members and member functions of a class can
be accessed using Dot(.) operator. For instance:
rec.height; //accessing data member
rec.findArea;//accessing member function

Sample Code: Find the area of a rectangle

#include<iostream>
using namespace std;
class Rectangle{
public: //access modifier
int height;
int width;
int area;
// member function declaration:
void findArea() {
area=height*width;
cout<<”Area of rectangle =”<<area<<”\n”;
}
}; //ending class
int main() {
Rectangle rec; // creating instance of class
rec.height = 25; // accessing data member
rec.width = 30;
rec.findArea(); // accessing member function
return 0;
} // copy out this program on a console and run.

Encapsulation
P a g e | 26

1. Is the process of combining many elements into a single entity; or it is the process of combining data
members and member functions into a single entity like class.
2. It is an important feature of OOP
3. It is used to prevent direct accessibility of data members and member functions; and this is
achievable through the use of access specifiers like public, private and protected.
Public Access Specifier: allows the accessibility of data members and member functions to the other
classes. Public element of a class can be accessed anywhere in the program.
Private Access Modifier: it is used to hide data members and member functions from other classes. Private
elements of a class can only be accessed within its own class and not outside that class.
Protected Access Modifier: is approximately same as private but it allows the accessibility of data
members and member functions to the child class. Protected is used in case of inheritance.
Sample Code: Program to calculate the area of a circle.

#include<iostream>
using namespace std;
class Circle{
private:
float area;
float radius;
public:
void getRadius() {
cout<<”Enter radius\n”;
cin>>radius;
}
void findArea() {
area=3.14*radius*radius;
cout<<”Area of circle = “<<area;
}
};
int main() {
Circle c;
c.getRadius();
c.findArea();
return 0;
}//run the program on console while providing radius

Inheritance
1. The process of getting property of one class into another class is called inheritance.
2. It is the process of deriving a new class called child or subclass from a pre-existing one called parent
or super or base class.
3. When a class inherits the property of a class then, it means it can access all the data members and
member functions of that class, except private elements.
P a g e | 27

How to Inherit (Syntax):


Derived_Class: access specifier base_Class

e.g. Sample Code to Illustrate Inheritance:


#include<iostream>
using namespace std;
class Addition {
public:
void add() {
int x, y=30, z=10;
x=y+z;
cout<<”Addition= ”<<x<<”\n”;
}
};
//Derived class
class Subtract: public Addition {
public:
void sub() {
int x, y=30, z=10;
x=y-z;
cout<<”Subtraction = “<<x<<”\n”;
}
};
Int main() {
Subtract sobj;
sobj.add();
sobj.sub();
return 0;
}
Notice here that, the class Subtract is inherited from a super class Addition; hence its object (sobj) can be
used to call all the functions from both classes.
Types of Inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
 Single Inheritance: in this type of inheritance only two classes are used in which one is inherited by
another. The illustration given above explains this.
 Multiple Inheritance: (1) When two or more classes are inherited by a single glass simultaneously,
this phenomenon is called multiple inheritance. (2) In this type of inheritance at least three classes
are compulsory.
 Multilevel Inheritance: (1) when first class is inherited by second class, the second is inherited by
the third, and so on… (2) in such inheritance each derived class is the base class for the next class.
(3) at least three classes are compulsory.
P a g e | 28

 Hierarchical Inheritance: (1) When a single class is inherited by two or more classes
simultaneously (2) Here, derived classes may be two or more classes but only one base class. (3) at
least 3 classes are compulsory.
 Hybrid Inheritance: (1) the combination of two or more inheritance is called hybrid. (2) in this type
of inheritance, at least three classes are compulsory.
Advantages of Inheritance
1. Code Reusability: function inside base class is shared by all the derived classes
2. Time Saving: because there is no need to define existing properties (same code) of a class in a
derived class.
3. Less cost: because existing code is reused, it leads to less development and maintenance costs.
4. It helps to reduce code redundancy.
Exercise:
Write C++ programs to implement:
(i) Multipule inheritance
(ii) Multilevel inheritance
(iii) Hierarchical inheritance
(iv) Hybrid inheritance

Polymorphism
1. It means one name, many forms; so we can say that in this type of programming paradigm, the same
function is used to perform different kinds of operation.
2. It is important part of object oriented programming language.
3. For example: (Sample Code)
#include<iostream>
using namespace std;
class Poly {
public:
void a() {
cout<<”No para\n”;
}
void a(int i){
cout<<”integer Para\n”;
}
void a(double d) {
cout<<”double Para\n”;
}
};
void main() {
Poly obj;
obj.a(12); // passing an integer value into ‘a’
P a g e | 29

obj.a(12.0); //passing a double value into ‘a’


}

Types of Polymorphism
 Compile Time Polymorphism
Function overloading and operator overloading are the examples of compile time polymorphism.
 Runtime Polymorphism
Function overriding is the example of Runtime polymorphism
Function Overloading: the function with same name and different parameter list is called function
overloading. The sample code below illustrates this in detail.

Program to calculate the areas of a rectangle and square


#include<iostream>
using namespace std;
class Geometry {
public:
void area(int h, int w) {
int ar=h*w;
cout<<”Area of rectangle”<<ar<< “\n”;
}
void area(int s){
int ar = s*s;
cout<<”Area of Square = “<<ar<<”\n”;
}
};
void main() {
Geometry obj;
obj.area(12,13); // passing 2 parameters
obj.a(12); //passing a single parameter
}

Operator Overloadidng
1) It is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it;
2) Overloaded operators are functions with special names; the keyword operator followed by the
symbol for the operator being defined;
3) By using an operator overloading we can change the meaning of operator.
4) Overloading operator is used to perform operation on user-defined data type.
EXAMPLE:
Class Smart{
void operator +(){
height =10;
width=20;
}
Void operator ++() {
Area=height*width;
P a g e | 30

Cout<<”Area of rectangle=”<<area;
}
Int main() {
Smart obj;
+obj;
++obj;
}
}
Exercise: Re-write the above example code into a full program and run it.
Function Overriding
1) This is a situation when two functions have the same name and same parameter list.
2) It is not possible to make two functions with same name and same parameters in a single class
therefore, to implement function overriding, derived class is used.
3) See the sample code below:
#include<iostream>
Using namespace std;
class Rectangle1 {
public:
void area (int h, int w) {
int ar=h*w;
cout<<”Area of rectangle1= “<<ar;
}
};
class Rectangle2 {
public:
void area(int h, int w) {
int ar = h*w;
cout<<”Area of rectangle 2=”<<ar”;
}
};
int main() {
Rectangle2 obj;
Obj.area(10,20);// only one of the functions is used,
// the other one is overridden
}
P a g e | 31

EXCEPTION HANDLING
Exception
To understand the exception firstly we should know about the error in prgram.Errors in program can
be categorized into two types.

1. Compile Time Errors


2. Run Time Errors

Compile Time Errors:- Errors caught during compiled time is called Compile time errors. Compile
time errors include library reference, syntax error or incorrect class import.
Run Time Errors:- The error that occours during the run time of program is called run time error.
They are also known as exceptions. Hence we can say that exception is a runtime error that occours
because of user's mistake.
Reasons of Exception
Mismatched Input :Suppose that we are entering our name in place of age,causing exception
because age is of data type int and name will be string.
File does not exist :Suppose that we are reading a text file easy.txt and that file does not exist in the
system,causing exception.
Exception related to array :Suppose that the array size is 5 and we are inserting more than 5
elements,causing exception.
Divide by zero exception :When a number is divided by zero then the output will be
undefined(infinity).
Exception Handling
The process of handling the exception is called exception handling. There are three main keywords
are used to solve the problem of exception.
try block: It is the place where actual code is written and exception occurs. When the code will lead
to any error, that error/exception will get caught inside the catch block.
catch block: catch block is intended to catch the error and handle the exception condition. We can
have multiple catch blocks to handle different types of exception and perform different actions when
the exceptions occur.
throw statement: It is used to show the user defined message about the exception.

Syntax of try-catch
try{
// protected code
}catch(ExceptionNamee1){
P a g e | 32

// catch block
}catch(ExceptionNamee2){
// catch block
}catch(ExceptionNameeN){
// catch block
}

Example: Sample Code:


#include<iostream>
using namespace std;
void divide(intx,int y)
{
try
{
if(y!=0)
{
int z=x/y;
cout<<"Div="<<z;
}
else
throw "Don't put zero in denominator";
}
catch(constchar*s)
{
cout<<s;
}
}
int main()
{
int a,b;
cout<<"Enter a\n";
cin>>a;
cout<<"Enter b\n";
cin>>b;
divide(a,b);

DasgfdfDFDKFHOEI
Tachia Saater

You might also like