Procedural and Object Oriented Programming of TU IT Adhikrit
Concept of Procedural Programming
Procedural programming is a conventional programming paradigm in which a complex task is broken down into a set of self-contained and sufficiently small functions or modules.
This paradigm uses a top down approach in the program design.
Programming languages like C, Pascal, FORTRAN, BASIC, etc are Procedure Oriented Programming languages.
They are also known as structured or modular programming languages.
Procedural programming is a conventional programming paradigm in which a complex task is broken down into a set of self-contained and sufficiently small functions or modules.
This paradigm uses a top down approach in the program design.
Programming languages like C, Pascal, FORTRAN, BASIC, etc are Procedure Oriented Programming languages.
They are also known as structured or modular programming languages.
As can be seen from the figure, in a procedure oriented program, a complex program is broken down in terms of self contained modules called functions. These functions interact with each other through the function calls.
A. Characteristics of POP
i. Emphasis is given on the functions or algorithm.
ii. A large program is divided into functions.
iii. Most of the functions use global variables/data.
iv. Data can flow freely among the functions.
v. Use a top down approach in the program design.
B. Advantages of POP
i. It is very easy to write and follow.
ii. It is easy to debug.
C. Disadvantages of POP
i. It is difficult to maintain the code for larger programs using the POP paradigm.
ii. Lack of code reusability.
iii. Lack of data hiding.
iv. Lack/ of other modern object oriented programming features.
Introduction to C
C is a procedural programming language initially developed by Dennis Ritchie in 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system.
The main features of C language include low-level access to memory, a simple set of keywords, and a clean style. These features make C language suitable for system programming like an operating system or compiler development.
C is a procedural programming language initially developed by Dennis Ritchie in 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system.
The main features of C language include low-level access to memory, a simple set of keywords, and a clean style. These features make C language suitable for system programming like an operating system or compiler development.
The main features of the C language include:
General Purpose and Portable
Procedural Programming Language
Low-level Memory Access
Fast Speed
Clean Syntax
These features make the C language suitable for system programming like an operating system or compiler development.
Features of C
Here are some of the most important features of the C language:
Procedural Language
Fast and Efficient
Modularity
Statically Type
General-Purpose Language
Rich set of built-in Operators
Libraries with Rich Functions
Middle-Level Language
Portability
Easy to Extend
1. Procedural Language
In a procedural language like C step by step, predefined instructions are carried out. A C program may contain more than one function to perform a particular task. New people to programming will think that this is the only way a particular programming language works. There are other programming paradigms as well in the programming world. Most of the commonly used paradigm is an object-oriented programming language.
2. Fast and Efficient
Newer languages like Java, python offer more features than C programming languages but due to additional processing in these languages, their performance rate gets down effectively. C programming language as the middle-level language provides programmers access to direct manipulation with the computer hardware but higher-level languages do not allow this. That’s one of the reasons C language is considered the first choice to start learning programming languages. It’s fast because statically typed languages are faster than dynamically typed languages.
3. Modularity
The concept of storing C programming language code in the form of libraries for further future uses is known as modularity. This programming language can do very little on its own, most of its power is held by its libraries. C language has its own library to solve common problems.
4. Statically Type
C programming language is a statically typed language. Meaning the type of variable is checked at the time of compilation but not at run time. This means each time a programmer types a program they have to mention the type of variables used.
5. General-Purpose Language
From system programming to photo editing software, the C programming language is used in various applications. Some of the common applications where it’s used are as follows:
Operating systems: Windows, Linux, iOS, Android, OXS
Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.
6. Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which are used in writing complex or simplified C programs.
7. Libraries with Rich Functions
Robust libraries and functions in C help even a beginner coder to code with ease.
8. Middle-Level Language
As it is a middle-level language, it has the combined form of both capabilities of assembly language and features of the high-level language.
9. Portability
C language is lavishly portable as programs that are written in C language can run and compile on any system with either no or small changes.
10. Easy to Extend
Programs written in C language can be extended means when a program is already written in it then some more features and operations can be added to it.
Beginning with C Programming
Writing the First Program in C
The following code is one of the simplest C programs that will help us understand the basic syntax structure of a C program.
Example:
#include <stdio.h>
int main(void)
{
// This prints "Hello World"
printf("Hello World");
return 0;
}
Output
Hello World
difference between C and C++
While C and C++ sound familiar, the usage and features of both languages differ to a certain extent. C++ is a superset and successor to the C language that uses an entirely different set of programming concepts. C is a procedural programming language, whereas C++ provides OOP support.
The following highlights the differences between the two languages:
C is a procedural language that provides no support for objects and classes. C++ is a combination of OOP and procedural programming languages.
C has 32 keywords and C++ has 63 keywords.
C supports built-in data types, while C++ supports both built-in and user-defined data types.
C doesn't have access modifiers, whereas C++ does.
C uses the <stdio.h> header file for input and output operations and C++ uses the <iostream.h> header file for input and output operations.
C can't hide data, while C++ is secure and provides encryption.
There's no direct exception handling support in C, but C++ supports it.
C doesn't support function and operator overloading, but C++ does.
In C, the main() function calls are made through other functions used in the code, but C++ doesn't provide that functionality.
Reference variables aren't supported by C, but C++ supports them.
Keyword and Identifier
Every programming language has Keywords and Identifiers, which are only understood by its compiler. Identifiers and Keywords in the C Language are the building block of any program. An Identifier is user-defined, which means you can specify identifiers while writing the C language program. While Keywords are predefined, which means the C language has a list of keywords. Let us discuss keywords and identifiers in detail.
Every programming language has Keywords and Identifiers, which are only understood by its compiler. Identifiers and Keywords in the C Language are the building block of any program. An Identifier is user-defined, which means you can specify identifiers while writing the C language program. While Keywords are predefined, which means the C language has a list of keywords. Let us discuss keywords and identifiers in detail.
Keywords
In every programming language, there are certain reserved words that are used internally and have some meaning for the language. These words are called Keywords. Keywords help in defining any statement in the program.
Here are some useful points related to Keywords.
We can not use a keyword as an identifier.
Keywords are always written in lowercase.
Keywords can only contain alphabetical characters.
A keyword is a reserved word whose meaning is already defined in the compiler.
Keywords have fixed meanings, and we can not change the meaning of keywords.
There are only 32 keywords in C language, which are given below
auto,signed,int,unsigned,break,default,float,short,case,enum,double,struct,char,goto,const,switch,do,register,continue,typedef,extern,,sizeof,for,volatile,if,void,long,whileelse,return,static,,union
Identifiers
All the words we use in our programs are always keywords or identifiers. Keywords are predefined words and can not be changed by the user, while Identifiers are user-defined words used to give names to entities like variables, functions, arrays, structures, etc. Identifiers are created to provide a unique name to an entity to identify it during the program's execution.
For example
int weight;
float height;
In the above example, int and float are Keywords, and weight and height are Identifiers.
Types of Identifiers
External identifier
Internal identifier
External Identifier
The identifier which is used in the external linkage is known as an external identifier. The external identifiers can be function names, global variables.
Internal Identifier
The identifier which is not used in the external linkage is known as an internal identifier. The internal identifiers can be local variables.
Rules for defining Identifiers
The first character of each identifier should be an alphabet or an underscore.
A Keyword cannot be represented as an identifier.
Identifiers should not begin with any numerical digit.
The name should be formed using only letters, numbers, or underscore.
Since C language is case-sensitive, the uppercase and lowercase letters are considered different. For example, value, Value, and VALUE are three different identifiers.
Identifiers are generally given meaningful names. Some valid identifiers names are Value, net_val, _data, mark, etc.
An identifier name may be arbitrarily long. But ANSI standard compilers recognize 31 characters.
Differences between Keyword and Identifier
Identifier
Keywords are predefined words, which means the C language has a list of keywords.
Keywords always start with a lowercase letter.
Keywords must be written in a lowercase letter.
Keywords can only contain alphabetical characters.
There is no special symbol or punctuation used.
Keywords specify the type of entity.
Examples of keywords are char, for, while, else, int, if, etc.
Identifier
Identifiers are user-defined words, which means you can specify identifiers while writing the C language program.
The first character of each identifier should be an alphabet or an underscore.
Identifiers can be written in both lowercase and uppercase letters.
Identifiers can consist of alphabetical characters, digits, and underscores.
There is no punctuation or special symbol, except the underscore, is used.
Identifiers classify the name of the entity.
Examples of identifiers are Value, _data, height, mark, etc.
Data type
An attribute that identifies a piece of data and instructs a computer system on how to interpret its value is called a data type.
The term "data type" in software programming describes the kind of value a variable possesses and the kinds of mathematical, relational, or logical operations that can be performed on it without leading to an error. Numerous programming languages, for instance, utilize the data types string, integer, and floating point to represent text, whole numbers, and values with decimal points, respectively.
An interpreter or compiler can determine how a programmer plans to use a given set of data by looking up its data type.
The data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc.
An attribute that identifies a piece of data and instructs a computer system on how to interpret its value is called a data type.
The term "data type" in software programming describes the kind of value a variable possesses and the kinds of mathematical, relational, or logical operations that can be performed on it without leading to an error. Numerous programming languages, for instance, utilize the data types string, integer, and floating point to represent text, whole numbers, and values with decimal points, respectively.
An interpreter or compiler can determine how a programmer plans to use a given set of data by looking up its data type.
The data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc.
The data comes in different forms. Examples include:
your name – a string of characters
your age – usually an integer
the amount of money in your pocket- usually decimal type
today's date - written in date time format
Common Data Types in Programming:
1. Primitive Data Types:
Primitives are predefined data types that are independent of all other kinds and include basic values of particular attributes, like text or numeric values. They are the most fundamental type and are used as the foundation for more complex data types. Most computer languages probably employ some variation of these simple data types.
Examples
Integer (int)
represent numeric data type for numbers without fractions
ex:-300, 0 , -300
Floating Point (float)
represent numeric data type for numbers with fractions
ex:-34.67, 56.99, -78.09
Character (char)
represent single letter, digit, punctuation mark, symbol, or blank space
ex:-a , 1, !
Boolean (bool)
True or false values
ex:-true- 1, false- 0
Date
Date in the YYYY-MM-DD format (ISO 8601 syntax)
ex:-2024-01-01
Time
Time in the hh:mm:ss format for the time of day, time since an event, or time interval between events
ex:-12:34:20
Datetime
Date and time together in the YYYY-MM-DD hh:mm:ss format
ex:-2024 -01-01 12:34:20
2. Composite Data Types:
Composite data types are made up of various primitive kinds that are typically supplied by the user. They are also referred to as user-defined or non-primitive data types. Composite types fall into four main categories: semi-structured (stores data as a set of relationships); multimedia (stores data as images, music, or videos); homogeneous (needs all values to be of the same data type); and tabular (stores data in tabular form).
Example
String (string)
Sequence of characters, digits, or symbols—always treated as text
ex:-hello , ram , i am a girl
array
List with a number of elements in a specific order—typically of the same type
ex:-arr[4]= [0 , 1 , 2 , 3 ]
pointers
Blocks of memory that are dynamically allocated are managed and stored
ex:-*ptr=9
3. User Defined Data Types:
A user-defined data type (UDT) is a data type that derived from an existing data type. You can use other built-in types already available and create your own customized data types.
Example:-
Enumerated Type (enum)
Small set of predefined unique values (elements or enumerators) that can be text-based or numerical
ex:-Sunday -0, Monday -1
Structure
allows to combining of data items of different kinds
ex:-struct s{ ...}
Union
contains a group of data objects that can have varied data types
ex:-union u {...}
Statement
https://telgurus.co.uk/what-is-statement-in-programming/
A statement is a command that the programmer gives to the computer.
Statement in a programming means any line of code that instructs the compiler to perform a specific task.
A computer program is a set of such statements. There can be multiple types of statements in a program code that controls the input and output of the actions that a program is designed for.
Role of a statement in a program
It’s the computer program that tells the computer to perform or to take action. A statement can be a set of symbols, numbers or pneumonics used in a program.
For example:
int x;
This is a simple declaration statement from C language which declares an integer variable named ‘x’.
Types of programming statements
A program consists of various types of statements.
There are essentially seven types of programming statements. Let’s have a look.
Declaration statements
Labeled statements
Expression statements
Selection statements
Iteration statements
Compound statements
Jump statements
Now, let’s discuss them in detail.
1). Declaration statements
As mentioned in the above example, a declaration statement is used to introduce a variable or an identifier into the program or module.
2). Labeled statements
These statements usually contain a label and are used to direct the flow of execution in a program.
Considering the C/C++ language, labels are used for redirecting the control to “switch” and “goto” statements. It can be a case label or a default label in a switch statement.
In C/C++ it is must to use a colon(:) after a label to define it.
For a switch statement, it is written as:
case label_expr : statement
This means that control of the program will reach this point if the label or the expression of the switch gets matched with that of the program.
You need to give a default label, which will make the thing run in case nothing matches with the labels of the switch statement.
3). Expression statements
With perspective to C/C++, any statement which is followed by a semicolon (;) is termed as an expression.
Example: The input/output commands such as printf and scanf statements are a typical example of expression statements.
4). Selection statements
These statements help to make a decision using “if” clause.
In C/CPP there are three types of selection statements:
1. IF Statement
Syntax:
if (expression)
statement_1;
Here, if the expression is true then, program control executes statement_1 else leaves.
2. IF-ELSE Statement
Syntax:
if (expression)
statement_1;
else
statement_2;
Here, if the expression is true then statement_1 gets executed else the program control shifts to statement_2.
3. Nested IF-ELSE Statement
Syntax:
if (expression_1)
{ if(expression_2) statement_1; }
else
statement_3;
Here, multiple if-else statements are used to decide the flow of control.
Apart from that switch statements also come under this category where the selection is made using the case statements.
5). Iteration statements
Iteration statements include the ones which require running the same code again and again till a fixed number of times.
In C/C++ there are three type of iteration statements.
For loop
While loop
Do-while loop
6). Compound statements
Compound statement is a group pr block of statements combined together.
Programs usually need brackets {,} to bind more than one statement. Thereby, forming a compound statement.
Also, variables that are declared within the braces have a scope limited to that block only.
7). Jump statements
To transfer the flow of control unconditionally, some jump statements are used.
For example: return, goto, continue, break etc.
While using jump statements every programmer must note that when the control jumps out of a block or loop, may involve destruction that were declared in the local scope.
Operators
The symbols such as +,-, *, /, &,->, etc are known as operators. Each of these operators perform some operation on operands.
Consider an expression:
c = a + b;
expression:- a+b
operand= a,b
operators:- +
OR,
Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations.
Operators in programming are symbols or keywords that represent computations or actions performed on operands. Operands can be variables, constants, or values, and the combination of operators and operands form expressions. Operators play a crucial role in performing various tasks, such as arithmetic calculations, logical comparisons, bitwise operations, etc.
Types of Operators in Programming:
Here are some common types of operators:
Arithmetic Operators: Perform basic arithmetic operations on numeric values. Examples: + (addition), - (subtraction), * (multiplication), / (division), % (modulo).
Comparison Operators: Compare two values and return a Boolean result (true or false). Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to).
Logical Operators: Perform logical operations on Boolean values. Examples: && (logical AND), || (logical OR), ! (logical NOT).
Assignment Operators: Assign values to variables. Examples: = (assign), += (add and assign), -=, *= (multiply and assign), /=, %=.
Increment and Decrement Operators: Increase or decrease the value of a variable by 1. Examples: ++ (increment), -- (decrement).
Bitwise Operators: Perform operations on individual bits of binary representations of numbers. Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift).
These operators provide the building blocks for creating complex expressions and performing diverse operations in programming languages. Understanding their usage is crucial for writing efficient and expressive code.
Preprocessor Directives
Preprocessing is an initial phase to process text before compilation. Preprocessor directives are lines of the source file where the first non-whitespace character is #, which distinguishes them from other lines of text. The effect of each preprocessor directive is a change to the text and the result is a transformation of the text that does not contain the directives nor comments. The compiler can optionally output the preprocessed text to a file that has a .i suffix. Preprocessing is always the initial phase of compilation, even when the text has already been preprocessed.
The preprocessor directives are the instructions to the preprocessor for doing some tasks such as text substitutions, macro expansions, including header files, and many more before compiling the code. All of these preprocessor directives begin with a ‘#’ hash symbol.
Preprocessing is an initial phase to process text before compilation. Preprocessor directives are lines of the source file where the first non-whitespace character is #, which distinguishes them from other lines of text. The effect of each preprocessor directive is a change to the text and the result is a transformation of the text that does not contain the directives nor comments. The compiler can optionally output the preprocessed text to a file that has a .i suffix. Preprocessing is always the initial phase of compilation, even when the text has already been preprocessed.
The preprocessor directives are the instructions to the preprocessor for doing some tasks such as text substitutions, macro expansions, including header files, and many more before compiling the code. All of these preprocessor directives begin with a ‘#’ hash symbol.
One of the most commonly used preprocessors is #include which is used to include the header files for different libraries in C programs.
Preprocessor directives consist of the following:
Macro definition directives, which replace tokens in the current file with specified replacement tokens
File inclusion directives, which imbed files within the current file
Conditional compilation directives, which conditionally compile sections of the current file
Message generation directives, which control the generation of diagnostic messages
The null directive (#), which performs no action
Pragma directives, which apply compiler-specific rules to specified sections of code
C99 preprocessor features adopted in C++11 (C++11)
Preprocessor directives begin with the # token followed by a preprocessor keyword. The # token must appear as the first character that is not white space on a line. The # is not part of the directive name and can be separated from the name with white spaces.
A preprocessor directive ends at the new-line character unless the last character of the line is the \ (backslash) character. If the \ character appears as the last character in the preprocessor line, the preprocessor interprets the \ and the new-line character as a continuation marker. The preprocessor deletes the \ (and the following new-line character) and splices the physical source lines into continuous logical lines. White space is allowed between backslash and the end of line character or the physical end of record. However, this white space is usually not visible during editing.
types of Preprocessor directives
Macros
Macros are used to define constants or create functions that are substituted by the preprocessor before the code is compiled. The two preprocessors #define and #undef are used to create and remove macros in C.
syntax
#define token value
#undef token
where after preprocessing, the token will be expanded to its value in the program.
Example:
#include <stdio.h>
// Macro Definition
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Output
0
1
2
3
4
In the above program, before the compilation begins, the word LIMIT is replaced with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
File Inclusion
File inclusion allows you to include external files (header files, libraries, etc.) into the current program. This is typically done using the #include directive, which can include both system and user-defined files.
Syntax
There are two ways to include header files.
#include <file_name>
#include “filename”
The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard directory while double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory.
Example:
// Includes the standard I/O library
#include <stdio.h>
int main() {
printf("Hello World");
return 0;
}
Output
Hello World
Conditional Compilation
Conditional compilation allows you to include or exclude parts of the code depending on certain conditions. This is useful for creating platform-specific code or for debugging. There are the following conditional preprocessor directives: #if, #ifdef, #ifndef, else, #elif and #endif
Syntax
The general syntax of conditional preprocessors is:
#if
// some code
#elif
// some more code
#else
// Some more code
#endif
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives.
Other Directives
Apart from the primary preprocessor directives, C also provides other directives to manage compiler behaviour and debugging.
#pragma:
Provides specific instructions to the compiler to control its behaviour. It is used to disable warnings, set alignment, etc.
Syntax
#pragma directive
Some of the #pragma directives are discussed below:
#pragma startup: These directives help us to specify the functions that are needed to run before program startup (before the control passes to main()).
#pragma exit: These directives help us to specify the functions that are needed to run just before the program exit (just before the control returns from main())
List of Preprocessor Directives
The following table lists some commonly used preprocessor directives available in the C programming language:
Preprocessor Directives
Description
#define
Used to define a macro.
#undef
Used to undefine a macro.
#include
Used to include a file in the source code program.
#ifdef
Used to include a section of code if a certain macro is defined by #define.
#ifndef
Used to include a section of code if a certain macro is not defined by #define.
#if
Check for the specified condition.
#else
Alternate code that executes when #if fails.
#endif
Used to mark the end of #if, #ifdef, and #ifndef.
#error
Used to generate a compilation error message.
#line
Used to modify line number and filename information.
#pragma once
To make sure the header is included only once.
#pragma message
Used for displaying a message during compilation.
Input/Output
Input-output operations are essential for interacting with users and handling data. These operations allow a program to take input from the user or external files and display results.
The input-output statements in C are part of the standard library, enabling programmers to perform tasks like reading data from the console, writing to the console, and managing files efficiently.
In C programming, input and output operations refer to reading data from external sources and writing data to external destinations outside the program. C provides a standard set of functions to handle input from the user and output to the screen or to files. These functions are part of the standard input/output library <stdio.h>.
Input-output operations are essential for interacting with users and handling data. These operations allow a program to take input from the user or external files and display results.
The input-output statements in C are part of the standard library, enabling programmers to perform tasks like reading data from the console, writing to the console, and managing files efficiently.
In C programming, input and output operations refer to reading data from external sources and writing data to external destinations outside the program. C provides a standard set of functions to handle input from the user and output to the screen or to files. These functions are part of the standard input/output library <stdio.h>.
In C, there are many functions used for input and output in different situations but the most commonly used functions for Input/Output are scanf() and printf() respectively.
Input in C
Input in C programming means gathering data from the user or external sources for processing. The most common way is through the console, where functions like scanf() are used for formatted input, and getchar() reads a single character.
Additionally, data can be read from files using functions like fscanf() and fgets().
For example, scanf("%d", &num); takes an integer input from the user.
Output in C
Output in C programming means displaying results or information from a program on the console or writing it to a file. Console output functions like printf() allow formatted data to be printed, while putchar() is used for single characters. File output operations in C involve writing data to a file using functions like fprintf() and fputs().
For example, printf("Result: %d", result); displays the value of a variable.
Input and Output Functions in C Programming
Below is the list of input and output functions in C language:
Function
Category
Description
scanf()
Input (Console)
Reads formatted input (e.g., integers, floats, strings) from the user.
getchar()
Input (Console)
Reads a single character from the user.
gets()
Input (Console)
Reads a string from the user (deprecated due to safety issues).
fscanf()
Input (File)
Reads formatted data from a file.
fgets()
Input (File)
Reads a line of text from a file.
printf()
Output (Console)
Prints formatted output to the console.
putchar()
Output (Console)
Outputs a single character to the console.
puts()
Output (Console)
Outputs a string to the console.
fprintf()
Output (File)
Writes formatted data to a file.
fputs()
Output (File)
Writes a string to a file.
fopen()
File Operation
Opens a file for reading, writing, or appending.
fclose()
File Operation
Closes an opened file.
fread()
Input (File)
Reads binary data from a file.
fwrite()
Output (File)
Writes binary data to a file.
feof()
File Operation
Checks if the end of a file has been reached.
perror()
Output (Error)
Prints an error message to the standard error stream
Input Functions in C
Below is a detailed explanation of common input functions in C programming:
1. scanf()
Reads formatted input from the user, such as integers, floats, and strings.
Example
int num;
printf("Enter a number: ");
scanf("%d", &num); // Takes integer input
printf("You entered: %d\n", num);
2. getchar()
Reads a single character from the user.
Example:
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads one character
printf("You entered: %c\n", ch);
3. gets()
Reads a string from the user, including spaces (deprecated due to safety concerns).
Example:
char str[50];
printf("Enter a string: ");
gets(str); // Reads the entire string
printf("You entered: %s\n", str);
4. fscanf()
Reads formatted data from a file.
Example:
FILE *file = fopen("data.txt", "r");
int num;
fscanf(file, "%d", &num); // Reads an integer from the file
printf("The number in the file is: %d\n", num);
fclose(file);
5. fgets()
Reads a line of text from a file or the console.
Example:
FILE *file = fopen("data.txt", "r");
char line[100];
fgets(line, 100, file); // Reads a line from the file
printf("The line in the file is: %s\n", line);
fclose(file);
Output Functions
Below is the explanation of common output functions in C programming:
1. printf()
Prints formatted output to the console.
Example:
int num = 10;
printf("The number is: %d\n", num); // Prints the value of num
2. putchar()
Outputs a single character to the console.
Example:
char ch = 'A';
putchar(ch); // Outputs the character 'A'
printf("\n");
3. puts()
Outputs a string to the console with a newline at the end.
Example:
char str[] = "Hello, World!";
puts(str); // Prints the string with a newline
4. fprintf()
Writes formatted data to a file.
Example:
FILE *file = fopen("output.txt", "w");
int num = 20;
fprintf(file, "The number is: %d\n", num); // Writes to the file
fclose(file);
5. fputs()
Writes a string to a file.
Example:
FILE *file = fopen("output.txt", "w");
fputs("This is a test string.", file); // Writes the string to the file
fclose(file);
Key Notes:
Input functions like scanf() and fgets() are used to take data from the user or files.
Output functions like printf() and fprintf() are used to display or save data.
Always use fopen() and fclose() when working with files to ensure proper file handling.
Control statements
In general, control statements help with the control flow of the program.
Control statements language are instructions that determine the flow of a program's execution based on certain conditions or repetitions. They help decide whether a block of code should run, repeat, or skip. These statements make programs dynamic by adding decision-making, looping, and jumping capabilities, which are essential for solving real-world problems.
In general, control statements help with the control flow of the program.
Control statements language are instructions that determine the flow of a program's execution based on certain conditions or repetitions. They help decide whether a block of code should run, repeat, or skip. These statements make programs dynamic by adding decision-making, looping, and jumping capabilities, which are essential for solving real-world problems.
Let’s understand it with a real-life example:
Think of control statements like traffic signals. A green light allows cars to move (execution), a red light stops them (condition not met), and a yellow light prepares them for the next action (transition).
Types of Control Statements
There are three types of control statements programming:
1. Decision-Making Statements: These statements allow the program to make decisions and execute specific blocks of code based on conditions.
2. Loop Control Statements: These statements repeatedly execute a block of code as long as a specified condition is true.
3. Jump Statements: These statements transfer the program's control from one part of the code to another, either conditionally or unconditionally.
Decision-Making Control Statements
Decision-making statements allow the program to make choices and execute specific blocks of code based on conditions.
These statements enable a program to behave dynamically and handle different scenarios effectively.
Let’s discuss the different types of decision control statements in C:
1. if Statement
The if statement executes a block of code only if the given condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.");
}
return 0;
}
When to Use: Use the if statement when you need to perform an action based on a single condition.
2. if-else Statement
The if-else statement executes one block of code if the condition is true and another block if it is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
#include <stdio.h>
int main() {
int number = -5;
if (number >= 0) {
printf("The number is non-negative.");
} else {
printf("The number is negative.");
}
return 0;
}
When to Use: Use if-else control statement in C programming when you need to perform one action for a true condition and another for a false condition.
3. nested if Statement
It is an if statement inside another if statement, used to check multiple conditions.
Syntax:
if (condition1) {
if (condition2) {
// Code if both conditions are true
}
}
Example:
#include <stdio.h>
int main() {
int number = 5;
if (number > 0) {
if (number % 2 == 0) {
printf("The number is positive and even.");
} else {
printf("The number is positive and odd.");
}
}
return 0;
}
When to Use: Use nested if when you need to test multiple related conditions.
4. if-else-if Ladder
This conditional statement checks multiple conditions one by one until a true condition is found.
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:
#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A");
} else if (marks >= 75) {
printf("Grade: B");
} else if (marks >= 50) {
printf("Grade: C");
} else {
printf("Grade: F");
}
return 0;
}
When to Use: Use the if-else-if ladder when you need to check multiple conditions in sequence.
Loop Control Statements
Loop control statements are used to repeatedly execute a block of code as long as a specific condition is true. They simplify repetitive tasks and help in writing concise programs.
Ex:-
Imagine you are filling bottles with water. You continue filling bottles one by one until you run out of empty bottles. Similarly, in programming, looping statements repeatedly perform tasks until a condition is met.
Let’s understand the different loops in C programming:
1. for Loop
The for loop executes a block of code a specific number of times, controlled by an initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use the for loop when the number of iterations is known beforehand.
2. while Loop
The while loop executes a block of code repeatedly as long as the specified condition is true.
Syntax:
while (condition) {
// Code to execute while condition is true
}
Example:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Number: %d\n", i);
i++;
}
return 0;
}
When to Use: Use the while loop when the number of iterations is not known and depends on a condition.
3. do-while Loop
The do-while loop executes a block of code at least once and then continues to execute as long as the condition is true.
Syntax:
do {
// Code to execute
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Number: %d\n", i);
i++;
} while (i <= 5);
return 0;
}
When to Use: Use the do-while loop when you want the code to execute at least once, regardless of the condition.
Jumping Control Statements
Jumping statements are used to transfer control of the program from one point to another. These statements enable conditional or unconditional jumps, allowing flexibility in program flow.
Real-Life Example:
Imagine reading a book:
You can skip pages you don’t need (continue).
You can stop reading altogether (break).
You can flip directly to a specific page (goto).
Jumping statements in C programming work similarly by moving control within the code.
There are four main jump control statements in C language:
1. break Statement
The break statement in C terminates the nearest enclosing loop or switch statement and transfers control to the next statement after it.
Syntax:
break;
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use break to exit a loop or switch prematurely when a specific condition is met.
2. continue Statement
The continue statement in C skips the current iteration of the loop and moves to the next iteration.
Syntax:
continue;
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use continue when you want to skip specific iterations of a loop without exiting it.
3. goto Statement
The goto statement in C transfers control to a labeled statement within the program.
Syntax:
goto label;
...
label:
// Code to execute
Example:
#include <stdio.h>
int main() {
int number = 3;
if (number < 5) {
goto small;
}
printf("Number is not small.\n");
return 0;
small:
printf("Number is small.\n");
}
When to Use: Use goto sparingly, typically in cases like error handling, where other approaches may complicate the code.
4. return Statement
The return statement in C exits the current function and optionally returns a value to the calling function.
Syntax:
return; // Without value
return value; // With value
Example:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5);
printf("Result: %d\n", result);
return 0;
}
When to Use: Use return to exit a function and optionally pass a value back to the calling function.
Loop
In programming, a loop is a fundamental concept that allows you to run a block of code multiple times. It is a key feature in many programming languages and is used to automate repetitive tasks, making code more efficient and easier to manage.
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're essential as they reduce hours of work to seconds.
Loops, also known as iterative statements, are used when we need to execute a block of code repetitively. Loops in programming are control flow structures that enable the repeated execution of a set of instructions or code block as long as a specified condition is met. Loops are fundamental to the concept of iteration in programming, enhancing code efficiency, readability and promoting the reuse of code logic.
In programming, a loop is a fundamental concept that allows you to run a block of code multiple times. It is a key feature in many programming languages and is used to automate repetitive tasks, making code more efficient and easier to manage.
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're essential as they reduce hours of work to seconds.
Loops, also known as iterative statements, are used when we need to execute a block of code repetitively. Loops in programming are control flow structures that enable the repeated execution of a set of instructions or code block as long as a specified condition is met. Loops are fundamental to the concept of iteration in programming, enhancing code efficiency, readability and promoting the reuse of code logic.
Types of Loops in Programming:
In programming, loops are categorized into two main types based on the control mechanism: entry-controlled loops and exit-controlled loops.
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 an example of Exit Controlled loop.
Primary types of loops(In exam u have to write these all tyoes not of upper types)
Loops in programming help in executing a set of instructions or code repeatedly based on a condition. There are three primary types of loops you will encounter in many programming languages:
For Loop: Used when the number of iterations is known.
While Loop: Continues as long as a given condition is true.
Do-While Loop: Similar to the while loop, but ensures that the loop is executed at least once before the condition is tested.
For loop:
For loop in programming is a control flow structure that iterates over a sequence of elements, such as a range of numbers, items in a list, or characters in a string. The loop is entry-controlled because it determines the number of iterations before entering the loop.
The for loop is particularly useful when you know in advance how many times you want the loop to run. This loop is designed to iterate a specific number of times.
The basic syntax for a for loop often includes a variable that takes on each value in the sequence, and the loop body contains the code to be executed during each iteration.
Below is the implementation of For Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output
0 1 2 3 4
While Loop:
A while loop in programming is an entry-controlled control flow structure that repeatedly executes a block of code as long as a specified condition is true. The loop continues to iterate while the condition remains true, and it terminates once the condition evaluates to false.
or,A while loop continues to execute a block of code as long as a specified condition is true. Unlike the for loop, the while loop does not require you to know how many times the loop will run in advance.
The basic syntax for a for loop often includes a condition which is checked before each iteration and if the condition evaluates to true, the loop body containing the code gets executed otherwise the loop gets terminated.
Below is the implementation of While Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
return 0;
}
Output
0 1 2 3 4
Do-While Loop:
A do-while loop in programming is an exit-controlled control flow structure that executes a block of code at least once and then repeatedly executes the block as long as a specified condition remains true.
The distinctive feature of a do-while loop is that the condition is evaluated after the code block, ensuring that the block is executed at least once, even if the condition is initially false.
or,The do-while loop guarantees at least one execution of the code block, since it checks the condition after the loop's initial iteration.
The basic syntax for a for loop includes a block of code followed by a condition which is checked after each iteration and if the condition evaluates to true, the next iteration takes place otherwise the loop gets terminated.
Below is the implementation of Do while Loop in Programming
#include <iostream>
using namespace std;
int main()
{
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Output
0 1 2 3 4
Nested Loops:
Nested loops in programming are when one loop is placed inside another. This allows for the iteration of one or more loops within the body of another loop. Each time the outer loop executes, the inner loop completes its full iteration.
Nested loops are commonly employed for tasks involving multidimensional data processing, pattern printing, or handling complex data structures. Efficient use of nested loops is essential, considering potential impacts on code readability and execution time for larger datasets.
Below is the implementation of Nested Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 3; i++) {
int j = 0;
while (j < 5) {
cout << "i = " << i << " j = " << j << " ";
j++;
}
cout << endl;
}
return 0;
}
Output
i = 0 j = 0 i = 0 j = 1 i = 0 j = 2 i = 0 j = 3 i = 0 j = 4
i = 1 j = 0 i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 1 j = 4
i = 2 j = 0 i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 2 j = 4
Procedure/Functions
A subroutine can be classified as a procedure or a function. This distinction can be confusing as not all programming languages differentiate between functions and procedures. However, in a theoretical context:
A procedure is a block of code that is called to perform a task
A function is a block of code that is called to perform a task and will return one or more values
Procedure
A procedure is a named block of code that performs a specific task, but does not return a value. The procedure can be called by another part of the program.
A procedure for a login menu could be written like this:
C#
public static void DisplayMenu() {
Console.WriteLine("1: Log in");
Console.WriteLine("2: Sign up");
Console.WriteLine("9: Quit");
}
This procedure will output menu options. It can be called anywhere in the program using its identifier (name), including the brackets.
Function
A function is a named block of code that has the purpose of returning a value (called the 'return value'). Like a procedure, a function can be called by another part of the program.
Consider the following example:
C#
public static void Main() {
float length = 12;
float result = CalculateArea(length);
Console.WriteLine(result);
}
public static float CalculateArea(float length) {
float area = length * length;
return area;
}
A function must be called as part of an expression, so that the return value is assigned to a variable. In this example, the function is called from main and the return value is assigned to a variable named result, which is then displayed to the user.
Array, String and Pointer
C is a powerful, general-purpose programming language that is widely used for developing operating systems and other low-level applications. One of the reasons for its popularity is its support for a variety of data types, including pointers, arrays, and strings.
Pointers
Pointers are a fundamental concept in C that allows programmers to manipulate memory directly. In C, a pointer is a variable that stores the memory address of another variable. This allows programmers to create dynamic data structures, such as linked lists and trees, and to pass arguments to functions by reference.
To declare a pointer in C, the programmer must use the * operator. For example, the following code declares a pointer p to an integer variable x:
int x = 5;
int *p = &x;
The & operator is used to retrieve the memory address of a variable, and the * operator is used to dereference a pointer and access the value stored at the memory address it points to.
In the example above, the value of x can be accessed through the pointer p using the * operator, like this:
int y = *p; // y is now equal to 5
Example:-
include <stdio.h>
int main () {
int variable1;
char variable2[10];
printf("Address of var1 variable: %x\n", &variable1);
printf("Address of var2 variable: %x\n", &variable2);
return 0;
}
Output:-
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
Arrays
Arrays are another important data type in C. An array is a contiguous block of memory that stores a fixed number of values of the same type. In C, arrays are indexed starting at 0, so the first element of an array with n elements is stored at index 0, the second element is stored at index 1, and so on.
To declare an array in C, the programmer must specify the type of the elements and the number of elements in the array. For example, the following code declares an array a of 10 integers:
int a[10];
Elements of an array can be accessed using their index in square brackets, like this:
a[0] = 5; // set the first element of the array to 5
int x = a[1]; // x is now equal to the second element of the array
Example:
-#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output:-
20
30
40
50
60
Strings
Strings are a special type of array in C that stores a sequence of characters. In C, strings are represented as arrays of characters terminated by a null character ('\0').
For example, the following code declares a string s with the value "Hello, world!":
char s[ ] = "Hello, world!";
The standard C library provides a number of functions for working with strings, such as strlen to determine the length of a string and strcpy to copy one string to another. For example, the following code uses the strlen function to determine the length of the string s declared above:
int len = strlen(s); // len is now equal to 13
other example:-
char c[ ] = "abcd";
char c[50] = "abcd";
char c[ ] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
In conclusion, pointers, arrays, and strings are important data types in C that enable programmers to manipulate memory directly and work with various types of data. These data types are fundamental to many aspects of C programming, and a thorough understanding of them is essential for anyone looking to master the language.
Structure and Union
Union is a user-defined data type declared with a "union" keyword. It is a collection of elements of different data types. All the elements are stored at the same memory location. Only one member can hold a value at a time in a union( only one member can store data at the given point in time.). The size of the memory depends on the largest member of the union.
Syntax of Union in C
union union_name {
type member1;
type member2;
type member3;
};union_variables;
Example:
{...}
union Data {
int i;
double d;
char c;
};
int main() {
// Create a union variable
union Data data;
// Store an integer in the union
data.i = 100;
printf("%d
", data.i);
// Store a double in the union (this will
// overwrite the integer value)
data.d = 99.99;
printf("%.2f
", data.d);
// Store a character in the union (this will
// overwrite the double value)
data.c = 'A';
printf("%c
", data.c);
printf("Size: %d", sizeof(data));
{...}
Output
100
99.99
A
Size: 8
Structure
The structure is a user-defined data type declared with a "struct" keyword. It combines different datatypes into a single datatype under one name. All the elements of a structure are stored at contiguous memory locations.
The total memory size of a structure is the sum of the sizes of all its elements. You can access the structure elements using the dot (.) operator.
The items in the structure are called its member and they can be of any valid data type.
Syntax:-
struct structure_name
{
type member1;
type member2;
type member3;
};structure_variables;
Example:
#include <stdio.h>
struct Student {
char name[50];
int age;
float grade;
};
int main() {
// Create a structure variable
struct Student s1 = {"Geek", 20, 85.5};
// Access structure members
printf("%s\n", s1.name);
printf("%d\n", s1.age);
printf("%.2f\n", s1.grade);
printf("Size: %d bytes", sizeof(s1));
return 0;
}
Output
Geek
20
85.50
Size: 60 bytes
Explanation: In this example, we create a structure Student to store a student’s name, age, and grade. Each of the members (name, age, grade) is stored in its own separate memory location, and we access them individually. The size is also the size of all members combined plus structure padding.
Difference between Structure and Union
Structure
A structure is declared using the "struct" keyword
All the structure members have a unique memory location.
Stores distinct values for all the members
The sum of the sizes of all the members of a structure
Multiple members can be initialized at the same time
You can access individual members at a time
It's used for storing various data types
Change in the value of any member does not affect other member's value
Union
A union is declared using the "union" keyword
All the members share the same memory location.
Stores same values for all the members
The size of the largest member of the union
Only one member can be initialized at a time
You can access only one member at a time
It's used to store one of the many available data types.
Change in the value of one member will affect the value of other members in the union.
File
A File is a collection of data stored in the secondary memory. So far data was entered into the programs through the keyboard.
So Files are used for storing information that can be processed by the programs. Files are not only used for storing the data, programs are also stored in files. In order to use files, we have to learn file input and output operations. That is, how data is read and how to write into a file.
A Text File can be thought of as a stream of characters that can be processed sequentially. It can only be processed in the forward direction.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file using a few commands in C.
You can easily move your data from one computer to another without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
Text files
Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and take up a lot of storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than text files.
Using Files in C:
To use a file four essential actions should be carried out. These are,
a. Declare a file pointer variable.
b. Open a file using the fopen() function.
c. Process the file using suitable functions.
d. Close the file using the fclose() and fflush() functions.
Declaration of file pointer:
A pointer variable is used to points a structure FILE. The members of the FILE structure are
used by the program in various file access operation, but programmers do not need to concerned
about them.
FILE *file_pointer_name;
Eg : FILE *fp;
Opening a file
To open a file using the fopen() function. Its syntax is,
FILE *fopen(const char *fname,const char* mode);
const char *fname represents the file name. The file name is like “D:\\501\example.txt”.
Here D: is a drive, 501 is the directory, example.txt is a file name.
const char *mode represents the mode of the file. It has the following values
Or,
in Case of file handling
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.
Features of file handling
So far the operations using the C program are done on a prompt/terminal which is not stored anywhere. The output is deleted when the program is closed. But in the software industry, most programs are written to store the information fetched from the program. The use of file handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of using files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part of a file using few instructions which saves a lot of time and reduces the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything simultaneously in a program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as follows:
Text Files
Binary File
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can only be read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
Object Oriented Programming(OOP)
Object oriented programming is a modern paradigm of programming in which a complex task is broken down in terms of classes and objects.
Classes specify the data to be used and functions that operate on them.
In fact, class gives the description of the objects to be created. Once the class has been created, one can create objects of type class. i.e. an object that holds the characteristics or features specified in the class definition.
Object Oriented Programming follows the bottom up approach in the program design.
Examples of object oriented programming languages are: C++, Java, C#.net, VB.net, Smalltalk, PHP, Perl, Prolog++ and so on.
Object oriented programming is a modern paradigm of programming in which a complex task is broken down in terms of classes and objects.
Classes specify the data to be used and functions that operate on them.
In fact, class gives the description of the objects to be created. Once the class has been created, one can create objects of type class. i.e. an object that holds the characteristics or features specified in the class definition.
Object Oriented Programming follows the bottom up approach in the program design.
Examples of object oriented programming languages are: C++, Java, C#.net, VB.net, Smalltalk, PHP, Perl, Prolog++ and so on.
Fig 1.1. Breakdown of an object oriented program in various objects.
As can be seen from the figure, in an object oriented program, a complex program is broken down in terms of different objects. These objects encapsulate data and functions as defined by the class definition. These objects can communicate with each other through message passing.
Features of OOP
Followings are the features of OOP:
A. Class
B. Objects
C. Polymorphism
D. Encapsulation
E. Data Abstraction
F. Message Passing
A. Class
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.
B. Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class student:
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class student:
student s1; // Declares s1 of type student
student s2; // Declares s2 of type student
Both of the objects s1 and s2 will have their own copy of data members.
C. Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects of another classes.
It supports the concept of hierarchical classification.
For example, the bird, „robin‟ is a part of class „flying bird‟ which is again a part of the class „bird‟.
The principal behind this sort of division is that each derived class shares common characteristics with the class from which it is derived.
In OOP, the concept of inheritance provides the idea of reusability.
This means that we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce any undesirable side-effects into the rest of classes.
Inheritance is the process by which objects of one class acquired the properties of objects of another classes.
It supports the concept of hierarchical classification.
For example, the bird, „robin‟ is a part of class „flying bird‟ which is again a part of the class „bird‟.
The principal behind this sort of division is that each derived class shares common characteristics with the class from which it is derived.
In OOP, the concept of inheritance provides the idea of reusability.
This means that we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce any undesirable side-effects into the rest of classes.
D. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form.
An operation may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation.
For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation.
The process of making an operator exhibit different behaviors in different instances is known as operator overloading.
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form.
An operation may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation.
For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation.
The process of making an operator exhibit different behaviors in different instances is known as operator overloading.
E. Encapsulation
Encapsulation is a process of combining data members and functions in a single unit called class.
This is to prevent the access to the data directly, the access to them is provided through the functions of the class.
It is one of the popular feature of Object Oriented Programming(OOPs) that helps in data hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. Now,
Encapsulation is a process of combining data members and functions in a single unit called class.
This is to prevent the access to the data directly, the access to them is provided through the functions of the class.
It is one of the popular feature of Object Oriented Programming(OOPs) that helps in data hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. Now,
The finance section handles all the financial transactions and keeps records of all the data related to finance. All the financial processes are done by this section.
Similarly, the sales section handles all the sales-related activities and keeps records of all the sales.
F. 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 a program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, But you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals.
In C++, classes provide a great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how the class has been implemented internally.
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 a program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, But you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals.
In C++, classes provide a great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how the class has been implemented internally.
ex:-// C++ Program to Demonstrate the
// working of Abstraction
#include <iostream>
using namespace std;
class implementAbstraction {
private:
int a, b;
public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}
Output
a = 10
b = 20
You can see in the above program we are not allowed to access the variables a and b directly, however, one can call the function set() to set the values in a and b and the function display() to display the values of a and b.
Types of Abstraction:
Data abstraction – This type only shows the required information about the data and ignores unnecessary details.
Control Abstraction – This type only shows the required information about the implementation and ignores unnecessary details.
Advantages of Data Abstraction
Helps the user to avoid writing the low-level code
Avoids code duplication and increases reusability.
Can change the internal implementation of the class independently without affecting the user.
Helps to increase the security of an application or program as only important details are provided to the user.
It reduces the complexity as well as the redundancy of the code, therefore increasing the readability.
F. Message Passing
→ An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, involves the following basic steps:-
i. Creating classes that define object and their behavior,
ii. Creating objects from class definitions, and
iii. Establishing communication among objects.
→ Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts.
→ A Message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired results. Message passing involves specifying the name of object, the name of the function (message)and the information to be sent.
Example:Employee. Salary (name);
Function overloading
Two or more functions can have the same name but different parameters; such functions are called function overloading in c++.
The function overloading in the c++ feature is used to improve the readability of the code. It is used so that the programmer does not have to remember various function names. If any class has multiple functions with different parameters having the same name, they are said to be overloaded. If we have to perform a single operation with different numbers or types of arguments, we need to overload the function.
Function overloading is similar to polymorphism that helps us to get different behaviour, with the same name of the function. Function overloading in c++ is used for code reusability and to save memory.
Two or more functions can have the same name but different parameters; such functions are called function overloading in c++.
The function overloading in the c++ feature is used to improve the readability of the code. It is used so that the programmer does not have to remember various function names. If any class has multiple functions with different parameters having the same name, they are said to be overloaded. If we have to perform a single operation with different numbers or types of arguments, we need to overload the function.
Function overloading is similar to polymorphism that helps us to get different behaviour, with the same name of the function. Function overloading in c++ is used for code reusability and to save memory.
Rules of Function Overloading in C++
Different parameters or three different conditions :
1. These functions have different parameter type
sum(int a, int b)
sum(double a, double b)
2.These functions have a different number of parameters
sum(int a, int b)
sum(int a, int b, int c)
3.These functions have a different sequence of parameters
sum(int a, double b)
sum(double a, int b)
The above three cases are valid cases of overloading. We can have any number of functions, but remember that the parameter list must be different. For example:
int mul(int, int)
double mul(int, int)
As the parameter list is the same, this is not allowed. Even though their return types are different, it’s not valid.
example:- #include <iostream>
using namespace std;
class Addition
{
public:
int sum(int a,int b)
{
return a+b;
}
int sum(int a,int b, int c)
{
return a+b+c;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output :
35
191
Types of function overloading in c++
There are two types of function overloading in c++-
Compile time overloading– In compile time overloading, functions are overloaded using different signatures. Signature of a function includes its return type, number of parameters and types of parameters.
Runtime overloading -In runtime overloading, functions are overloaded using a different number of parameters.
Causes of function overloading in c++
Type Conversion.
Function with default arguments.
Function with a pass-by reference
Inheritance
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Syntax
class DerivedClass : mode_of_inheritance BaseClass {
// Body of the Derived Class
};
where mode of inheritance controls the access level of the inherited members of the base class in the derived class.
In C++, there are 3 modes of inheritance:
Public Inheritance Mode
Public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.
Protected Inheritance Mode
Both public and protected members of the base class will become protected in the derived class.
Private Inheritance Mode
Both public members and protected members of the base class will become private in the derived class. Private mode is the default mode that is applied when we don’t specify any mode.
Types Of Inheritance in C++
The inheritance can be classified on the basis of the relationship between the derived class and the base class. In C++, we have 5 types of inheritances:
Single inheritance
Multilevel inheritance
Multiple inheritance
Hierarchical inheritance
Hybrid inheritance
1. Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is inherited by one derived class only.
Example:
#include <bits/stdc++.h>
using namespace std;
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle"<< endl;
}
};
// Sub class derived from a single base classes
class Car : public Vehicle {
public:
Car() {
cout << "This Vehicle is Car"<< endl;
}
};
int main() {
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
This Vehicle is Car
2. Multiple Inheritance
Multiple Inheritance is a feature of C++ where a class can inherit from more than one class. i.e one subclass is inherited from more than one base class.
ex:-
class LandVehicle {
public:
LandVehicle() {
cout << "This is a LandVehicle"<< endl;
}
};
class WaterVehicle {
public:
WaterVehicle() {
cout << "This is a WaterVehicle"<< endl;
}
};
// sub class derived from two base classes
class AmphibiousVehicle : public WaterVehicle, public LandVehicle {
public:
AmphibiousVehicle() {
cout << "This is an AmphibiousVehicle"<< endl;
}
};
int main() {
// Creating object of sub class will
// invoke the constructor of base classes.
AmphibiousVehicle obj;
return 0;
}
3. Multilevel Inheritance
In multilevel inheritance, a derived class is created from another derived class and that derived class can be derived from a base class or any other derived class. There can be any number of levels. For example, a vehicle can be a four-wheeler, and a four-wheeler vehicle can be a car.
Example:
{...}
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle"<< endl;
}
};
class fourWheeler : public Vehicle {
public:
fourWheeler() {
cout << "4 Wheeler Vehicles"<< endl;
}
};
class Car : public fourWheeler {
public:
Car() {
cout << "This 4 Wheeler Vehical is a Car";
}
};
int main() {
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car
4. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class. For example, cars and buses both are vehicle.
Example:
{...}
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle"<< endl;
}
};
class Car : public Vehicle {
public:
Car() {
cout << "This Vehicle is Car"<< endl;
}
};
class Bus : public Vehicle {
public:
Bus() {
cout << "This Vehicle is Bus"<< endl;
}
};
{...}
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
5. Hybrid Inheritance
Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance will create hybrid inheritance in C++.
There is no particular syntax of hybrid inheritance. We can just combine two of the above inheritance types. Below image shows one of the combinations of hierarchical and multiple inheritances:
Example:
{...}
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle"<< endl;
}
};
class Fare {
public:
Fare() {
cout << "Fare of Vehicle"<< endl;
}
};
class Car : public Vehicle {
public:
Car() {
cout << "This Vehical is a Car"<< endl;
}
};
class Bus : public Vehicle, public Fare {
public:
Bus() {
cout << "This Vehicle is a Bus with Fare";
}
};
int main() {
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}
Output
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare
Polymorphism
The word polymorphism means having many forms. A real-life example of polymorphism is a person who 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 exhibits different behaviour in different situations. This is called polymorphism.
In C++, polymorphism concept can be applied to functions and operators. A single function can work differently in different situations. Similarly, an operator works different when used in different context.
The word polymorphism means having many forms. A real-life example of polymorphism is a person who 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 exhibits different behaviour in different situations. This is called polymorphism.
In C++, polymorphism concept can be applied to functions and operators. A single function can work differently in different situations. Similarly, an operator works different when used in different context.
Types of Polymorphism
Polymorphism in C++ can be classified into two types:
Compile-time Polymorphism
Runtime Polymorphism
1. Compile-Time Polymorphism
Also known as early binding and static polymorphism, in compile-time polymorphism, the compiler determines how the function or operator will work depending on the context. This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but behave differently for different parameters. Such functions are said to be overloaded; hence, this is known as Function Overloading. Functions can be overloaded either by changing the number of arguments or changing the type of arguments.
B. Operator Overloading
C++ has the ability to provide the operators with a special meaning for particular data type, this ability is known as operator overloading. For example, we can make use of the addition operator (+) for string to concatenate two strings and for integer to add two integers. The << and >> operator are binary shift operators but are also used with input and output streams. This is possible due to operator overloading.
2. Runtime Polymorphism
Also known as late binding and dynamic polymorphism, the function call in runtime polymorphism is resolved at runtime in contrast with compile time polymorphism, where the compiler determines which function call to bind at compilation. Runtime polymorphism is implemented using function overriding with virtual functions.
a.Function Overriding
Function Overriding occurs when a derived class defines one or more member functions of the base class. That base function is said to be overridden. The base class function must be declared as virtual function for runtime polymorphism to happen.
Template
template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don’t need to write the same code for different data types.
For example, same sorting algorithm can work for different type, so rather than writing and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.
template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don’t need to write the same code for different data types.
For example, same sorting algorithm can work for different type, so rather than writing and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.
Syntax:-
Define Templates
Templates can be defined using the keywords “template” and “typename” as shown:
template <typename A, typename B, ...>
entity_definition
The template keyword is used to define that the given entity is a template and typename keyword is used to define template parameters which are nothing but types that will be provided when an instance is created. The keyword typename can be replaced by keyword class anytime.
Difference between Class and Object
Class
Class is used as a template for declaring and creating the objects.
When a class is created, no memory is allocated.
The class has to be declared first and only once.
A class can not be manipulated as they are not
available in the memory.
A class is a logical entity.
It is declared with the class keyword
Class does not contain any values which can be associated with the field.
A class is used to bind data as well as methods together as a single unit.
Syntax: Declaring Class in C++ is as follows:
class <classname> {};
Example: Bike
Object
An object is an instance of a class.
Objects are allocated memory space whenever they are created.
An object is created many times as per requirement.
Objects can be manipulated.
An object is a physical entity.
It is created with a class name in C++ and
with the new keywords in Java.
Each object has its own values, which are associated with it.
Objects are like a variable of the class.
Syntax: Instantiating an object for a Class in C++ is as follows:
class Student {
public:
void put(){
cout<<“Function Called”<<endl;
}
}; // The class is declared here
int main(){
Student s1; // Object created
s1.put();
}
Example: Ducati, Suzuki, Kawasaki
Difference between Inheritance and Polymorphism:
Inheritance
Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class).
It is basically applied to classes.
Inheritance supports the concept of reusability and reduces code length in object-oriented programming.
Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance.
It is used in pattern designing.
Example : The class bike can be inherit from the class of two-wheel vehicles, which is turn could be a subclass of vehicles.
Polymorphism
Whereas polymorphism is that which can be defined in multiple forms.
Whereas it is basically applied to functions or methods.
Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding).
Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).
While it is also used in pattern designing.
Example : The class bike can have method name set_color(), which changes the bike’s color based on the name of color you have entered.
Difference between Abstraction and Encapsulation:
Abstraction
Abstraction is the process or method of gaining the information.
In abstraction, problems are solved at the design or interface level.
Abstraction is the method of hiding the unwanted information.
We can implement abstraction using abstract class and interfaces.
In abstraction, implementation complexities are hidden using abstract classes and interfaces.
he objects that help to perform abstraction are encapsulated.
Encapsulation
While encapsulation is the process or method to contain the information.
While in encapsulation, problems are solved at the implementation level.
Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
Whereas encapsulation can be implemented using by access modifier i.e. private, protected and public.
While in encapsulation, the data is hidden using methods of getters and setters.
Whereas the objects that result in encapsulation need not be abstracted.
Exception handling
Exception handling is a programming concept used to manage errors that occur during the execution of a program. When an error occurs, the normal flow of the program is disrupted. The program creates an “exception” object that contains information about the error. The process of responding to this exception is called “exception handling”.
Basics of Exception Handling :
Exception Handling mainly Revolves around two concepts one is Exception other is Handling.
Exception: An exception is an unwanted event that interrupts the normal flow of the program.
Handling: A block of Code that Handles or continues the flow of the program even after the exception is occurred (e.g. Try-Catch Block).
Components of Exception Handling:
Exception handling typically involves three main components:
Try Block: The code that may potentially throw an exception is enclosed within a try block. If an exception occurs within this block, the control is transferred to the corresponding catch block.
Catch Block: This block catches and handles the exceptions thrown within the try block. Each catch block is associated with a specific type of exception, allowing developers to handle different types of errors separately.
Finally Block (Optional): The finally block is executed regardless of whether an exception occurs or not. It is commonly used to perform cleanup tasks, such as closing files or releasing resources.
Comments
Post a Comment