C - Programming - COM 121
C - Programming - COM 121
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
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
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.
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
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>
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
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.
Logical Operators
Page |9
Assignment Operators
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
}
}
}
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.
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
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];
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.
#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
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
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
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
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
#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
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
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.
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.
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
}
DasgfdfDFDKFHOEI
Tachia Saater