KEMBAR78
Unit 2 Complete With Assignment 2 | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
21 views77 pages

Unit 2 Complete With Assignment 2

The document outlines assignments for Basic Computer Engineering, covering topics such as Object-Oriented Programming principles, programming paradigms, algorithm complexities, and the importance of algorithms and flowcharts. It includes specific questions for students to answer, such as defining programming terms, writing C++ programs, and explaining data structures. Additionally, it discusses the characteristics of algorithms, flowcharts, and programming languages, including low-level and high-level languages, along with their advantages and disadvantages.

Uploaded by

Ayushi Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views77 pages

Unit 2 Complete With Assignment 2

The document outlines assignments for Basic Computer Engineering, covering topics such as Object-Oriented Programming principles, programming paradigms, algorithm complexities, and the importance of algorithms and flowcharts. It includes specific questions for students to answer, such as defining programming terms, writing C++ programs, and explaining data structures. Additionally, it discusses the characteristics of algorithms, flowcharts, and programming languages, including low-level and high-level languages, along with their advantages and disadvantages.

Uploaded by

Ayushi Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Basic Computer Engineering – BT 205

Assignment No. 2.1

SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY


Branch: CS Session: 2025
Semester: II Date:
Subject: Basic Computer Engineering Subject Code: BT 205
Assignment No. 2.1 Attempt all questions

Q. No. Questions

1. List and describe the fundamental principles of Object-Oriented Programming (OOP).

2. Compare different programming paradigms, including Procedural Programming, Object-


Oriented Programming, and Functional Programming. Discuss the advantages and
disadvantages of each.

3. Explain different types of algorithm complexities.

4. Discuss why algorithms and flowcharts are essential prior to writing a computer program

5. Define a programming language. Compare Assembly language with High-Level Language


Basic Computer Engineering – BT 205
Assignment No. 2.2

SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY


Branch: CS Session: 2025
Semester: II Date:
Subject: Basic Computer Engineering Subject Code: BT 205
Assignment No. 2.2 Attempt all questions

Q. No. Questions
1. Define the following terms with suitable examples:
i. Character Set
ii. Tokens
iii. Identifiers
iv. Keywords
2.
Write a C++ program for finding roots of a Quadratic equation

3. Describe the general structure of a C++ program with example.

4. What is an Array in C++? Explain the types of arrays with examples. Also, discuss the advantages
and limitations of using arrays in C++.
OR
Write a C++ program to Calculates and displays the total marks and average for each student
for 5 students in 3 subjects using Array
5. What is a function in C++? Explain with proper syntax and examples. Why are functions
important in programming?
OR
Write a program in C++ using function for
 Prints "Positive" if the number is greater than 0
 Prints "Negative" if the number is less than 0.
 Prints "Zero" if the number is 0.
Basic Computer Engineering
BT 205

UNIT- II
Unit II
ALGORITHM
Algorithm can be defined as: “A sequence of activities to be processed for getting
desired output from a given input.”
“A formula or set of steps for solving a particular problem. To be an algorithm, a set of
rules must be unambiguous and have a clear stopping point”.
There may be more than one way to solve a problem, so there may be more than one
algorithm for a problem.
Then we can say that:
1. Getting specified output is essential after algorithm is executed
2. One will get output only if algorithm stops after finite time.
3. Activities in an algorithm to be clearly defined in other words for it to be
unambiguous.
ALGORITHM
Before writing an algorithm for a problem, one should find out what is/are the inputs to
the algorithm and what is/are expected output after running the algorithm. Now let us
take some exercises to develop an algorithm for some simple problems: While writing
algorithms we will use following symbol for different operations:
• ‘+’ for Addition
• ‘-’ for Subtraction
• ‘*’ for Multiplication
• ‘/’ for Division and ‘ ’ for assignment.
Example of Algorithm
Problem:
Write an algorithm to read two numbers and find their sum. Inputs to the algorithm: First
num1. Second num2.
Expected output: Sum of the two numbers.
Algorithm:
Step1: Start
Step2: Read num1 \input the first num1.
Step3: Read num2 \input the second num2.
Step4: Sum num1+num2 \ calculation of sum
Step5: Print Sum
Step6: End
Properties of algorithm
Finiteness: An algorithm must always terminate after a finite number of steps. It means after every step
one reach closer to solution of the problem and after a finite number of steps algorithm reaches to an
end point.
Definiteness: Each step of an algorithm must be defined. It is done by well thought actions to be
performed at each step of the algorithm. Also the actions are defined for each activity in the algorithm.
Input: Any operation you perform need some beginning value/quantities associated with different
activities in the operation. So the value/quantities are given to the algorithm before it begins.
Output: One always expects output/result (expected value/quantities) in terms of output from an
algorithm. The result may be obtained at different stages of the algorithm. If some result is from the
intermediate stage of the operation then it is known as intermediate result and result obtained at the
end of algorithm is known as end result. The output is expected value/quantities always have a specified
relation to the inputs.
Effectiveness: Algorithms to be developed/written using basic operations. Actually operations should be
basic, so that even they can be done exactly and in a finite amount of time by a person, by using paper
and pencil only.
Unit II
FLOWCHART
A flowchart is a type of diagram that visually explains a process or workflow. A flowchart is a visual
representation of the sequence of steps and decisions needed to perform a process. Each step in the
sequence is noted within a diagram shape. Steps are linked by connecting lines and directional arrows.
This allows anyone to view the flowchart and logically follow the process from beginning to end.

For example suppose you are going for a picnic with your friends then you plan for the activities you will do there. If
you have a plan of activities then you know clearly when you will do what activity. Similarly when you have a
problem to solve using computer or in other word you need to write a computer program for a problem then it will
be good to draw a flowchart prior to writing a computer program. Flowchart is drawn according to defined rules.
FLOWCHART SYMBOLS
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the
sequence of the steps, and the relationships among them. These are known as flowchart symbols.

Oval or Pill Shape - Represents the start or end Parallelogram - Represents input/output

Rectangle Shape - Represents a process Diamond Shape - Represents a decision


FLOWCHART SYMBOLS
FLOWCHART: GENERAL RULES
• Start and End must be clearly defined.
• Flow direction should be top-to-bottom or left-to-right.
• Use standard symbols (e.g., oval, rectangle, diamond).
• Each symbol should have one entry point.
• Decisions must have two or more exit points.
• Keep it clear, simple, and readable.
• Label arrows, especially after decisions.
• Ensure consistent symbol size and spacing.
• Avoid crossing lines – use connectors.
• Break complex flows into sub-flowcharts
FLOWCHART: EXAMPLES

FLOWCHART: Area of a Circle FLOWCHART: To check a number is Even or Odd


Unit II
ALGORITHM COMPLEXITY
Algorithmic complexity is concerned about how fast or slow particular algorithm
performs. Algorithmic complexity is a measure of how long an algorithm would take to
complete given an input of size n. If an algorithm has to scale, it should compute the
result within a finite and practical time bound even for large values of n. For this
reason, complexity is calculated asymptotically as n approaches infinity. While
complexity is usually in terms of time, sometimes complexity is also analysed in terms
of space, which translates to the algorithm's memory requirements.
TYPES

• Space Complexity
• Time Complexity
Space Complexity: It is the amount of memory which is needed by the algorithm (program) to run for
completion. We can measure the space by finding out that how much memory will be consumed by
the instructions and by the variables used. Suppose we want to add two integer numbers. To solve this
problem we have following two algorithms:
Algorithm 1: Algorithm 2:
Step 1- Input A. Step 1- Input A.
Step 2- Input B. Step 2- Input B.
Step 3- Set C: = A+ B. Step 3- Write: ‘Sum is ‘, A+B.
Step 4- Write: ‘Sum is ‘, C. Step 4- Exit.
Step 5- Exit.
• Both algorithms will produce the same result.
• First takes 6 bytes and second takes 4 bytes (2 bytes for each integer).
• First has more instructions than the second one.

We will choose the second one as it takes less space than the first one.
Time Complexity: It is the amount of time which is needed by the algorithm (program) to run to completion. We
can measure the time by finding out the compilation time and run time. The compilation time is the time which is
taken by the compiler to compile the program. This time is not under the control of programmer. It depends on
the compiler and differs from compiler to compiler. One compiler can take less time than other compiler to
compile the same program. So, we ignore the compilation time and only consider the run time. The run time is
the time which is taken to execute the program. We can measure the run time on the basis of number of
instructions in the algorithm.

Algorithm 1: Algorithm 2:
Step 1- Input A. Step 1- Input A.
Step 2- Input B. Step 2- Input B.
Step 3- Set C: = A+ B. Step 3- Write: ‘Sum is ‘, A+B.
Step 4- Write: ‘Sum is ‘, C. Step 4- Exit.
Step 5- Exit.
Suppose 1 second is required to execute one instruction. Algorithm 1 will take 4 sec Algorithm 2 will
take 3 sec. for execution.
So, we will choose the second one as it will take less time.
PROGRAM
• A program is a set of instructions given to a computer to perform a specific operation. or
computer is a computational device which is used to process the data under the control of
a computer program.
• While executing the program, raw data is processed into a desired output format. These
computer programs are written in a programming language which are high level
languages.
• High level languages are nearly human languages which are more complex then the
computer understandable language which are called machine language, or low level
language. So after knowing the basics, we are ready to create a very simple and basic
program.
• Like we have different languages to communicate with each other, likewise, we have
different languages like C, C++, C#, Java, python, etc to communicate with the computers.
• The computer only understands binary language (the language of 0’s and 1’s) also called
machine-understandable language or low-level language but the programs we are going
to write are in a high-level language which is almost similar to human language.
PROGRAMMING LANGUAGE
Computers understand instructions that are written in a specific syntactical form called a programming
language. A programming language provides a way for a programmer to express a task so that it could
be understood and executed by a computer
“Instruct the computer”: this basically means that you provide the computer a set of instructions that
are written in a language that the computer can understand. The instructions could be of various types.
For example: Adding 2 numbers, Rounding off a number, etc.
Just like we humans can understand a few languages (English, Spanish, Hindi, French, etc.), so is the
case with computers. Computers understand instructions that are written in a specific syntactical form
called a programming language.
“Perform various tasks”: the tasks could be simple ones like we discussed above (adding 2 numbers,
rounding off a number) or complex ones which may involve a sequence of multiple instructions. For
example:
• Calculating simple interest, given principal, rate and time.
• Calculating the average return on a stock over the last 5 years.
The above 2 tasks require complex calculations. They cannot usually be expressed in simple instructions
like adding 2 numbers, etc.
Programming is a way to tell computers to do a specific task
TYPES OF PROGRAMMING LANGUAGE
There are two types of programming languages, which can be categorized into the
following ways:
Low level language
a) Machine language (1GL)
b) Assembly language (2GL)
High level language
a) Procedural-Oriented language (3GL)
b) Problem-Oriented language (4GL)
c) Natural language (5GL)
Low level language
This language is the most understandable language used by computer to perform its
operations. It can be further categorized into:
Machine Language (1GL)
Machine language consists of strings of binary numbers (i.e. 0s and 1s) and it is the only
one language, the processor directly understands. Machine language has an Merits of very
fast execution speed and efficient use of primary memory.
Merits::It is directly understood by the processor so has faster execution time since the
programs written in this language need not to be translated. It doesn’t need larger
memory.
Demerits: It is very difficult to program using 1GL since all the instructions are to be
represented by 0s and 1s.
• Use of this language makes programming time consuming.
• It is difficult to find error and to debug.
• It can be used by experts only.
Assembly Language
Assembly language is also known as low-level language because to design a program programmer
requires detailed knowledge of hardware specification. This language uses mnemonics code
(symbolic operation code like ‘ADD’ for addition) in place of 0s and 1s. The program is converted
into machine code by assembler. The resulting program is referred to as an object code.
Merits: It makes programming easier than 1GL since it uses mnemonics code for programming.
Eg: ADD for addition, SUB for subtraction, DIV for division, etc.
• It makes programming process faster.
• Error can be identified much easily compared to 1GL.
Demerits: Programs written in this language is not directly understandable by computer so
translators should be used.
• It is hardware dependent language so programmers are forced to think in terms of computer’s
architecture rather than to the problem being solved.
• Being machine dependent language, programs written in this language are almost not portable.
• Programmers must know its mnemonics codes to perform any task.
High level language
Instructions of this language closely resembles to human language or English like
words. It uses mathematical notations to perform the task. The high level language
is easier to learn. It requires less time to write and is easier to maintain the errors.
The high-level language is converted into machine language by one of the two
different languages translator programs; interpreter or compiler.
High level language can be further categorized as:
• Procedural-Oriented language (3GL)
• Problem-Oriented language (4GL)
Procedural-Oriented language (3GL)
Procedural Programming is a methodology for modeling the problem being solved, by determining the
steps and the order of those steps that must be followed in order to reach a desired outcome or specific
program state. It is a programming paradigm based on the concept of procedures or functions. The main
focus is on writing procedures/functions to perform operations on data. such as Pascal, COBOL, C, FORTAN,
etc. Because of their flexibility, procedural languages are able to solve a variety of problems. Programmer
does not need to think in term of computer architecture which makes them focused on the problem.
• Program is divided into small procedures or functions.
• Emphasis is on how to solve the problem (i.e., the algorithm or steps).
Advantages:
• Simple and easy to understand for small projects.
• Code reusability through functions.
• Programs written in this language are portable
Disadvantages:
• Difficult to manage large codebases.
• Low security due to global data access.
Problem-Oriented language (4GL)
Problem-Oriented Programming refers to programming languages or styles that are designed to
solve specific types of problems within a particular domain or field. It allows the users to
specify what the output should be, without describing all the details of how the data should be
manipulated to produce the result. This is one step ahead from 3GL. These are result oriented
and include database query language. It is more abstract and focused on what needs to be
done rather than how. Such as C#, HTML, SQL
• Focuses on solving the problem, not implementation details.
• Languages or tools are tailored to a particular domain.
Advantages:
• Easier and faster development for specific tasks.
• Increases productivity in specialized areas.
Disadvantages:
• Not suitable for general-purpose programming.
• Limited flexibility outside the target domain.
Key Difference
Procedural and Problem-Oriented Programming
Features Procedural-Oriented Problem-Oriented

Focus How to solve the problem What problem to solve

Approach Step-by-step (procedural) Goal or task specific

Flexibility General-purpose Limited to a specific domain

Use Case Algorithmic/logical problems Domain-specific tasks


High Level Language vs Low Level Language
Features High-Level Language Low-Level Language
Abstraction Level High-level languages are more abstracted Low-level languages are closer to the machine
from the computer’s hardware and closer to language and hardware.
human language.
Difficulty Level Easy to use Hard to use
Development Time High-level languages allow for faster Low-level languages require more coding and
development time since they require less debugging, which increases development time.
coding and debugging.
Memory use More Less
Code Readability High-level languages have a more natural Low-level languages have a more cryptic
and readable syntax, which makes it easier syntax that is difficult to read and understand.
for programmers to read and understand
the code.
Portability High-level languages are more portable Low-level languages are more hardware-
across different hardware and software dependent.
platforms.
Application Area High-level languages are often used for Low-level languages are typically used for
software development, web development, system programming, device driver
and database management, development, and embedded systems.
Examples Python, C++, C, C#, Visual Basic, Machine language and Assembly language.
and JavaScript.
Natural language (5GL)
Natural language are still in developing stage where we could write statements that would look
like normal sentences.
Merits:
• Easy to program.
• Since, the program uses normal sentences, they are easy to understand.
• The programs designed using 5GL will have artificial intelligence (AI).
• The programs would be much more interactive and interesting.
Demerits:
• It is slower than previous generation language as it should be completely translated into binary
code which is a tedious task.
• Highly advanced and expensive electronic devices are required to run programs developed in
5GL. Therefore, it is an expensive approach.
Unit II
Program Design
Program Design is the process of planning and organizing the structure, logic, and flow of a
computer program before writing the actual code. It serves as a blueprint that guides
programmers in developing efficient, maintainable, and error-free software.

Benefits of Program Design

• Improves code clarity and maintainability.

• Helps in debugging and testing.

• Allows team collaboration and reuse of code.

• Enhances program performance and scalability.


Programming Paradigm
A programming paradigm is the classification, style or way of programming. It is an approach to solve
problems by using programming languages.
• Programming paradigms dictate how programmers should think about and structure their code.
• There are lots for programming language that are known but all of them need to follow some strategy
when they are implemented and this methodology/strategy is paradigms. Apart from varieties of
programming language there are lots of paradigms to fulfill each and every demand. Each
programming paradigm has its own set of concepts and features.
For example, procedural programming focuses on procedures and functions, object-
oriented programming revolves around objects and classes
• Many programming languages support multiple paradigms, allowing programmers to combine
and leverage different approaches to suit their needs.
• Programming paradigms are not languages or tools. You can't "build" anything with a
paradigm. They're more like a set of ideals and guidelines that many people have agreed on,
followed, and expanded upon.
Imperative Programming Paradigm
Imperative programming consists of sets of detailed instructions that are given to the
computer to execute in a given order. It's called "imperative" because as programmers we
dictate exactly what the computer has to do, in a very specific way.
Imperative programming focuses on describing how a program operates, step by step.

Advantage
• Very simple to implement
• It contains loops, variables etc.
Disadvantage
• Complex problem cannot be solved (as the complexity increase the code become lengthy
and long imperative code becomes unmanageable)
• Less efficient and less productive (Due to manually manage the flow of control the
development process become slower and sometime lead to inefficient state handling)
• *Parallel programming is not possible (Variables in imperative coding keep changing as
program execution so, it is difficult to run many parts at the same time without problems)

*Parallel programming Parallel programming means running many parts of a program at the same time
eg: multiple developer working on a same project to finish faster.
Imperative Programming
Imperative programming is divided into three broad categories:
• Procedural
• OOP
• Parallel processing
Procedural
• This paradigm emphasizes on procedure in terms of under lying machine model.
• There is no difference in between procedural and imperative approach.
• It has the ability to reuse the code and it was boon at that time when it was in use because of its
reusability.
Object Oriented Programming
• The program is written as a collection of classes and object which are meant for communication.
• The smallest and basic entity is object and all kind of computation is performed on the objects
only.
• More emphasis is on data rather procedure. It can handle almost all kind of real life problems
which are today in scenario.
Imperative Paradigm Types
Parallel Processing Approach
• Parallel processing is the processing of program instructions by dividing them among
multiple processors.
• This approach posses many numbers of processor with the objective of running a program in
less time by dividing them.
• It seems to be like divide and conquer. Examples are NESL (one of the oldest one) and C/C++
also supports because of some library function.
Declarative Programming Paradigm
• Declarative programming is a style of building programs that
expresses logic of computation without talking about its control
flow. It is divided as Logic, Functional, Database.
• It may simplify writing parallel programs. It often considers programs
as theories of some logic.
• The focus is on what needs to be done rather how it should be done
basically emphasize on what code is actually doing.
• It just declares the result we want rather how it has be produced.

imperative (how to do) vs declarative (what to do)


Declarative Paradigm Types

Logic Programming Paradigms


• It can be described as an abstract model of computation used to
solve logical problems such as puzzles and sequences.
• In logic programming, we use a predefined knowledge base
along with the given problem.
• The machine processes both the knowledge base and the
problem to generate a solution.
• The main emphasize is on knowledge base and the problem.
• The execution of the program is very much like proof of
mathematical statement
Declarative Paradigm Types
Functional Programming Paradigms
• The functional programming paradigms has its roots in mathematics
and it is language independent.
• The key principle of this paradigms is the execution of series of
mathematical functions.
• The central model for the abstraction is the function which are meant
for some specific computation not data structures.
• Data are loosely coupled to functions.
• The function hide their implementation.
• Function can be replaced with their values without changing the
meaning of the program.
• Some of the languages like perl, javascript mostly uses this paradigm.
Declarative Paradigm Types
Database/Data driven programming approach
• This programming methodology is based on data and its movement.
• Program statements are defined by data rather than hard-coding a
series of steps.
• There are several programming languages that are developed mostly
for database application. For example SQL.
• A database program is the heart of a business information system and
provides file creation, data entry, update, query and reporting
functions.
Characteristics or Concepts of OOP
Object-oriented programming – As the name suggests uses objects in programming. Object-oriented
programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in
programming. The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
Characteristics of an Object Oriented Programming language
Procedure Oriented Programming VS object oriented programming.

POP OOP
In procedural programming, program is divided In object oriented programming, program is divided
into small parts called functions. into small parts called objects.

Procedural programming follows top down Object oriented programming follows bottom up
approach. approach.
There is no access specifier in procedural Object oriented programming have access specifiers
programming. like private, public, protected etc.
Adding new data and function is not easy. Adding new data and function is easy.

Procedural programming does not have any Object oriented programming provides data hiding so
proper way for hiding data so it is less secure. it is more secure.

In procedural programming, overloading is not Overloading is possible in object oriented


possible. programming.
In procedural programming, function is more In object oriented programming, data is more
important than data. important than function.
Procedural programming is based on unreal Object oriented programming is based on real world.
world.
Objects:
In other words object is an instance of a class. An Object is an instance of a Class. An Object is an instance of a
Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.

Classes:
A class in C++ is a user-defined type or data structure declared with keyword class that has data and functions
(also called member variables and member functions) as its members whose access is governed by the
three access specifiers private, protected or public. By default access to members of a C++ class is private. The
private members are not accessible outside the class; they can be accessed only through methods of the class.
The public members form an interface to the class and are accessible outside the class.

Defining Class and Declaring Objects


A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside
the curly brackets and terminated by a semicolon at the end.
• Inheritance is the process by which objects of one class acquire the properties of objects of another
class. In OOP, the concept of inheritance provides the idea of reusability. This means we can add
additional features to an existing class without modifying it.
• Data Encapsulation : The wrapping up of data and functions into a single unit is known as
encapsulation. The data is not accessible to the outside world, only those function which are
wrapped in, can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding or
information hiding.
• Polymorphism, The process of representing one Form in multiple forms is known as Polymorphism.
Here one form represent original form or original method always resides in base class and multiple
forms represents overridden method which resides in derived classes. Polymorphism is derived from 2
greek words: poly and morphs. The word "poly" means many and morphs means forms. So
polymorphism means many forms.
• Abstraction refers to the act of representing essential features without including the background
details or explanations. It means hiding the unnecessary details and showing only the important stuff
to make things easier to use. Since classes use the concept of data abstraction, they are known as
Abstract Data Types (ADT)
Introduction to C++
• Bjarne Stroustrup (Bell Labs, 1979)
• started as extension to C (macros and variables)
• added new useful, features
• C++ (the next thing after C)
• Also known as C with Classes
Introduction to C++

• Developed by Bjarne Stroustrup (Bell Labs)


• Started as extension to C (macros and variables)
• It is a high-level programming language that was first released in 1985
• It has become the foundation of many modern technologies like game engines,
web browsers, operating systems, financial systems, etc.
• Also known as C with Classes
Introduction to C++ Unit II
Character set
• It is the combination of English language (Alphabets and White spaces) and math's
symbols (Digits and Special symbols).
• Letters A-Z, a-z.
• Digits 0-9
• Special Characters Space + - * / ^ \ ( ) [ ] { } = ! = < > . ‘ " $ , ; : % ! & ? _ # <= >= @
• White spaces Horizontal tab (—>), Blank space, Carriage return (< ) Newline, form feed.
• Character Set means that the characters and symbols that a C++ Program can understand
and accept.
• These are grouped to form the commands, expressions, words, c-statements and other
tokens for C++ Language.
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}
Introduction to C++
Tokens
• Tokens are the smallest units in a program that have meaningful representations.
• The programmer can write a program by using tokens.
• They are the building blocks of a program, and they are recognized by the compiler to form valid
expressions and statements.
• Tokens can be classified into various categories, each with specific roles in the program.
C++ uses the following types of tokens.

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}
Introduction to C++
Preprocessors
• They are the Source of our Program those are Executed when they are passing to
Compiler.
• Preprocessors are always executed at the Time of Compilations.
• These provide many features called Preprocessor directives. Each Preprocessor is
declared with # symbol and must be written before a main program.

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}
C++ Syntax..
Syntax
Syntax refers to the rules and regulations for writing statements in a programming
language. They can also be viewed as the grammatical rules defining the structure of a
programming language.

Header File
The header files contain the definition of the functions
#include <iostream>
and macros we are using in our program. In line #1, we
using namespace std;
used the #include <iostream> statement to tell the
compiler to include an iostream header file library which int main() {
stores the definition of the cin and cout standard cout << "Hello, World!";
input/output streams that we have used for input and return 0;
output. #include is a preprocessor directive using which }
we import header files.
..C++ Syntax..

Namespace
A namespace in C++ is used to provide a scope or a region
where we define identifiers. In line #2, we have used
the using namespace std statement for specifying that we
will be the standard namespace where all the standard
#include <iostream>
library functions are defined.
using namespace std;
Main Function
int main() {
In line #3, we defined the main function as int main(). The cout << "Hello, World!";
program execution always starts from the main function. All return 0;
the other functions are called from the main function. }
In C++, the main function is required to return some value
indicating the execution status.
..C++ Syntax..

Blocks
Blocks are the group of statements that are enclosed within {
} braces. The body of the main function is from line #4 to line
#5 enclosed within { }.
#include <iostream>
Semicolons using namespace std;
Each statement in the given code is followed by a ( ; ) semicolon
symbol. It is used to terminate each line of the statement of the int main() {
program. cout << "Hello, World!";
return 0;
Identifiers }
We use identifiers for the naming of variables, functions, and
other user-defined data types. An identifier may consist of
uppercase and lowercase alphabetical characters, underscore,
and digits. The first letter must be an underscore or an alphabet.
..C++ Syntax
Keywords
In the C++ programming language, there are some reserved words that are used for some special meaning
in the C++ program. It can’t be used for identifiers. For example, the words int, return, and using are
some keywords used in our program.

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}
..C++ Syntax

Basic Output cout


In line #4, we have used the cout stream object (declared in the <iostream> header file)
to print the Hello, World! to the standard output stream (stdout).

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}
Dev C++
Data Types in C++
A data type determines the type and the operations that can be performed on the
data. It specify the size of the variable and the type of the value that can be stored in
computer memory. C++ provides various data types and each data type is
represented differently within the computer's memory.

https://www.geeksforgeeks.org/cpp-data-types/
Basic or built-in data type
They are also known as the fundamental data type. They are integral, floating point and void data
type. Among these data types, the integral and floating-point data types can be preceded by
several type modifiers. These modifiers (also known as type qualifiers) are the keywords that alter
either size or range or both of the data types. The various modifiers are short, long, signed and
unsigned. By default the modifier is signed.
eg: int, char, float, short, double, long etc

• Integer: Numbers without the fractional part represent integer data. Keyword used for
integer data types is int. Integers typically requires 4 bytes of memory space and ranges from
-2147483648 to 2147483647.

• Character: Characters refer to the alphabet, numbers and other characters (such as {, @, #,
etc.) defined in the ASCII character set. Character data type is used for storing characters.
Keyword used for character data type is char. Characters typically requires 1 byte of memory
space and ranges from -128 to 127 or 0 to 255.

• Floating-point Data Type: A floating-point data type is used to store real numbers such as 3
.28, 64. 755765, 8.01, -24.53. This data type includes float and double' data types.

https://www.geeksforgeeks.org/cpp-data-types/
Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store
either true or false. Keyword used for boolean data type is bool.

https://www.geeksforgeeks.org/cpp-data-types/
Derived Data Types:
Data types that are derived from the built-in data types are known as derived data types. The various
derived data types provided by C++ are
arrays, functions, references and pointers.

Array: An array is a set of elements of the same data type either all are integers, or floating pt, or all
characters that are referred to by the same name. All the elements in an array are stored at contiguous
(one after another) memory locations and each element is accessed by a unique index or subscript
value. The subscript value indicates the position of an element in an array.
The elements field within brackets [] which represents the number of elements the array is going to
hold, must be a constant value. Arrays are blocks of non-dynamic memory whose size must be
determined before execution.
Eg: Int marks[10];

Memory allocation

https://www.geeksforgeeks.org/cpp-data-types/
Sample Array Memory allocation

Syntax:
DataType ArrayName[size_of_array];

https://www.geeksforgeeks.org/cpp-data-types/
Drawback of Array

• Contiguous memory
• Use only one type of data type(homogeneous)
• But if we want to store different data type then array is not suitable.
• The size of the array must be defined in advance for eg: if we declared
the array of 20 element
• Int x[20];

https://www.geeksforgeeks.org/cpp-data-types/
Function
• A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions
which can be invoked from other parts of a program, if required.
• A function is generally defined to save the user from writing the same
lines of code again and again for the same input. All the lines of code are
put together inside a single function and this can be called anywhere
required. main() is a default function that is defined in every program of
C++.
Reference
A reference is an alternative name for a variable. That is, a reference is an alias for a
variable in a program. A variable and its reference can be used interchangeably in a
program as both refer to the same memory location. Hence, changes made to any of
them (say, a variable) are reflected in the other (on a reference).
int main ()
{
// declare simple variables
int i; double d;
// declare reference variables
int& r = i;
Pointer
A pointer is a variable that can store the memory address of another variable.
Pointers allow to use the memory dynamically. That is, with the help of pointers,
memory can be allocated or de-allocated to the variables at run-time, thus,
making a program more efficient.
Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data
structures. It’s general declaration in C/C++ has the format
Syntax: datatype *var_name;
Instructions in C++

There are many different types of Constants variables and Keywords in c++ Language.
There are basically four types of Instructions in C++.
• Type Declaration Instructions
In the Type Declaration generally variables are declared
• Input/output Instructions
In Input and output instructions we performs input data to the program and also obtaining
the output Results from it.
• Arithmetic Instructions
Arithmetic instructions are used for performing the Arithmetic operations like addition,
subtraction and Multiplication etc.
• Control Instruction
Control Instructions are used for controlling the execution of the Program or these are used
for changing the Sequence of the Program
User-defined Data Types
It use the built-in data types and other user-defined data types as the building blocks
for data types that model the structure and behavior of data in applications. User-defined
types are schema objects. Their use is subject to the same kinds of administrative control as
other schema objects.
• Class It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is
like a blueprint for an object.
• Structure is a collection of different types of variables works under one name and
providing convenient way of keeping related information
• Union is a group of variables of different data types. the member of union shares same
memory area.
Both structure and union are used to group number of different variables together. But the
member of structure occupies different memory area for different member. But the
members of the union shares same memory area for all members
#include <iostream> C++ Class Program : Sample
#include <string>
using namespace std;

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
• class Box
• { public:
• double length; // Length of a box
• double breadth; // Breadth of a box
• double height; // Height of a box
• };
The keyword public determines the access attributes of the members of the class that follow it.
A public member can be accessed from outside the class anywhere within the scope of the class
object. You can also specify the members of a class as private or protected.
Structure
Struct book
{
Int book no.=1;
Float book price=200;
Char book name[3]=“fcse”;
};

Union:
Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the C++ program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
Control Statements
C++ supports the usual logical conditions from mathematics:

Less than: a < b


Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
we can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

•Use if to specify a block of code to be executed, if a specified condition is true


•Use else to specify a block of code to be executed, if the same condition is false
•Use else if to specify a new condition to test, if the first condition is false
•Use switch to specify many alternative blocks of code to be executed
IF STATEMENT eg
If we want more than a single statement to be executed in case
that the condition is true we can specify a block using braces { }:
if (condition)
{statement1;}
Example
if (20 > 18)
{
cout << "20 is greater than 18";
}
If-else
We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:

if (condition)
{statement1;}
else
{statement2;}
Switch
The switch expression is evaluated once. The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
C++ Loops/control structures
• Loops can execute a block of code as long as a specified condition is
reached.
• They are handy because they save time, reduce errors, and they make
code more readable.
For loop
for(initialization; condition,checking; increment or decrement)
while/do..while loop
• When creating a while-loop, we must always consider that it has to end at some point, therefore we must
provide within the block some method to force the condition to become false at some point, otherwise
the loop will continue looping forever.
• In the example below, the code in the loop will run, over and over again, as long as a variable (i) is
less than 5:

#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
return 0;
}
Do-while loop
• The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.
• The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
break
This statement can be used to terminate a repeated structure (loops) such as while, do while and
for and multi branching statements like switch.
The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4

for (int i = 0; i < 10; i++)


{
if (i == 4)
{
break;
}
cout << i << "\n";
}
Continue:
Like the statement break continue can be used in repeated structure. However this statements
repeats the loop for next value (next iteration) i.e. the statement continue transfers the control
back to the beginning of the loop by ignoring a set of statements written after it.
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 4:
OUTPUT
goto
This statement transfers control from one part of the program to the other part.
Exist statement
• It is used to terminate the execution of the program.it is used when
we want to stop the execution of the program depending on some
condition.it is present in process .h header file.

You might also like