C - C - and Oop-2
C - C - and Oop-2
1 + 2 + 3 + 4 +.................................. + 𝑛 =?
#include<stdio.h>
int main()
{
int n,sum=0;
printf("Enter the number of term:");
scanf("%d",&n);
sum=(n*(n+1))/2;
printf("Summation is: %d",sum);
return 0;
}
Sum of the series
2 2 2 2
1 + 2 + 3 +............................. + 𝑛 =?
#include<stdio.h>
int main()
{
int n,sum=0;
printf("Enter the number of term:");
scanf("%d",&n);
sum=(n*(n+1)*(2*n+1))/6;
//By using loop….from 1 to n;
//sum += i*i;
printf("Summation is: %d",sum);
return 0;
}
Sum of the series
3 3 3 3
1 + 2 + 3 +............................. + 𝑛 =?
#include<stdio.h>
#include<math.h>
int main()
{
int n,sum=0;
printf("Enter the number of term:");
scanf("%d",&n);
sum=pow((n*(n+1))/2,2);
printf("Summation is: %d",sum);
return 0;
}
Arithmetic progression(AP)....
#include<stdio.h>
#include<math.h>
int main()
{
int a, d, n,sum=0;
printf("Enter first term:");
scanf("%d",&a);
printf("Enter the difference:");
scanf("%d",&d);
printf("Enter the number of term:");
scanf("%d",&n);
sum=(n*(2*a+(n-1)*d))/2;
printf("Summation is: %d",sum);
}
Geometric progression(GP)....
discriminant = b * b - 4 * a * c;
return 0;
}
Dynamic Memory Allocation:
C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like
Array) is changed during the runtime.
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any
form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default
garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified
number of blocks of memory of the specified type. it is very much similar to malloc() but has two
different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing
it.
Syntax of free() in C
free(ptr);
C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of malloc
or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory
maintains the already present value and new blocks will be initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables or a memory
location. We can access and manipulate the data stored in that memory location using pointers.
As the pointers in C store the memory addresses, their size is independent of the type of data they are
pointing to. This size of pointers in C only depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
datatype * ptr;
where
● ptr is the name of the pointer.
● datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to functions,
structures, etc.
Benefits(use) of pointers in c:
Pointers provide direct access to memory
Pointers provide a way to return more than one value to the functions
Reduces the storage space and complexity of the program
Reduces the execution time of the program
Provides an alternate way to access array elements
Pointers can be used to pass information back and forth between the calling function and called
function.
Pointers allows us to perform dynamic memory allocation and deallocation.
Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
Pointers allows us to resize the dynamically allocated memory block.
Addresses of objects can be extracted using pointers
Difference between the Call by Value and Call by Reference in C++
Call by Value in C++
In the call-by-value method, function arguments are passed by copying the value of the actual
parameter, ensuring the original values remain unchanged. The value is copied to the formal parameter.
One is the original copy and the other is the function copy. Any changes made to the parameters within
the function do not change the original values outside the function.
Call by Reference in C++
In the call-by-reference method, the memory address (reference) of the actual parameter is passed to
the function, allowing direct access and modification of the original values. The actual and the formal
parameters point to the same memory address. Any changes made to the parameters within the
function are directly reflected in the original values outside the function.
Difference between the Call by Value and Call by Reference in C++
The major difference between the two methods of passing the parameters is given below:
Feature Call by Value Call by Reference
Value Passed In this method, the value of the variable is In call by reference memory address of the
passed to the function. variable is passed.
Scope of In this method, the original value remains In this method, the changes made are
Changes unchanged even when we make changes in reflected in the original variable.
the function.
Performance It may require extra memory and time to It is more memory and time efficient as
copy so less efficient. compared to “call by value”.
Memory The memory addresses of the actual and The actual and the formal parameters point at
Location formal parameters are different. the same memory address.
Applications Mainly used to pass values for small data It is used when we want to modify the original
or when we do not want to change original value or save resources.
values.
Class b:public a
{
public:
void display(){ cout << "bye";}
};
The difference between function overloading and overriding.
Threads: A thread is a basic unit of execution of any process. A program comprises many processes and
all the processes comprise much simpler units known as threads. So, the thread can be referred to as the
basic unit of a process or it is the simpler unit that tother makes the CPU utilization
static keyword
static keyword has different meanings when used with different types. We can use static keywords with:
1. Static Variables: Variables in a function, Variables in a class
2. Static Members of Class: Class objects and Functions in a class Let us now look at each one of
these uses of static in detail.
Static Variables
Static variables in a Function: When a variable is declared as static, space for it gets allocated for the
lifetime of the program. Even if the function is called multiple times, space for the static variable is
allocated only once and the value of the variable in the previous call gets carried through the next
function call. This is useful for implementing coroutines in C/C++ or any other application where the
previous state of function needs to be stored.
Static Members of Class
Class objects as static: Just like variables, objects also when declared as static have a scope till the
lifetime of the program. Consider the below program where the object is non-static.
Examples of using the Static Keyword in C Programs
The static keyword in c is used to define variables and functions that have a limited scope and a static
lifetime. Here are some examples of how the static keyword can be used in C programs:
Static variables:
C
void myFunction() {
static int count = 0;
count++;
printf(“The function has been called %d times.n”, count);
}
In the above example, the count variable is declared as a static variable inside the myFunction function.
Since static variables retain their values between function calls, the count variable will be incremented
each time the function is called, and the value will be retained across function calls.
Static functions:
C
static int myHelperFunction(int a, int b) {
return a + b;
}
int myFunction(int a, int b) {
return myHelperFunction(a, b);
}
In this example, the myHelperFunction function is declared as a static function. Since static functions
have a limited scope, they can only be called within the same file where they are defined. The
myFunction function calls the myHelperFunction function, which can be considered as a utility function
that is used only within the same file.
Static variables with external linkage:
C
static int x = 0;
void incrementX() {
x++;
}
int getX() {
return x;
}
In this example, the x variable is declared as a static variable with external linkage. This means that the
variable is only visible within the same file, but it can be accessed from other functions within the same
file. The incrementX function increments the x variable, and the getX function returns the value of x.
Overall, the static keyword in c provides a way to define variables and functions with a limited scope and
a static lifetime, which can be useful for managing memory more efficiently, improving performance, and
reducing potential problems such as naming conflicts and poor encapsulation.
What is Structure?
Structure is a user-defined data type in C programming language that combines logically related data
items of different data types together.
All the structure elements are stored at contiguous memory locations. Structure type variable can store
more than one data item of varying data types under one name.
Enumeration (enums)
Enum is short for “Enumeration”. It allows the user to create custom data types with a set of named
integer constants. The “enum” keyword is used to declare an enumeration. Enum simplifies and makes
the program more readable.
Syntax
enum enum_name {const1, const2, ..., constN};
Typedef
typedef is used to redefine the existing data type names. Basically, it is used to provide new names to the
existing data types. The “typedef” keyword is used for this purpose;
Syntax
typedef existing_name alias_name;
Differences between Structure and Union
Differences between Structure and Union are as shown below in tabular format as shown below as
follows:
C – Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A loop
statement allows programmers to execute a statement or group of statements multiple times without
repetition of code.
There are mainly two types of loops in C Programming:
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before entering
the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the
loop body. The loop body will execute at least once, irrespective of whether the condition is true
or false. do-while Loop is Exit Controlled loop.
for Loop
for loop in C programming is a repetition control structure that allows programmers to write a loop that
will be executed a specific number of times. for loop enables programmers to perform n number of steps
together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test
condition. If the test condition will become false then it will break from the while loop else body will be
executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least
once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
Escape Sequence in C
The escape sequence in C is the characters or the sequence of characters that can be used inside the
string literal. The purpose of the escape sequence is to represent the characters that cannot be used
normally using the keyboard. Some escape sequence characters are the part of ASCII charset but some
are not.
Different escape sequences represent different characters but the output is dependent on the compiler
you are using.
Escape Sequence List
Escape Name Description
Sequence
\a Alarm or Beep It is used to generate a bell sound in the C program.
\b Backspace It is used to move the cursor one place backward.
\f Form Feed It is used to move the cursor to the start of the next logical
page.
\n New Line It moves the cursor to the start of the next line.
\r Carriage Return It moves the cursor to the start of the current line.
\t Horizontal Tab It inserts some whitespace to the left of the cursor and moves
the cursor accordingly.
\v Vertical Tab It is used to insert vertical space.
\\ Backlash Use to insert backslash character.
\’ Single Quote It is used to display a single quotation mark.
\” Double Quote It is used to display double quotation marks.
\? Question Mark It is used to display a question mark.
\ooo Octal Number It is used to represent an octal number.
\xhh Hexadecimal Number It represents the hexadecimal number.
Tokens in C
A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword
which is not allowed. You cannot redefine keywords. However, you can specify the text to be substituted
for keywords before compilation by using C preprocessor directives. C language supports 32 keywords
which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Note: The number of keywords may change depending on the version of C you are using. For example,
keywords present in ANSI C are 32 while in C11, it was increased to 44. Moreover, in the latest c23, it is
increased to around 54.
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and arrays. These
are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter
or the underscore(_) as a first character. Identifier names must differ in spelling and case from any
keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you
can use the identifier in later program statements to refer to the associated value. A special identifier
called a statement label can be used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
● They must begin with a letter or underscore(_).
● They must consist of only letters, digits, or underscore. No other special character is allowed.
● It should not be a keyword.
● It must not contain white space.
● It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,
● main: method name.
● a: variable name.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;
4. C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null character
indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character is
enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
5. C Token – Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used for
some other purpose. Some of these are listed below:
● Brackets[]: Opening and closing brackets are used as array element references. These indicate
single and multidimensional subscripts.
● Parentheses(): These special symbols are used to indicate function calls and function
parameters.
● Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
● Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
● Colon(:): It is an operator that essentially invokes something called an initialization list.
● Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
● Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
● Assignment operator(=): It is used to assign values and for logical operation validation.
● Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
● Period (.): Used to access members of a structure or union.
● Tilde(~): Bitwise One’s Complement Operator.
6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The data
items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified as
follows:
● Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators.For Example increment and decrement operators
● Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
● Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.
class Room {
public:
double length;
double breadth;
double height;
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}
};
int main()
{
room room1,room2;
return 0;
}
Polymorphism
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form. A person at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So the same person
possesses different behavior in different situations. This is called polymorphism. An operation may
exhibit different behaviors in different instances. The behavior depends upon the types of data used in
the operation. C++ supports operator overloading and function overloading.
● Operator Overloading: The process of making an operator exhibit different behaviors in different
instances is known as operator overloading.
● Function Overloading: Function overloading is using a single function name to perform different
types of tasks. Polymorphism is extensively used in implementing inheritance.
Inheritance
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important features of Object-Oriented Programming.
● Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
● Super Class: The class whose properties are inherited by a sub-class is called Base Class or
Superclass.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime. C++
has virtual functions to support this. Because dynamic binding is flexible, it avoids the drawbacks of static
binding, which connected the function call and definition at build time.
Message Passing
Objects communicate with one another by sending and receiving information. A message for an object is
a request for the execution of a procedure and therefore will invoke a function in the receiving object
that generates the desired results. Message passing involves specifying the name of the object, the
name of the function, and the information to be sent.
Constructor:
A constructor is a member function of a class that has the same name as the class name.It is a special
type of member function that is used to initialize the data members for an object of a class automatically
when an object of the same class is created. It can either accept the arguments or not. It is used to
allocate memory to an object of the class. It is called whenever an instance of the class is created. It can
be defined manually with arguments or without arguments. There can be many constructors in a class. It
can be overloaded, but it can not be inherited or virtual. It has no return type, not even a void.
Syntax:
ClassName()
{
//Constructor's Body
}
Default Constructors
The default constructor is the most basic type of constructor. We can define the default constructor as
the constructor that does not take any argument. The default constructor is also known as the
no-parameter constructor
Parameterized Constructors
Parameterized constructor is a type of constructor in which we provide the parameters.
So, we can define the parameterized constructor as the constructor which can take the arguments that
help in object initialization.
The parameterized constructor is used to initialize all the class elements at the time of object creation
with the values present in the argument.
Copy Constructors
As the name suggests, a copy constructor is a constructor that initializes an object using another object
of the same class. We usually use the copy constructor to copy data from one object to another.
Destructor:
Like a constructor, Destructor is also a member function of a class that has the same name as the class
name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while
the object of the class is freed or deleted. In a class, there is always a single destructor without any
parameters so it can’t be overloaded. It is always called in the reverse order of the constructor. if a class
is inherited by another class and both the classes have a destructor then the destructor of the child class
is called first, followed by the destructor of the parent or base class.
Syntax:
~ClassName()
{
//Destructor's Body
}
// Driver Program
int main()
{
int n = 15;
if (isPrime(n))
cout << "Yes";
else
cout << "No";
return 0;
}