BCom - III Semester
BCom - III Semester
History:
C programming language was developed in 1972 by Dennis Ritchie at bell
laboratories of AT&T (American Telephone & Telegraph), located
in U.S.A.
Dennis Ritchie is known as the founder of c language.
It was developed to overcome the problems of previous languages
such as B, BCPL etc.Initially, C language was developed to be
used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.
The above table shows programming languages that were developed before C
language.
STRUCTURE OF A C PROGRAM
Subprogram section:
If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
KEYWORDS
Keywords are the reserved words that have predefined meaning in that language.
These are the basic building blocks of the program. We cannot use it as a
variable name, constant name etc.C supports 32 keywords.
A list of 32 keywords in ‘c’ language is given below:
IDENTIFIERS
Identifiers refer to the names of variables, functions & arrays. Both uppercase &
lowercase letters are permitted, although lowercase letters are commonly used.
The underscore character is also permitted in identifiers.
Symbol Operator
Arithmetic Operators: C provides all the basic Name
arithmetic operators. There are five arithmetic + Addition
operators - Subtraction
* Multiplication
/ Division
% Modulus
Symbol Operator Name
> Greater Than
< Less Than
>= Greater Than Equal To
<= Less Than Equal To
FORMATTED INPUT: Input data can be entered into the computer from a
standard input device by means of the C library function scanf(). This function
can be used to enter any combination of numerical values, single characters and
strings. The function returns the number of data items that have been entered
successfully.
In general terms, the scanf() function is written as
scanf(“control string”, arg1,arg2,…,argn);
Where control string refers to a string containing certain required formatting
information and arg1, arg2,…arg n arqe arguments that specifies the address
locations where the data is stored.
Type specifiers for scanf() are
FORMAT SPECIFIER DESCRIPTION
%d Integer Format Specifier
%f Float Format Specifier
%c Character Format Specifier
%s String Format Specifier
%u Unsigned Integer Format Specifier
%ld Long int Format Specifier
if else statement:
If is a keyword, it checks only single condition.
Suppose if we want to check two conditions we
may use if..else. The general syntax of an if else
statement is,
if (condition)
{
statement1;
}
else
{
statement2;
}
The first statement or block of statements is executed if the condition is true, and
the second statement or block of statements (following the keyword else) is
executed if the condition is not true.
if-else-if Ladder:
A multi way decision can be written by using if-
else-if ladder construct. The conditions are
evaluated from the top. As soon as a true
condition is met, the associated statement
blocks get executed and rest of the ladder is by
passed. If none of the condition are met then
the finale else block gets executed. Its syntax is
if( expression1 )
statement1;
else if( expression2 )
statement2;
else
statement3;
next statement;
do while loop:
In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do
statement evaluates the body of the loop first and at the end, the condition is
checked using while statement. It means that for at least
one time, the body of the loop will be executed, even
though the starting condition inside while is initialized to
false.
It is also known as EXIT loop.
The structure of the do...while loop is as follows:
do
{
Statement;
}while (condition);
Break statement:
In C programming break is used to terminating
the loop immediately after it is encountered. The
break statement is used with conditional if
statement. The general syntax of break
statement is:
while(text expression){
if(text expression)
break;
}
The break statement can be used in terminating all the three loops as while, do
while and for.
Continue statement: it is sometimes desirable to
skip some statements inside the loop. In such
cases, continue statement is used. Continue
statement also can be used in all looping
statements.
The general syntax of the continue statement is:
while(text expression)
{
if(text expression)
continue;
}
ARRAYS
We know how to declare a variable with a specified data type, such as char, int,
float, or double. In many cases, you have to declare a set of variables that have
the same data type. Instead of declaring them individually, C allows you to
declare a set of variables of the same data type collectively as an array.
An array is a collection of variables that are of the same data type. Each item in
an array is called an element. All elements in an array are referenced by the name
of the array and are stored in a set of consecutive memory slots.
Declaring Arrays:
The following is the general form to declare an array:
data-type array-Name [array-Size];
The array indexing starts at 0. In other words, the index to the first element in an
array is 0, not 1. Therefore, the first element in the array of day is day [0].
Because there are 4 elements in the day array, the last element is day [3], not day
[4].
Initializing Arrays:
We can initialize each element in an array.
intarray_name[5] = {50,60,70,80,90};
Here the integers inside the braces ({and}) are assigned to the corresponding
elements of the array_name.
void main()
{
int i;
int marks[5]= {50,60,70,80,90};
clrscr();
for (i=0; i<5; i++)
{
printf(” marks[%d] is %d \n”, i,marks[i]);
}
getch();
}
OUTPUT:
Marks[0]=50
Marks[1]=60
Marks[2]=70
Marks[3]=80
Marks[4]=90
Two dimensional arrays will be in the form of rows and columns format.
Syntax: datatype arrayname[rows][cols];
Data type refers to the nature of the data elements in the array such as
character type, integer type, or float etc.,
array name refers to multidimensional array.
rows refers to the number of rows of the array.
cols refers to the number of columns of the array.
Two Dimensional Array in the memory:
0 1 2
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
The c language follows row major order to store the data in two-dimensional
array.
For instance the statement
int a[3][3]={{1,2,3},{4,5,6},{7,8,9} };
The above statement defines two dimensional array of order 3/3 and initializes all
its elements. The first subscript can be omitted. Hence the above definition can
be replaced by
int a[][3]={{1,2,3},{4,5,6},{7,8,9} }
Multi-dimensional Array:
Multidimensional arrays are defined in much the same manner as one
dimensional array except that a separate pair of brackets is required for each
subscript.
Thus a two dimensional array will require two pairs of square brackets, a three
dimensional array will require three pair of brackets and so on. In general terms a
multi-dimensional array definition can be written as:
data typearray name [size1][size2][size3]…..[size3];
Where the data type is built in or user defined data type, array name is the name
of the array, and size1, size2, size3….sizen are indicate the number of elements
associated with each subscript. The following are same valid array definition
statements.
int marks[2][10][5];//integer array of size 2*10*5=100elements.
char name[30][25];
Introduction:
If the program is lengthier then it is very difficult for the programmer to handle it.
such programs should be broken down into a number of small pieces called
modules and that phenomenon are called as a function.
Definition:
A function is a self-contained block of statements to perform a specific well
defined task.
By using functions, it is possible to reduce the size of a program by calling and
using them at different places in the program.
Types:
There are two types of functions available in C.
• Built in function or Library Function
• User defined function.
Arguments used in a program are of two types the formal argument and the
actual argument. The arguments used in calling function are called as actual
arguments and arguments used in the called function are called as formal
arguments.
User defined functions can be divided into four types. They are:
1. A function without parameter and without return value:
In this type of function the control is just passed to the called function and after
execution of all the statements from the control is just returned back to the called
function without any value. There is no data transfer between the calling function
and called function.
void fun( ){
printf(“hello”);
} Calling Called
void main(){ Function Function
fun( );
}
Output:
Enter two values: 4 5
Values before swapping A=4 B=5
Values after swapping A=5 B=4
Pass by Address:Rather than passing copy of actual argument here we pass the
address of actual argument. So formal argument will be pointer that holds the
address of actual argument. So performs manipulation on the actual argument
address. So in this case any changes made on the formal argument will reflect on
the actual argument.
void swap(int *,int *);
void main()
{ inta,b;
clrscr();
printf(“Enter two values:”);
scanf(“%d%d”,&a,&b);
printf(“\nValues before swapping A=%d,B=%d”,a,b);
swap(&a,&b);
printf(“\nValues after swapping A=%d,B=%d”,a,b);
}
void swap(int *x,int *y)
{ int t=*x;
*x=*y;
*y=t;
}
Output:
Enter two values: 4 5
Values before swapping A=5 B=4
Values after swapping A=5 B=4
Output : Output :
Before X = 10 Before X = 10
After X = 10 After X = 11
The basic idea behind a recursive function is that you can solve a problem by
breaking it into smaller pieces, solving each of those smaller pieces by breaking
them up into even smaller pieces, and so on.
The two basic parts of a recursive function:
1. The base case - without a base case, your recursive function will never
terminate. For functions of natural numbers, N=0 is usually the base case.
2. The recursive part - this part implements the concept that you can 'solve the
problem' by solving a smaller problem.
Types of recursion:
1. Direct recursion: a function is said to be directly recursive if it explicitly calls
itself.
2. Indirect recursion: a function is said to be indirectly recursive if it contains a
call to another function which ultimately calls it.
3. Tail recursion: a recursive function is said to be tail recursive if no operations
are pending to be performed when the recursive function returns to its caller.
When the called function returns, the returned value is immediately returned
from the calling function.
Advantages:
It is easy to use.
It represents compact programming structures.
Disadvantages:
It is slower than that of looping statements because each time function is called.
Introduction to OOP and its basic features - C++ program structure - Classes and
objects - Friend Functions- Static Functions –Constructor – Types of constructors
– Destructors - Unary Operators
Method Method
Data
Method
Method
Applications of OOP
OOP are being used in many areas of computer programming. OOP are used in
solving complicated and complex based system because it can simplify a complex
problem. The most important application of OOP include
Real- Time systems
Simulation and Modeling
Object Oriented databases
Database management systems.
Web based applications.
Hypertext, hypermedia
AI and expert systems
Neural networks and parallel programming
Decision support and office & automation systems
CIM/CAD/CAM system
Introduction To C++:
C++, as we all know is an extension to C language and was developed by “ Bjarne
stroustrup” at bell labs. C++ is an intermediate level language, as it comprises a
confirmation of both high level and low level language features. C++ is a statically
typed, free form, multi paradigm, compiled general-purpose language.
C++ is an Object Oriented Programming language but is not purely Object
Oriented. Its features like Friend and Virtual, violate some of the very important
OOPS features, rendering this language unworthy of being called completely
Object Oriented. It’s a middle level language.
Features
Simple
Machine Independent or Portable
Mid-level programming language
Structured programming language
Rich Library
Memory Management
Fast Speed
Pointers
Recursion
Extensible
Object Oriented
Compiler based
1) Simple: C++ is a simple language in the sense that it provides structured
approach (to break the problem into parts), rich set of library functions, data
types etc.
2) Machine Independent or Portable: Unlike assembly language, c programs
can be executed in many machines with little bit or no change. However, it is not
platform-independent.
3) Mid-level programming language: C++ is also used to do low level
programming. It is used to develop system applications such as kernel, driver etc.
It also supports the feature of high level language. That is why it is known as
mid-level language.
4) Structured programming language: C++ is a structured programming
language in the sense that we can break the program into parts using functions.
So, it is easy to understand and modify.
5) Rich Library: C++ provides a lot of inbuilt functions that makes the
development fast.
Class:
Class is a model for creating objects which consists of data members and member
functions. Data members are also known as properties or variables and member
functions are also known as actions or methods.
Declaring a Class: class may be declared as,
class Class_Name
{
< access specifiers > :
data members;
member functions();
< access specifiers > :
data members;
member functions();
}
Object:
These are the basic run time
entities in an object oriented
system. They may be represent
a person, a place, a bank
account, a table of data or any
item that the program to
handle. They may also represent
user defined data such as
vectors, trees and lists.
Polymorphism:
Polymorphism is a Greek word. Poly means many and morphism means forms.
Therefore, Polymorphism means many forms.
I.e., Ability to take more than one form are known as Polymorphism
The different classification of polymorphism can be shown above.
Data 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.
Encapsulation:
Packing of data or wrapping of data are known as Encapsulation.
In other words, to store data or functions in a single unit is known as
Encapsulation.
public:
staticvoid Print(){//static member function
cout<<"Value of X: "<< X <<endl;
cout<<"Value of Y: "<< Y <<endl;
}
};
voidmain(){
Demo OB;
Copy Constructor:
Copy constructors are used when the compiler has to create a temporary object of
class object. Copy constructors are used in the following situations.
The initialization of an object by another object of the same class.
Return of objects as a function value.
Stating the object as by value parameters of a function.
The copy constructor can accept a single argument of reference to same class
type.
Syntax: class_name::class_name(class_name&ptr)
Eg: X :: X(X &ptr)
The copy constructor n may be used in the following format also using a const
Keyword. Syntax:
class_name::class_name(constclass_name&ptr)
public:
SampleCopyConstructor(int x1, int y1){
x = x1;
y = y1;
}
/* Copy constructor */
SampleCopyConstructor(constSampleCopyConstructor&samp){
x = sam.x;
y = sam.y;
}
Default Constructor:
The default constructor is a special member function which is invoked by C++
compiler, without any argument for initializing the objects of a class.
The purpose of default constructor is to construct a default object of that class
type.
Syntax: class class_name{
access specifier:
data members;
member functions();
class_name(){
-----------;
-----------;
}
};
// program to print student details using a default constructor
#include<iostream.h>
#include<conio.h>
class Student {
private:
char ename[20];
long introllno;
char gender;
float height,weight;
public:
Student();
void display();
};
Student::Student() {
ename[10]=’\0’;
rollno=0;
gender=’\0’;
Parameterized Constructor:
A constructor, which has parameters, is called parameterized constructor. It is
used to provide different values to different objects of a class.
class class_name {
Access Specifier :
Member - Variables
Member - Functions
public:
class_name(variables) {
// Constructor code
}
//... other Variables & Functions
}
Overloaded Constructor:
The overloaded constructor is a concept in oops in which the same constructor
name is called with different arguments, the constructor will be invoked
automatically by the compiler to initialize the objects.
Or
Writing two or more constructors with a same name but different types of
arguments or number of arguments are known as Constructor Overloading.
// Program to demonstrate to print Overloaded Constructor
#include<iostream.h>
#include<conio.h>
class abc {
public:
abc();
abc(int);
abc(float);
abc(int,float);
};
void main() {
abcobj;
clrscr();
abc(10);
abc(75.25);
abc(30, 10.25);
getch();
}
Destructors:
A Destructor is a function that automatically executes when an object is
destroyed. The primary usage of destructor function is to release space.
Syntax: class class_name{
access specifiers :
data members;
member functions();
class_name(); // constructor
~class_name(); // destructor
};
Rules for Destructors:
A destructor function name is the same as that of a class name. The first
character of the destructor name must be a “Tilde(~)”.
It is declared with no return type, not even void.
It takes no arguments and therefore cannot be overloaded.
It should have public access specifier in class declaration.
Program to demonstrate to print destructors
#include<iostream.h>
#include<conio.h>
// declare a class
~Hello() { // Destructor
cout<< "Destructor is Called." <<endl;
}
// Member Function
int display() {
cout<< "Hello, Programmer." <<endl;
}
};
void main() {
Hello obj1; // create an object
obj1.display(); // Member function called
getch();
}
Output
Hey look I am in constructor
Hello, Programmer.
Operator Overloading:
Operator overloading is an important concept in C++. It is a type of polymorphism
in which an operator is overloaded to give user defined meaning to it. Overloaded
operator is used to perform operation on user-defined data type.
Operator that cannot be overloaded are as follows:
➢ Scope operator (::)
➢Sizeof
➢member selector(.)
➢member pointer selector(*)
➢ ternary operator(?:)
Syntax of Operator Overloading:
return_typeclass_name : : operator op(argument_list)
{
// body of the function.
}
class String {
public:
char str[20];
void accept_string() {
cout<<"\n Enter String : ";
cin>>str;
}
void display_string() {
cout<<str;
}
String operator+(String x) { //’+’ operator overloading
String s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
};
void main()
{
String str1, str2, str3;
str1.accept_string();
str2.accept_string();
cout<<"\n\n First String is : ";
str1.display_string(); //Displaying First String
cout<<"\n\n Second String is : ";
str2.display_string(); //Displaying Second String
str3 = str1 + str2; //String is concatenated. Overloaded '+' operator
cout<<"\n\n Concatenated String is : ";
str3.display_string();
}
/* (2) C++ Program to Compare Two Strings using operator "==" Overloading */
#include<iostream>
#include<stdio.h>
#include<string.h>
class String {
char str[20];
return 0;
}
};
void main() {
String s1,s2;
getch();
}
INHERITANCE
Inheritance is one of the most powerful and essential characteristics of
OOP.
Types of Derivation:
C++ provides a no. of ways to establish access to class members. One such
access control mechanism is the derived class are declared. A derived class can
be declared with one of the access control specifiers private, public or protected
and thus there are 3 types of derivations. The access specifier determines how the
derived class inherits the elements of the base class.
Public Derivation:
When the access specifier for the inherited base class is public, all public member
of the base class become public member of the derived class. All protected
members of the base class become protected members of the derived class. All
Private Derivation:
If the access specifier is private, all public members of the base class becomes
private member of the derived class and they are accessible by the member
function of the derived class. All protected members of the base class also
becomes private members of the derived class. All private members of the base
class are remain to it and are inaccessible by the derived class.
Eg: class baseA{
private:
public:
int a;
};
class derived: private baseA{
private:
public:
void read(){
cin>>a;
}
void display(){
cout<<a;
}
};
void main(){
derived sample;
sample.read();
sample.disp();
}
Protected Derivation:
A base class can also be inherited with the access specifier protected by a derived
class then the public and protected members of the base class become protected
member of the derived class. All private members of the base class remains
Types of Inheritance:
Inheritances are of five types.
Singleinheritance
MultipleInheritance
MultilevelInheritance
HierarchicalInheritance
Hybrid, and
MultipathInheritance
Single Inheritance
Single Inheritance is the process of creating new
classes from an existing base class. The existing class
is known as the base class and the newly created
class is called as derived class.
Single inheritance is the ability of a derived class to
inherit the member functions and data members of
the existing base class.
void main() {
programmer p;
clrscr();
cout<<"Salary :"<<p.salary<<"\n";
cout<<"Bonus :"<<p.bonus<<"\n";
getch();
}
MULITPLE INHERITANCE
It is the process of creating a new class from more than one base classes.
The syntax for multiple inheritance is similar to that of single inheritance.
Syntax:
class baseA{
;
;
};
Class baseB{
;
;
};
Class C : public baseA, public baseB{
;
;
};
Hierarchical Inheritance:
Hierarchical Inheritance in C++ refers to the type
of inheritance that has a hierarchical structure
of classes. A single base class can have multiple
derived classes, and other subclasses can further
inherit these derived classes, forming a hierarchy of classes.
classA{
public void methodA(){
//Do Something
}
};
class B : public A{
void main() {
Dog dog1; // Create object of Dog class
cout<< "Dog Class:" <<endl;
dog1.info(); // Parent Class function
dog1.bark();
Hybrid Inheritance
The process of combining more than one type of Inheritance together while
deriving subclasses in a program is called a Hybrid Inheritance.
class A {
// block of statement(s)
}:
class B: public A { // class B derived from a single class A -- follows single
inheritance
// block of statement(s)
};
class C {
// block of statement(s)
};
class D: public B, public C {
// class D derived from two classes, class B and class C -- follows multiple
//inheritance
// block of statement(s)
};
void main() {
Cow c;
}