0 ratings0% found this document useful (0 votes) 28 views19 pagesC and CPP Complete Notes Img Oct 2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
1
What is an Algorithm?
‘An algorithm is a procedure or formula for solving a problem. In other words, an algorithm is a list of rules
to follow in order to solve a problem. Algorithms need to have their steps in the right order.
What is a Flowchart?
Flowchart is a graphical or diagrammatic representation of a computer program in relation to its sequence
of functions. Some of the shapes used in flowchart are Arrow, Decision, Connector, Oval etc.
What is a Keyword?
Keywords are certain “Reserved words” which has got some predefined meaning in C. There are 32
keywords available in C. Some of them are Auto, Break, Case, Switch, If, Else, While, Do, Int, Char, Float, Long,
Double ete.
What is an Identifier?
Identifiers are the names given to variables, constants, functions and user-define data. These identifier has
a set of rules.
Identifier name must be a sequence of letter and digits, and must begin with a letter.
The underscore character (_} is considered as letter.
Names shouldn't be a keyword
Both upper-case letter and lower-case letter characters are allowed. However, they're not
interchangeable.
* No identifier may be keyword.
© _No special characters, such as semicolon, period, blank space, slash or comma are permitted
Example float number; float a; (Legal) _ float :e; float for; (illegal)
What is a Constant?
‘A constant is also a variable whose values cannot be changed during the execution of a program.
Constants refer to fixed values.
Define Variable?
A variable is an identifier which is used to store a value. There four commonly used data types with variables are
int, float, char and double
‘What is a Function?
A large program is divided into basic building blocks called function, Function contains set of instructions
enclosed by “{ }° which performs specific operation in a program.
‘+ C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be traced when it is divided into functions.
‘The core concept of C functions are, re-usability.
Dividing a big task into small pieces to achieve the functionality
‘To improve understandability of very large C programs.
History of C Language
+ Cis a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in
1972.
C was originally developed for UNIX operating system to beat the issues of previous languages
It is a very popular language, despite being old
It is one of the most popular programming language in the world
If we know C, we will have no problem learning other popular programming languages
Cis very fast, compared to other programming languages
Now a days C is exclusively used for building OS, application packages and customized software
Structure of C Program
‘The structure of a C program means the specific structure to start the programming in the C language. The
basic structure of a C Program is
tinchideestdio.h>
#includeeconio.h>
void main )
‘
int a,b;
elrser()}s
printf.
getcht }s
}
Dr. R N MUHAMMAD ILYAS2
What is a Union? Give Example
Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The
only differences is in terms of storage. In structure each member has its own storage location, whereas union
uses a single shared memory location which is equal to the size of its largest data member.
Eg:
union job
char name[32J;
float salary;
int worker_no;
&
What is a Pointer? Give Example.
Pointer is a variable which holds the address of another variable. Pointers are the powerful feature of C.
there are two types of operators used in pointer. They are Reference operator (&) and Dereference operator (*).
If varis a variable then, &var is the address in memory.
Pointer is used to allocate memory dynamically i.e. at run time the pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
data_type" pointer_variable name;
int* p; //statement defines, p as pointer variable of type int.
“ Use Call By Reference or Practical Program as Example ”
Data Types in C
Data types specify how we enter data into our programs and what type of data we enter. C language has
some predefined set of data types to handle various kinds of data. These datatypes have different storage
capacities. C language supports 2 different type of data types. They are Primary and Secondary or Derived Data
types.
‘There are four primary data types:
int - integer: a whole number.
float - floating point value : ie a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
‘The Derived Data
Pointer types
Array types
Structure types
Union types.
Function types.
Keyword _TbvtesRequred] ange
Cac [ew te)
spel dunce [wide [nT ts
ter
Secinge [sore awn |
wipe 2 does
Taped eye
Vesela ge Teese
Array
it
Pointer
Structure
Union
Enumete,
Tenn wien
Dr. R N MUHAMMAD ILYASIf- Else and Nested If-Ele
3
In decision control statements a group of statements are executed when condition is true. If condition is
false, then else part statements are executed. There are 3 types of decision making control statements in C
language. They are
© Simple if statement
© ifelse statement
+ Nested ifelse statement
If Statement (Syntax, Flowchart and Example)
£f (condition)
{
block of staterent
}
int maing
{
int m
if(m
{
printi{'m and n are equal’);
}
0,.n=40;
n)
3
If Else Statement (Syntax, Flowchart and Example)
int main()
int m=40,
if (m == n)
{
printf['m and n are equal’);
a
{
printf{'m and n are not equal");
}
}
Nested If Bise Statement (Syntax, Flowchart and Example)
if\condition_1)
£
if{condition_2)
block statement_1;
$
else
‘
block statement_2;
else
t
block statement_3;
}
block statement_4;
int main()
t
int m=40,
if (m>n)
printi('m is greater than n'};
else iffin Greater than
/ Division < Less than
% Modulus > Greater than or equal to
Less than or equal to
Logical Operators
Special Operators
Operator | Description Operator | Description
&& | Logical AND Sizeof() | Returns the size of a memory location.
ul Logical OR & Returns the address of a memory location.
! Logical NOT ‘ Pointer to a variable.
Bitwise Operators
Assignment Operators
Operator
Description
Assign
Increments then assign
Operator | Description
<< | Binary Left Shift Operator
>>| Binary Right Shift Operator
- Binary Ones Complement Operator
& Binary AND Operator
Decrements then assign
i
Binary XOR Operator
Binary OR Operator
Multiplies then assign
Divides then assign
Dr. R N MUHAMMAD ILYAS6
What is an Array? Give Example
Array is a collection of variables belongings to the “Similar or Homogencous” data type. Arrays are of two
types: They are One-dimensional array and Multidimensional array. General form of Array declaration is,
data-type variable-name|sizc|
Eg: int arr[10);
Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can
only contain 10 elements of int type.
#finclude rer
int main() ea
A
int art[5}, is
for(i = 0; 1 < 5; i+)
Cust ee oy
printi(’Enter a[Pod]: ", i;
scanf("%ed", &arz{i); Ae
5 pear eer)
printi['\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i+)
printt('%d *, arrfi)s
}
return 0;
‘Two Dimensional Array
+The simplest form of multidimensional array is the two-dimensional array
* Two dimensional array is nothing but array of array.
syntax : data type array_name|num_of rows|[num_of column);
finclude
ones
4 acetone Column 0 Column 1 Column 2 _Column 3
inti, j, k; Row 0 af 0] aot) | af Oz) af 03]
roll Ente ainay eeinanty,
permease nowt | atiyoy | attyity | attm2y | ats)
for(j = 0; j < 4; j++) Row 2 | azo} | af2ut) | al2uz) | af213)
scanf(‘%d", &arr[illj]);
,?
for(i = 0; i< 3; i+)
{
for(j = 0; j < 4; j++)
printi('%d", arrili);
?
}
What is a Structure? Give Example
‘Structure is a collection of variables belongings to the “Dissimilar or Heterogeneous” data type under a
single name. Keyword “struct” is used for creating a structure. General form of Structure declaration is,
struct structure_name Eg:
{ struct person
data_type member1;
data_type member2; char name[50|;
int cit_no;
float salary;
b h
Dr. R N MUHAMMAD ILYASCall by Value
fincludesstdio.h>
void interchange(int number1 int number2)
temp = number];
number] = number2;
number2
int num1=50,num2=70;
interchange(mum|,num2);
print{{"\nNumber 1 : %d",num 1);
printf(’\nNumber 2 : %d",num2);
return(0};
3
Output:
Number 1: 50
Number 2: 70
‘+ While Passing Parameters using call by value , xerox copy of original parameter is created and passed to
the called function.
Any update made inside method will not modify the original value of variable in calling function.
In the above example num1 and num? are the original values and xerox copy of these values is passed to
the function and these values are copied into number 1,number2 variable of sum function respectively.
* As their scope is limited to only function so they cannot alter the values inside main function,
Call by Reference
#include
void interchange(int *num I int *num2)
{
int temp;
temp ="numl;
*numl = *num2;
“num? = tem)
int main()
int num1=50,num2=70;
interchange(énum1,&num2);
printf{"\nNumber 1 : 9d",num1)};
printf[’\nNumber 2 : %d"num2):
return(0};
}
Output
Number 1: 70
Number 2: 50
© While passing parameter using call by address scheme, we are passing the actual address of the variable to
the called function.
© Any updates made inside the called function will medify the original value since we are directly
modifying the content of the exact memory location.
Dr. R N MUHAMMAD ILYASC++ OOPS Concept 6B
‘The core of the pure object-oriented programming is to create an object, in code, that has certain properties and
methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an
object which has certain properties such as color, number of doors, and the like. It also has certain methods such
as accelerate, brake, and 50 on.
‘There are a few principle concepts that form the foundation of object-oriented programming:
Object:
‘This is the basic unit of object oriented programming, That is both data and function that operate on data are
bundied as a unit called as object.
Class:
When you define a class, you define a blueprint for an object. This doesn't actually define any data, but it does
define what the class name means, that is, what an object of the class will consist of and what operations can be
performed on such an object.
Abstraction:
Data abstraction refers to, providing only essential information to the outside world and hiding their background
details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained. Similar
way, C++ classes provides different methods to the outside world without giving internal detail about those
methods and data.
Encapsulation:
Encapsulation is placing the data and the functions that work on that data in the same place. While working with
procedural languages, it is not always clear which functions work on which variables but object-oriented
programming provides you framework to place the data and the relevant functions together in the same object.
Inheritance:
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests
Inheritance is the process of forming a new class from an existing class that is from the existing class called as
base class, new class is formed called as derived class.
‘This is a very important concept of object-oriented programming since this feature helps to reduce the code size.
Polymorphism:
The ability to use an operator or function in different ways in other words giving different meaning or functions to
the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator
functioning in many ways different upon the usage is called polymorphism.
Inheritance: (Refer Page 14 and 15 for Example Program)
Inheritance is a mechanism of acquiring the features and behaviors of a class by another class. The class
whose members are inherited is called the base class, and the class that inherits those members is called the
derived class.
Inheritance lets you create new classes from existing class. Any new class that you create from an existing
class is called derived ciass; existing class is called base class.
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.
Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base class
Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base class.
Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of
inheritance.
Fy
a oe
HEHE
Dr. R N MUHAMMAD ILYAS7
Files Opening And Closing
In C++, to open a file, you must first obtain a stream. There are three types of streams:
© input
© output
* input/output
To create an input stream, you must declare the stream to be of class ifstream. Here is an example:
ifstream fin;
To create an output stream, you must declare it as class ofstream. Here is an example:
ofstream fout;
Streams that will be performing both input and output operations must be declared as class fstream, Here is
an example:
fstream fio;
In C++, a file is opened by linking it to a stream. There are three types of streams: input, output and
input/output. To open an input stream you must declare the stream to be of class ifstream. To open an output
stream, it must be declared as class ofstream. A stream that will be performing both input and output operations
must be declared as class fstream. For cxample, this fragment creates onc input stream, one output stream and
one stream that is capable of both input and output.
Once you have created s stream, one way to associate it with a file is by using openl). This function is a
member of each of the three stream classes. Its prototype is shown here
void open(const char “filename, int mode, int access);
Here, filename is the name of the file. The value of the mode determines how the file is opened. It must be
one or more of the following values which are defined in the fetream.b
iffstream in;
ofstream out;
fstream both;
// writing on a text file
#include
#include
using namespace std;
int main () {
ofstream myfile (‘example.txt’);
if (myfile.is_opend)
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close);
y
else cout << "Unable to open file";
return 0;
}
Dr. R N MUHAMMAD ILYAS8
Inline Function:
C++ inline function is powerful concept that is commonly used with classes. The inline functions are a C++
enhancement feature to increase the execution time of a program. If a function is inline, the compiler places a
copy of the code of that function at cach point where the function is called at compile time.
To inline a function, place the keyword inline before the function name and define the function before any
calls are made to the function. A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
We must keep inline functions small,
‘Small inline functions have better efficiency.
Inline functions do increase efficiency, but we should not make all the functions inline.
If we make large functions inline, it may affect the speed too.
Hence, it is advised to define large functions outside the class definition using scope resolution (::) operator
inline float triangle_area(float base, float height)
{
float area;
area = (0.5 * base * height);
return area;
3
int main(void)
{
float b, h, a;
bea
h=6;
// compiler will substitute the inline function code here.
a= triangle _area(b, h);
//cout
using namespace std;
class Box
public:
double length;
double breadth;
double height;
int main( )
BoxB1; —_// Declare B1 of type Box
Box B2; —_// Declare B2 of type Box
double volume = 0.0;
1] box 1 specification
BL height = 5.0;
B1 length = 6.0;
BL breadth = 7.0;
1] box 2 specification
B2.height = 10.0;
B2 length = 12.0;
B2.breadth = 13.0;
volume = BI height * B1.length *B1 breadth;
cout << "Volume of Box! : " << volume <
using namespace std;
class Circle / /specify a class
{
private :
double radius; //class data members
public:
Circle) //default constructor
radius = 0;
Circle(double r) / /parameterized constructor
{
}
Circle(Circle &t) //copy constructor
{
radius = 1;
radius = t.radius;
‘oid setRadius(double 1) //function to set data
{
radius = 1;
double getAreat)
{
return 3.14 * radius * radius;
}
~Circle() / /destructor
a
int main
{
Cirele ¢1; //defatut constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Cirele ¢3(¢2); //copy constructor invoked
cout <« cl.getAreal)<
using namespace std;
friend return_type function_name(argument/s);
class sample
{
int a,b;
public:
void setvalue()
{
8°25; b=40;
}
friend float mean(sample s);
%
float mean(sample s)
t
return float(s.a+s.b)/2.0;
}
int main()
{sample X;
X.setvalue();
cout<<"mean value = “<
int main
float a, b, c;
printf{’Enter three numbers: *);
scanf["%f %f %f Bua, 8b, 8c);
iflaeb és a>=c)
printif’Largest number = %.2f, a);
iffb>=a &és b>=c)
printf{’Largest number = %.2f", b);
iflc>=a && c>=b)
printf{’Largest number = %.2f, c};
return;
}
Dr. R N MUHAMMAD ILYASArray of Objects 12
‘An array of a class type is also known as an array of objects. Arrays of variables of type "class" is known as
“Array of objects’. An array of objects is declared in the same way as an array of any built-in data type. Like array
of other user-defined data types, an array of type class can also be created. The array of type class contains the
objects of the class as its individual elements.
Syntax
class_name array_name [size] ;
A program to demonstrate the concept of array of objects
fincludesiostream>
class rect
{
private:
int ls // int L for length
int b;
public:
rect{int a,int ¢)
{
Ira;
}
void put()
{
cout<<"Area is : "<
using namespace std;
int volume(int);
double volume (double,int);
Jong volume(long,int, int);
int volumefint s) // volume of cube
{
}
double volume(double r, int b) // volume of a cylinder
{
}
long volumeflong |, int b, inth) —_// volume of a cuboid
{
return s*s*s;
return (3.14*r'r*h);
return "bth;
3
int main()
t
cout << volume(10) << "\n"
Dr. R N MUHAMMAD ILYAScout <« volume(2.5, 8) << “\n"; 13
cout <« volume(100, 75, 15) << \n";
return 0;
}
‘Virtual Base Class
‘An ambiguity (doubt) can arise when several paths exist to a class from the same base class. This means
that a child class could have duplicate sets of members inherited from a single base class. C++ solves this issue by
introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is
avoided regardless of the number of paths that exist to the child class.
When two or more objects are derived from a common base class, we can prevent multiple copies of the
base class being present in an object derived from those objects by declaring the base class as virtual, when it is
being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base
class’ name with the word virtual.
class A
{
public:
int i;
%
class B : virtual public A
public:
int j
class C: virtual public A
public:
x
class D: public B, public C
{
public:
int sum;
b
int main()
{
Dob;
ob.i = 10; //unambiguous since only one copy of iis inherited.
ob,j = 20;
ob.k = 30;
ob.sum = ob.i + ob, + ob.k;
cout << “Value of i is : "<< ob.ie<"\n";
cout << “Value of is : "<< ob je<"\n"; cout << “Value of kis!
cout << “Sum is :"<< ob.sum <<"\n";
"<< ob.ke<"\n";
return 0;
Dr. R N MUHAMMAD ILYAS14
Inheritance
‘One of the most important concepts in object-oriented programming is that of inheritance. This also
provides an opportunity to reuse the code functionality and fast implementation time. When creating a class,
instead of writing completely new data members and member functions, the programmer can designate that the
new class should inherit the members of an existing class. This existing class is called the base class, and the new
class is referred to as the derived class.
A class can be derived from more than one classes, which means it can inherit data and functions from
multiple base classes. To define a derived class, we use a class derivation list to specify the base classes. The
general form is
class derived-class: access-specifier base-class
Where access-specificr is onc of public, protected, or private, and basc-class is the name of a previously
defined class. If the access-specifier is not used, then it is private by default. Consider a base class Shape and its
derived class Rectangle as follows:
Single Inheritance
#inchade
using namespace std;
1] Base class
class Shape
{
public:
void setWidth(int w)
width = w;
void setHeight{int h)
height = hy;
}
protected:
int width;
int height;
%
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
return (width * height);
3
%
int main(void)
t
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
1 Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
Dr. R N MUHAMMAD ILYASMultiple Inheritance 15
include
using namespace std;
// Base class Shape
class Shape
{
public:
void setWidth(int w)
width = w;
void setHeight(int h)
height = h;
+
protected:
int width;
int height;
// Base class PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
%
// Derived class
class Rectangle: public Shape, public PaintCost
public:
int getArea()
return (width * height);
#
%
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7};
area = Rect.getAreal);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
1] Print the total cost of painting
cout << “Total paint cost: $"< Rect.getCost{area) << endl;
return 0;
Dr. R N MUHAMMAD ILYAS16
Virtual Function
If there are member functions with same name in base class and derived class, virtual functions gives
programmer capability to call member function of different class by a same function call depending upon different
context. If a base class and derived class has same function and if you write code to access that function using
pointer of base class then, the function in the base class is executed even if, the object of derived class is
referenced with that pointer variable,
If you want to execute the member function of derived class then, you can declare display( ) in the base
class virtual which makes that function existing in appearance only but, you can't call that function. In order to
make a function virtual, you have to add keyword virtual in front of a function, Virtual keyword determines if @
member function of a class can be over-ridden in its derived classes.
finclade
using namespace std;
class Car // Base class for C++ virtual function example
{
public:
virtual void Create) // virtual function for C++ virtual function example
4
cout << "Parent class: Car\n";
}
i
class Sedan: public Car {
public:
void Createt) {
cout << "Derived class: Sedan - Overridden C++ virtual function";
3
%
int main {
Car *x, *y;
x= new Car();
x->Create();
new Sedan);
y->Create);
Ihre wil produce the result as:
Parent class: Car
Derived class: Sedan - Overridden C++ virtual function
By simply remove the keyword “virtual”, the result would be
Parent class: Car
Parent class: Car
If Else (Even Odd Prog)
int maint
int num;
printi(’Enter an integer you want to check: ");
scanf{"%d" gsnum);
if((um%2)==0)
printff'%d is even.";num);
else
printf('%d is odd.” num);
retumnd;
}
Dr. R N MUHAMMAD ILYAS17
Other Example of 2D Array
include
int main () {
_ int a[5][2] = {40,0}, {1,2}, (2,4), (8,614.8);
inti, js
for (i= O;1< 5; 14+) {
for (j= 03) <2) j++) {
, Printi('al%d)[%d] = %d\n", i,j, lili bs
3
return 0;
}
ate]te]:
afe](a]}:
ati]tel:
ata}(a):
af2][e]:
a2}(2}:
af3]fe]:
af3](a]:
e[4ile]:
as](a]}:
BROURNNHOO
Dr. R N MUHAMMAD ILYAS