This document provides an overview of various fundamental concepts in problem solving and computer programming, including data types, operators, control flow statements, arrays, and functions. It describes the different types of data types like integer, floating point, character, boolean, derived, and user-defined types. It also explains various categories of operators like unary, binary, arithmetic, relational, logical, and bitwise operators. Additionally, it covers decision making statements, loops, jumping statements, and escape sequences to control program flow. The document also discusses arrays, pointers, functions, and classes.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
it covers the following topics:
Java Evolution
Overview
Constants, variables & data types
Operators and expressions
Decision making and branching
Decision making and looping
Classes, objects & methods
Arrays, Strings and Vectors
Interface
Packages
Multi-threading
Managing errors and exceptions
Applet programming
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
it covers the following topics:
Java Evolution
Overview
Constants, variables & data types
Operators and expressions
Decision making and branching
Decision making and looping
Classes, objects & methods
Arrays, Strings and Vectors
Interface
Packages
Multi-threading
Managing errors and exceptions
Applet programming
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation on data stored in variables. The variables that are operated are termed as operands.
C operators can be classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Increment and decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators
Now, let us discuss each category in detail.
In this session you learn about
1. How to download and install java in your PC
2, How to write simple Java Program
3. Operators in Java
4. Types of operators
i) Arithmetic operators
ii) Relational operators
iii) Logical operators
iv)Ternary operator
v) Bitwise operators
vi) Assignment operators
vii) Unary operators
viii) Special operators
5. Operators precedence
Complete Information till 2D arrays. In this slides you can also find information about loops and control decision....
Best slides for beginners who wants to learn about C programming language..
Control structures in C++ Programming LanguageAhmad Idrees
The aim of this list of programming languages is to include all notable programming languages in existence, both those in current use and ... Note: This page does not list esoteric programming languages. .... Computer programming portal ...
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
More Related Content
Similar to Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation on data stored in variables. The variables that are operated are termed as operands.
C operators can be classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Increment and decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators
Now, let us discuss each category in detail.
In this session you learn about
1. How to download and install java in your PC
2, How to write simple Java Program
3. Operators in Java
4. Types of operators
i) Arithmetic operators
ii) Relational operators
iii) Logical operators
iv)Ternary operator
v) Bitwise operators
vi) Assignment operators
vii) Unary operators
viii) Special operators
5. Operators precedence
Complete Information till 2D arrays. In this slides you can also find information about loops and control decision....
Best slides for beginners who wants to learn about C programming language..
Control structures in C++ Programming LanguageAhmad Idrees
The aim of this list of programming languages is to include all notable programming languages in existence, both those in current use and ... Note: This page does not list esoteric programming languages. .... Computer programming portal ...
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
1. Problem Solving and Computer Programming 1
Problem Solving and Computer
Programming
Data Types
Operators- arithmetic, relational, logical, bitwise, pointer, miscalleneous
Decision making Statements
Loops
Jump statements
Escape sequences
Arrays
Searching
Sorting
Pointers and references
Functions
Methods of passing parameters
Recursion
Function overloading/polymorphism,
Function templating
Storage classes
Structures
Unions
OOP and Classes:
Class
Constructor
2. Problem Solving and Computer Programming 2
Destructor
Binary operator overloading
Friend functions
Friend Classes
Inheritance
File management
Strings
Data Types
Data types define the type of data that a variable can hold.
Primary/Fundamental Data Types
1. Integer Types:
int : Integer type, representing whole numbers.
short : Short integer type.
3. Problem Solving and Computer Programming 3
long : Long integer type.
2. Floating-Point Types:
float : Single-precision floating-point type.
double : Double-precision floating-point type.
long double : Extended precision floating-point type.
3. Character Types:
char : Character type, representing a single character.
wchar_t : Wide character type.
4. Boolean Type:
bool : Boolean type, representing true or false values.
Derived Data Types
1. Function : A derived data type that encapsulates executable code, declared with a
return type and parameters.
2. Array : Collection of elements of the same data type arranged in a fixed-size
sequence.
3. Pointer : A variable that stores the memory address of another variable.
4. Reference : An alternative name for an existing variable.
User-defined Data Types
1. Class : A user-defined data type that can encapsulate data members and
member functions.
2. Structure : A user-defined composite data type that groups variables of different
data types under a single name.
3. Union : Similar to a structure, but it uses the same memory location for all its
members, allowing different data types to share the same memory space.
4. Enum : A user-defined data type consisting of named integer constants.
typedef : It is a keyword used to create an alternate name for a data type,
enhancing code readability and providing a convenient way to declare complex or
compound data types.
4. Problem Solving and Computer Programming 4
Example:
typedef long int lint;
lint x1,x2;//declares long integers x1 and x2
Operators
Operators are symbols that perform operations on operands, which can be variables,
constants, or expressions.
They can be classified into the following major types:
Unary operators
Unary operators operate on a single operand.
Prefix Increment ( ++x ):
Increments the value of x before its current value is used and the updated value is
immediately available for use in the expression.
Example:
int x = 5;
int y = ++x; // y is 6, x is 6
Postfix Increment ( x++ ):
Uses the current value of x in an expression before incrementing it and the update
occurs after the current value is used.
Example:
int x = 5;
int y = x++; // y is 5, x is 6
Add and Assign ( += ):
Adds the right operand to the left operand and assigns the result to the left operand.
5. Problem Solving and Computer Programming 5
int a = 3;
a += 2; // Equivalent to a = a + 2; a is now 5
Operators like -- , -= , *= , /= , %= also work accordingly.
Binary operators
Binary operators operate on two operands.
Arithmetic Operators:
1. + (Addition): Adds two operands.
2. - (Subtraction): Subtracts the right operand from the left operand.
3. * (Multiplication): Multiplies two operands.
4. / (Division): Divides the left operand by the right operand.
5. % (Modulus): Returns the remainder of the division of the left operand by the
right operand.
Relational Operators:
1. == (Equal to): Checks if the values of two operands are equal.
2. != (Not equal to): Checks if the values of two operands are not equal.
3. > (Greater than): Checks if the value of the left operand is greater than the
value of the right operand.
4. < (Less than): Checks if the value of the left operand is less than the value of
the right operand.
5. >= (Greater than or equal to): Checks if the value of the left operand is greater
than or equal to the value of the right operand.
6. <= (Less than or equal to): Checks if the value of the left operand is less than
or equal to the value of the right operand.
Logical Operators:
1. && (Logical AND): Returns true if both operands are true.
2. || (Logical OR): Returns true if at least one of the operands is true.
3. ! (Logical NOT): Returns true if the operand is false and vice versa.
6. Problem Solving and Computer Programming 6
Bitwise Operators:
1. & (Bitwise AND): Performs bitwise AND operation on corresponding bits of two
operands.
2. | (Bitwise OR): Performs bitwise OR operation on corresponding bits of two
operands.
3. ^ (Bitwise XOR): Performs bitwise XOR (exclusive OR) operation on
corresponding bits of two operands.
4. ~ (Bitwise NOT): Flips the bits of the operand, changing 1s to 0s and vice
versa.
5. << (Left Shift): Shifts the bits of the left operand to the left by a specified
number of positions.
6. >> (Right Shift): Shifts the bits of the left operand to the right by a specified
number of positions.
Pointer operators:
1. & (Address-of Operator): Returns the memory address of a variable.
2. * (Pointer Declaration): Declares a pointer variable or dereferences a pointer,
depending on the context.
Miscalleneous Operators:
1. = (Assignment Operator): Assigns the value of the right operand to the left
operand.
2. sizeof : Returns the size, in bytes, of an object or data type.
3. :: (Scope Resolution Operator): Specifies the scope of a variable or function,
especially in the context of namespaces and classes.
4. new : Dynamically allocates memory for a variable or object during runtime.
5. delete : Deallocates memory that was previously allocated using new .
6. ? : (Ternary Conditional Operator): A shorthand way of writing an if-else
statement, allowing conditional expressions.
7. . ( Dot operator): Member access
8. -> (Arrow operator): Member access through pointer
7. Problem Solving and Computer Programming 7
Decision-Making Statements
Decision-making statements are used to control the flow of a program based on
certain conditions.
If statement
Executes a block of code if the specified condition is true. If the condition is false, the
code block is skipped.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
int x = 10;
if (x > 5)
{
cout << "x is greater than 5." << endl;
}
If - else Statement
Executes one block of code if the condition is true and another block if the condition
is false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
8. Problem Solving and Computer Programming 8
// Code to execute if the condition is false
}
Example:
int x = 3;
if (x > 5)
{
cout << "x is greater than 5." << endl;
}
else
{
cout << "x is not greater than 5." << endl;
}
If - else if - else Statement
Allows you to specify multiple conditions and execute different code blocks based on
which condition is true. It's used for choosing from several options.
Syntax:
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
//...
else
{
// Code to execute if neither condition1 nor conditio
}
Example:
9. Problem Solving and Computer Programming 9
int x = 7;
if (x < 5)
{
cout << "x is less than 5." << endl;
}
else if (x == 5)
{
cout << "x is equal to 5." << endl;
}
else
{
cout << "x is greater than 5." << endl;
}
//Output: x is greater than 5.
Switch Statement
Provides a way to select one of many code blocks to execute based on the value of
an expression. It's often used for menu-like selection.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ...
default:
// Code to execute if none of the cases match
}
Example:
int choice = 2;
switch (choice)
10. Problem Solving and Computer Programming 10
{
case 1:
cout << "You chose option 1." << endl;
break;
case 2:
cout << "You chose option 2." << endl;
break;
case 3:
cout << "You chose option 3." << endl;
break;
default:
cout << "Invalid choice." << endl;
}
//Output: You chose option 2.
Conditional (Ternary) Operator
Offers a concise way to choose between two expressions based on a condition. It
returns one of two values depending on whether the condition is true or false.
Syntax:
(condition) ? expression_if_true : expression_if_false;
Example:
int x = 7;
string result = (x > 5) ? "x is greater than 5" : "x is not g
cout << result << endl;
return 0;
//Output : x is greater than 5
These decision making statements can be nested to handle more complex decision-
making scenarios where you need to evaluate multiple conditions within a
hierarchical structure.
11. Problem Solving and Computer Programming 11
Loop Statements
Loop statements are used to repeatedly execute a block of code as long as a
specific condition is met.
for Loop
The for loop is commonly used for iterating over a range or sequence of values. It
includes an initialization step, a condition to check before each iteration, and an
updation step that is executed after each iteration.
Syntax:
for (initialization; condition; update)
{
// Code to repeat while the condition is true
}
Example:
for (int i = 0; i < 5; ++i)
{
cout<<i<<" ";
}
//output: 0 1 2 3 4
while Loop
The while loop repeatedly executes a block of code as long as the specified
condition is true. It does not require an initialization step, but it's crucial to ensure that
the condition eventually becomes false to avoid an infinite loop.
Syntax:
while (condition)
{
// Code to repeat while the condition is true
}
12. Problem Solving and Computer Programming 12
Example:
int i = 0;
while (i < 5)
{
cout<< i<<" ";
i++;
}
//output: 0 1 2 3 4
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once before checking the initial condition. The loop continues as
long as the condition remains true.
Syntax:
do
{
// Code to repeat at least once
} while (condition);
Example:
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
//output: 0 1 2 3 4
Example to show the difference between the working of while and do-while loops:
int i = 0;
while (i < 0)
{
cout << i << " ";
i++;
13. Problem Solving and Computer Programming 13
}
// No output
In a while loop with the condition i < 0 , the loop body would not be executed at all
because the initial value of i is 0, which does not satisfy the condition.
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 0);
//output: 0
In a do-while loop with the condition i < 0 , the loop body would be executed at least
once before checking the condition. The output would be 0 , and the loop would
terminate after the first iteration.
The do-while loop guarantees at least one execution of the loop body before
evaluating the condition.
Nesting of these loop statements allows for the creation of complex and structured
control flow, enabling the execution of repetitive tasks within other repetitive tasks.
Nesting loop statements with decision-making (conditional) statements allows for
executing certain blocks of code repeatedly based on conditions, leading to more
flexible and powerful program logic.
Jumping Statements
Jumping statements change the normal flow of control within a program. The main
jumping statements are break , continue , return and goto .
The break and continue statements are generally used within loops ( for , while , do-
while ) and
switch statements.
1. break : Terminates the innermost loop or switch statement and transfers control
to the statement following the terminated loop or switch.
14. Problem Solving and Computer Programming 14
2. continue : Skips the rest of the loop's code and proceeds to the next iteration of
the loop.
3. return : Terminates the execution of a function and returns a value (if applicable)
to the calling function.
4. goto : Transfers control to a labeled statement in the program.
Note: Using goto is generally discouraged due to its potential to create unreadable
and unmaintainable code.
Escape Sequences
Escape sequences are special combinations of characters that represent non-
printable or special characters.
Commonly used escape sequences:
1. t : Horizontal tab character
2. v : Vertical tab character
3. n : Newline character, indicating a new line
4. a : Produces an audible alert or beep
5. : Represents a backslash character
6. " : Represents a double quote character within a string
7. ' : Represents a single quote character within a string
8. b : Backspace character
9. r : Carriage return character → move the cursor or print-head back to the
beginning of the line.
Arrays
Arrays are used to store a collection of elements of the same data type under a
single name. They provide a way to efficiently manage and access multiple values
15. Problem Solving and Computer Programming 15
using a single identifier. They provide a convenient way to manage and iterate over
sequential data.
Syntax:
data_type array_name[array_size]={element1, element2, element3
//The number of elements the array can store is the value of a
data_type : Specifies the type of elements the array will hold.
array_name : The name assigned to the array.
array_size : The number of elements the array can hold.
Indexing: Array elements are accessed using their index, starting from 0 for the
first element and incrementing by 1 for each subsequent element.
array_name[index]
Examples:
#include <iostream>
using namespace std;
int main() {
// Declaration and initialization of an integer array
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing and printing array elements
cout << "Element at index 0: " << numbers[0] << endl;
cout << "Element at index 2: " << numbers[2] << endl;
return 0;
}
//Output:
//Element at index 0: 10
//Element at index 2: 30
Taking input from the user:
16. Problem Solving and Computer Programming 16
#include <iostream>
using namespace std;
int main() {
cout<<"Enter the size of the array: ";
cin>>size;
int numbers[size];
cout<<"Enter the elements: ";
for(int i=0;i<size;i++){
cin>>numbers[i];
}
return 0;
}
2D Arrays
A two-dimensional array is a data structure that represents a grid or matrix of
elements arranged in rows and columns. It can be visualized as an array of arrays,
where each element in the array is itself an array. This structure allows for the
representation of tables, matrices, and other two-dimensional data. Accessing
elements in a 2D array requires specifying both the row and column indices.
Example:
#include <iostream>
using namespace std;
int main() {
int rows1, cols1, rows2, cols2;
//Inputting the matrices
cout<<"Enter the number of rows of matrix 1: ";
cin>>rows1;
cout<<"Enter the number of columns of matrix 1: ";
17. Problem Solving and Computer Programming 17
cin>>cols1;
cout<<"Enter the number of rows of matrix 2: ";
cin>>rows2;
cout<<"Enter the number of columns of matrix 2: ";
cin>>cols2;
int matrix1[rows1][cols1];
int matrix2[rows2][cols2];
cout<<"Enter the elements of matrix 1: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cin>>matrix1[i][j];
}
}
cout<<"Enter the elements of matrix 2: ";
for(int i=0;i<rows2;i++){
for(int j=0;j<cols2;j++){
cin>>matrix2[i][j];
}
}
//Displaying the matrices
cout<<"Matrix 1: "<<endl;
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<matrix1[i][j]<<" ";
}
cout<<endl;
}
cout<<"Matrix 2: "<<endl;
for(int i=0;i<rows2;i++){
for(int j=0;j<cols2;j++){
cout<<matrix2[i][j]<<" ";
18. Problem Solving and Computer Programming 18
}
cout<<endl;
}
//Adding the matrices
if(rows1==rows2 && cols1==cols2){
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
cout<<"Addition matrix: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix addition is not possible!"<<endl;
}
//Subtracting the matrices
if(rows1==rows2 && cols1==cols2){
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
cout<<"Subtraction matrix: ";
for(int i=0;i<rows1;i++){
19. Problem Solving and Computer Programming 19
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix subtraction is not possible!"<<endl;
}
//Multiplying the matrices
if(cols1==rows2){
int common = cols1;
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] =0;
for(int k=0;k<common;k++){
result[i][j] += matrix1[i][k]*matrix2[k][j
}
}
}
cout<<"Multiplication matrix: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix multiplication is not possible!"<<endl;
}
return 0;
}
20. Problem Solving and Computer Programming 20
Character arrays
A character array is an array of characters. It is a data structure that allows you to
store a sequence of characters under a single identifier. Character arrays are used to
represent strings in C++.
They are null-terminated, meaning that the end of the string is marked by a null
character ( 0 ). This null character is automatically appended when a character array
is initialised.
#include <iostream>
using namespace std;
int main() {
const int arraySize = 10;
char greeting[arraySize] = "Hello";
cout << "The greeting is " << greeting << endl;
return 0;
}
//Output: The greeting is Hello
Searching
Searching is an operation that finds the location of a given element in a list. The
search is said to be successful or unsuccessful depending on whether the element
that is to be searched is found or not. Here, we will discuss two standard searching
methods - Linear search and Binary search.
Linear Search
21. Problem Solving and Computer Programming 21
#include <iostream>
using namespace std;
// Function to perform linear search
int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; ++i) {
if (arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}
int main() {
const int size = 5;
int arr[size] = {10, 25, 30, 15, 20};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = linearSearch(arr, size, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
22. Problem Solving and Computer Programming 22
}
return 0;
}
Binary Search
Example:
#include <iostream>
using namespace std;
// Function to perform binary search
int binarySearch(int arr[], int size, int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + (high - low)) / 2;
23. Problem Solving and Computer Programming 23
if (arr[mid] == key) {
return mid; // Return the index if the key is fou
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Return -1 if the key is not found
}
int main() {
int size = 10;
int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = binarySearch(arr, size, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
24. Problem Solving and Computer Programming 24
Binary search using Recursion (refer Recursion topic)
Sorting
Sorting refers to arranging elements of a set in some order. The data is generally
sorted in ascending or descending order.
Bubble sort
25. Problem Solving and Computer Programming 25
#include <iostream>
using namespace std;
// Function to perform bubble sort on an array
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) { // Outer loop for t
for (int j = 0; j < size - i - 1; j++) { // Inner loo
if (arr[j] > arr[j + 1]) {
// If the current element is greater than the nex
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display the sorted array
cout << "The sorted array is: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
// Set the size of the array
int size = 5;
// Initialize the array with values
int arr[size] = {25, 17, 31, 13, 2};
// Call the bubbleSort function to sort the array
bubbleSort(arr, size);
27. Problem Solving and Computer Programming 27
#include <iostream>
using namespace std;
// Function to perform selection sort on an array
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) { // Outer loop for i
for (int j = i + 1; j < size; j++) { // Inner loop fo
if (arr[i] > arr[j]) { // If the current element i
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Display the sorted array
cout << "The sorted array is: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int size = 5;
int arr[size] = {25, 17, 31, 13, 2};
28. Problem Solving and Computer Programming 28
// Call the selectionSort function to sort the array
selectionSort(arr, size);
return 0;
}
29. Problem Solving and Computer Programming 29
Pointers and references
Pointers
Pointers are variables that store the memory address of another variable. They allow
direct manipulation of memory and facilitate dynamic memory allocation.
int x = 10;
int* ptr = &x;//declares a pointer ptr to an integer and initi
References
References are alternative names for existing variables. They provide a way to
manipulate variables indirectly. The reference must be initialized upon declaration
and always refers to the same object.
int x = 10;
int& ref = x; //declares and initializes a reference to x
//Now ref can be used like x to read or modify the value of t
Dereferencing
Dereferencing is retrieving the value at the memory address held by a pointer. It
involves using the dereference operator * to retrieve the value associated with the
pointer.
int x = 10;
int* ptr = &x; // ptr holds the address of x
// Dereferencing the pointer to access the value at the memory
int value = *ptr; // value now holds the value of x (10)
Pointer to Pointer
int x = 10;
int* ptr1 = &x; // ptr1 holds the address of x
30. Problem Solving and Computer Programming 30
int** ptr2 = &ptr1; // ptr2 holds the address of ptr1
// Dereferencing the double pointer to access the value of x
int value = **ptr2; // value now holds the value of x (10)
Here, ptr2 is a pointer to a pointer. It stores the memory address of ptr1 , which
itself holds the address of the integer variable x .
Functions
A function in programming is a set of program statements used to perform a specific
task. When invoked, a function operates as if its code is seamlessly integrated at the
point of the function call. The interaction between the caller (the function making
the call) and the callee (the function being called) occurs through parameters,
allowing for effective communication and data exchange between different parts of
the program.
The advantages of functions include the following:
1. Modular programming
2. Reduction in the amount of work and development time
3. Program and function debugging is easier
4. Division of work is simplified due to the use of divide-and-conquer principle
5. Reduction in size of the program due to code reusability
6. Functions can be accessed repeatedly without redevelopment, which in turn
promotes reuse
of code
7. Library of functions can be implemented by combining well-designed, tested, and
proven
functions
Syntax:
return_type function_name(parameter1_type parameter1_name, pa
// Function body
31. Problem Solving and Computer Programming 31
// Statements to perform the desired task
// Optional: return statement to return a value if the functio
return return_value;
}
Function prototype
A function prototype is a declaration of a function that tells the compiler about the
function's name, return type, and the types of its parameters. A function prototype is
typically placed at the beginning of a program or in a header file.
return_type function_name(parameter_type parameter_name, ...)
Function Calling
Function calling involves invoking a function to execute its code. If the function has
parameters, values are passed to the function during the call.
Examples:
// Function prototype
int add(int a, int b);
// Function definition
int add(int a, int b) {
return a + b;
}
// Function call
int sum = add(3, 4);
Roots of a quadratic equation :
#include<iostream>
#include<cmath>
using namespace std;
32. Problem Solving and Computer Programming 32
void quadratic(int a,int b,int c){
double disc,root1,root2,real,imag,root;
disc = b*b-4*a*c;
if(disc>0){
root1 = (-b + sqrt(disc))/2*a;
root2 = (-b - sqrt(disc))/2*a;
cout<<"The 2 real roots of this equation are: "<<root1
}
else if(disc == 0){
root = -b/2*a;
cout<<"There are 2 equal roots.Hence the root is: "<<
}
else{
real = -b/2*a;
imag = sqrt(disc)/2*a;
root1 = real + imag;
root2 = real - imag;
cout<<"The imaginary roots are: "<<root1<<" and "<<roo
}
}
int main()
{
int a,b,c;
cout<<"Enter the values of a , b , c: ";
cin>>a>>b>>c;
quadratic(a,b,c);
}
Sine of an angle:
#include<iostream>
#include<cmath>
using namespace std;
//factorial function
33. Problem Solving and Computer Programming 33
double factori(double num)
{
double fact=1;
for(int i=1;i<=num;i++){
fact = fact * i;
}
return fact;
}
//sine function
void sine(double rad,int terms){
double sum=0;
for(int i=0;i<terms;i++){
sum = sum +(pow(rad,2*i+1)*pow(-1,i))/factori(2*i+1);
}
cout<<"Sine of the angle is: "<<sum<<endl;
}
int main(){
int degree,terms;
double rad;
cout<<"Enter the angle in degrees: ";
cin>>degree;
rad = (M_PI*degree)/180;
cout<<"Enter the no of terms till which you want to c
cin>>terms;
sine(rad,terms);
}
Methods of passing parameters
34. Problem Solving and Computer Programming 34
Pass by Value
In "pass by value," a copy of the argument is passed to the function.
Any changes made to the parameter within the function do not affect the
original argument.
It is suitable for situations where you want to work with a local copy of the data
and not modify the original.
It's the default way of passing arguments to functions in C++.
Example:
void increment(int x) {
x++; // Changes the local copy of x, not the original
}
int main() {
int num = 5;
increment(num);
// num remains 5, as the function works with a copy of num
return 0;
}
Pass by Pointer
In "pass by pointer," a pointer to the argument is passed to the function.
The function can modify the original data by dereferencing the pointer.
Any changes made to the pointed-to data within the function affect the original
data outside the function.
Example:
void increment(int* ptr) {
(*ptr)++; // Modifies the original data
}
int main() {
int num = 5;
increment(&num);
35. Problem Solving and Computer Programming 35
// num is now 6, as the function modified the original da
return 0;
}
Pass by Reference
In "pass by reference," a reference to the argument is passed to the function.
The function operates directly on the original data, not on a copy.
Changes made to the reference parameter within the function affect the
original data outside the function.
It's often used when you want to modify the original data without the overhead of
pointer syntax.
Example:
void increment(int& ref) {
ref++; // Modifies the original data
}
int main() {
int num = 5;
increment(num);
// num is now 6, as the function modified the original da
return 0;
}
Pass by Const Reference
In "pass by const reference," a constant reference to the argument is passed
to the function.
The function can access the original data but cannot modify it.
It's useful when you want to avoid making a copy of the data and ensure that the
function does not accidentally modify it.
It's commonly used for efficiency and safety.
Example:
36. Problem Solving and Computer Programming 36
void print(const int& ref) {
// Can read the original data, but cannot modify it
cout << ref << endl;
}
int main() {
int num = 5;
print(num); // The original data remains unchanged
return 0;
}
Recursion
A function which calls itself is called a recursive function. Recursive functions can be
powerful and elegant tools for solving certain types of problems.
Two important conditions which must be satisfied by any recursive function are the
following:
1. Each time a function calls itself, it must be nearer, in some sense, to a solution.
2. There must be a decision criterion for stopping the process or computation.
Example:
// Recursive function to calculate factorial
long factorial(int n) {
// Base case
if (n == 1) {
return 1;
}
// Recursive case
else {
return n * factorial(n - 1);
}
}
37. Problem Solving and Computer Programming 37
Binary search using Recursion
#include <iostream>
using namespace std;
int recBinarySearch(int arr, int lower, int upper int key){
int mid = (lower + (upper - lower))/2;
if(arr[mid] == key){
return mid; // Return the index if the key is found
}
else if(arr[mid] < key){
recBinarySearch(arr, lower, mid-1, key); // Search in
}
else if(arr[mid] > key) {
recBinarySearch(arr, mid+1, upper, key); // Search
}
return -1; // Return -1 if the key is not found
}
int main() {
int size = 10;
int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = recBinarySearch(arr, 0, size-1, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
38. Problem Solving and Computer Programming 38
Function Overloading
Function polymorphism, also known as function overloading, is a concept that
enables multiple functions to use the same name but with different parameter
types. This allows a single function name to have multiple forms, each tailored to
handle specific argument types. Function overloading, or function-name overloading,
is the practice of associating one or more function bodies with the same function
name.
39. Problem Solving and Computer Programming 39
#include <iostream>
using namespace std;
void swap ( char& x, char& y )
{
char t; // temporary used in swapping
t = x;
x = y;
y = t;
}
void swap( int& x, int& y )
{
int t; // temporary used in swapping
t = x;
x = y;
y = t;
}
void swap( float& x, float& y )
{
float t; // temporary used in swapping
t = x;
x = y;
y = t;
}
int main()
{
char chl, ch2;
cout << "Enter two Characters <chl, ch2>: ";
cin >> chl >> ch2;
swap( chl, ch2 );
cout << "On swapping <chl, ch2>: " << chl << " " << ch2 <<
int a, b;
cout << "Enter two integers <a, b>: ";
cin >> a >> b;
swap( a, b );
40. Problem Solving and Computer Programming 40
cout << "On swapping <a, b>: " << a << " " << b << endl;
float c, d;
cout << "Enter two floats <c, d>: ";
cin >> c >> d;
swap( c, d );
cout << "On swapping <c, d>: " << c << " " << d;
return 0;
}
//Output:
//Enter two Characters <chl, ch2>: a b
//On swapping <chl, ch2>: b a
//Enter two integers <a, b>: 3 5
//On swapping <a, b>: 5 3
//Enter two floats <c, d>: 3.6 2.4
//On swapping <c, d>: 2.4 3.6
Function Template
A function template, also called a generic function, combines the functionalities of
several functions differing only in data types. This allows us to write a single source
declaration that can generate multiple functions tailored to various data types.
Function templates provide a concise and flexible way to express the same logic for
different types, promoting code reusability and simplicity.
Syntax:
41. Problem Solving and Computer Programming 41
Example:
#include <iostream>
using namespace std;
template <class T>
void my_swap( T& x, T& y )
{
T t; // temporarily used in my_swap, template variable
t = x;
x = y;
y = t;
}
int main()
{
char chl, ch2;
cout << "Enter two Characters <chl, ch2>: ";
cin >> chl >> ch2;
my_swap( chl, ch2 ); // compiler calls my_swap( char &x, c
cout << "On swapping <chl, ch2>: " << chl << " " << ch2 <<
int a, b;
cout << "Enter two integers <a, b>: ";
cin >> a >> b;
my_swap( a, b ); // compiler creates and calls my_swap( i
cout << "On swapping <a, b>: " << a << " " << b << endl;
42. Problem Solving and Computer Programming 42
float c, d;
cout << "Enter two floats <c, d>: ";
cin >> c >> d;
my_swap( c, d ); // compiler creates and calls my_swap( fl
cout << "On swapping <c, d>: " << c << " " << d;
return 0;
}
//Output:
//Enter two Characters <chl, ch2>: a b
//On swapping <chl, ch2>: b a
//Enter two integers <a, b>: 3 5
//On swapping <a, b>: 5 3
//Enter two floats <c, d>: 3.5 6.8
//On swapping <c, d>: 6.8 3.5
Storage Classes
C++ provides several storage classes that determine the scope, lifetime, and
accessibility of variables. The main storage classes are auto , register , static , and
extern .
auto Storage Class
The auto storage class is the default storage class for all local variables. It
specifies that the variable has a local scope and a lifetime limited to the block in
which it is defined.
auto is rarely used for local variables since it's the default.
Scope: Local scope within the block or function where they are defined.
Extent: Limited to the block or function execution; destroyed upon block or
function exit.
register Storage Class
43. Problem Solving and Computer Programming 43
The register storage class suggests that the variable should be stored in a CPU
register for faster access. However, the compiler may ignore this suggestion since
modern compilers are optimized.
The register keyword is rarely used because compilers are often better at optimizing
variable storage than programmers.
Scope: Local scope within the block or function where they are defined.
Extent: Limited to the block or function execution; destroyed upon block or
function exit.
static Storage Class
The static storage class is used for variables that persist throughout the
program's lifetime. Static variables have local scope within the function or block
but retain their
values between function calls
. They are initialised only once.
Scope: Local (if within a block or function) or global (if outside any function).
Extent: Local static variables persist throughout program execution, retaining
values across function calls. Global static variables are accessible from any part
of the program.
extern Storage Class
The extern storage class is used to declare variables that are defined in other
files. It tells the compiler that the variable is defined externally and should be linked
at the linking phase.
Scope: Global within the file where declared; used for accessing variables
defined in other files.
Extent: Depends on the storage duration of the referenced variable.
// File1.cpp
int globalVar = 42;
// File2.cpp
#include <iostream>
extern int globalVar; // Declare 'globalVar' defined in anothe
int main()
{
44. Problem Solving and Computer Programming 44
cout << "GlobalVar: " << globalVar << endl;
return 0;
}
//Output:
//GlobalVar: 42
Structures
Structures combine logically related data items into a single unit. The data items
enclosed within a structure are known as members and they can be of the same or
different data types. Hence, a structure can be viewed as a heterogeneous user-
defined data type. It can be used to create variables, which can be manipulated in
the same way as variables of standard data types. It encourages better
organization and management of data in a program.
The individual members of a structure can be variables of built-in data types,
pointers, arrays, or even other structures.
The period or dot(.) operator is used to access the members of a structure
independently. The dot operator connects a structure variable and its member.
Syntax:
struct struct_name {
// Member variables (fields)
data_type member1_name;
data_type member2_name;
// ...
};
Example:
#include <iostream>
using namespace std;
struct student {
45. Problem Solving and Computer Programming 45
int roll_no;
char name[25];
char branch[15];
int marks;
};
int main() {
// Creating a variable of type student and initializing i
struct student s1 = {1, "Om", "Mechanical", 100}; // Using
// Accessing and printing the 'name' member of the struct
cout << s1.name << endl;
return 0;
}
Array of structures
#include <iostream>
using namespace std;
struct student {
int roll_no;
char name[25];
char branch[15];
int marks;
};
int main() {
cout<<"Enter the size of the array: "<<endl;
cin>>size;
student students[size]; // Array of structures to store s
// Inputting data for each student using a for loop
for (int i = 0; i < size; ++i) {
cout << "Enter details for student " << i + 1 << ":
cout << "Roll No: ";
46. Problem Solving and Computer Programming 46
cin >> students[i].roll_no;
cout << "Name: ";
cin>>students[i].name;
cout << "Branch: ";
cin>>students[i].branch;
cout << "Marks: ";
cin >> students[i].marks;
cout << endl;
}
return 0;
}
Nesting of structures
A member of a structure may itself be a structure. Such nesting enables building of
very powerful data structures.
For example, here, the student structure can be enhanced to accommodate the date
of birth of a student.
#include <iostream>
using namespace std;
struct date {
int day;
int month;
int year;
}
struct student {
int roll_no;
char name[25];
struct date birthday;
char branch[15];
int marks;
47. Problem Solving and Computer Programming 47
};
int main() {
// Creating a variable of type student and initializing i
student s1 = {1, "Vivek", "Mechanical", 100};
// Accessing and printing the 'name' member of the struct
cout << s1.name << endl;
return 0;
}
48. Problem Solving and Computer Programming 48
Structures and Functions
Structure variables or an array of structure variables may be passed to functions just
like any other variables. It is also possible for functions to return structure variables
through the use of the return statement.
//Passing Structure to a Function
Passing Structure to a Function
void show(student stu) //taking structure type parameter
{
cout<<"Name"<<stu.name<<endl;
cout<<"Roll number:"<<stu.roll_no<<endl;
cout<<"Branch:"<<stu.branch<<endl;
cout<<"Marks:"<<stu.marks<<endl;
}
//Returning Structure from Function
student read()
{
student stu;
cout<<"Name"<<endl;
cin>>stu.name;
cout<<"Roll number:"<<endl;
cin>>stu.roll_no;
cout<<"Branch:"<<endl;
cin>>stu.branch;
cout<<"Marks:"<<endl;
cin>>stu.marks;
return stu; //returning structure type variable
}
Unions
A union is a user-defined data type that allows you to store different data types in
the same memory location. Unlike structures, where each member has its own
49. Problem Solving and Computer Programming 49
memory space, members of a union share the same memory location.
The amount of memory required to store a structure variable is the sum of the
size of all the members. On the other hand, in the case of unions, the amount of
memory required is always equal to that required by its largest member.
Members of the union can be accessed using either the dot . or the arrow ->
operator. It is similar to accessing the structure variable. Only one member of a union
can be accessed at any given time. This is because, at any instant, only one of the
union variables can be active.
Syntax:
Object Oriented Programming and Classes
Object-oriented modeling is a modern approach to problem-solving that revolves
around real-world concepts. In this methodology, objects are the fundamental
building blocks, created through programming constructs known as classes. These
classes encapsulate both data and functions related to a specific concept into
a single unit.
Class
50. Problem Solving and Computer Programming 50
A class is a user-defined data type which is like a blueprint, defining the
structure and behavior of the objects of that class. The process of creating
variables (instances) based on a class is called class instantiation, and these
variables are referred to as objects. Each object is a unique instance of its class.
Within a class, we find two key components:
1. Data Members: These represent the variables of an object. By default, these are
private.
2. Member Functions: These define the actions or operations that can be
performed on the data members. By default, these are public.
private , public , and protected are access specifiers that determine the visibility and
accessibility of class members (data members and member functions) within the
class and from outside the class.
private members are only accessible within the class.
public members are accessible from anywhere.
protected members are accessible within the class and its derived classes.
Syntax:
class ClassName {
private:
data_type privateMember1;
data_type privateMember2;
// ...
public:
return_type memberFunction1(data_type param1, data_ty
return_type memberFunction2(data_type param1, data_ty
// ...
};
return_type CLassName::memberFunction1(data_type param1, data_
//function body of memberFunction1
}
return_type CLassName::memberFunction2(data_type param1, data_
//function body of memberFunction2
51. Problem Solving and Computer Programming 51
}
//...
Example:
class ratio{
private:
int num, den;
public:
void read(){
cout<<"Enter the numerator: ";
cin>>num;
cout<<"Enter the denominator: ";
cin>>den;
}
void print(){
cout<<num<<"/"<<den<<endl;
}
double convert(){
double r = num/den;
return r;
}
};
The difference between structures and classes is that all the members of structures
are public by default whereas, the members of classes are private by default. Class
follows the principle that the information about a module should be private to the
module unless it is specifically declared public.
Constructor
A constructor is a special member function that allocates memory and initializes
the object of a class. It is automatically called when an object is created to set its
initial state or perform any necessary setup.
52. Problem Solving and Computer Programming 52
It has the same name as the class to which it belongs.
It has no return type and return statement.
A constructor which takes no arguments is called a default constructor.
Example of a constructor:
#include <iostream>
using namespace std;
class ComplexNumber {
private:
double real;
double imaginary;
public:
//Default constructor
ComplexNumber() {
real = 0;
imaginary = 0;
}
};
Constructor overloading
An interesting feature of the constructors is that a class can have multiple
constructors. This is called constructor overloading. All the constructors have the
same name as the corresponding class, and they differ only in terms of their
signature (in terms of the number of arguments, or data types of their arguments, or
both).
In such a case, a constructor is invoked during the creation of an object depending
on the number and type of arguments passed.
Example:
53. Problem Solving and Computer Programming 53
Destructor
A destructor is a special (public) member function of a class that is responsible for
releasing resources held by an object.
The destructor has the same name as the class but is preceded by a tilde ~ .
Destructors are automatically called when an object goes out of scope or is explicitly
deleted using the delete operator.
Destructors have no return type, and they don't take any parameters/arguments.
Binary Operator Overloading
Binary operator overloading allows you to define custom behaviors for operators
when they are applied to objects of user-defined classes. This means you can use
operators like + , - , * , / , and more with your custom data types, making your
code more intuitive and readable. It provides a way to define how two objects of
your class should interact when operated upon with a binary operator.
Here's an example of how you can create a class for complex numbers and overload
the + operator for two complex numbers:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i){
54. Problem Solving and Computer Programming 54
real = r;
imag = i;
}
// Overloading the + operator for adding two complex
Complex operator+(Complex other){
Complex temp;
temp.real = real + other.real;
temp.imag = imag + other.imag;
return temp;
}
// Display the complex number
void display(){
cout << real << " + " << imaginary << "i" << endl
}
};
int main() {
Complex num1(3, 4);
Complex num2(1, 2);
Complex sum = num1 + num2;
cout << "Result of addition: ";
sum.display();
return 0;
}
In this code:
1. We define a Complex class to represent complex numbers, with real and
imaginary parts.
2. Inside the class, we overload the + operator by defining the operator+ member
function. This function takes another Complex object ( other ) as a parameter and
returns a new Complex object that represents the sum of the two complex
numbers.
55. Problem Solving and Computer Programming 55
3. The display member function is used to display the complex number.
4. In the main function, we create two Complex objects, num1 and num2 , and then
add them using the + operator.
5. The result of the addition is stored in the sum object, and we display the result
using the display member function.
Friend Functions
A friend function is a function that is not a member of a class but has access to its
private and protected members. A friend function is declared within a class, but
it is defined outside of the class scope.
A friend function can access private and protected members of the class for which it
is declared as a friend.
Friend functions are declared within the class using the friend keyword.
A function can be friend to any number of classes.
A friend function is used to bridge classes.
Friend function allows a more obvious syntax for calling a function rather than
what a member function can do.
It is used to increase the versatility of overloaded functions.
Example:
#include <iostream>
using namespace std;
class Car {
private:
int speed;
public:
Car(int initialSpeed) {
speed = initialSpeed;
}
56. Problem Solving and Computer Programming 56
// Friend function declaration
friend bool isCarMoving(const Car& car1);
};
// Friend function definition
bool isCarMoving(const Car& car1) {
// Compare the speed of the car
return (car1.speed > 0);
}
int main() {
Car car1(50); // Speed of car1 is 50
// Check if the caris moving using the friend function
if (isCarMoving(car1)) {
cout << "The car is moving!" << endl;
} else {
cout << "The car is not moving." << endl;
}
return 0;
}
Friend Classes
Similar to friend functions, we can also declare an entire class as a friend of
another class. This allows all the member functions of the friend class to access the
private and protected members of the other class.
#include <iostream>
using namespace std;
class Boy {
private:
int boyNumber;
57. Problem Solving and Computer Programming 57
int age;
public:
Boy(const int phNum, int age){
boyNumber = phNum;
age = age;
}
// Declaration of Girl class as a friend
friend class Girl;
};
class Girl {
public:
// Function to access private members of Boy
void displayBoyInfo(const Boy& boy);
private:
int girlNumber;
};
// Definition of the function to access private members of Boy
void Girl::displayBoyInfo(const Boy& boy) {
cout << "Girl accessing Boy's info:" << endl;
cout << "Boy's Number: " << boy.boyNumber << endl;
cout << "Boy's Age: " << boy.age << endl;
}
int main() {
Boy Pradeep(123456789, 26);
Girl Nikitha;
// Girl accesses and displays information from Boy
Nikitha.displayBoyInfo(Pradeep);
58. Problem Solving and Computer Programming 58
return 0;
}
In this example:
The Girl class is declared as a friend of the Boy class, allowing the Girl class
to access private members of the Boy class.
The Boy class has private members boyNumber and age .
The Girl class has a function displayBoyInfo that takes a Boy object as a
parameter and can access and display the private information of the Boy class.
Inheritance
Inheritance is a technique of organizing information in a hierarchical form. It is like a
child inheriting the features of its parents.
Inheritance allows new classes to be built from older and less specialized classes
instead of being rewritten from scratch.
Inheritance, a prime feature of OOP, can be stated as the process of creating new
classes (called derived classes), from the existing classes (called base classes).
The derived class inherits the features of the base class (depending on the visibility
mode and level of inheritance) and adds its own features.
59. Problem Solving and Computer Programming 59
Derived class accesses features of the base class and not vice versa.
Syntax:
The visibility mode enclosed within the square brackets implies that it is optional. The
default visibility mode is private. It specifies whether the features of the base class
are publicly or privately inherited.
60. Problem Solving and Computer Programming 60
Forms of inheritance
(a)Single Inheritance: Derivation of a class from only one base class.
(b)Multiple Inheritance: Derivation of a class from several (two or more) base
classes.
(c)Hierarchical Inheritance: Derivation of several classes from a single base class,
i.e., the traits of one class may be inherited by more than one class.
(d)Multilevel Inheritance: Derivation of a class from another derived class.
(e)Hybrid Inheritance: Derivation of a class involving more than one form of
inheritance.
61. Problem Solving and Computer Programming 61
(f)Multipath Inheritance: Derivation of a class from other derived classes, which are
derived from the same base class.
Constructors of the base class and the derived class are automatically invoked when
the
derived class is instantiated. The constructors of the base class are invoked first and
then the constructors of the derived class.
Abstract Classes:
An abstract class is one that has no instances and is not designed to create objects.
An
abstract class is only designed to be inherited.
Example codes:
multipath_inheritance.cpp
multiple_inheritance.cpp
hierarchical_inheritance.cpp
62. Problem Solving and Computer Programming 62
multilevel_inheritance.cpp
hybrid_inheritance.cpp
File Management
File management involves reading from and writing to files on a computer's file
system. We can use the fstream library to handle file operations in C++.
Opening Files:
To open a file for reading or writing, you can use the open method. You specify the
file's name and the mode (e.g., ios::in for input or ios::out for output) in the open call.
If the file doesn't exist, it will be created when opened for writing.
Closing Files:
It's important to close the files once you are done with them using the close method.
This ensures that all data is written to the file, and the file resources are released.
#include <iostream>
#include <fstream>
using namespace std;
fstream fin, fout;
int main(){
fin.open("input.txt", ios::in);
fout.open("output.txt", ios::out);
fin.close();
fout.close();
}
63. Problem Solving and Computer Programming 63
Reading from Files :
To read from a file, use the >> operator along with the fstream object. You can read
various data types from the file, including integers, strings, and more.
Writing to Files:
To write to a file, use the << operator along with the fstream object. You can write
data of various types, similar to how you read data.
Example :
int value = 1;
fin >> value; // Reads an integer from the file
int a = 3;
fout << text; // Writes the string to the file
File modes
ios::in : Input mode, used for reading from a file.
ios::out : Output mode, used for writing to a file.
ios::ate : Open the file and seek to the end.
ios:app : Append mode, it always appends the data (writes data at the end of the
file).
ios::trunc : Truncates the file if it already exists.
ios::nocreate : Open fails if the file does not exist.
ios::binary : Opens the file as a binary file (rather than text).
ios::noreplace : Open fails if the file already exists.
Seek calls
Seek calls refer to functions or methods that manipulate the position of the file
pointer within a file. The file pointer is an indicator that points to the current position
in a file, and seek operations allow you to move this pointer to different locations
within the file. This is particularly useful when reading from or writing to files.
seekg : Used with input file streams to move the input file pointer.
seekp : Used with output file streams to move the output file pointer.
64. Problem Solving and Computer Programming 64
Example:
inputFile.seekg(10, ios::beg); // Move 10 bytes from the begi
Strings
Strings are used in programming languages for storing and manipulating text, such
as
words, names, and sentences.
A string is represented as an array of characters and the end of the string is marked
by the
NULL (‘0’) character.
String constants are enclosed in double quotes. For instance, “Hello World” is a
string.
An array of characters representing a string is defined as follows:
char array-name[size];
Menu Driven C++ Code for String Operations without using STL of C++:
#include <iostream>
using namespace std;
class mystring
{
private:
char str[100]; // Assuming a character array of size 1
public:
mystring()
{
str[0] = '0'; // Initialize the character array
}
// Function to get mystring length
65. Problem Solving and Computer Programming 65
int length() const
{
int len = 0;
while (str[len] != '0')
{
++len;
}
return len;
}
// Function to concatenate mystrings
mystring concatenate(const mystring& other) const
{
mystring result;
int len = this->length();
for (int i = 0; i < len; ++i)
{
result.str[i] = this->str[i];
}
int j = 0;
while (other.str[j] != '0')
{
result.str[len + j] = other.str[j];
++j;
}
result.str[len + j] = '0'; // Null-terminate the result
return result;
}
// Function to compare mystrings
int compare(const mystring& other) const
{
int i = 0;
while (this->str[i] != '0' && other.str[i] != '0' && thi
{
++i;
}
return this->str[i] - other.str[i];
66. Problem Solving and Computer Programming 66
}
// Function to reverse the mystring
mystring reverse() const
{
mystring result;
int len = this->length();
for (int i = 0; i < len; ++i)
{
result.str[i] = this->str[len - i - 1];
}
result.str[len] = '0'; // Null-terminate the result
return result;
}
// Operator overloading for concatenation using +
mystring operator+(const mystring& other) const
{
return this->concatenate(other);
}
// Function to enter the mystring
void enter()
{
cout << "Enter the mystring: ";
cin.ignore(); // Clear the input buffer
cin.getline(str, sizeof(str));
}
// Function to display the mystring
void display() const
{
cout << "mystring: " << str << endl;
}
};
int main()
{
67. Problem Solving and Computer Programming 67
mystring str1, str2, result;
int choice;
do
{
cout<< "nmystring Operations Menu:n"
<< "1. Enter mystring 1n"
<< "2. Enter mystring 2n"
<< "3. mystring Lengthn"
<< "4. Concatenate mystringsn"
<< "5. Compare mystringsn"
<< "6. Reverse mystringn"
<< "7. Exitn"
<< "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
str1.enter();
break;
case 2:
str2.enter();
break;
case 3:
cout << "mystring 1 Length: " << str1.length() <<
cout << "mystring 2 Length: " << str2.length() <<
break;
case 4:
result = str1 + str2;
cout << "Concatenated mystring: ";
result.display();
break;
case 5:
if (str1.compare(str2) == 0)
{
cout << "mystrings are equal.n";
}
else
68. Problem Solving and Computer Programming 68
{
cout << "mystrings are not equal.n";
}
break;
case 6:
cout << "Reversed mystring 1: ";
str1.reverse().display();
cout << "Reversed mystring 2: ";
str2.reverse().display();
break;
case 7:
cout << "Exiting program.n";
break;
default:
cout << "Invalid choice. Please try again.n";
}
} while (choice != 7);
return 0;
}