0% found this document useful (0 votes)
16 views12 pages

Unit - 3ooda Notes

C++ is a versatile programming language that supports procedural, object-oriented, and generic programming, widely used in various applications. Key features include input/output operations with cin and cout, control flow statements, functions, and memory management through pointers. The language also emphasizes object-oriented principles such as encapsulation, inheritance, and polymorphism, along with a rich set of libraries for developers.

Uploaded by

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

Unit - 3ooda Notes

C++ is a versatile programming language that supports procedural, object-oriented, and generic programming, widely used in various applications. Key features include input/output operations with cin and cout, control flow statements, functions, and memory management through pointers. The language also emphasizes object-oriented principles such as encapsulation, inheritance, and polymorphism, along with a rich set of libraries for developers.

Uploaded by

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

UNIT-III

Introduction to C++
C++ is a powerful, high-performance programming language that combines
procedural, object-oriented, and generic programming paradigms. It was
created by Bjarne Stroustrup in 1979 as an extension of the C language to
include object-oriented features. C++ is widely used for systems
programming, application software, game development, real-time systems,
and large-scale software projects.
Key Parts of the Program:
#include <iostream>: This preprocessor directive tells the compiler to
include the standard input-output library, allowing us to use functions like
cout (for output) and cin (for input).
int main(): The main function is the entry point of every C++ program. The
program starts executing from here.
cout << "Hello, World!": This is how you output text to the console. cout is
the standard output stream in C++.
return 0;: The return statement indicates the program executed
successfully. In C++, returning 0 typically means no error occurred.
2. Variables and Data Types
C++ provides a wide variety of built-in data types, including:
Integer types: int, short, long, long long
Floating-point types: float, double
Character types: char
Boolean type: bool
Void type: void (used for functions that don't return a value)
3. Control Flow
C++ includes standard control flow statements like if-else, switch, for
loop, while loop, and do-while loop.
4. Functions
Functions in C++ allow you to modularize code by breaking it into smaller,
reusable pieces. A function is defined with a return type, a name, and
optional parameters.
Function Overloading:
C++ also supports function overloading, meaning you can define multiple
functions with the same name, but with different parameter lists.
5. Object-Oriented Programming (OOP)
C++ is known for its strong support for object-oriented programming. In
OOP, everything is treated as objects, and classes define the structure and
behavior of these objects.
Key Concepts in OOP:
Class: A blueprint for creating objects, defining attributes (data) and
methods (functions).
Object: An instance of a class.
Encapsulation: Bundling data and methods that operate on the data within
one unit (class), restricting access to some components.
Inheritance: Allows a class to inherit properties and behaviors from
another class.
Polymorphism: The ability to use a derived class object through a pointer
or reference of the base class type.
Abstraction: Hiding the implementation details and showing only the
necessary features.
Memory Management in C++
C++ allows you to control memory management manually. This is done
through the use of pointers and dynamic memory allocation.
Pointers: A pointer is a variable that stores the memory address of another
variable.
Dynamic Memory Allocation: You can dynamically allocate memory during
runtime using new and delete keywords.
C++ includes the Standard Template Library (STL), a powerful library that
provides generic algorithms, containers, and iterators. Some of the key
features in STL are:
Containers: Data structures like vector, list, map, set.
Algorithms: Functions like sort(), find(), reverse().
Iterators: Objects used to traverse containers.
Key Advantages of C++
Performance: C++ provides low-level control over system resources,
making it ideal for performance-critical applications (e.g., operating
systems, real-time systems, games).
Portability: C++ programs can be compiled and run on a variety of
platforms with minimal modification.
Extensive Libraries: C++ has a rich set of libraries for different tasks, such
as file handling, networking, and graphics.
input and output statement in c++
In C++, input and output operations are commonly performed using the
standard input and output streams. These streams are part of the
<iostream> header file. The most commonly used streams are:
cin for input
coat for output
cerr for error output (optional)
Clog for logging (optional)
1. Output Statement (Using cout)
To output data to the console, you use the cout object followed by the
insertion operator (<<). You can print multiple items by chaining <<.
Syntax:
cpp
Copy code
std::cout << expression;
Example:
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // Printing a message
int x = 5;
cout << "Value of x is: " << x << endl; // Printing variable value
return 0;
}
2. Input Statement (Using cin)
To take input from the user, you use the cin object followed by the
extraction operator (>>). You can read multiple inputs in sequence by
chaining >>.
Syntax:
cpp
Copy code
std::cin >> variable;
Example:
cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num; // Taking input from the user
cout << "You entered: " << num << endl;
return 0;
}
Example Program: Input and Output in C++
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
// Declare variable
int age;
double height;
// Ask user for input
cout << "Enter your age: ";
cin >> age; // User inputs age
cout << "Enter your height in meters: ";
cin >> height; // User inputs height
// Output the values
cout << "You are " << age << " years old and " << height << " meters tall."
<< endl;
return 0;
Input and Output Statements in C++ (5 Marks)
In C++, input and output operations are essential for interaction with the
user and the environment. These operations use the standard streams cin
for input and cout for output, which are defined in the <iostream> library.
1. Output (Using cout)
The cout (character output stream) is used to display information to the
user. The insertion operator << is used to send data to the output.
Syntax:
cpp
Copy code
std::cout << expression;
Example:
cpp
Copy code
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl; // Print a message
return 0;
}
2. Input (Using cin)
The cin (character input stream) is used to read data from the user. The
extraction operator >> is used to take input.
Syntax:
cpp
Copy code
std::cin >> variable;
Example:
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number; // Input from user
cout << "You entered: " << number << endl;
return 0;
}
3. Complete Example:
cpp
Copy code
#include <iostream>
using namespace std;

int main() {
int age;
double height;

// Taking user input


cout << "Enter your age: ";
cin >> age;

cout << "Enter your height in meters: ";


cin >> height;

// Displaying output
cout << "You are " << age << " years old and " << height << " meters tall."
<< endl;
return 0;
}
Key Points:
cout is used to display output to the console.
cin is used to take input from the user.
The << operator is used with cout to send data to the output.
The >> operator is used with cin to retrieve data from the user.
This fundamental usage of cin and cout allows basic input-output
operations in C++.
Declaration in C++
In C++, declaration refers to the process of introducing a variable,
function, or other identifiers to the program, specifying its name and data
type, but not necessarily assigning it a value (in the case of variables).
Declaration informs the compiler about the type of a variable, its name, and
its role in the program. Once declared, a variable can be used later in the
code.
Types of Declarations in C++:
Variable Declaration
Function Declaration
Class Declaration
Pointer and Reference Declaration
1. Variable Declaration
A variable declaration introduces a new variable and specifies its type,
but it does not necessarily assign it a value. The data type defines what
kind of data the variable will store (such as integers, floating-point
numbers, characters, etc.).
Syntax
data_type variable_name;
data_type: Specifies the type of data the variable will hold (e.g., int, float,
char).
variable_name: The name you assign to the variable for identification.
Example:
cpp
Copy code
int x; // Declare an integer variable named x
float y; // Declare a floating-point variable named y
char letter; // Declare a character variable named letter
Initial Value Assignment (Optional): You can assign a value to a variable
at the time of declaration.
cpp
Copy code
int age = 25; // Declare and initialize age with 25
float height = 5.9; // Declare and initialize height with 5.9
2. Function Declaration (Function Prototype)
A function declaration (also known as a function prototype) provides
the function's signature to the compiler, specifying the return type, function
name, and parameters. A function declaration informs the compiler about
the function before its definition, ensuring that the function can be called
before the actual function body appears in the program.
Syntax:
cpp
Copy code
return_type function_name(parameter_list);
return_type: Specifies the type of value that the function will return (e.g.,
int, void, float).
function_name: The name of the function.
parameter_list: A comma-separated list of input parameters, specifying
their types and names (or void if the function takes no parameters).
Example:
cpp
Copy code
void displayMessage(); // Function declaration (prototype)

int add(int a, int b); // Function declaration for a function that returns an
integer
You would define the function later in the code:
cpp
Copy code
void displayMessage() {
cout << "Hello, World!" << endl;
}

int add(int a, int b) {


return a + b;
}
3. Class Declaration
In C++, classes are used to define custom data types that group related
variables (called attributes) and functions (called methods) together. A
class declaration specifies the structure of the class without necessarily
providing a complete implementation of the functions.
Syntax:
cpp
Copy code
class ClassName {
// data members (variables)
// member functions (methods)
};
ClassName: The name of the class.
data members: The variables that belong to the class.
member functions: The functions that operate on the data members of the
class.
Example:
cpp
Copy code
class Student {
public:
string name;
int age;
void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
In this example, the Student class has two data members (name and age)
and one member function (displayInfo).
4. Pointer and Reference Declaration
C++ allows declaring pointers and references that store the memory
address of variables. A pointer is a variable that holds the memory address
of another variable, while a reference is an alias for another variable.
Pointer Declaration:
A pointer variable is declared using the * symbol.
cpp
Copy code
int *ptr; // Declare a pointer to an integer
int *ptr; declares a pointer ptr that can store the address of an integer.
You can also declare and initialize a pointer in a single statement:
cpp
Copy code
int num = 10;
int *ptr = &num; // Declare and initialize pointer ptr to the address of num
Reference Declaration:
A reference variable is declared using the & symbol.
cpp
Copy code
int num = 10;
int &ref = num; // Declare a reference to num
Here, ref becomes an alias for the variable num. Any changes made to ref
will also affect num.
5. Array Declaration
Arrays are a collection of elements of the same type stored in contiguous
memory locations. The array declaration specifies the type of elements
and the number of elements in the array.
Syntax:
cpp
Copy code
data_type array_name[array_size];
data_type: The type of elements the array will hold (e.g., int, float).
array_name: The name of the array.
array_size: The number of elements in the array.
Example:
cpp
Copy code
int numbers[5]; // Declare an array of 5 integers
float scores[10]; // Declare an array of 10 floating-point numbers
You can also initialize an array during declaration:
cpp
Copy code
int numbers[5] = {1, 2, 3, 4, 5}; // Initialize an integer array with values
6. Constant DeclarationIn C++, you can declare constants using the const
keyword. A constant is a variable whose value cannot be changed after it is
initialized.
Syntax:const data_type constant_name = value;
Example:const int MAX_SCORE = 100; // Declare a constant integer
MAX_SCOREconst float PI = 3.14159; // Declare a constant floating-point
value PI
CONTROL STRUCTUREControl structures are fundamental concepts in
programming that allow you to dictate the flow of a program's execution.
These structures enable decision-making, repeating tasks, and defining
conditions under which certain actions should be taken. The most common
control structures are:
1. Conditional Statements (Decision Making)
These allow you to execute certain code only if a specific condition is true
or false.
if statement: Executes a block of code if the condition is true.
if condition:
# execute this block if condition is true
else statement: Executes a block of code if the if condition is false
if condition:
sssss
else:
# execute this block if condition is false
elif (else if): Provides an alternative condition to check if the if condition is
false.
python
Copy code
if condition1:
# code for condition1
elif condition2:
# code for condition2
else:
# code if neither condition1 nor condition2 is true
2. Loops (Repetition)
These allow you to repeat a block of code multiple times under certain
conditions.
for loop: Iterates over a sequence (like a list, tuple, or range).
python
Copy code
for i in range(5):
print(i) # This will print 0 to 4
while loop: Repeats a block of code as long as a specified condition is true.
python
Copy code
while condition:
# execute as long as condition is true
break: Exits the loop immediately, even if the loop's condition is still true.
python
Copy code
for i in range(5):
if i == 3:
break # Exit loop when i equals 3
continue: Skips the current iteration and moves to the next iteration of the
loop.
python
Copy code
for i in range(5):
if i == 3:
continue # Skip when i equals 3
print(i)
3. Switch/Case (or Equivalent)
Some languages (e.g., C, JavaScript) offer a switch-case structure, which is
an alternative to multiple if-elif conditions.
Example in JavaScript:
javascript
Copy code
switch (expression) {
case value1:
// code block for value1
break;
case value2:
// code block for value2
break;
default:
// default block if no cases match
}
4. Exception Handling (Error Handling)
Used to handle runtime errors gracefully.
try and except: Catches exceptions (errors) and executes a block of code to
handle them.
python
Copy code
try:
# Code that may raise an error
except SomeException:
# Code to handle the exception
finally: Executes code whether or not an exception is raised.
python
Copy code
try:
# Code that may raise an error
except SomeException:
# Handle exception
finally:
# Always execute this block
5. Functions/Methods (Encapsulation of Logic)
Functions are a way of grouping code into reusable blocks. In most
languages, functions allow for passing parameters, performing some
operations, and returning results.
python
Copy code
def my_function(parameter1):
# Code to execute
return result
6. Ternary Operator (Shortened Conditional)
This is a shorthand for simple if-else conditions in languages that support
it.
Example in Python:
python
Copy code
result = "Yes" if condition else "No"
Key Ideas:
If-Else: Decision-making based on conditions.
Loops: Repeating tasks.
Break/Continue: Controlling loop flow.
Functions: Grouping logic into reusable blocks.
Error Handling: Dealing with unexpected situations.
These control structures form the backbone of most programs, enabling
developers to implement complex logic and interact with data efficiently.

You might also like