A Training Report File: 9 Milestone, Kaithal Road, Kurukshetra1 (Haryana)
A Training Report File: 9 Milestone, Kaithal Road, Kurukshetra1 (Haryana)
on
Submitted by
SWATI
(3521206)
BACHELOR OF TECHNOLOGY
COMPUTER SCIENCE & ENGINEERING
November, 2022
1
CERTIFICATE
2
TECHNOLOGY EDUCATION & RESEARCH INTEGRATED INSTITUTE,
KURUSHETRA
CANDIDATE’S DECLARATION
I hereby declare that the proposed work presented in the report entitled “PROGRAMMING
WITH C AND C++” in fulfillment of the requirement for the award of the Degree of Bachelor
of Technology in the Department of Computer science and Engineering of TERII
Kurukshetra University, Kurukshetra, Haryana is an authentic work carried out by me
during 3rd semester.
I further declare that no material of this report has been copied from any known source and
submitted before the award of any certificate.
SWATI
3521206
Signature
Rahul Arora
CSE(AP)
3
ACKNOWLEDGEMENT
We own our deepest gratitude to the Department of Computer Science and Engineering, TERI
College, Kurukshetra for providing. It is an Honor for us to express our gratitude to course
supervisor “Mr. Sriyank Siddhartha” for his constant support and guidance throughout the
course. We are thankful to Mr. Sriyank Siddhartha for providing the constant feedbacks
throughout the development of this report. Their suggestion throughout the development of this
project helped us to cope up with different obstacles. We are grateful to all our teachers for
their suggestions and inspirational lectures that paved towards the completion of this course.
Last but not the least, we would like to thank our colleagues for their valuable comments and
their suggestion during this course. Any kind of suggestion or criticism will be highly
appreciated and acknowledged.
Swati (3521206)
4
INDEX
C Programming Operators
3 16-19
5 C Loops 23-26
6 Array 27-29
7 Pointer 30-31
12 Conclusion 46
13 Reference 47
5
LIST OF FIGURES
6
LIST OF TABLES
1 Keywords 12
3 Arithmetic Operator 17
4 Relational Operator 17
5 Logical Operator 18
6 Bitwise Operator 18
7 Assignment Operator 19
8 Access Specifiers 40
7
C – BASIC INTRODUCTION
What is C Programming Language?
C is a programming language that is extremely popular, simple, and flexible to use. It is a
structured programming language that is machine-independent and extensively used to write
various applications.
The popularity of the language is so huge that it has made to the list of top 10 programming
languages in the world. It is widely C is a general-purpose programming language and it was
developed by Dennis Ritchie in 1972. These Programs are simply set of instructions given by
a programmer to the computer in high level language. The program execution process consists
of two steps, first it uses a compiler to translate/convert the high-level program into machine
code then execute the instruction set.
C is a general-purpose programming language which features economy of expression, modern
control flow and data structures, and a rich set of operators. C is not a "very high level"
language, nor a "big" one, and is not specialized to any particular-area of application. But its
absence of restrictions and its generality make it more convenient and effective for many tasks
than supposedly more powerful languages.
Write Features of C?
C has wide features −
o Easy to learn its fundamental concepts and as a beginner level entity in programming.
o It follows structured programming approach scheme.
o It produces efficient programs that accomplish a given task.
o It can handle low-level activities.
o It can be compiled on a variety of computer platforms.
8
Fig 1: Features of c
9
Fig 2: History of C language
Basic syntax of C
The basic syntax of the C program consists of header, main () function, variable
declaration, body, and return type of the program.
• the body of the function, we perform operations required inside the function like printing,
sum, average, sorting, searching, etc.
• The last part of the C program is the return statement which refers to returning values of
the program. If the return type is void then there will be no return statement.
• The header is the first line in the C program with extension .h which contains macro
definitions and C functions.
• Programs must contain main () function, because execution in C programming starts from
main ().
• Variable declaration in C is done inside the main function and can be used in the body
anywhere but before the main, we can also declare variables which are known as Global
variables.
• In
// Basic Syntax of C Program
#include <stdio.h>
10
// main function
int main()
{
// body
printf(" Hi This is a Basic C program ");
// return statement
return 0;
}
Fig 3: working of c
Constants in C
As the name suggests the name constants is given to such variables or values in C
programming language which cannot be modified once they are defined. They are fixed values
in a program. There can be any types of constants like integer, float, octal, hexadecimal,
character constants etc. Every constant has some range. The integers that are too big to fit into
an int will be taken as a long. Now there are various ranges that differ from unsigned to signed
bits. Under the signed bit, the range of an int varies from -128 to +127 and under the unsigned
bit, int varies from 0 to 255.
11
Variables in C
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location
Keywords in C
Keywords are generally called as pre-defined or reserved words in a programming language.
Every keyword in C language performs a specific function in a program.
• Keywords cannot be used as variable names.
• Keywords have fixed meanings, and that meaning cannot be changed.
• They are the building block of a 'C' program.
• C supports 32 keywords.
• All the keywords are written in lowercase letters.
do If static while
Table 1: Keywords
12
Data Types in C Language
The data-type in a programming language is the collection of data with values having fixed
meanings and characteristics. Some of them are an integer, floating point, character, etc.
Usually, programming languages specify the range values for a given data-type.
A data-type in C programming is a set of values and is determined to act on those values. C
provides various types of data-types, allowing the programmer to select the appropriate type
for the variable to set its value.
13
Primary data types:
These are fundamental data types in C namely integer(int), floating point(float), character(char)
and void.
Here are the five primitive or primary data types that one can find in C programming language:
1. Integer – We use these for storing various whole numbers, such as 5, 8, 67, 2390, etc.
2. Character – It refers to all ASCII character sets as well as the single alphabets, such as ‘x’,
‘Y’, etc.
3. Double – These include all large types of numeric values that do not come under either
floating-point data type or integer data type.
4. Floating-point – These refer to all the real number values or decimal points, such as 40.1,
820.673, 5.9, etc.
5. Void – This term refers to no values at all. We mostly use this data type when defining the
functions in a program.
Various keywords are used in a program for specifying the data types mentioned above. Here
are the keywords that we use:
Int Integer
Float Floating-point
Void Void
Char Character
Double Double
14
Derived data types:
Derived data types are nothing but primary datatypes but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later. Data type
determines the type of data a variable will hold. If a variable x is declared as int. it means x can
hold only integer values. Every variable which is used in the program must be declared as what
data-type it is.
[Link] - Same as any other language, Array in C stores multiple values of the same data type.
That means we can have an array of integers, chars, floats, doubles, etc.
[Link] - A pointer is just a variable that stores the address of another variable. A pointer
can store the address of variables of any data types. This allows for dynamic memory
allocations in c .
[Link] -A struct is a composite structure that can contain variables of different data types.
[Link] - With a union, you can store different data types in the same memory location. The
union can have many members, but only one member can have a value at one time. Union, is
thus, a special kind of data type in C.
15
C Programming Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators-
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
Fig 6: Operator in C
16
TYPES OF OPERATORS
1. Arithmetic Operators:
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constant and variables). These operators are
used to perform arithmetic/mathematical operations on operands.
[Link] Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operators Meanings
< is less then
<= is less than or equal to
> is greater than
=> is greater than or equal to
== is equal to
!= is not equal to
Table 4: Relational Operator
17
[Link] Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Description Example
Operator
&& Called Logical AND operator. If both the operands are non-zero, then the (A &&
condition becomes true. B) is
false.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.
[Link] Operator
During computation, mathematical operations like: addition, subtraction, multiplication,
division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
18
[Link] Operator
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is “=”
Syntax: variable name=expression (or) value (or) variable
Ex: x=10;
y=a + b; z=p
‘C’ provides compound assignment operators to assign a value to variable in order to assign a
new value to a variable after performing a specified operation.
19
Conditions Statements
20
The If-Else statement
The if-else is statement is an extended version of If. The general form of if-else is as
follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
Example:
include<stdio.h>
int main ()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
21
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The value is greater than 10
Switch statement: When there are several options and we have to choose only one option
from the available ones, we can use switch statement. Depending on the selected option, a
particular task can be performed. A task represents one or more statements.
Syntax:
switch(expression)
{
case value-1:
statement/block-1;
break;
case value-2:
statement/block-2;
break;
case value-1:
statement/block-3;
break;
default:
default- statement/block t;
break;
}
The expression following the keyword switch in any “c” expression that must yield an
integer value. It must be ab integer constants like 1,2,3. The keyword case is followed by an
integer or a character constant, each constant in each must be different from all the other.
22
C Loops
What are Loops in C?
Loop is used to execute the block of code several times according to the condition given in the
loop. It means it executes the same code multiple times so it saves code and also helps to
traverse the elements of an array.
There are 3 types of loop –
o while loop
o do – while loop
o for loop
1. while Loop –
A while loop is the most straightforward looping structure. While loop syntax in C
programming language is as follows:
Syntax of While Loop in C:
while (condition) {
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body
of the loop. If a condition is true then and only then the body of a loop is executed. After the
body of a loop is executed then control again goes back at the beginning, and the condition is
checked if it is true, the same process is executed until the condition becomes false. Once the
condition becomes false, the control goes out of the loop.
.
Fig 8: Flow chart of while loop
23
Following program illustrates while loop in C programming example:
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=4) //while loop with condition
{
printf("%d\n”, num);
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
2. do – while loop
It also executes the code until condition is false. In this at least once, code is executed whether
condition is true or false but this is not the case with while. While loop is executed only when
the condition is true.
24
As we saw in a while loop, the body is executed if and only if the condition is true. In some
cases, we have to execute a body of the loop at least once even if the condition is false. This
type of operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the body is
executed, then it checks the condition. If the condition is true, then it will again execute the
body of a loop otherwise control is transferred out of the loop.
example to print a table of number 2:
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=5);
return 0;
}
Output:
2
4
6
8
10
3. for Loop
It also executes the code until condition is false. In these three parameters are given that is
• Initialization
• Condition
• Increment/Decrement
25
The general structure of for loop syntax in C is as follows:
Syntax of For Loop in C:
for (initial value; condition; incrementation or decrementation)
{
statements;
}
For Loop:
• The initial value of the for loop is performed only once.
• The condition is a Boolean expression that tests and compares the counter to a fixed
value after each iteration, stopping the for loop when false is returned.
• The incrementation/decrementation increases (or decreases) the counter by a set
value.
Following program illustrates the for loop in C programming example:
#include<stdio.h>
int main()
{
int number;
for(number=1; number<=5; number++) //for loop to print 1-10 numbers
{
printf("%d\n”, number); //to print the number
}
return 0;
}
Output:
1
2
3
4
5
26
Array in C
What is Array in C?
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger
group. These entities or elements can be of int, float, char, or double data type or can be of
user-defined data types too like structures. However, in order to be stored together in a single
array, all the elements should be of the same data type. The elements are stored from left to
right with the left-most index being the 0th index and the rightmost index being the (n-1) index.
For example, if you want to store 100 integers, you can create an array for it.
int data [100]
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Fig 9: Array in C
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
type arrayName[arraySize];
This is called a single-dimensional array. The arraySize must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows –
Double balance[ ] = {1000.0, 2.0, 3.4, 7.0, 50.0}
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
27
Why Do We Need Arrays?
If we have a small number of elements, let us say we want 3 variables, then we can declare
them separately like var1, var2, and var3. But if we have a large number of variables then we
can use arrays to store them.
Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits.
Now in C language, you can achieve this by 2 methods. The first one is to make 100 variables
and store the numbers from 1-100 in those variables separately and then print each digit. The
second method is to create an array of size 100 and store the numbers in that array using a loop.
These digits can be printed using a single loop in linear complexity. It is clear that the second
method is more optimized and desirable than the first one as it is more convenient to store these
values in a single array rather than creating 100 variables.
Advantages of Array in C
Arrays have a great significance in the C language. They provide several advantages to the
programmers while programming. Some of them are:
o Arrays make the code more optimized and clean since we can store multiple
elements in a single array at once, so we do not have to write or initialize them
multiple times.
o Every element can be traversed in an array using a single loop.
o Arrays make sorting much easier. Elements can be sorted by writing a few lines of
code.
o Any array element can be accessed in any order either from the front or rear in O (1)
time.
o Insertion or deletion of the elements can be done in linear complexity in an array.
Types of Arrays in C:
In c programming language, arrays are classified into two types. They are as follows.
1. Single Dimensional Array / One Dimensional Array
2. Multi-Dimensional Array
[Link] Dimensional Array
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called
as one-dimensional arrays, Linear Arrays or simply 1-D Arrays.
28
Fig 10: Single Dimensional Array
Declaration of Single Dimensional Array:
We use the following general syntax for declaring and initializing a single dimensional array with size and
initial values:
Datatype arrayName [size];
[Link]-Dimensional Array
An array of arrays is called as multi-dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi-dimensional array. Multi-dimensional array
can be of two-dimensional array or three-dimensional array or four-dimensional array or
more...
Most popular and commonly used multi-dimensional array is two-dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.
29
POINTER
What is pointer in C?
The Pointer in C, is a variable that stores address of another variable. A pointer can also be
used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to
point to the next/ previous memory location. The purpose of pointer is to save memory space
and achieve faster execution time.
Syntax of a pointer
The syntax to assign the address of a variable to a pointer is:
datatype var1, *var2
Declaring a Pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
30
How to Use Pointers in C?
If we declare a variable v of type int, v will actually store a value.
Int v =0;
v is equal to zero now.
However, each variable, apart from value, also has its address (or, simply put, where it is
located in the memory). The address can be retrieved by putting an ampersand (&) before the
variable name.
&v
If you print the address of a variable on the screen, it will look like a totally random number
(moreover, it can be different from run to run).
31
C++ BASIC INTRODUCTION
32
o Rich library support: Has a rich library support (Both standard ~ built-in data
structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast
and rapid development.
o Rich library support: Has a rich library support (Both standard ~ built-in data
structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast
and rapid development.
o peed of execution: C++ programs excel in execution speed. Since, it is a
compiled language, and also hugely procedural. Newer languages have extra in-
built default features such as garbage-collection, dynamic typing etc. which slow
the execution of the program overall. Since there is no additional processing
overhead like this in C++, it is blazing fast.
o Pointer and direct Memory-Access: C++ provides pointer support which aids
users to directly manipulate storage address. This helps in doing low-level
programming (where one might need to have explicit control on the storage of
variables).
o Object-Oriented: One of the strongest points of the language which sets it apart
from C. Object-Oriented support helps C++ to make maintainable and extensible
programs. i.e. Large-scale applications can be built. Procedural code becomes
difficult to maintain as code-size grows.
o Compiled Language: C++ is a compiled language, contributing to its speed.
Applications of C++:
C++ finds varied usage in applications such as:
o Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
o Browsers (Chrome & Firefox)
o Graphics & Game engines (Photoshop, Blender, Unreal-Engine)
o Database Engines (MySQL, MongoDB, Redis etc.)
o Cloud/Distributed Systems
33
o C++ is one of every green programming languages and loved by millions of
software developers. If you are a great C++ programmer then you will never sit
without work and more importantly you will get highly paid for your work.
o C++ is the most widely used programming languages in application and system
programming. So, you can choose your area of interest of software development
34
OOPS using C++
What is OOPS?
OOP stands for Object-Oriented Programming.
Object Oriented Programing “Object oriented programming as an approach that provides a way
of modularizing programs by creating partitioned memory area for both data and functions that
can be used as templates for creating copies of such modules on demand”
OOPs, or Object-oriented programming is an approach or a programming pattern where the
programs are structured around objects rather than functions and logic. It makes the data
partitioned into two memory areas, i.e., data and functions, and helps make the code flexible
and modular.
Object-oriented programming mainly focuses on objects that are required to be manipulated.
In OOPs, it can represent data as objects that have attributes and function.
35
Features of the Object-Oriented programming
36
[Link]
Object is the physical as well as logical entity whereas class is the only logical entity.
It is a basic unit of Object-Oriented Programming and represents the real-life entities. A
C++ program creates many objects which interact by invoking methods.
[Link]
Class is a blue print which is containing only list of variables and method and no memory
is allocated for them. A class is a group of objects that has common properties.
A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type.
[Link]
Encapsulation is a process of wrapping of data and methods in a single unit is called
encapsulation. Encapsulation is achieved in C++ language by class concept. The main
advantage of using of encapsulation is to secure the data from other methods, when we make
a data private then these data only use within the class, but these data not accessible outside
the class.
[Link]
Abstraction is the concept of exposing only the required essential characteristics and
behaviour with respect to a context.
Hiding of data is known as data abstraction. In object-oriented programming language this
is implemented automatically while writing the code in the form of class and object.
37
[Link]
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented
programming.
38
ACCESS SPECIFIERS
What are access specifiers?
Data hiding is an important concept of Object-Oriented Programming, implemented with these
Access modifiers' help. It is also known as Access Specifier. Access Specifiers in a class decide
the accessibility of the class members, like variables or methods in other classes. That is, it will
decide whether the members or methods will get directly accessed by the blocks present outside
the class or not, depending on the type of Access Specifier. In a program, we need to create
methods or variables that can be accessed by the object of the same class or accessible in the
entire program. And Access Modifiers help us to specify that.
39
other classes and functions. The public members of a class can be accessed from anywhere in
the program using the (.) with the object of that class.
2. Private Access Specifiers
The private keyword is used to create private variables or private functions. The private
members can only be accessed from within the class. Only the member functions or the friend
functions are allowed to access the private data of a class or the methods of a class.
2. Private Access Specifiers
The private keyword is used to create private variables or private functions. The private
members can only be accessed from within the class. Only the member functions or the friend
functions are allowed to access the private data of a class or the methods of a class.
40
Friend class and function in C++
Friend Class: A friend class can access private and protected members of other class in
which it is declared as friend. It is sometimes useful to allow a particular class to access
private members of other class. For example, a LinkedList class may be allowed to access
private members of Node.
A friend class can access both private and protected members of the class in which it has
been declared as friend.
Syntax :
lass Node {
private:
int key;
Node* next;
/* Other members of Node Class */
Example:
#include<iostream>
using namespace std;
class A
{
int x;
public:
A()
{
x=10;
}
41
friend class B; //friend class
};
class B
{
public:
void display(A &t)
{
cout<<endl<<"The value of x="<<t.x;
}
};
main()
{
A _a;
B _b;
_b.display(_a);
return 0;
}
Output:
The value of x=10
Friend Function: Like friend class, a friend function can be given a special grant to
access private and protected members. A friend function can be:
a) A member of another class
b) A global function
• A friend function is a special function in C++ which in-spite of not being member
function of a class has privilege to access private and protected data of a class.
• A friend function is a non-member function or ordinary function of a class, which
is declared as a friend using the keyword “friend” inside the class. By declaring a
function as a friend, all the access permissions are given to the function.
• The keyword “friend” is placed only in the function declaration of the friend
function and not in the function definition.
42
• When friend function is called neither name of object nor dot
• operator is used. However, it may accept the object as argument whose value it
wants to access.
• Friend function can be declared in any section of the class i.e., public or private or
protected.
Syntax: -
class <class_name>
{
friend <return_type> <function_name>(argument/s);
};
#include<iostream>
using namespace std;
class Largest
{
int a, b, m;
public:
void set data ();
friend void finds_max(Largest);
};
43
if (t. a>t. b)
t.m=t. a;
else
t.m=t. b;
main()
{
Largest l;
l.set_data();
find_max(l);
return 0;
}
Output
Enter the First No: Enter the Second No: Maximum Number is 0
Output: -
Enter the First No: 21
Enter the Second No:32
Maximum Number is 32
44
Merits: -
• A friend function is able to access members without the need of inheriting the
class.
• Friend function acts as a bridge between two classes by accessing their private
data.
• It can be used to increase the versatility of overloaded operator.
• It can be declared either in the public or private or protected part of class.
Demerits: -
• Friend functions have access to private members of a class from outside the class
which violates the law of the data hiding.
• Friend functions cannot do any run time polymorphism in its members.
45
Conclusion
At the end of the course, one clearly understands the importance C and C++
PROGRAMMING in our daily life. By learning C, you will be able to understand
and visualize the inner workings of computer systems (like allocation and memory
management), their architecture and the overall concepts that drive programming.
As a programming language, C also allows you to write more complex and
comprehensive programs. In turn, this teaches you how to write code that is
exceedingly more efficient in C and other programming languages.
C++ has the same advantages as C, but with more features. C++ has a steep learning
curve that makes it less approachable by a novice programmer. C++ is an
intermediate-level language; learning this language will give you a much deeper
understanding of programming structure. In C++, you have to write, declare, and
explain everything in the source code, giving you a deeper knowledge of all the
program parts.
46
Reference
1. [Link]
2. [Link]
3. [Link]
47